xref: /plugin/sqlite/helper.php (revision 665af209c806ba4aed49d020a8a318fde94d28be)
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
16a1e6784eSAndreas Gohrclass helper_plugin_sqlite extends DokuWiki_Plugin {
17a1e6784eSAndreas Gohr    var $db     = null;
18a1e6784eSAndreas Gohr    var $dbname = '';
19a1e6784eSAndreas Gohr
20a1e6784eSAndreas Gohr    function getInfo() {
21a1e6784eSAndreas Gohr        return confToHash(dirname(__FILE__).'plugin.info.txt');
22a1e6784eSAndreas Gohr    }
23a1e6784eSAndreas Gohr
24a1e6784eSAndreas Gohr    /**
25a1e6784eSAndreas Gohr     * constructor
26a1e6784eSAndreas Gohr     */
27a1e6784eSAndreas Gohr    function helper_plugin_sqlite(){
28a1e6784eSAndreas Gohr        if (!extension_loaded('sqlite')) {
29a1e6784eSAndreas Gohr            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
30a1e6784eSAndreas Gohr            if(function_exists('dl')) @dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
31a1e6784eSAndreas Gohr        }
32a1e6784eSAndreas Gohr
33a1e6784eSAndreas Gohr        if(!function_exists('sqlite_open')){
34a1e6784eSAndreas Gohr            msg('SQLite support missing in this PHP install - plugin will not work',-1);
35a1e6784eSAndreas Gohr        }
36a1e6784eSAndreas Gohr    }
37a1e6784eSAndreas Gohr
38a1e6784eSAndreas Gohr    /**
39a1e6784eSAndreas Gohr     * Initializes and opens the database
40a1e6784eSAndreas Gohr     *
41a1e6784eSAndreas Gohr     * Needs to be called right after loading this helper plugin
42a1e6784eSAndreas Gohr     */
43a1e6784eSAndreas Gohr    function init($dbname,$updatedir){
44a1e6784eSAndreas Gohr        global $conf;
45a1e6784eSAndreas Gohr
46a1e6784eSAndreas Gohr        // check for already open DB
47a1e6784eSAndreas Gohr        if($this->db){
48a1e6784eSAndreas Gohr            if($this->dbname == $dbname){
49a1e6784eSAndreas Gohr                // db already open
50a1e6784eSAndreas Gohr                return true;
51a1e6784eSAndreas Gohr            }
52a1e6784eSAndreas Gohr            // close other db
53a1e6784eSAndreas Gohr            sqlite_close($this->db);
54a1e6784eSAndreas Gohr            $this->db     = null;
55a1e6784eSAndreas Gohr            $this->dbname = '';
56a1e6784eSAndreas Gohr        }
57a1e6784eSAndreas Gohr
58a1e6784eSAndreas Gohr        $this->dbname = $dbname;
59a1e6784eSAndreas Gohr        $dbfile = $conf['metadir'].'/'.$dbname.'.sqlite';
60a1e6784eSAndreas Gohr        $init   = (!@file_exists($dbfile) || ((int) @filesize($dbfile)) < 3);
61a1e6784eSAndreas Gohr
62a1e6784eSAndreas Gohr        $error='';
63a1e6784eSAndreas Gohr        $this->db = sqlite_open($dbfile, 0666, $error);
64a1e6784eSAndreas Gohr        if(!$this->db){
65a1e6784eSAndreas Gohr            msg("SQLite: failed to open SQLite ".$this->dbname." database ($error)",-1);
66a1e6784eSAndreas Gohr            return false;
67a1e6784eSAndreas Gohr        }
68a1e6784eSAndreas Gohr
69b5b947d7SAndreas Gohr        // register our custom aggregate function
70b5b947d7SAndreas Gohr        sqlite_create_aggregate($this->db,'group_concat',
71b5b947d7SAndreas Gohr                                array($this,'_sqlite_group_concat_step'),
72b5b947d7SAndreas Gohr                                array($this,'_sqlite_group_concat_finalize'), 2);
73b5b947d7SAndreas Gohr
74a1e6784eSAndreas Gohr        $this->_updatedb($init,$updatedir);
75a1e6784eSAndreas Gohr        return true;
76a1e6784eSAndreas Gohr    }
77a1e6784eSAndreas Gohr
78a1e6784eSAndreas Gohr    /**
79a1e6784eSAndreas Gohr     * Return the current Database Version
80a1e6784eSAndreas Gohr     */
81a1e6784eSAndreas Gohr    function _currentDBversion(){
82a1e6784eSAndreas Gohr        $sql = "SELECT val FROM opts WHERE opt = 'dbversion';";
83a1e6784eSAndreas Gohr        $res = $this->query($sql);
84a1e6784eSAndreas Gohr        if(!$res) return false;
85a1e6784eSAndreas Gohr        $row = $this->res2row($res,0);
86a1e6784eSAndreas Gohr        return (int) $row['val'];
87a1e6784eSAndreas Gohr    }
88a1e6784eSAndreas Gohr    /**
89a1e6784eSAndreas Gohr     * Update the database if needed
90a1e6784eSAndreas Gohr     *
91a1e6784eSAndreas Gohr     * @param bool   $init      - true if this is a new database to initialize
92a1e6784eSAndreas Gohr     * @param string $updatedir - Database update infos
93a1e6784eSAndreas Gohr     */
94a1e6784eSAndreas Gohr    function _updatedb($init,$updatedir){
95a1e6784eSAndreas Gohr        if($init){
96a1e6784eSAndreas Gohr            $current = 0;
97a1e6784eSAndreas Gohr        }else{
98a1e6784eSAndreas Gohr            $current = $this->_currentDBversion();
99a1e6784eSAndreas Gohr            if(!$current){
100a1e6784eSAndreas Gohr                msg('SQLite: no DB version found. '.$this->dbname.' DB probably broken.',-1);
101a1e6784eSAndreas Gohr                return false;
102a1e6784eSAndreas Gohr            }
103a1e6784eSAndreas Gohr        }
104a1e6784eSAndreas Gohr
105a1e6784eSAndreas Gohr        // in case of init, add versioning table
106a1e6784eSAndreas Gohr        if($init){
107a1e6784eSAndreas Gohr            if(!$this->_runupdatefile(dirname(__FILE__).'/db.sql',0)){
108*665af209SAdrian Lang                msg('SQLite: '.$this->dbname.' database initialization failed', -1);
109a1e6784eSAndreas Gohr                return false;
110a1e6784eSAndreas Gohr            }
111a1e6784eSAndreas Gohr        }
112a1e6784eSAndreas Gohr
113a1e6784eSAndreas Gohr        $latest  = (int) trim(io_readFile($updatedir.'/latest.version'));
114a1e6784eSAndreas Gohr
115a1e6784eSAndreas Gohr        // all up to date?
116a1e6784eSAndreas Gohr        if($current >= $latest) return true;
117a1e6784eSAndreas Gohr        for($i=$current+1; $i<=$latest; $i++){
118a1e6784eSAndreas Gohr            $file = sprintf($updatedir.'/update%04d.sql',$i);
119a1e6784eSAndreas Gohr            if(file_exists($file)){
120a1e6784eSAndreas Gohr                if(!$this->_runupdatefile($file,$i)){
121a1e6784eSAndreas Gohr                    msg('SQLite: '.$this->dbname.' database upgrade failed for version '.$i, -1);
122a1e6784eSAndreas Gohr
123a1e6784eSAndreas Gohr
124a1e6784eSAndreas Gohr                    return false;
125a1e6784eSAndreas Gohr                }
126a1e6784eSAndreas Gohr            }
127a1e6784eSAndreas Gohr        }
128a1e6784eSAndreas Gohr        return true;
129a1e6784eSAndreas Gohr    }
130a1e6784eSAndreas Gohr
131a1e6784eSAndreas Gohr    /**
132a1e6784eSAndreas Gohr     * Updates the database structure using the given file to
133a1e6784eSAndreas Gohr     * the given version.
134a1e6784eSAndreas Gohr     */
135a1e6784eSAndreas Gohr    function _runupdatefile($file,$version){
136a1e6784eSAndreas Gohr        $sql  = io_readFile($file,false);
137a1e6784eSAndreas Gohr
138a1e6784eSAndreas Gohr        $sql = explode(";",$sql);
139a1e6784eSAndreas Gohr        array_unshift($sql,'BEGIN TRANSACTION');
140a1e6784eSAndreas Gohr        array_push($sql,"INSERT OR REPLACE INTO opts (val,opt) VALUES ($version,'dbversion')");
141a1e6784eSAndreas Gohr        array_push($sql,"COMMIT TRANSACTION");
142a1e6784eSAndreas Gohr
143a1e6784eSAndreas Gohr        foreach($sql as $s){
144a1e6784eSAndreas Gohr            $s = preg_replace('!^\s*--.*$!m', '', $s);
145a1e6784eSAndreas Gohr            $s = trim($s);
146a1e6784eSAndreas Gohr            if(!$s) continue;
147fd69a32cSAndreas Gohr
148fd69a32cSAndreas Gohr
149a1e6784eSAndreas Gohr            $res = $this->query("$s;");
150a1e6784eSAndreas Gohr            if ($res === false) {
151a1e6784eSAndreas Gohr                sqlite_query($this->db, 'ROLLBACK TRANSACTION');
152a1e6784eSAndreas Gohr                return false;
153a1e6784eSAndreas Gohr            }
154a1e6784eSAndreas Gohr        }
155a1e6784eSAndreas Gohr
156a1e6784eSAndreas Gohr        return ($version == $this->_currentDBversion());
157a1e6784eSAndreas Gohr    }
158a1e6784eSAndreas Gohr
159a1e6784eSAndreas Gohr    /**
160fd69a32cSAndreas Gohr     * Emulate ALTER TABLE
161fd69a32cSAndreas Gohr     *
162fd69a32cSAndreas Gohr     * The ALTER TABLE syntax is parsed and then emulated using a
163fd69a32cSAndreas Gohr     * temporary table
164fd69a32cSAndreas Gohr     *
165fd69a32cSAndreas Gohr     * @author <jon@jenseng.com>
166fd69a32cSAndreas Gohr     * @link   http://code.jenseng.com/db/
167fb394683SAndreas Gohr     * @author Andreas Gohr <gohr@cosmocode.de>
168fd69a32cSAndreas Gohr     */
169fd69a32cSAndreas Gohr    function _altertable($table,$alterdefs){
170fb394683SAndreas Gohr
171fb394683SAndreas Gohr        // load original table definition SQL
172fd69a32cSAndreas Gohr        $result = $this->query("SELECT sql,name,type
173fd69a32cSAndreas Gohr                                  FROM sqlite_master
174fd69a32cSAndreas Gohr                                 WHERE tbl_name = '$table'
175fb394683SAndreas Gohr                                   AND type = 'table'");
176fb394683SAndreas Gohr
177fb394683SAndreas Gohr        if(($result === false) || (sqlite_num_rows($result)<=0)){
178fd69a32cSAndreas Gohr            msg("ALTER TABLE failed, no such table '".hsc($table)."'",-1);
179fd69a32cSAndreas Gohr            return false;
180fd69a32cSAndreas Gohr        }
181fb394683SAndreas Gohr        $row = sqlite_fetch_array($result);
182fd69a32cSAndreas Gohr
183fb394683SAndreas Gohr        // prepare temporary table SQL
184fd69a32cSAndreas Gohr        $tmpname = 't'.time();
185fd69a32cSAndreas Gohr        $origsql = trim(preg_replace("/[\s]+/"," ",
186fd69a32cSAndreas Gohr                        str_replace(",",", ",
187fd69a32cSAndreas Gohr                        preg_replace('/\)$/',' )',
188fd69a32cSAndreas Gohr                        preg_replace("/[\(]/","( ",$row['sql'],1)))));
189fd69a32cSAndreas Gohr        $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
190fd69a32cSAndreas Gohr        $createindexsql = array();
191fb394683SAndreas Gohr
192fb394683SAndreas Gohr        // load indexes to reapply later
193fb394683SAndreas Gohr        $result = $this->query("SELECT sql,name,type
194fb394683SAndreas Gohr                                  FROM sqlite_master
195fb394683SAndreas Gohr                                 WHERE tbl_name = '$table'
196fb394683SAndreas Gohr                                   AND type = 'index'");
197fb394683SAndreas Gohr        if(!$result){
198fb394683SAndreas Gohr            $indexes = array();
199fb394683SAndreas Gohr        }else{
200fb394683SAndreas Gohr            $indexes = $this->res2arr($result);
201fb394683SAndreas Gohr        }
202fb394683SAndreas Gohr
203fb394683SAndreas Gohr
204fd69a32cSAndreas Gohr        $i = 0;
205fd69a32cSAndreas Gohr        $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
206fd69a32cSAndreas Gohr        $prevword = $table;
207fd69a32cSAndreas Gohr        $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
208fd69a32cSAndreas Gohr        $newcols = array();
209fd69a32cSAndreas Gohr
210*665af209SAdrian Lang        for($i=0;$i<count($oldcols);$i++){
211fd69a32cSAndreas Gohr            $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
212fd69a32cSAndreas Gohr            $oldcols[$i] = $colparts[0];
213fd69a32cSAndreas Gohr            $newcols[$colparts[0]] = $colparts[0];
214fd69a32cSAndreas Gohr        }
215fd69a32cSAndreas Gohr        $newcolumns = '';
216fd69a32cSAndreas Gohr        $oldcolumns = '';
217fd69a32cSAndreas Gohr        reset($newcols);
218fd69a32cSAndreas Gohr        while(list($key,$val) = each($newcols)){
219fd69a32cSAndreas Gohr            $newcolumns .= ($newcolumns?', ':'').$val;
220fd69a32cSAndreas Gohr            $oldcolumns .= ($oldcolumns?', ':'').$key;
221fd69a32cSAndreas Gohr        }
222fd69a32cSAndreas Gohr        $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
223fd69a32cSAndreas Gohr        $dropoldsql = 'DROP TABLE '.$table;
224fd69a32cSAndreas Gohr        $createtesttableSQL = $createtemptableSQL;
225fd69a32cSAndreas Gohr
226fd69a32cSAndreas Gohr        foreach($defs as $def){
227fd69a32cSAndreas Gohr            $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
228fd69a32cSAndreas Gohr            $action = strtolower($defparts[0]);
229fd69a32cSAndreas Gohr            switch($action){
230fd69a32cSAndreas Gohr                case 'add':
231*665af209SAdrian Lang                    if(count($defparts) < 2){
232fd69a32cSAndreas Gohr                        msg('ALTER TABLE: not enough arguments for ADD statement',-1);
233fd69a32cSAndreas Gohr                        return false;
234fd69a32cSAndreas Gohr                    }
235fd69a32cSAndreas Gohr                    $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
236*665af209SAdrian Lang                    for($i=1;$i<count($defparts);$i++)
237fd69a32cSAndreas Gohr                        $createtesttableSQL.=' '.$defparts[$i];
238fd69a32cSAndreas Gohr                    $createtesttableSQL.=')';
239fd69a32cSAndreas Gohr                    break;
240fd69a32cSAndreas Gohr
241fd69a32cSAndreas Gohr                case 'change':
242*665af209SAdrian Lang                    if(count($defparts) <= 3){
243fd69a32cSAndreas Gohr                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error',-1);
244fd69a32cSAndreas Gohr                        return false;
245fd69a32cSAndreas Gohr                    }
246fd69a32cSAndreas Gohr
247fd69a32cSAndreas Gohr                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
248fd69a32cSAndreas Gohr                        if($newcols[$defparts[1]] != $defparts[1]){
249fd69a32cSAndreas Gohr                            msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
250fd69a32cSAndreas Gohr                            return false;
251fd69a32cSAndreas Gohr                        }
252fd69a32cSAndreas Gohr                        $newcols[$defparts[1]] = $defparts[2];
253fd69a32cSAndreas Gohr                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
254fd69a32cSAndreas Gohr                        $insertval = '';
255*665af209SAdrian Lang                        for($i=2;$i<count($defparts);$i++)
256fd69a32cSAndreas Gohr                            $insertval.=' '.$defparts[$i];
257fd69a32cSAndreas Gohr                        if($nextcommapos)
258fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
259fd69a32cSAndreas Gohr                        else
260fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
261fd69a32cSAndreas Gohr                    } else {
262fd69a32cSAndreas Gohr                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
263fd69a32cSAndreas Gohr                        return false;
264fd69a32cSAndreas Gohr                    }
265fd69a32cSAndreas Gohr                    break;
266fd69a32cSAndreas Gohr                case 'drop':
267*665af209SAdrian Lang                    if(count($defparts) < 2){
268fd69a32cSAndreas Gohr                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error',-1);
269fd69a32cSAndreas Gohr                        return false;
270fd69a32cSAndreas Gohr                    }
271fd69a32cSAndreas Gohr                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
272fd69a32cSAndreas Gohr                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
273fd69a32cSAndreas Gohr                        if($nextcommapos)
274fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
275fd69a32cSAndreas Gohr                        else
276fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
277fd69a32cSAndreas Gohr                        unset($newcols[$defparts[1]]);
278fd69a32cSAndreas Gohr                    }else{
279fd69a32cSAndreas Gohr                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
280fd69a32cSAndreas Gohr                        return false;
281fd69a32cSAndreas Gohr                    }
282fd69a32cSAndreas Gohr                    break;
283fd69a32cSAndreas Gohr                default:
284fd69a32cSAndreas Gohr                    msg('ALTER TABLE: near "'.$prevword.'": syntax error',-1);
285fd69a32cSAndreas Gohr                    return false;
286fd69a32cSAndreas Gohr            }
287*665af209SAdrian Lang            $prevword = $defparts[count($defparts)-1];
288fd69a32cSAndreas Gohr        }
289fd69a32cSAndreas Gohr
290fd69a32cSAndreas Gohr        // this block of code generates a test table simply to verify that the
291fd69a32cSAndreas Gohr        // columns specifed are valid in an sql statement
292fd69a32cSAndreas Gohr        // this ensures that no reserved words are used as columns, for example
293fd69a32cSAndreas Gohr        $res = $this->query($createtesttableSQL);
294fd69a32cSAndreas Gohr        if($res === false) return false;
295fd69a32cSAndreas Gohr
296fd69a32cSAndreas Gohr        $droptempsql = 'DROP TABLE '.$tmpname;
297fd69a32cSAndreas Gohr        $res = $this->query($droptempsql);
298fd69a32cSAndreas Gohr        if($res === false) return false;
299fd69a32cSAndreas Gohr
300fd69a32cSAndreas Gohr
301fd69a32cSAndreas Gohr        $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
302fd69a32cSAndreas Gohr        $newcolumns = '';
303fd69a32cSAndreas Gohr        $oldcolumns = '';
304fd69a32cSAndreas Gohr        reset($newcols);
305fd69a32cSAndreas Gohr        while(list($key,$val) = each($newcols)){
306fd69a32cSAndreas Gohr            $newcolumns .= ($newcolumns?', ':'').$val;
307fd69a32cSAndreas Gohr            $oldcolumns .= ($oldcolumns?', ':'').$key;
308fd69a32cSAndreas Gohr        }
309fd69a32cSAndreas Gohr
310fd69a32cSAndreas Gohr        $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
311fd69a32cSAndreas Gohr
312fd69a32cSAndreas Gohr        $res = $this->query($createtemptableSQL); //create temp table
313fd69a32cSAndreas Gohr        if($res === false) return false;
314fd69a32cSAndreas Gohr        $res = $this->query($copytotempsql); //copy to table
315fd69a32cSAndreas Gohr        if($res === false) return false;
316fd69a32cSAndreas Gohr        $res = $this->query($dropoldsql); //drop old table
317fd69a32cSAndreas Gohr        if($res === false) return false;
318fd69a32cSAndreas Gohr
319fd69a32cSAndreas Gohr        $res = $this->query($createnewtableSQL); //recreate original table
320fd69a32cSAndreas Gohr        if($res === false) return false;
321fd69a32cSAndreas Gohr        $res = $this->query($copytonewsql); //copy back to original table
322fd69a32cSAndreas Gohr        if($res === false) return false;
323fb394683SAndreas Gohr
324fb394683SAndreas Gohr        foreach($indexes as $index){ // readd indexes
325fb394683SAndreas Gohr            $res = $this->query($index['sql']);
326fb394683SAndreas Gohr            if($res === false) return false;
327fb394683SAndreas Gohr        }
328fb394683SAndreas Gohr
329fd69a32cSAndreas Gohr        $res = $this->query($droptempsql); //drop temp table
330fd69a32cSAndreas Gohr        if($res === false) return false;
331fd69a32cSAndreas Gohr
332fd69a32cSAndreas Gohr        return $res; // return a valid resource
333fd69a32cSAndreas Gohr    }
334fd69a32cSAndreas Gohr
335fd69a32cSAndreas Gohr    /**
336a1e6784eSAndreas Gohr     * Execute a query with the given parameters.
337a1e6784eSAndreas Gohr     *
338a1e6784eSAndreas Gohr     * Takes care of escaping
339a1e6784eSAndreas Gohr     *
340a1e6784eSAndreas Gohr     * @param string $sql - the statement
341a1e6784eSAndreas Gohr     * @param arguments...
342a1e6784eSAndreas Gohr     */
343a1e6784eSAndreas Gohr    function query(){
344a1e6784eSAndreas Gohr        if(!$this->db) return false;
345a1e6784eSAndreas Gohr
346a1e6784eSAndreas Gohr        // get function arguments
347a1e6784eSAndreas Gohr        $args = func_get_args();
348a1e6784eSAndreas Gohr        $sql  = trim(array_shift($args));
349fd69a32cSAndreas Gohr        $sql  = rtrim($sql,';');
350a1e6784eSAndreas Gohr
351a1e6784eSAndreas Gohr        if(!$sql){
352a1e6784eSAndreas Gohr            msg('No SQL statement given',-1);
353a1e6784eSAndreas Gohr            return false;
354a1e6784eSAndreas Gohr        }
355a1e6784eSAndreas Gohr
356a1e6784eSAndreas Gohr        $argc = count($args);
35712f8c9c7SAdrian Lang        if($argc > 0 && is_array($args[0])) {
35812f8c9c7SAdrian Lang            $args = $args[0];
35912f8c9c7SAdrian Lang            $argc = count($args);
36012f8c9c7SAdrian Lang        }
361a1e6784eSAndreas Gohr
362a1e6784eSAndreas Gohr        // check number of arguments
363a1e6784eSAndreas Gohr        if($argc < substr_count($sql,'?')){
364a1e6784eSAndreas Gohr            msg('Not enough arguments passed for statement. '.
365a1e6784eSAndreas Gohr                'Expected '.substr_count($sql,'?').' got '.
366a1e6784eSAndreas Gohr                $argc.' - '.hsc($sql),-1);
367a1e6784eSAndreas Gohr            return false;
368a1e6784eSAndreas Gohr        }
369a1e6784eSAndreas Gohr
370a1e6784eSAndreas Gohr        // explode at wildcard, then join again
371a1e6784eSAndreas Gohr        $parts = explode('?',$sql,$argc+1);
372a1e6784eSAndreas Gohr        $args  = array_map(array($this,'quote_string'),$args);
373a1e6784eSAndreas Gohr        $sql   = '';
374a1e6784eSAndreas Gohr
375a1e6784eSAndreas Gohr        while( ($part = array_shift($parts)) !== null ){
376a1e6784eSAndreas Gohr            $sql .= $part;
377a1e6784eSAndreas Gohr            $sql .= array_shift($args);
378a1e6784eSAndreas Gohr        }
379a1e6784eSAndreas Gohr
380fd69a32cSAndreas Gohr        // intercept ALTER TABLE statements
381fd69a32cSAndreas Gohr        if(preg_match('/^ALTER\s+TABLE\s+([\w\.]+)\s+(.*)/i',$sql,$match)){
382fd69a32cSAndreas Gohr            return $this->_altertable($match[1],$match[2]);
383fd69a32cSAndreas Gohr        }
384fd69a32cSAndreas Gohr
385a1e6784eSAndreas Gohr        // execute query
386a1e6784eSAndreas Gohr        $err = '';
387a1e6784eSAndreas Gohr        $res = @sqlite_query($this->db,$sql,SQLITE_ASSOC,$err);
388a1e6784eSAndreas Gohr        if($err){
389d9cff31cSAndreas Gohr            msg($err.':<br /><pre>'.hsc($sql).'</pre>',-1);
390a1e6784eSAndreas Gohr            return false;
391a1e6784eSAndreas Gohr        }elseif(!$res){
392a1e6784eSAndreas Gohr            msg(sqlite_error_string(sqlite_last_error($this->db)).
393d9cff31cSAndreas Gohr                ':<br /><pre>'.hsc($sql).'</pre>',-1);
394a1e6784eSAndreas Gohr            return false;
395a1e6784eSAndreas Gohr        }
396a1e6784eSAndreas Gohr
397a1e6784eSAndreas Gohr        return $res;
398a1e6784eSAndreas Gohr    }
399a1e6784eSAndreas Gohr
400a1e6784eSAndreas Gohr    /**
401a1e6784eSAndreas Gohr     * Returns a complete result set as array
402a1e6784eSAndreas Gohr     */
403a1e6784eSAndreas Gohr    function res2arr($res){
404a1e6784eSAndreas Gohr        $data = array();
405a1e6784eSAndreas Gohr        if(!sqlite_num_rows($res)) return $data;
406a1e6784eSAndreas Gohr        sqlite_rewind($res);
407a1e6784eSAndreas Gohr        while(($row = sqlite_fetch_array($res)) !== false){
408a1e6784eSAndreas Gohr            $data[] = $row;
409a1e6784eSAndreas Gohr        }
410a1e6784eSAndreas Gohr        return $data;
411a1e6784eSAndreas Gohr    }
412a1e6784eSAndreas Gohr
413a1e6784eSAndreas Gohr    /**
414a1e6784eSAndreas Gohr     * Return the wanted row from a given result set as
415a1e6784eSAndreas Gohr     * associative array
416a1e6784eSAndreas Gohr     */
417a1e6784eSAndreas Gohr    function res2row($res,$rownum=0){
418a1e6784eSAndreas Gohr        if(!@sqlite_seek($res,$rownum)){
419a1e6784eSAndreas Gohr            return false;
420a1e6784eSAndreas Gohr        }
421a1e6784eSAndreas Gohr        return sqlite_fetch_array($res);
422a1e6784eSAndreas Gohr    }
423a1e6784eSAndreas Gohr
424a1e6784eSAndreas Gohr
425a1e6784eSAndreas Gohr    /**
426a1e6784eSAndreas Gohr     * Join the given values and quote them for SQL insertion
427a1e6784eSAndreas Gohr     */
428a1e6784eSAndreas Gohr    function quote_and_join($vals,$sep=',') {
429a1e6784eSAndreas Gohr        $vals = array_map(array('helper_plugin_sqlite','quote_string'),$vals);
430a1e6784eSAndreas Gohr        return join($sep,$vals);
431a1e6784eSAndreas Gohr    }
432a1e6784eSAndreas Gohr
433a1e6784eSAndreas Gohr    /**
434a1e6784eSAndreas Gohr     * Run sqlite_escape_string() on the given string and surround it
435a1e6784eSAndreas Gohr     * with quotes
436a1e6784eSAndreas Gohr     */
437a1e6784eSAndreas Gohr    function quote_string($string){
438a1e6784eSAndreas Gohr        return "'".sqlite_escape_string($string)."'";
439a1e6784eSAndreas Gohr    }
440a1e6784eSAndreas Gohr
441a1e6784eSAndreas Gohr
442b5b947d7SAndreas Gohr    /**
443b5b947d7SAndreas Gohr     * Aggregation function for SQLite
444b5b947d7SAndreas Gohr     *
445b5b947d7SAndreas Gohr     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
446b5b947d7SAndreas Gohr     */
447b5b947d7SAndreas Gohr    function _sqlite_group_concat_step(&$context, $string, $separator = ',') {
448b5b947d7SAndreas Gohr         $context['sep']    = $separator;
449b5b947d7SAndreas Gohr         $context['data'][] = $string;
450b5b947d7SAndreas Gohr    }
451b5b947d7SAndreas Gohr
452b5b947d7SAndreas Gohr    /**
453b5b947d7SAndreas Gohr     * Aggregation function for SQLite
454b5b947d7SAndreas Gohr     *
455b5b947d7SAndreas Gohr     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
456b5b947d7SAndreas Gohr     */
457b5b947d7SAndreas Gohr    function _sqlite_group_concat_finalize(&$context) {
458b5b947d7SAndreas Gohr         $context['data'] = array_unique($context['data']);
459b5b947d7SAndreas Gohr         return join($context['sep'],$context['data']);
460b5b947d7SAndreas Gohr    }
461b5b947d7SAndreas Gohr
462e7112ccbSAdrian Lang    /**
463e7112ccbSAdrian Lang     * Keep separate instances for every call to keep database connections
464e7112ccbSAdrian Lang     */
465e7112ccbSAdrian Lang    function isSingleton() {
466e7112ccbSAdrian Lang         return false;
467e7112ccbSAdrian Lang    }
468a1e6784eSAndreas Gohr}
469a1e6784eSAndreas Gohr
470a1e6784eSAndreas Gohr// vim:ts=4:sw=4:et:enc=utf-8:
471