xref: /plugin/sqlite/helper.php (revision ff97cc8f18504c1569934b2286f6ffefc6d89df4)
1<?php
2/**
3 * DokuWiki Plugin sqlite (Helper Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr <gohr@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) die();
11
12if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
13if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
14if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
15
16if (!defined('DOKU_EXT_SQLITE')) define('DOKU_EXT_SQLITE', 'sqlite');
17if (!defined('DOKU_EXT_PDO')) define('DOKU_EXT_PDO', 'pdo');
18
19
20class helper_plugin_sqlite extends DokuWiki_Plugin {
21    var $db     = null;
22    var $dbname = '';
23    var $extension = false;
24    function getInfo() {
25        return confToHash(dirname(__FILE__).'plugin.info.txt');
26    }
27
28    /**
29     * constructor
30     */
31    function helper_plugin_sqlite(){
32
33      if(!$this->extension)
34      {
35        if (!extension_loaded('sqlite')) {
36            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
37            if(function_exists('dl')) @dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
38        }
39
40        if(function_exists('sqlite_open')){
41           $this->extension = DOKU_EXT_SQLITE;
42        }
43      }
44
45      if(!$this->extension)
46      {
47        if (!extension_loaded('pdo_sqlite')) {
48            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
49            if(function_exists('dl')) @dl($prefix . 'pdo_sqlite.' . PHP_SHLIB_SUFFIX);
50        }
51
52        if(class_exists('pdo')){
53            $this->extension = DOKU_EXT_PDO;
54        }
55      }
56
57      if(!$this->extension)
58      {
59        msg('SQLite & PDO SQLite support missing in this PHP install - plugin will not work',-1);
60      }
61    }
62
63    /**
64     * Initializes and opens the database
65     *
66     * Needs to be called right after loading this helper plugin
67     */
68    function init($dbname,$updatedir){
69        global $conf;
70
71        // check for already open DB
72        if($this->db){
73            if($this->dbname == $dbname){
74                // db already open
75                return true;
76            }
77            // close other db
78            if($this->extension == DOKU_EXT_SQLITE)
79            {
80              sqlite_close($this->db);
81            }
82            else
83            {
84              $this->db->close();
85            }
86            $this->db     = null;
87            $this->dbname = '';
88        }
89
90        $this->dbname = $dbname;
91
92        $fileextension = '.sqlite';
93        if($this->extension == DOKU_EXT_PDO)
94        {
95          $fileextension = '.sqlite3';
96        }
97
98        $this->dbfile = $conf['metadir'].'/'.$dbname.$fileextension;
99
100        $init   = (!@file_exists($this->dbfile) || ((int) @filesize($this->dbfile)) < 3);
101
102        if($this->extension == DOKU_EXT_SQLITE)
103        {
104          $error='';
105          $this->db = sqlite_open($this->dbfile, 0666, $error);
106          if(!$this->db){
107              msg("SQLite: failed to open SQLite ".$this->dbname." database ($error)",-1);
108              return false;
109          }
110
111          // register our custom aggregate function
112          sqlite_create_aggregate($this->db,'group_concat',
113                                  array($this,'_sqlite_group_concat_step'),
114                                  array($this,'_sqlite_group_concat_finalize'), 2);
115        }
116        else
117        {
118          $dsn = 'sqlite:'.$this->dbfile;
119
120          try {
121              $this->db = new PDO($dsn);
122          } catch (PDOException $e) {
123            msg("SQLite: failed to open SQLite ".$this->dbname." database (".$e->getMessage().")",-1);
124              return false;
125          }
126          $this->db->sqliteCreateAggregate('group_concat',
127                                  array($this,'_pdo_group_concat_step'),
128                                  array($this,'_pdo_group_concat_finalize'));
129        }
130
131        $this->_updatedb($init,$updatedir);
132        return true;
133    }
134
135    /**
136     * Return the current Database Version
137     */
138    function _currentDBversion(){
139        $sql = "SELECT val FROM opts WHERE opt = 'dbversion';";
140        $res = $this->query($sql);
141        if(!$res) return false;
142        $row = $this->res2row($res,0);
143        return (int) $row['val'];
144    }
145    /**
146     * Update the database if needed
147     *
148     * @param bool   $init      - true if this is a new database to initialize
149     * @param string $updatedir - Database update infos
150     */
151    function _updatedb($init,$updatedir){
152        if($init){
153            $current = 0;
154        }else{
155            $current = $this->_currentDBversion();
156            if(!$current){
157                msg('SQLite: no DB version found. '.$this->dbname.' DB probably broken.',-1);
158                return false;
159            }
160        }
161
162        // in case of init, add versioning table
163        if($init){
164            if(!$this->_runupdatefile(dirname(__FILE__).'/db.sql',0)){
165                if($this->extension == DOKU_EXT_SQLITE)
166                {
167                  msg('SQLite: '.$this->dbname.' database upgrade failed for version ', -1);
168                }
169                return false;
170            }
171        }
172
173        $latest  = (int) trim(io_readFile($updatedir.'/latest.version'));
174
175        // all up to date?
176        if($current >= $latest) return true;
177        for($i=$current+1; $i<=$latest; $i++){
178            $file = sprintf($updatedir.'/update%04d.sql',$i);
179            if(file_exists($file)){
180                if(!$this->_runupdatefile($file,$i)){
181                    msg('SQLite: '.$this->dbname.' database upgrade failed for version '.$i, -1);
182
183
184                    return false;
185                }
186            }
187        }
188        return true;
189    }
190
191    /**
192     * Updates the database structure using the given file to
193     * the given version.
194     */
195    function _runupdatefile($file,$version){
196        $sql  = io_readFile($file,false);
197
198        $sql = explode(";",$sql);
199        array_unshift($sql,'BEGIN TRANSACTION');
200        array_push($sql,"INSERT OR REPLACE INTO opts (val,opt) VALUES ($version,'dbversion')");
201        array_push($sql,"COMMIT TRANSACTION");
202
203        foreach($sql as $s){
204            $s = preg_replace('!^\s*--.*$!m', '', $s);
205            $s = trim($s);
206            if(!$s) continue;
207
208
209            $res = $this->query("$s;");
210            if ($res === false) {
211              if($this->extension == DOKU_EXT_SQLITE)
212              {
213                sqlite_query($this->db, 'ROLLBACK TRANSACTION');
214                return false;
215              }
216            }
217        }
218
219        return ($version == $this->_currentDBversion());
220    }
221
222    /**
223     * Emulate ALTER TABLE
224     *
225     * The ALTER TABLE syntax is parsed and then emulated using a
226     * temporary table
227     *
228     * @author <jon@jenseng.com>
229     * @link   http://code.jenseng.com/db/
230     * @author Andreas Gohr <gohr@cosmocode.de>
231     */
232    function _altertable($table,$alterdefs){
233
234        // load original table definition SQL
235        $result = $this->query("SELECT sql,name,type
236                                  FROM sqlite_master
237                                 WHERE tbl_name = '$table'
238                                   AND type = 'table'");
239
240        if(($result === false) || ($this->extension == DOKU_EXT_SQLITE && sqlite_num_rows($result)<=0)){
241            msg("ALTER TABLE failed, no such table '".hsc($table)."'",-1);
242            return false;
243        }
244
245        if($this->extension == DOKU_EXT_SQLITE )
246        {
247          $row = sqlite_fetch_array($result);
248        }
249        else
250        {
251           $row = $result->fetch(PDO::FETCH_ASSOC);
252        }
253
254        if($row === false){
255            msg("ALTER TABLE failed, table '".hsc($table)."' had no master data",-1);
256            return false;
257        }
258
259
260        // prepare temporary table SQL
261        $tmpname = 't'.time();
262        $origsql = trim(preg_replace("/[\s]+/"," ",
263                        str_replace(",",", ",
264                        preg_replace('/\)$/',' )',
265                        preg_replace("/[\(]/","( ",$row['sql'],1)))));
266        $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
267        $createindexsql = array();
268
269        // load indexes to reapply later
270        $result = $this->query("SELECT sql,name,type
271                                  FROM sqlite_master
272                                 WHERE tbl_name = '$table'
273                                   AND type = 'index'");
274        if(!$result){
275            $indexes = array();
276        }else{
277            $indexes = $this->res2arr($result);
278        }
279
280
281        $i = 0;
282        $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
283        $prevword = $table;
284        $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
285        $newcols = array();
286
287        for($i=0;$i<count($oldcols);$i++){
288            $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
289            $oldcols[$i] = $colparts[0];
290            $newcols[$colparts[0]] = $colparts[0];
291        }
292        $newcolumns = '';
293        $oldcolumns = '';
294        reset($newcols);
295        while(list($key,$val) = each($newcols)){
296            $newcolumns .= ($newcolumns?', ':'').$val;
297            $oldcolumns .= ($oldcolumns?', ':'').$key;
298        }
299        $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
300        $dropoldsql = 'DROP TABLE '.$table;
301        $createtesttableSQL = $createtemptableSQL;
302
303        foreach($defs as $def){
304            $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
305            $action = strtolower($defparts[0]);
306            switch($action){
307                case 'add':
308                    if(count($defparts) < 2){
309                        msg('ALTER TABLE: not enough arguments for ADD statement',-1);
310                        return false;
311                    }
312                    $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
313                    for($i=1;$i<count($defparts);$i++)
314                        $createtesttableSQL.=' '.$defparts[$i];
315                    $createtesttableSQL.=')';
316                    break;
317
318                case 'change':
319                    if(count($defparts) <= 3){
320                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error',-1);
321                        return false;
322                    }
323
324                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
325                        if($newcols[$defparts[1]] != $defparts[1]){
326                            msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
327                            return false;
328                        }
329                        $newcols[$defparts[1]] = $defparts[2];
330                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
331                        $insertval = '';
332                        for($i=2;$i<count($defparts);$i++)
333                            $insertval.=' '.$defparts[$i];
334                        if($nextcommapos)
335                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
336                        else
337                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
338                    } else {
339                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
340                        return false;
341                    }
342                    break;
343                case 'drop':
344                    if(count($defparts) < 2){
345                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error',-1);
346                        return false;
347                    }
348                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
349                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
350                        if($nextcommapos)
351                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
352                        else
353                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
354                        unset($newcols[$defparts[1]]);
355                    }else{
356                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
357                        return false;
358                    }
359                    break;
360                default:
361                    msg('ALTER TABLE: near "'.$prevword.'": syntax error',-1);
362                    return false;
363            }
364            $prevword = $defparts[count($defparts)-1];
365        }
366
367        // this block of code generates a test table simply to verify that the
368        // columns specifed are valid in an sql statement
369        // this ensures that no reserved words are used as columns, for example
370        $res = $this->query($createtesttableSQL);
371        if($res === false) return false;
372
373        $droptempsql = 'DROP TABLE '.$tmpname;
374        $res = $this->query($droptempsql);
375        if($res === false) return false;
376
377
378        $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
379        $newcolumns = '';
380        $oldcolumns = '';
381        reset($newcols);
382        while(list($key,$val) = each($newcols)){
383            $newcolumns .= ($newcolumns?', ':'').$val;
384            $oldcolumns .= ($oldcolumns?', ':'').$key;
385        }
386
387        $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
388
389        $res = $this->query($createtemptableSQL); //create temp table
390        if($res === false) return false;
391        $res = $this->query($copytotempsql); //copy to table
392        if($res === false) return false;
393        $res = $this->query($dropoldsql); //drop old table
394        if($res === false) return false;
395
396        $res = $this->query($createnewtableSQL); //recreate original table
397        if($res === false) return false;
398        $res = $this->query($copytonewsql); //copy back to original table
399        if($res === false) return false;
400
401        foreach($indexes as $index){ // readd indexes
402            $res = $this->query($index['sql']);
403            if($res === false) return false;
404        }
405
406        $res = $this->query($droptempsql); //drop temp table
407        if($res === false) return false;
408
409        return $res; // return a valid resource
410    }
411
412    /**
413     * Execute a query with the given parameters.
414     *
415     * Takes care of escaping
416     *
417     * @param string $sql - the statement
418     * @param arguments...
419     */
420    function query(){
421        if(!$this->db) return false;
422
423        // get function arguments
424        $args = func_get_args();
425        $sql  = trim(array_shift($args));
426        $sql  = rtrim($sql,';');
427
428        if(!$sql){
429            msg('No SQL statement given',-1);
430            return false;
431        }
432
433        $argc = count($args);
434        if($argc > 0 && is_array($args[0])) {
435            $args = $args[0];
436            $argc = count($args);
437        }
438
439        // check number of arguments
440        if($argc < substr_count($sql,'?')){
441            msg('Not enough arguments passed for statement. '.
442                'Expected '.substr_count($sql,'?').' got '.
443                $argc.' - '.hsc($sql),-1);
444            return false;
445        }
446
447        // explode at wildcard, then join again
448        $parts = explode('?',$sql,$argc+1);
449        $args  = array_map(array($this,'quote_string'),$args);
450        $sql   = '';
451
452        while( ($part = array_shift($parts)) !== null ){
453            $sql .= $part;
454            $sql .= array_shift($args);
455        }
456
457        // intercept ALTER TABLE statements
458        $match = null;
459        if(preg_match('/^ALTER\s+TABLE\s+([\w\.]+)\s+(.*)/i',$sql,$match)){
460            return $this->_altertable($match[1],$match[2]);
461        }
462
463        // execute query
464        $err = '';
465        if($this->extension == DOKU_EXT_SQLITE )
466        {
467          $res = @sqlite_query($this->db,$sql,SQLITE_ASSOC,$err);
468          if($err){
469              msg($err.':<br /><pre>'.hsc($sql).'</pre>',-1);
470              return false;
471          }elseif(!$res){
472              msg(sqlite_error_string(sqlite_last_error($this->db)).
473                  ':<br /><pre>'.hsc($sql).'</pre>',-1);
474              return false;
475          }
476        }
477        else
478        {
479          $result = false;
480
481          $res = $this->db->query($sql);
482
483          if(!$res){
484            $err = $this->db->errorInfo();
485              msg($err[2].':<br /><pre>'.hsc($sql).'</pre>',-1);
486              return false;
487          }
488        }
489        return $res;
490    }
491
492    /**
493     * Returns a complete result set as array
494     */
495    function res2arr($res){
496        $data = array();
497        if($this->extension == DOKU_EXT_SQLITE )
498        {
499          if(!sqlite_num_rows($res)) return $data;
500          sqlite_rewind($res);
501          while(($row = sqlite_fetch_array($res)) !== false){
502              $data[] = $row;
503          }
504        }
505        else
506        {
507          $data = $res->fetchAll(PDO::FETCH_ASSOC);
508          if(!count(data))
509          {
510            return false;
511          }
512        }
513        return $data;
514    }
515
516    /**
517     * Return the wanted row from a given result set as
518     * associative array
519     */
520    function res2row($res,$rownum=0){
521        if($this->extension == DOKU_EXT_SQLITE )
522        {
523          if(!@sqlite_seek($res,$rownum)){
524              return false;
525          }
526          return sqlite_fetch_array($res);
527        }
528        else
529        {
530          //very dirty replication of the same functionality (really must look at cursors)
531          $data = array();
532          //do we need to rewind?
533          $data = $res->fetchAll(PDO::FETCH_ASSOC);
534          if(!count(data))
535          {
536            return false;
537          }
538
539          if(!isset($data[$rownum]))
540          {
541            return false;
542          }
543          else
544          {
545            return $data[$rownum];
546          }
547        }
548    }
549
550    /**
551     * Return the first value from the first row.
552     */
553    function res2single($res)
554    {
555      if($this->extension == DOKU_EXT_SQLITE )
556      {
557        return sqlite_fetch_single($res);
558      }
559      else
560      {
561        $data = $res->fetchAll(PDO::FETCH_NUM);
562        if(!count(data))
563        {
564          return false;
565        }
566        return $data[0][0];
567      }
568    }
569
570    /**
571     * Join the given values and quote them for SQL insertion
572     */
573    function quote_and_join($vals,$sep=',') {
574        $vals = array_map(array('helper_plugin_sqlite','quote_string'),$vals);
575        return join($sep,$vals);
576    }
577
578    /**
579     * Run sqlite_escape_string() on the given string and surround it
580     * with quotes
581     */
582    function quote_string($string){
583      if($this->extension == DOKU_EXT_SQLITE )
584      {
585        return "'".sqlite_escape_string($string)."'";
586      }
587      else
588      {
589        return $this->db->quote($string);
590      }
591    }
592
593
594    /**
595     * Escape string for sql
596     */
597    function escape_string($str)
598    {
599      if($this->extension == DOKU_EXT_SQLITE )
600      {
601        return sqlite_escape_string($str);
602      }
603      else
604      {
605        return trim($this->db->quote($str), "'");
606      }
607    }
608
609
610
611    /**
612    * Aggregation function for SQLite
613    *
614    * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
615    */
616    function _sqlite_group_concat_step(&$context, $string, $separator = ',') {
617         $context['sep'] = $separator;
618         $context['data'][] = $string;
619    }
620
621    /**
622    * Aggregation function for SQLite
623    *
624    * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
625    */
626    function _sqlite_group_concat_finalize(&$context) {
627         $context['data'] = array_unique($context['data']);
628         return join($context['sep'],$context['data']);
629    }
630
631
632    /**
633     * Aggregation function for SQLite via PDO
634     *
635     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
636     */
637    function _pdo_group_concat_step(&$context, $rownumber, $string, $separator = ',') {
638         if(is_null($context))
639         {
640           $context = array(
641             'sep'  => $separator,
642             'data' => array()
643             );
644         }
645
646         $context['data'][] = $string;
647         return $context;
648    }
649
650     /**
651     * Aggregation function for SQLite via PDO
652     *
653     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
654     */
655    function _pdo_group_concat_finalize(&$context, $rownumber)
656    {
657        if(!is_array($context))
658        {
659          return null;
660        }
661        $context['data'] = array_unique($context['data']);
662        return join($context['sep'],$context['data']);
663    }
664
665    /**
666     * Keep separate instances for every call to keep database connections
667     */
668    function isSingleton() {
669         return false;
670    }
671
672     /**
673     * fetch the next row as zero indexed array
674     */
675    function res_fetch_array($res)
676    {
677      if($this->extension == DOKU_EXT_SQLITE )
678      {
679        return sqlite_fetch_array($res, SQLITE_NUM);
680      }
681      else
682      {
683        return $res->fetch(PDO::FETCH_NUM);
684      }
685    }
686
687
688    /**
689     * fetch the next row as assocative array
690     */
691    function res_fetch_assoc($res)
692    {
693      if($this->extension == DOKU_EXT_SQLITE )
694      {
695        return sqlite_fetch_array($res, SQLITE_ASSOC);
696      }
697      else
698      {
699       return $res->fetch(PDO::FETCH_ASSOC);
700      }
701    }
702
703
704    /**
705    * Count the number of records in rsult
706    */
707    function res2count($res) {
708      if($this->extension == DOKU_EXT_SQLITE )
709      {
710        return sqlite_num_rows($res);
711      }
712      else
713      {
714        $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
715        if (preg_match($regex, $res->queryString, $output) > 0) {
716            $stmt = $this->db->query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);
717
718            return $stmt->fetchColumn();
719        }
720
721        return false;
722      }
723    }
724
725
726    /**
727    * Count the number of records changed last time
728    */
729    function countChanges($db, $res)
730    {
731      if($this->extension == DOKU_EXT_SQLITE )
732      {
733        return sqlite_changes($db);
734      }
735      else
736      {
737        return $res->rowCount();
738      }
739    }
740}
741
742// vim:ts=4:sw=4:et:enc=utf-8:
743