PageRenderTime 39ms CodeModel.GetById 9ms app.highlight 21ms RepoModel.GetById 3ms app.codeStats 0ms

/web/editor/common/delegate.php

https://bitbucket.org/PokatilovArt/diagramo-art
PHP | 770 lines | 490 code | 141 blank | 139 comment | 73 complexity | 09cb50b53dffaa8746ecf98c6ce850e9 MD5 | raw file
  1<?php
  2define('DEBUG', false);
  3
  4require_once dirname(__FILE__) . '/utils.php';
  5
  6
  7
  8/**
  9 * LICENSE
 10 * License Class is not reflected in the Database (it was not generates by SQLarity)
 11 * To generate a license you need first 8 fields completed
 12 * @deprecated
 13 */
 14class License {
 15    //from client
 16    public $serial;   // buyer's serial number
 17    public $host; //Where the license will be installed
 18    
 19    //from server
 20    public $date;   // purchase date (SQL datetime) as 'yyyy-mm-dd'
 21    public $unlockKey;  // full key of the license (license object saved to a string)
 22
 23    /**
 24     * Saves the License object (this) object to a string
 25     */
 26    public function save() {
 27        $this->unlockKey = $this->computeUnlockKey();
 28        return base64_encode(strrev(serialize($this)));
 29    }
 30
 31    /**
 32     * Load the License object (this) from a string
 33     */
 34    public function load($str) {
 35        //nothing
 36    }
 37
 38    /*
 39     * Computes License's full key based on its other values
 40     * The key is based on email, date, expiryDate, maxUsers and serial
 41     */
 42
 43    protected function computeUnlockKey() {
 44        return "";
 45    }
 46
 47    /** Check a license */
 48    public function checkLicense() {
 49        return true;
 50    }
 51
 52}
 53
 54class Diagram {
 55
 56    public $id;
 57    public $title;
 58    public $description;
 59    public $public;
 60    public $createdDate;
 61    public $lastUpdate;
 62
 63    function loadFromSQL($row) {
 64        $this->id = is_null($row['id']) ? null : $row['id'];
 65        $this->title = is_null($row['title']) ? null : $row['title'];
 66        $this->description = is_null($row['description']) ? null : $row['description'];
 67        $this->public = is_null($row['public']) ? null : $row['public'];
 68        $this->createdDate = is_null($row['createdDate']) ? null : $row['createdDate'];
 69        $this->lastUpdate = is_null($row['lastUpdate']) ? null : $row['lastUpdate'];
 70    }
 71
 72}
 73
 74class User {
 75
 76    public $id;
 77    public $email;
 78    public $password;
 79    public $name;
 80    public $createdDate;
 81    public $lastLoginDate;
 82    public $lastLoginIP;
 83    public $lastBrowserType;
 84    public $admin;
 85
 86    function loadFromSQL($row) {
 87        $this->id = is_null($row['id']) ? null : $row['id'];
 88        $this->email = is_null($row['email']) ? null : $row['email'];
 89        $this->password = is_null($row['password']) ? null : $row['password'];
 90        $this->name = is_null($row['name']) ? null : $row['name'];
 91        $this->createdDate = is_null($row['createdDate']) ? null : $row['createdDate'];
 92        $this->lastLoginDate = is_null($row['lastLoginDate']) ? null : $row['lastLoginDate'];
 93        $this->lastLoginIP = is_null($row['lastLoginIP']) ? null : $row['lastLoginIP'];
 94        $this->lastBrowserType = is_null($row['lastBrowserType']) ? null : $row['lastBrowserType'];
 95        $this->admin = is_null($row['admin']) ? null : $row['admin'];
 96    }
 97
 98}
 99
