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