Added templates
[bibliodb.git] / CiteData.php
blobd95e0872bb44b22596e079c973415cbd90ea2c3f
1 <?php
2 define("field_not_exist","field doesn`t exist");
3 define("error_message","Error occured: ");
4 define("bad_data","multiple fields, should be just one");
5 class CiteData{
6 private static $instance;
7 private $data=array();
8 private $fieldslist=array();
9 public $current=array();
10 private function __construct()
13 public static function getInstance()
15 if (self::$instance === NULL) {
16 self::$instance = new self;
18 return self::$instance;
20 protected function uniqueKey($key,$suffix){
21 $instance=self::getInstance();
22 if(array_key_exists($key,$instance->data))return $instance->uniqueKey($key.$suffix,++$suffix);
23 return $key;
25 protected function getKey($data){
26 if(count($data)<1)throw new Exception("Empty record");
27 $key=array_key_exists("key",$data)?$data["key"]:strtolower($data["author"][0]["last"].$data["date"]);
28 return self::uniqueKey($key,"a");
30 public function loadData($data){
31 $instance=self::getInstance();
32 for($i=0;$i<count($data);$i++){
33 try{
34 $key= $instance->getKey($data[$i]);
35 $instance->data[$key]=$data[$i];
36 }catch(Exception $e){}
38 reset($instance->data);
39 $instance->setCurrent();
40 //print_r($instance->data);
41 return $this;
43 public function getCiteKey(){
44 $instance=self::getInstance();
45 return $instance->current["key"];
47 public function setCurrent(){
48 $instance=self::getInstance();
49 $data=current($instance->data);
50 $key=key($instance->data);
51 if($data){
52 $instance->current=array("key"=>$key,
53 "data"=>$data);
54 }else{
55 $instance->current=false;
58 public function getData($field){
59 $instance=self::getInstance();
60 if(array_key_exists($field,$instance->current["data"])){
61 /*$list=array();
62 foreach($instance->fieldslist[$field] as $record){
63 $list[]=$instance->data[$record];
65 return $list;*/
66 return $instance->current["data"][$field];
67 }else{
68 //throw new Exception(field_not_exist);
69 return null;
72 public function records($records){
73 $instance=self::getInstance();
74 $instance->keys=is_array($records)?$records:$instance->key;
76 public function current(){
77 $instance=self::getInstance();
78 return is_array($instance->current)===false?false:true;
80 public function next(){
81 $instance=self::getInstance();
82 each($instance->data);
83 $instance->setCurrent();
84 return is_array($instance->current)===false?false:true;
86 public function getField($field){
87 try{
88 $instance=self::getInstance();
89 $list=$instance->getData($field);
90 if(count($list)==1){
91 return($list);
92 }else{
93 throw new Exception(bad_data);
95 }catch(Exception $e){
96 $instance->printError($e);
99 public function getList($field){
100 $instance=self::getInstance();
101 return $instance->getData($field);
103 public function printError(Exception $e){
104 echo "<div style=\"border:1px solid black;color:red;\">".error_message.$e->getMessage()."</div>\n";