100
101class Diagramdata {
102	const TYPE_DMO = 'dia';
103	const TYPE_SVG = 'svg';
104	const TYPE_JPG = 'jpg';
105	const TYPE_PNG = 'png';
106	const TYPE_CSV = 'csv';
107
108	public $diagramId;
109	public $type;
110	public $fileName;
111	public $fileSize;
112	public $lastUpdate;
113
114	function loadFromSQL($row) {
115		$this->diagramId = is_null($row['diagramId']) ? null : $row['diagramId'];
116		$this->type = is_null($row['type']) ? null : $row['type'];
117		$this->fileName = is_null($row['fileName']) ? null : $row['fileName'];
118		$this->fileSize = is_null($row['fileSize']) ? null : $row['fileSize'];
119		$this->lastUpdate = is_null($row['lastUpdate']) ? null : $row['lastUpdate'];
120	}
121}
122
123
124
125class Setting {
126
127	public $name;
128	public $value;
129
130	function loadFromSQL($row) {
131		$this->name = is_null($row['name']) ? null : $row['name'];
132		$this->value = is_null($row['value']) ? null : $row['value'];
133	}
134}
135
136class Delegate extends SQLite3 {
137
138    function __construct() {
139        $this->open( dirname(__FILE__) .  '/../data/diagramo.db');
140    }
141
142    /**a wrapper method for executing a query*/
143    public function executeSQL($query) {
144        $result = $this->query($query);
145
146        return $result;
147    }
148    
149    /*     * Add a new entry. We should make wrappers around this function (make it private !?!)
150     *  and never call it directly from outside Delegate
151     *  $tableName - name of the table
152     *  $object - the object
153     *  $ids -  list of ids (default 'id'), usefull for multiple key or keys other then 'id'
154     *  $nullify - if true unset values will be set to NULL, if false we will not touch existing column value
155     * returns the 'id' of the created entry
156     *  author: alex
157     */
158
159    protected function create($object, $ids = array('id'), $tableName = null, $nullify = false, $autoincrement = true) {
160
161        //detect class name
162        if (empty($tableName)) {
163            $tableName = strtolower(get_class($object));
164        }
165
166        //start query
167        $query = "INSERT INTO `{$tableName}` ( ";
168
169        //start collecting column names
170        $comma = false;
171        foreach ($object as $key => $value) {
172            //ignore the primary keys (usually id) if autogenerated
173            if ($autoincrement && in_array($key, $ids)) {
174                continue;
175            }
176
177            //set column names
178            if (isset($value)) { //ok the value is set
179                if (is_null($value)) { //but it's set to null
180                    if ($nullify) { //we will add columns that will have NULL values
181                        if ($comma) {
182                            $query .= ",";
183                        } else {
184                            $comma = true;
185                        }
186                        $query .= "`{$key}`"; #protect the column names in case they are the same as SQL keywords (ex: order)
187                    } else { //we will ignore the columns with null values
188                        //do nothing
189                    }
190                } else { //now, it's not null
191                    if ($comma) {
192                        $query .= ",";
193                    } else {
194                        $comma = true;
195                    }
196                    $query .= "`{$key}`";
197                }
198            } else {
199                //just ignore unset values
200            }
201        }//end collecting column names
202        //start collecting values
203        $query .= ') VALUES (';
204        //TODO: test for cases where there is not need for a value - ex. table with 1 autogenerated column
205        //even if this is kinda stupid :P
206        $comma = false;
207        foreach ($object as $key => $value) {
208
209            //ignore the primary keys (usually id) if autogeneated
210            if ($autoincrement && in_array($key, $ids)) {
211                continue;
212            }
213
214            //add VALUES(....)
215            //right now we skip not set NULL values...but maybe we should reconsider for set to Null values (ex: $o->deadDate = null)
216            if (isset($value)) {
217                if ($comma) {
218                    $query .= ", ";
219                } else {
220                    $comma = true;
221                }
222
223                //based on it's type we quote the value
224                switch (gettype($value)) {
225                    case 'string':
226                        $query .= sprintf("'%s'", addslashes($value));
227                        break;
228                    case 'boolean': //special case as a 'false' value can not be concatenated with a string
229                        $query .= $value ? 'true' : 'false';
230                        break;
231                    case 'NULL' : //if $conditionValue is null the gettype($conditionValue) returns 'NULL'
232                        $query .= 'NULL';
233                        break;
234                    default:
235                        $query .= sprintf("%s", $value);
236                }
237            } else {
238                if ($nullify) { //should we set the unset values to null ?
239                    if ($comma) {
240                        $query .= ", ";
241                    } else {
242                        $comma = true;
243                    }
244                    $query .= " NULL";
245                }
246            }
247        }//end collecting values
248
249
250        $query .= ')';
251
252//        print $query;
253        #exit();
254
255        (DEBUG) ? $_SESSION['logs'][] = "&nbsp;&nbsp;&nbsp;&nbsp;" . __CLASS__ . '{#}' . __FUNCTION__ . "{#}{$query}{#}" . __LINE__ : '';
256        //EXECUTE
257        $result = $this->query($query);
258
259        if ($autoincrement) {//autogenerated ID
260//            print "log: autoincrement used";
261            return $this->lastId();
262        } else { //"by hand" ids
263//            print "log: by hand used";
264            if ($this->changes() > 0) {
265//                print "log: affected";
266                return true;
267            } else {
268//                print "log: not affected";
269                return false;
270            }
271        }
272    }
273
274    /* retuns last inserted Id */
275
276    protected function lastId() {
277        $result = $this->query('SELECT last_insert_rowid() as last_insert_rowid')->fetchArray();
278        return $result['last_insert_rowid'];
279    }
280
281    /*     * Update an entry from an object. We should make wrappers around this function (make it private !?!)
282     *  and never call it directly from outside Delegate
283     *  $tableName - name of the table
284     *  $object - the object
285     *  $ids -  list of ids (default 'id'), usefull for multiple key or keys other then 'id'
286     *  $nullify - if true unset values will be set to NULL, if false we will not touch existing column value
287     *  author: liviu, alex
288     * 
289     *  Note: The update is made based on the object/record id, so the id should not be changed!
290     */
291
292    protected function update($object, $ids = array('id'), $tableName = null, $nullify = false) {
293
294        //detect class name
295        if (empty($tableName)) {
296            $tableName = strtolower(get_class($object));
297        }
298
299        //start query
300        $query = "UPDATE `{$tableName}` SET ";
301
302
303        $comma = false;
304        foreach ($object as $key => $value) {
305
306            //ignore the primary keys (usually id)
307            if (in_array($key, $ids)) {
308                continue;
309            }
310
311            //set values
312//            if(isset($value)) { //pick only set values and ignore not set ones
313            //TODO: here is wrong as $v= null; isset($v) returns False and we can not get inside this branch/scope
314
315            if (is_null($value)) { //the value is null so we have to see what to do with it
316                if ($nullify) { //should we set the unset values to null ?
317                    if ($comma) {
318                        $query .= ", ";
319                    } else {
320                        $comma = true;
321                    }
322                    $query .= "{$key} = NULL ";
323                } else {
324                    //do nothing, we will ignore set & null values
325                }
326            } else { //the value is not null
327                if ($comma) {
328                    $query .= ", ";
329                } else {
330                    $comma = true;
331                }
332
333                //based on it's type we quote the value
334                switch (gettype($value)) {
335                    case 'string':
336                        $query .= sprintf(" `{$key}` = '%s' ", addslashes($value));
337                        break;
338//                    case 'boolean':
339//                        $query .= sprintf(" `{$key}` = %s ", $value ? "true" : "false");
340//                        break;
341                    default:
342                        $query .= sprintf(" `{$key}` = %s ", addslashes($value));
343                        break;
344                }
345            }
346//            } else {
347//                //ignore unset values
348//            }
349        }//end foreach
350        //use the keys
351        $query .= " WHERE "; //'WHERE' should always be present as there should always be an id
352        $comma = false;
353        foreach ($ids as $id) {
354            foreach ($object as $key => $value) {
355//                print "ID: $id -------" . "($key,$value) ----------- " . var_export($object, true) . "<br>";
356                if ($id == $key) { //ok we found a key
357                    if ($comma) {
358                        $query .= " AND ";
359                    } else {
360                        $comma = true;
361                    }
362
363                    switch (gettype($value)) {
364                        case 'string':
365                            $query .= sprintf(" {$key} = '%s' ", addslashes($value));
366                            break;
367                        default: //we place together integers, booleans and aliens
368                            $query .= sprintf(" {$key} = %s ", addslashes($value));
369                            break;
370                    }
371                }
372            }
373        } //end foreach
374//        print $query;
375//        exit();
376
377        (DEBUG) ? $_SESSION['logs'][] = "&nbsp;&nbsp;&nbsp;&nbsp;" . __CLASS__ . '{#}' . __FUNCTION__ . "{#}{$query}{#}" . __LINE__ : '';
378
379        /* EXECUTE
380         * @see http://www.php.net/manual/en/sqlite3.query.php
381         */
382        return $this->query($query);
383    }
384
385    /**
386     * Get a number of object from the database
387     * $tableName - table name
388     * $conditions - AND like conditions ex: array('name'=>'alex', 'age'=>'31')
389     * $orders - ORDER BY part ex: array('name'=>'ASC', 'age'=>'DESC')
390     * $start - start offset
391     * $nr - number of rows returned
392     * author: alex
393     */
394    protected function getMultiple($tableName, $conditions = null, $orders = null, $start = null, $nr = null) {
395        $objects = array(); //this will contain all the found objects
396
397        $tableName = strtolower($tableName);
398
399        //start query building
400        $query = sprintf("SELECT * FROM `%s`", $tableName);
401
402        //conditions
403        if (count($conditions) > 0) {
404            $query .= " WHERE ";
405            $and = false;
406            foreach ($conditions as $conditionName => $conditionValue) {
407                if ($and) {
408                    $query .= " AND ";
409                } else {
410                    $and = true;
411                }
412
413                //based on it's type we quote the value
414                switch (gettype($conditionValue)) {
415                    case 'string':
416                        $query .= sprintf(" `%s` = '%s'", $conditionName, addslashes($conditionValue));
417                        break;
418                    case 'boolean': //special case as a 'false' value can not be concatenated with a string
419                        $query .= sprintf(" `%s` = %s", $conditionName, $conditionValue ? 'true' : 'false');
420                        break;
421                    case 'NULL' : //if $conditionValue is null the gettype($conditionValue) returns 'NULL'
422                        $query .= sprintf(" `%s` IS NULL", $conditionName);
423                        break;
424                    default:
425                        $query .= sprintf(" `%s` = %s", $conditionName, $conditionValue);
426                }
427            }
428        }
429
430
431        //add orders
432        if (count($orders) > 0) {
433            $query .= " ORDER BY ";
434            $comma = false;
435            foreach ($orders as $order => $direction) {
436                if ($comma) {
437                    $query .= sprintf(", `%s`  %s ", $order, $direction);
438                } else {
439                    $query .= sprintf(" `%s`  %s", $order, $direction);
440                    $comma = true;
441                }
442            }
443        }
444
445
446        if (!is_null($start)) {
447            $query .= sprintf(" LIMIT %d", $start);
448        }
449
450        if (!is_null($nr)) {
451            $query .= sprintf(", %d", $nr);
452        }
453
454        #print $query;
455        #exit();
456        (DEBUG) ? $_SESSION['logs'][] = "&nbsp;&nbsp;&nbsp;&nbsp;" . __CLASS__ . '{#}' . __FUNCTION__ . "{#}{$query}{#}" . __LINE__ : '';
457
458        //EXECUTE query
459        $result = $this->query($query);
460        $className = ucfirst($tableName);
461        while ($row = $result->fetchArray()) {
462            $object = new $className;
463            $object->loadFromSQL($row);
464            $objects[] = $object;
465        }
466
467
468
469        return $objects;
470    }
471
472    /*     * Return single */
473
474    protected function getSingle($tableName, $conditions = null) {
475        $foundedObjects = $this->getMultiple($tableName, $conditions);
476        if (isset($foundedObjects) && count($foundedObjects) > 0) {
477            return $foundedObjects[0];
478        }
479
480        return;
481    }
482
483    /*     * Return single */
484
485    protected function getCount($tableName, $conditions = null) {
486        $foundedObjects = $this->getMultiple($tableName, $conditions);
487        return count($foundedObjects);
488    }
489
490    /*     * Remove all entries from a table that met conditions
491     * param: $conditions (an array of $key=>$value)
492     * Returns true if data was deleted, false otherwise
493     *
494     * Ex: delete('user', array('id'=>1)) //delete the user with id 1
495     * Ex2: delete('user') //delete ALL users
496     */
497
498    protected function delete($tableName, $conditions = null) {
499        $tableName = strtolower($tableName);
500
501        //start query building
502        $query = sprintf("DELETE FROM `%s`", $tableName);
503
504        //conditions
505        if (count($conditions) > 0) {
506            $query .= " WHERE ";
507            $and = false;
508            foreach ($conditions as $conditionName => $conditionValue) {
509                if ($and) {
510                    $query .= " AND ";
511                } else {
512                    $and = true;
513                }
514
515                //based on it's type we quote the value
516                switch (gettype($conditionValue)) {
517                    case 'string':
518                        $query .= sprintf(" %s = '%s'", $conditionName, addslashes($conditionValue));
519                        break;
520                    case 'boolean': //special case as a 'false' value can not be concatenated with a string
521                        $query .= sprintf(" %s = %s", $conditionName, $conditionValue ? 'true' : 'false');
522                        break;
523                    default:
524                        $query .= sprintf(" %s = %s", $conditionName, $conditionValue);
525                }
526            }
527        }
528
529
530//        print $query;
531//        exit();
532        (DEBUG) ? $_SESSION['logs'][] = "&nbsp;&nbsp;&nbsp;&nbsp;" . __CLASS__ . '{#}' . __FUNCTION__ . "{#}{$query}{#}" . __LINE__ : '';
533
534        $this->query($query);
535
536        /*
537         * @see: http://stackoverflow.com/questions/313567/how-can-i-determine-the-number-of-affected-rows-in-a-sqlite-2-query-in-php
538         */
539        if ($this->changes() > 0) {
540            return true;
541        } else {
542            return false;
543        }
544    }
545
546    /************************************************************************* */
547    /************************************************************************* */
548    /************************************************************************* */
549    public function userGetByEmailAndPassword($email,$password) {
550        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
551        return $this->getSingle('user', array('email'=>$email, 'password'=>md5($password) ));
552    }
553    
554    public function userGetByEmailAndCryptedPassword($email,$cryptedPassword) {
555        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
556        return $this->getSingle('user', array('email'=>$email, 'password'=>$cryptedPassword ));
557    }
558    
559    public function userGetById($userId) {
560        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
561        return $this->getSingle('user', array('id'=>$userId));
562    }
563    
564    public function userGetAll() {
565        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
566        return $this->getMultiple('user', null, array('email' => 'ASC'));
567    }
568    
569    
570
571    
572    /************************************************************************* */
573    /************************************************************************* */
574    /************************************************************************* */
575    public function diagramGetAll() {
576        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ . '{#}' . __FUNCTION__ . "{#}{#}" . __LINE__ : '';
577        return $this->getMultiple('diagram', null, array('title' => 'DESC'));
578    }
579
580    public function diagramCreate($entry) {
581        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ . '{#}' . __FUNCTION__ . "{#}{#}" . __LINE__ : '';
582        return $this->create($entry);
583    }
584    
585    public function diagramGetById($diagramId) {
586        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
587        return $this->getSingle('diagram', array('id'=>$diagramId));
588    }
589    
590    public function diagramDeleteById($diagramId) {
591        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
592        return $this->delete('diagram', array('id'=>$diagramId));
593    }
594    
595    public function diagramUpdate($diagram) {
596        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
597        return $this->update($diagram);
598    }
599    
600        /**This create a cascade delete to diagramdata*/
601    public function diagramDelete($diagramId){
602        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
603        return $this->delete('diagram', array('id'=>$diagramId));
604    }
605    
606    /**************************************************************************/
607    /*********************************SETTINGS*********************************/
608    /**************************************************************************/
609    public function settingsGetByKeyNative($key){
610        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
611        
612
613        $query = sprintf("select `value` from `setting` where `name` = '%s' ",$key);
614
615        (DEBUG) ? $_SESSION['logs'][] = "&nbsp;&nbsp;&nbsp;&nbsp;" . __CLASS__ .'{#}'. __FUNCTION__ ."{#}{$query}{#}". __LINE__ : '';
616
617        $value = '';
618
619        //EXECUTE query
620        $result = $this->query($query);
621        if( $row = $result->fetchArray() ){
622            $value = $row['value'];
623        }
624                
625
626        return $value;
627    }
628    
629    
630    public function settingsSaveNative($key, $value){
631        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
632        
633        //see http://stackoverflow.com/questions/418898/sqlite-upsert-not-insert-or-replace
634        $query = sprintf("insert or REPLACE  into `setting` (`value`,`name`) VALUES('%s', '%s')", $value, $key);
635        
636        $this->query($query);
637        
638        if($this->changes() > 0) {
639            return true;
640        } else {
641            return false;
642        }
643    }
644    
645    
646    /**************************************************************************/
647    /*********************************USER*************************************/
648    /**************************************************************************/
649    public function userCreate($user) {
650        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
651        return $this->create($user);
652    }
653    
654    public function userDeleteById($id) {
655        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
656        return $this->delete('user', array('id' => $id));
657    }
658    
659    
660    public function userUpdate($user) {
661        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
662        return $this->update($user);
663    }
664    
665    
666    /**************************************************************************/
667    /*****************************DIAGRAMDATA**********************************/
668    /**************************************************************************/
669    public function diagramdataCreate($entry) {
670        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
671        //$object, $ids = array('id'), $tableName=null,  $nullify=false, $autoincrement=true) {
672        return $this->create($entry, array('diagramId', 'type'), 'diagramdata', false, false);
673    }
674
675    public function diagramdataGetByDiagramIdAndType($diagramId, $type) {
676        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
677        return $this->getSingle('diagramdata', array('diagramId'=>$diagramId, 'type'=>$type));
678    }
679    
680    public function diagramdataUpdate($diagramdata) {
681        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
682        return $this->update($diagramdata, array('diagramId', 'type'), 'diagramdata'); //do not update the key
683    }
684    
685    public function diagramdataGetByDiagramId($diagramId) {
686        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
687        return $this->getMultiple('diagramdata', array('diagramId'=>$diagramId));
688    }
689    
690    /**This create a cascade delete to diagramdata*/
691    public function diagramdataDeleteByDiagramIdAndType($diagramId, $type){
692        (DEBUG) ? $_SESSION['logs'][] = __CLASS__ .'{#}'. __FUNCTION__ ."{#}{#}". __LINE__ : '';
693        return $this->delete('diagramdata', array('diagramId'=>$diagramId, 'type'=>$type));
694    }
695        
696}
697
698function diagramCreate($dbhandle, $title, $description, $public) {
699    $stm1 = sprintf("INSERT INTO diagram (title, description, public, createdDate, lastUpdate) 
700        VALUES('%s', '%s', '%s', '%s', '%s')", $title, $description, $public, gmdate('Y-m-d H:i:s'), gmdate('Y-m-d H:i:s'));
701    #print($stm1);
702    $ok1 = sqlite_exec($dbhandle, $stm1);
703    if (!$ok1)
704        die("Cannot execute statement.");
705}
706
707function diagramGetById($dbhandle, $diagramId) {
708    $d = false;
709    $query = sprintf("SELECT * FROM diagram where id=%d", $diagramId);
710    $result = sqlite_query($dbhandle, $query);
711    if ($result) {
712        $row = sqlite_fetch_array($result, SQLITE_ASSOC);
713        if ($row) {
714            $d = new Diagram();
715            $d->loadFromSQL($row);
716        }
717    }
718
719    return $d;
720}
721
722function diagramGetAll2($dbhandle) {
723    $diagrams = array();
724    $query = "SELECT * FROM diagram ORDER BY title";
725    $results = $this->query($query);
726    if ($results) {
727        while ($row = $results->fetchArray()) {
728            #print_r($row);
729            $d = new Diagram();
730            $d->loadFromSQL($row);
731            $diagrams[] = $d;
732        }
733    }
734
735    return $diagrams;
736}
737
738function diagramDeleteById($dbhandle, $diagramId) {
739    $query = sprintf("delete FROM diagram where id=%d", $diagramId);
740    $result = sqlite_query($dbhandle, $query);
741    if ($result) {
742        
743    }
744}
745
746if(false && PHP_SAPI == 'cli'){ //see http://php.net/manual/en/features.commandline.php
747    print("\nOn the console");
748
749    //test
750    $d = new Delegate();
751    $diagrams = $d->diagramGetAll();
752    print_r($diagrams);
753
754    $diagram = new Diagram();
755    $diagram->title = 'Ana are mere';
756    $diagram->description = 'Ana are foarte multe mere';
757    $diagram->public = 0;
758    $diagram->createdDate = gmdate('Y-m-d h:i:s');
759    $diagram->lastUpdate = gmdate('Y-m-d h:i:s');
760
761    $dId = $d->diagramCreate($diagram);
762    print("Diagram Id: " + $dId);
763
764    $nd = $d->diagramGetById($dId);
765    $nd->title = 'Zzoz';
766    $d->diagramUpdate($nd);
767
768    $d->close();
769}
770?>