xref: /plugin/sqlite/helper.php (revision f10ea6c1c079855c1869b3bc3edab520bc0832f5)
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
1687fa2c18Sstretchyboyif(!defined('DOKU_EXT_SQLITE')) define('DOKU_EXT_SQLITE', 'sqlite');
1787fa2c18Sstretchyboyif(!defined('DOKU_EXT_PDO')) define('DOKU_EXT_PDO', 'pdo');
1887fa2c18Sstretchyboy
19aa81d781SKlap-inrequire_once(DOKU_PLUGIN.'sqlite/classes/adapter.php');
2087fa2c18Sstretchyboy
21a1e6784eSAndreas Gohrclass helper_plugin_sqlite extends DokuWiki_Plugin {
22aa81d781SKlap-in    var $adapter = null;
23aa81d781SKlap-in
24aa81d781SKlap-in    public function getInfo() {
25a1e6784eSAndreas Gohr        return confToHash(dirname(__FILE__).'plugin.info.txt');
26a1e6784eSAndreas Gohr    }
27a1e6784eSAndreas Gohr
28a1e6784eSAndreas Gohr    /**
29aa81d781SKlap-in     * Keep separate instances for every call to keep database connections
30aa81d781SKlap-in     */
31aa81d781SKlap-in    public function isSingleton() {
32aa81d781SKlap-in        return false;
33aa81d781SKlap-in    }
34aa81d781SKlap-in
35aa81d781SKlap-in    /**
36a1e6784eSAndreas Gohr     * constructor
37a1e6784eSAndreas Gohr     */
38aa81d781SKlap-in    public function helper_plugin_sqlite() {
3987fa2c18Sstretchyboy
4013896259SKlap-in        if(!$this->adapter) {
41aa81d781SKlap-in            if($this->existsPDOSqlite()) {
42aa81d781SKlap-in                require_once(DOKU_PLUGIN.'sqlite/classes/adapter_pdosqlite.php');
43aa81d781SKlap-in                $this->adapter = new helper_plugin_sqlite_adapter_pdosqlite();
44aa81d781SKlap-in            }
45aa81d781SKlap-in        }
46aa81d781SKlap-in
4713896259SKlap-in        if(!$this->adapter) {
48aa81d781SKlap-in            if($this->existsSqlite2()) {
49aa81d781SKlap-in                require_once(DOKU_PLUGIN.'sqlite/classes/adapter_sqlite2.php');
50aa81d781SKlap-in                $this->adapter = new helper_plugin_sqlite_adapter_sqlite2();
51aa81d781SKlap-in            }
52aa81d781SKlap-in        }
53aa81d781SKlap-in
5413896259SKlap-in        if(!$this->adapter) {
55aa81d781SKlap-in            msg('SQLite & PDO SQLite support missing in this PHP install - plugin will not work', -1);
56aa81d781SKlap-in        }
57aa81d781SKlap-in    }
58aa81d781SKlap-in
59aa81d781SKlap-in    /**
60aa81d781SKlap-in     * check availabilty of PHPs sqlite extension (for sqlite2 support)
61aa81d781SKlap-in     */
62aa81d781SKlap-in    public function existsSqlite2() {
63aa81d781SKlap-in        if(!extension_loaded('sqlite')) {
64aa81d781SKlap-in            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
65aa81d781SKlap-in            if(function_exists('dl')) @dl($prefix.'sqlite.'.PHP_SHLIB_SUFFIX);
66aa81d781SKlap-in        }
67aa81d781SKlap-in
68aa81d781SKlap-in        return function_exists('sqlite_open');
69aa81d781SKlap-in    }
70aa81d781SKlap-in
71aa81d781SKlap-in    /**
72aa81d781SKlap-in     * check availabilty of PHP PDO sqlite3
73aa81d781SKlap-in     */
74aa81d781SKlap-in    public function existsPDOSqlite() {
7587fa2c18Sstretchyboy        if(!extension_loaded('pdo_sqlite')) {
7687fa2c18Sstretchyboy            $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
7787fa2c18Sstretchyboy            if(function_exists('dl')) @dl($prefix.'pdo_sqlite.'.PHP_SHLIB_SUFFIX);
7887fa2c18Sstretchyboy        }
7987fa2c18Sstretchyboy
8087fa2c18Sstretchyboy        if(class_exists('pdo')) {
81aa81d781SKlap-in            foreach(PDO::getAvailableDrivers() as $driver) {
82aa81d781SKlap-in                if($driver == 'sqlite') {
83aa81d781SKlap-in                    return true;
8487fa2c18Sstretchyboy                }
8587fa2c18Sstretchyboy            }
867ed6069fSAdrian Lang        }
87aa81d781SKlap-in        return false;
88a1e6784eSAndreas Gohr    }
89a1e6784eSAndreas Gohr
90a1e6784eSAndreas Gohr    /**
91a1e6784eSAndreas Gohr     * Initializes and opens the database
92a1e6784eSAndreas Gohr     *
93a1e6784eSAndreas Gohr     * Needs to be called right after loading this helper plugin
94aa81d781SKlap-in     *
95aa81d781SKlap-in     * @param string $dbname
96aa81d781SKlap-in     * @param string $updatedir - Database update infos
97aa81d781SKlap-in     * @return bool
98a1e6784eSAndreas Gohr     */
99aa81d781SKlap-in    public function init($dbname, $updatedir) {
100a1e6784eSAndreas Gohr
101aa81d781SKlap-in        $init = null; // set by initdb()
102c5e5294cSKlap-in        if(!$this->adapter OR !$this->adapter->initdb($dbname, $init)) return false;
103a1e6784eSAndreas Gohr
104aa81d781SKlap-in        return $this->_updatedb($init, $updatedir);
105a1e6784eSAndreas Gohr    }
106a1e6784eSAndreas Gohr
107a1e6784eSAndreas Gohr    /**
108a1e6784eSAndreas Gohr     * Return the current Database Version
109a1e6784eSAndreas Gohr     */
110aa81d781SKlap-in    private function _currentDBversion() {
111a1e6784eSAndreas Gohr        $sql = "SELECT val FROM opts WHERE opt = 'dbversion';";
112a1e6784eSAndreas Gohr        $res = $this->query($sql);
113a1e6784eSAndreas Gohr        if(!$res) return false;
114a1e6784eSAndreas Gohr        $row = $this->res2row($res, 0);
115a1e6784eSAndreas Gohr        return (int) $row['val'];
116a1e6784eSAndreas Gohr    }
117aa81d781SKlap-in
118a1e6784eSAndreas Gohr    /**
119a1e6784eSAndreas Gohr     * Update the database if needed
120a1e6784eSAndreas Gohr     *
121a1e6784eSAndreas Gohr     * @param bool   $init      - true if this is a new database to initialize
122a1e6784eSAndreas Gohr     * @param string $updatedir - Database update infos
123aa81d781SKlap-in     * @return bool
124a1e6784eSAndreas Gohr     */
12513896259SKlap-in    private function _updatedb($init, $updatedir) {
126a1e6784eSAndreas Gohr        if($init) {
1274d9093b4Sstretchyboy
128a1e6784eSAndreas Gohr            $current = 0;
129a1e6784eSAndreas Gohr        } else {
130a1e6784eSAndreas Gohr            $current = $this->_currentDBversion();
131a1e6784eSAndreas Gohr            if(!$current) {
132aa81d781SKlap-in                msg("SQLite: no DB version found. '".$this->adapter->getDbname()."' DB probably broken.", -1);
133a1e6784eSAndreas Gohr                return false;
134a1e6784eSAndreas Gohr            }
135a1e6784eSAndreas Gohr        }
136a1e6784eSAndreas Gohr
137a1e6784eSAndreas Gohr        // in case of init, add versioning table
138a1e6784eSAndreas Gohr        if($init) {
139a1e6784eSAndreas Gohr            if(!$this->_runupdatefile(dirname(__FILE__).'/db.sql', 0)) {
140aa81d781SKlap-in                msg("SQLite: '".$this->adapter->getDbname()."' database upgrade failed for version ", -1);
141a1e6784eSAndreas Gohr                return false;
142a1e6784eSAndreas Gohr            }
143a1e6784eSAndreas Gohr        }
144a1e6784eSAndreas Gohr
145a1e6784eSAndreas Gohr        $latest = (int) trim(io_readFile($updatedir.'/latest.version'));
146a1e6784eSAndreas Gohr
147a1e6784eSAndreas Gohr        // all up to date?
148a1e6784eSAndreas Gohr        if($current >= $latest) return true;
149a1e6784eSAndreas Gohr        for($i = $current + 1; $i <= $latest; $i++) {
150a1e6784eSAndreas Gohr            $file = sprintf($updatedir.'/update%04d.sql', $i);
151a1e6784eSAndreas Gohr            if(file_exists($file)) {
152a1e6784eSAndreas Gohr                if(!$this->_runupdatefile($file, $i)) {
153aa81d781SKlap-in                    msg("SQLite: '".$this->adapter->getDbname()."' database upgrade failed for version ".$i, -1);
154a1e6784eSAndreas Gohr                    return false;
155a1e6784eSAndreas Gohr                }
156a1e6784eSAndreas Gohr            }
157a1e6784eSAndreas Gohr        }
158a1e6784eSAndreas Gohr        return true;
159a1e6784eSAndreas Gohr    }
160a1e6784eSAndreas Gohr
161a1e6784eSAndreas Gohr    /**
162a1e6784eSAndreas Gohr     * Updates the database structure using the given file to
163a1e6784eSAndreas Gohr     * the given version.
164a1e6784eSAndreas Gohr     */
165aa81d781SKlap-in    private function _runupdatefile($file, $version) {
166a1e6784eSAndreas Gohr        $sql = io_readFile($file, false);
167a1e6784eSAndreas Gohr
168*f10ea6c1SKlap-in        $sql = $this->SQLstring2array($sql);
169a1e6784eSAndreas Gohr        array_unshift($sql, 'BEGIN TRANSACTION');
170a1e6784eSAndreas Gohr        array_push($sql, "INSERT OR REPLACE INTO opts (val,opt) VALUES ($version,'dbversion')");
171a1e6784eSAndreas Gohr        array_push($sql, "COMMIT TRANSACTION");
172a1e6784eSAndreas Gohr
173*f10ea6c1SKlap-in        if(!$this->doTransaction($sql)) {
174*f10ea6c1SKlap-in            return false;
175*f10ea6c1SKlap-in        }
176*f10ea6c1SKlap-in        return ($version == $this->_currentDBversion());
177*f10ea6c1SKlap-in    }
178*f10ea6c1SKlap-in
179*f10ea6c1SKlap-in    /**
180*f10ea6c1SKlap-in     * Split sql queries on semicolons, unless when semicolons are quoted
181*f10ea6c1SKlap-in     *
182*f10ea6c1SKlap-in     * @param string $sql
183*f10ea6c1SKlap-in     * @return array sql queries
184*f10ea6c1SKlap-in     */
185*f10ea6c1SKlap-in    public function SQLstring2array($sql) {
186*f10ea6c1SKlap-in        return preg_split("/;(?=([^']*'[^']*')*[^']*$)/", $sql);
187*f10ea6c1SKlap-in    }
188*f10ea6c1SKlap-in
189*f10ea6c1SKlap-in    /**
190*f10ea6c1SKlap-in     * @param array $sql queries without terminating semicolon
191*f10ea6c1SKlap-in     * @param bool  $sqlpreparing
192*f10ea6c1SKlap-in     * @return bool
193*f10ea6c1SKlap-in     */
194*f10ea6c1SKlap-in    public function doTransaction($sql, $sqlpreparing = true) {
195a1e6784eSAndreas Gohr        foreach($sql as $s) {
196a1e6784eSAndreas Gohr            $s = preg_replace('!^\s*--.*$!m', '', $s);
197a1e6784eSAndreas Gohr            $s = trim($s);
198a1e6784eSAndreas Gohr            if(!$s) continue;
199fd69a32cSAndreas Gohr
200*f10ea6c1SKlap-in            if($sqlpreparing) {
201a1e6784eSAndreas Gohr                $res = $this->query("$s;");
202*f10ea6c1SKlap-in            } else {
203*f10ea6c1SKlap-in                $res = $this->adapter->executeQuery("$s;");
204*f10ea6c1SKlap-in            }
205a1e6784eSAndreas Gohr            if($res === false) {
206*f10ea6c1SKlap-in                //TODO check rollback for sqlite PDO
20713896259SKlap-in                if($this->adapter->getName() == DOKU_EXT_SQLITE) {
2081dc19626SKlap-in                    $this->query('ROLLBACK TRANSACTION');
209a1e6784eSAndreas Gohr                }
21005f176edSstretchyboy                return false;
21105f176edSstretchyboy            }
212a1e6784eSAndreas Gohr        }
213*f10ea6c1SKlap-in        return true;
214a1e6784eSAndreas Gohr    }
215a1e6784eSAndreas Gohr
216*f10ea6c1SKlap-in
217*f10ea6c1SKlap-in
218a1e6784eSAndreas Gohr    /**
2193ae3f79eSKlap-in     * Registers a User Defined Function for use in SQL statements
2203ae3f79eSKlap-in     */
221aa81d781SKlap-in    public function create_function($function_name, $callback, $num_args) {
222aa81d781SKlap-in        $this->adapter->create_function($function_name, $callback, $num_args);
2233ae3f79eSKlap-in    }
2243ae3f79eSKlap-in
2253ae3f79eSKlap-in    /**
226a1e6784eSAndreas Gohr     * Execute a query with the given parameters.
227a1e6784eSAndreas Gohr     *
228a1e6784eSAndreas Gohr     * Takes care of escaping
229a1e6784eSAndreas Gohr     *
230aa81d781SKlap-in     * @internal param string $sql - the statement
231aa81d781SKlap-in     * @internal param $arguments ...
232aa81d781SKlap-in     * @return bool|\SQLiteResult
233a1e6784eSAndreas Gohr     */
234aa81d781SKlap-in    public function query() {
235a1e6784eSAndreas Gohr        // get function arguments
236a1e6784eSAndreas Gohr        $args = func_get_args();
237a1e6784eSAndreas Gohr
238aa81d781SKlap-in        return $this->adapter->query($args);
23987fa2c18Sstretchyboy    }
240a1e6784eSAndreas Gohr
241a1e6784eSAndreas Gohr    /**
242a1e6784eSAndreas Gohr     * Join the given values and quote them for SQL insertion
243a1e6784eSAndreas Gohr     */
244aa81d781SKlap-in    public function quote_and_join($vals, $sep = ',') {
245aa81d781SKlap-in        return $this->adapter->quote_and_join($vals, $sep);
246a1e6784eSAndreas Gohr    }
247a1e6784eSAndreas Gohr
248a1e6784eSAndreas Gohr    /**
249a1e6784eSAndreas Gohr     * Run sqlite_escape_string() on the given string and surround it
250a1e6784eSAndreas Gohr     * with quotes
251a1e6784eSAndreas Gohr     */
252aa81d781SKlap-in    public function quote_string($string) {
253aa81d781SKlap-in        return $this->adapter->quote_string($string);
254a1e6784eSAndreas Gohr    }
255a1e6784eSAndreas Gohr
256b5b947d7SAndreas Gohr    /**
257fee3b689Sstretchyboy     * Escape string for sql
258fee3b689Sstretchyboy     */
259aa81d781SKlap-in    public function escape_string($str) {
260aa81d781SKlap-in        return $this->adapter->escape_string($str);
261ff97cc8fSstretchyboy    }
262ff97cc8fSstretchyboy
263ff97cc8fSstretchyboy    /**
264aa81d781SKlap-in     * Returns a complete result set as array
265ff97cc8fSstretchyboy     */
266ef383ac5SKlap-in    public function res2arr($res, $assoc = true) {
267ef383ac5SKlap-in        return $this->adapter->res2arr($res, $assoc);
268b5b947d7SAndreas Gohr    }
269b5b947d7SAndreas Gohr
270b5b947d7SAndreas Gohr    /**
271aa81d781SKlap-in     * Return the wanted row from a given result set as
272aa81d781SKlap-in     * associative array
273b5b947d7SAndreas Gohr     */
274aa81d781SKlap-in    public function res2row($res, $rownum = 0) {
275aa81d781SKlap-in        return $this->adapter->res2row($res, $rownum);
276b5b947d7SAndreas Gohr    }
277b5b947d7SAndreas Gohr
278e7112ccbSAdrian Lang    /**
279aa81d781SKlap-in     * Return the first value from the first row.
280e7112ccbSAdrian Lang     */
281aa81d781SKlap-in    public function res2single($res) {
282aa81d781SKlap-in        return $this->adapter->res2single($res);
283e7112ccbSAdrian Lang    }
284fee3b689Sstretchyboy
285fee3b689Sstretchyboy    /**
286fee3b689Sstretchyboy     * fetch the next row as zero indexed array
287fee3b689Sstretchyboy     */
288aa81d781SKlap-in    public function res_fetch_array($res) {
289aa81d781SKlap-in        return $this->adapter->res_fetch_array($res);
29087fa2c18Sstretchyboy    }
291fee3b689Sstretchyboy
292fee3b689Sstretchyboy    /**
293fee3b689Sstretchyboy     * fetch the next row as assocative array
294fee3b689Sstretchyboy     */
295aa81d781SKlap-in    public function res_fetch_assoc($res) {
296aa81d781SKlap-in        return $this->adapter->res_fetch_assoc($res);
297fee3b689Sstretchyboy    }
298fee3b689Sstretchyboy
299fee3b689Sstretchyboy    /**
30078977d74SKlap-in     * Count the number of records in result
3013157674bSAndreas Gohr     *
302db58e525SKlap-in     * This function is really inperformant in PDO and should be avoided!
303fee3b689Sstretchyboy     */
304aa81d781SKlap-in    public function res2count($res) {
305aa81d781SKlap-in        return $this->adapter->res2count($res);
306fee3b689Sstretchyboy    }
30724a03f6cSstretchyboy
30824a03f6cSstretchyboy    /**
30924a03f6cSstretchyboy     * Count the number of records changed last time
31024a03f6cSstretchyboy     */
311aa81d781SKlap-in    public function countChanges($db, $res) {
312aa81d781SKlap-in        return $this->adapter->countChanges($db, $res);
313a1e6784eSAndreas Gohr    }
314a1e6784eSAndreas Gohr
315aa81d781SKlap-in}
316