xref: /plugin/sqlite/helper.php (revision fd69a32c016ce02ddc42177a639af2079ff519c1)
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)){
108a1e6784eSAndreas Gohr                msg('SQLite: '.$this->dbname.' database upgrade failed for version '.$i, -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;
147*fd69a32cSAndreas Gohr
148*fd69a32cSAndreas 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    /**
160*fd69a32cSAndreas Gohr     * Emulate ALTER TABLE
161*fd69a32cSAndreas Gohr     *
162*fd69a32cSAndreas Gohr     * The ALTER TABLE syntax is parsed and then emulated using a
163*fd69a32cSAndreas Gohr     * temporary table
164*fd69a32cSAndreas Gohr     *
165*fd69a32cSAndreas Gohr     * @author <jon@jenseng.com>
166*fd69a32cSAndreas Gohr     * @link   http://code.jenseng.com/db/
167*fd69a32cSAndreas Gohr     */
168*fd69a32cSAndreas Gohr    function _altertable($table,$alterdefs){
169*fd69a32cSAndreas Gohr        $result = $this->query("SELECT sql,name,type
170*fd69a32cSAndreas Gohr                                  FROM sqlite_master
171*fd69a32cSAndreas Gohr                                 WHERE tbl_name = '$table'
172*fd69a32cSAndreas Gohr                              ORDER BY type DESC");
173*fd69a32cSAndreas Gohr        if(!$result || sqlite_num_rows($result)<=0){
174*fd69a32cSAndreas Gohr            msg("ALTER TABLE failed, no such table '".hsc($table)."'",-1);
175*fd69a32cSAndreas Gohr            return false;
176*fd69a32cSAndreas Gohr        }
177*fd69a32cSAndreas Gohr
178*fd69a32cSAndreas Gohr        $row = sqlite_fetch_array($result); //table sql
179*fd69a32cSAndreas Gohr        $tmpname = 't'.time();
180*fd69a32cSAndreas Gohr
181*fd69a32cSAndreas Gohr        $origsql = trim(preg_replace("/[\s]+/"," ",
182*fd69a32cSAndreas Gohr                        str_replace(",",", ",
183*fd69a32cSAndreas Gohr                        preg_replace('/\)$/',' )',
184*fd69a32cSAndreas Gohr                        preg_replace("/[\(]/","( ",$row['sql'],1)))));
185*fd69a32cSAndreas Gohr        $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
186*fd69a32cSAndreas Gohr        $createindexsql = array();
187*fd69a32cSAndreas Gohr        $i = 0;
188*fd69a32cSAndreas Gohr        $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
189*fd69a32cSAndreas Gohr        $prevword = $table;
190*fd69a32cSAndreas Gohr        $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
191*fd69a32cSAndreas Gohr        $newcols = array();
192*fd69a32cSAndreas Gohr
193*fd69a32cSAndreas Gohr        for($i=0;$i<sizeof($oldcols);$i++){
194*fd69a32cSAndreas Gohr            $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
195*fd69a32cSAndreas Gohr            $oldcols[$i] = $colparts[0];
196*fd69a32cSAndreas Gohr            $newcols[$colparts[0]] = $colparts[0];
197*fd69a32cSAndreas Gohr        }
198*fd69a32cSAndreas Gohr        $newcolumns = '';
199*fd69a32cSAndreas Gohr        $oldcolumns = '';
200*fd69a32cSAndreas Gohr        reset($newcols);
201*fd69a32cSAndreas Gohr        while(list($key,$val) = each($newcols)){
202*fd69a32cSAndreas Gohr            $newcolumns .= ($newcolumns?', ':'').$val;
203*fd69a32cSAndreas Gohr            $oldcolumns .= ($oldcolumns?', ':'').$key;
204*fd69a32cSAndreas Gohr        }
205*fd69a32cSAndreas Gohr        $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
206*fd69a32cSAndreas Gohr        $dropoldsql = 'DROP TABLE '.$table;
207*fd69a32cSAndreas Gohr        $createtesttableSQL = $createtemptableSQL;
208*fd69a32cSAndreas Gohr
209*fd69a32cSAndreas Gohr        foreach($defs as $def){
210*fd69a32cSAndreas Gohr            $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
211*fd69a32cSAndreas Gohr            $action = strtolower($defparts[0]);
212*fd69a32cSAndreas Gohr            switch($action){
213*fd69a32cSAndreas Gohr                case 'add':
214*fd69a32cSAndreas Gohr                    if(sizeof($defparts) < 2){
215*fd69a32cSAndreas Gohr                        msg('ALTER TABLE: not enough arguments for ADD statement',-1);
216*fd69a32cSAndreas Gohr                        return false;
217*fd69a32cSAndreas Gohr                    }
218*fd69a32cSAndreas Gohr                    $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
219*fd69a32cSAndreas Gohr                    for($i=1;$i<sizeof($defparts);$i++)
220*fd69a32cSAndreas Gohr                        $createtesttableSQL.=' '.$defparts[$i];
221*fd69a32cSAndreas Gohr                    $createtesttableSQL.=')';
222*fd69a32cSAndreas Gohr                    break;
223*fd69a32cSAndreas Gohr
224*fd69a32cSAndreas Gohr                case 'change':
225*fd69a32cSAndreas Gohr                    if(sizeof($defparts) <= 3){
226*fd69a32cSAndreas Gohr                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error',-1);
227*fd69a32cSAndreas Gohr                        return false;
228*fd69a32cSAndreas Gohr                    }
229*fd69a32cSAndreas Gohr
230*fd69a32cSAndreas Gohr                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
231*fd69a32cSAndreas Gohr                        if($newcols[$defparts[1]] != $defparts[1]){
232*fd69a32cSAndreas Gohr                            msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
233*fd69a32cSAndreas Gohr                            return false;
234*fd69a32cSAndreas Gohr                        }
235*fd69a32cSAndreas Gohr                        $newcols[$defparts[1]] = $defparts[2];
236*fd69a32cSAndreas Gohr                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
237*fd69a32cSAndreas Gohr                        $insertval = '';
238*fd69a32cSAndreas Gohr                        for($i=2;$i<sizeof($defparts);$i++)
239*fd69a32cSAndreas Gohr                            $insertval.=' '.$defparts[$i];
240*fd69a32cSAndreas Gohr                        if($nextcommapos)
241*fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
242*fd69a32cSAndreas Gohr                        else
243*fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
244*fd69a32cSAndreas Gohr                    } else {
245*fd69a32cSAndreas Gohr                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
246*fd69a32cSAndreas Gohr                        return false;
247*fd69a32cSAndreas Gohr                    }
248*fd69a32cSAndreas Gohr                    break;
249*fd69a32cSAndreas Gohr                case 'drop':
250*fd69a32cSAndreas Gohr                    if(sizeof($defparts) < 2){
251*fd69a32cSAndreas Gohr                        msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error',-1);
252*fd69a32cSAndreas Gohr                        return false;
253*fd69a32cSAndreas Gohr                    }
254*fd69a32cSAndreas Gohr                    if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
255*fd69a32cSAndreas Gohr                        $nextcommapos = strpos($createtesttableSQL,',',$severpos);
256*fd69a32cSAndreas Gohr                        if($nextcommapos)
257*fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
258*fd69a32cSAndreas Gohr                        else
259*fd69a32cSAndreas Gohr                            $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
260*fd69a32cSAndreas Gohr                        unset($newcols[$defparts[1]]);
261*fd69a32cSAndreas Gohr                    }else{
262*fd69a32cSAndreas Gohr                        msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1);
263*fd69a32cSAndreas Gohr                        return false;
264*fd69a32cSAndreas Gohr                    }
265*fd69a32cSAndreas Gohr                    break;
266*fd69a32cSAndreas Gohr                default:
267*fd69a32cSAndreas Gohr                    msg('ALTER TABLE: near "'.$prevword.'": syntax error',-1);
268*fd69a32cSAndreas Gohr                    return false;
269*fd69a32cSAndreas Gohr            }
270*fd69a32cSAndreas Gohr            $prevword = $defparts[sizeof($defparts)-1];
271*fd69a32cSAndreas Gohr        }
272*fd69a32cSAndreas Gohr
273*fd69a32cSAndreas Gohr        // this block of code generates a test table simply to verify that the
274*fd69a32cSAndreas Gohr        // columns specifed are valid in an sql statement
275*fd69a32cSAndreas Gohr        // this ensures that no reserved words are used as columns, for example
276*fd69a32cSAndreas Gohr        $res = $this->query($createtesttableSQL);
277*fd69a32cSAndreas Gohr        if($res === false) return false;
278*fd69a32cSAndreas Gohr
279*fd69a32cSAndreas Gohr        $droptempsql = 'DROP TABLE '.$tmpname;
280*fd69a32cSAndreas Gohr        $res = $this->query($droptempsql);
281*fd69a32cSAndreas Gohr        if($res === false) return false;
282*fd69a32cSAndreas Gohr
283*fd69a32cSAndreas Gohr
284*fd69a32cSAndreas Gohr        $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
285*fd69a32cSAndreas Gohr        $newcolumns = '';
286*fd69a32cSAndreas Gohr        $oldcolumns = '';
287*fd69a32cSAndreas Gohr        reset($newcols);
288*fd69a32cSAndreas Gohr        while(list($key,$val) = each($newcols)){
289*fd69a32cSAndreas Gohr            $newcolumns .= ($newcolumns?', ':'').$val;
290*fd69a32cSAndreas Gohr            $oldcolumns .= ($oldcolumns?', ':'').$key;
291*fd69a32cSAndreas Gohr        }
292*fd69a32cSAndreas Gohr
293*fd69a32cSAndreas Gohr        $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
294*fd69a32cSAndreas Gohr
295*fd69a32cSAndreas Gohr        $res = $this->query($createtemptableSQL); //create temp table
296*fd69a32cSAndreas Gohr        if($res === false) return false;
297*fd69a32cSAndreas Gohr        $res = $this->query($copytotempsql); //copy to table
298*fd69a32cSAndreas Gohr        if($res === false) return false;
299*fd69a32cSAndreas Gohr        $res = $this->query($dropoldsql); //drop old table
300*fd69a32cSAndreas Gohr        if($res === false) return false;
301*fd69a32cSAndreas Gohr
302*fd69a32cSAndreas Gohr        $res = $this->query($createnewtableSQL); //recreate original table
303*fd69a32cSAndreas Gohr        if($res === false) return false;
304*fd69a32cSAndreas Gohr        $res = $this->query($copytonewsql); //copy back to original table
305*fd69a32cSAndreas Gohr        if($res === false) return false;
306*fd69a32cSAndreas Gohr        $res = $this->query($droptempsql); //drop temp table
307*fd69a32cSAndreas Gohr        if($res === false) return false;
308*fd69a32cSAndreas Gohr
309*fd69a32cSAndreas Gohr        return $res; // return a valid resource
310*fd69a32cSAndreas Gohr    }
311*fd69a32cSAndreas Gohr
312*fd69a32cSAndreas Gohr    /**
313a1e6784eSAndreas Gohr     * Execute a query with the given parameters.
314a1e6784eSAndreas Gohr     *
315a1e6784eSAndreas Gohr     * Takes care of escaping
316a1e6784eSAndreas Gohr     *
317a1e6784eSAndreas Gohr     * @param string $sql - the statement
318a1e6784eSAndreas Gohr     * @param arguments...
319a1e6784eSAndreas Gohr     */
320a1e6784eSAndreas Gohr    function query(){
321a1e6784eSAndreas Gohr        if(!$this->db) return false;
322a1e6784eSAndreas Gohr
323a1e6784eSAndreas Gohr        // get function arguments
324a1e6784eSAndreas Gohr        $args = func_get_args();
325a1e6784eSAndreas Gohr        $sql  = trim(array_shift($args));
326*fd69a32cSAndreas Gohr        $sql  = rtrim($sql,';');
327a1e6784eSAndreas Gohr
328a1e6784eSAndreas Gohr        if(!$sql){
329a1e6784eSAndreas Gohr            msg('No SQL statement given',-1);
330a1e6784eSAndreas Gohr            return false;
331a1e6784eSAndreas Gohr        }
332a1e6784eSAndreas Gohr
333a1e6784eSAndreas Gohr        if(is_array($args[0])) $args = $args[0];
334a1e6784eSAndreas Gohr        $argc = count($args);
335a1e6784eSAndreas Gohr
336a1e6784eSAndreas Gohr        // check number of arguments
337a1e6784eSAndreas Gohr        if($argc < substr_count($sql,'?')){
338a1e6784eSAndreas Gohr            msg('Not enough arguments passed for statement. '.
339a1e6784eSAndreas Gohr                'Expected '.substr_count($sql,'?').' got '.
340a1e6784eSAndreas Gohr                $argc.' - '.hsc($sql),-1);
341a1e6784eSAndreas Gohr            return false;
342a1e6784eSAndreas Gohr        }
343a1e6784eSAndreas Gohr
344a1e6784eSAndreas Gohr        // explode at wildcard, then join again
345a1e6784eSAndreas Gohr        $parts = explode('?',$sql,$argc+1);
346a1e6784eSAndreas Gohr        $args  = array_map(array($this,'quote_string'),$args);
347a1e6784eSAndreas Gohr        $sql   = '';
348a1e6784eSAndreas Gohr
349a1e6784eSAndreas Gohr        while( ($part = array_shift($parts)) !== null ){
350a1e6784eSAndreas Gohr            $sql .= $part;
351a1e6784eSAndreas Gohr            $sql .= array_shift($args);
352a1e6784eSAndreas Gohr        }
353a1e6784eSAndreas Gohr
354*fd69a32cSAndreas Gohr        // intercept ALTER TABLE statements
355*fd69a32cSAndreas Gohr        if(preg_match('/^ALTER\s+TABLE\s+([\w\.]+)\s+(.*)/i',$sql,$match)){
356*fd69a32cSAndreas Gohr            return $this->_altertable($match[1],$match[2]);
357*fd69a32cSAndreas Gohr        }
358*fd69a32cSAndreas Gohr
359a1e6784eSAndreas Gohr        // execute query
360a1e6784eSAndreas Gohr        $err = '';
361a1e6784eSAndreas Gohr        $res = @sqlite_query($this->db,$sql,SQLITE_ASSOC,$err);
362a1e6784eSAndreas Gohr        if($err){
363d9cff31cSAndreas Gohr            msg($err.':<br /><pre>'.hsc($sql).'</pre>',-1);
364a1e6784eSAndreas Gohr            return false;
365a1e6784eSAndreas Gohr        }elseif(!$res){
366a1e6784eSAndreas Gohr            msg(sqlite_error_string(sqlite_last_error($this->db)).
367d9cff31cSAndreas Gohr                ':<br /><pre>'.hsc($sql).'</pre>',-1);
368a1e6784eSAndreas Gohr            return false;
369a1e6784eSAndreas Gohr        }
370a1e6784eSAndreas Gohr
371a1e6784eSAndreas Gohr        return $res;
372a1e6784eSAndreas Gohr    }
373a1e6784eSAndreas Gohr
374a1e6784eSAndreas Gohr    /**
375a1e6784eSAndreas Gohr     * Returns a complete result set as array
376a1e6784eSAndreas Gohr     */
377a1e6784eSAndreas Gohr    function res2arr($res){
378a1e6784eSAndreas Gohr        $data = array();
379a1e6784eSAndreas Gohr        if(!sqlite_num_rows($res)) return $data;
380a1e6784eSAndreas Gohr        sqlite_rewind($res);
381a1e6784eSAndreas Gohr        while(($row = sqlite_fetch_array($res)) !== false){
382a1e6784eSAndreas Gohr            $data[] = $row;
383a1e6784eSAndreas Gohr        }
384a1e6784eSAndreas Gohr        return $data;
385a1e6784eSAndreas Gohr    }
386a1e6784eSAndreas Gohr
387a1e6784eSAndreas Gohr    /**
388a1e6784eSAndreas Gohr     * Return the wanted row from a given result set as
389a1e6784eSAndreas Gohr     * associative array
390a1e6784eSAndreas Gohr     */
391a1e6784eSAndreas Gohr    function res2row($res,$rownum=0){
392a1e6784eSAndreas Gohr        if(!@sqlite_seek($res,$rownum)){
393a1e6784eSAndreas Gohr            return false;
394a1e6784eSAndreas Gohr        }
395a1e6784eSAndreas Gohr        return sqlite_fetch_array($res);
396a1e6784eSAndreas Gohr    }
397a1e6784eSAndreas Gohr
398a1e6784eSAndreas Gohr
399a1e6784eSAndreas Gohr    /**
400a1e6784eSAndreas Gohr     * Join the given values and quote them for SQL insertion
401a1e6784eSAndreas Gohr     */
402a1e6784eSAndreas Gohr    function quote_and_join($vals,$sep=',') {
403a1e6784eSAndreas Gohr        $vals = array_map(array('helper_plugin_sqlite','quote_string'),$vals);
404a1e6784eSAndreas Gohr        return join($sep,$vals);
405a1e6784eSAndreas Gohr    }
406a1e6784eSAndreas Gohr
407a1e6784eSAndreas Gohr    /**
408a1e6784eSAndreas Gohr     * Run sqlite_escape_string() on the given string and surround it
409a1e6784eSAndreas Gohr     * with quotes
410a1e6784eSAndreas Gohr     */
411a1e6784eSAndreas Gohr    function quote_string($string){
412a1e6784eSAndreas Gohr        return "'".sqlite_escape_string($string)."'";
413a1e6784eSAndreas Gohr    }
414a1e6784eSAndreas Gohr
415a1e6784eSAndreas Gohr
416b5b947d7SAndreas Gohr    /**
417b5b947d7SAndreas Gohr     * Aggregation function for SQLite
418b5b947d7SAndreas Gohr     *
419b5b947d7SAndreas Gohr     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
420b5b947d7SAndreas Gohr     */
421b5b947d7SAndreas Gohr    function _sqlite_group_concat_step(&$context, $string, $separator = ',') {
422b5b947d7SAndreas Gohr         $context['sep']    = $separator;
423b5b947d7SAndreas Gohr         $context['data'][] = $string;
424b5b947d7SAndreas Gohr    }
425b5b947d7SAndreas Gohr
426b5b947d7SAndreas Gohr    /**
427b5b947d7SAndreas Gohr     * Aggregation function for SQLite
428b5b947d7SAndreas Gohr     *
429b5b947d7SAndreas Gohr     * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine
430b5b947d7SAndreas Gohr     */
431b5b947d7SAndreas Gohr    function _sqlite_group_concat_finalize(&$context) {
432b5b947d7SAndreas Gohr         $context['data'] = array_unique($context['data']);
433b5b947d7SAndreas Gohr         return join($context['sep'],$context['data']);
434b5b947d7SAndreas Gohr    }
435b5b947d7SAndreas Gohr
436b5b947d7SAndreas Gohr
437a1e6784eSAndreas Gohr}
438a1e6784eSAndreas Gohr
439a1e6784eSAndreas Gohr// vim:ts=4:sw=4:et:enc=utf-8:
440