]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PDO.php
Reformat code
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PDO.php
1 <?php
2
3 /*
4  * Copyright 2005 $ThePhpWikiProgrammingTeam
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * @author: Reini Urban
25  */
26
27 require_once 'lib/WikiDB/backend.php';
28
29 class WikiDB_backend_PDO
30     extends WikiDB_backend
31 {
32
33     function WikiDB_backend_PDO($dbparams)
34     {
35         $this->_dbparams = $dbparams;
36         if (strstr($dbparams['dsn'], "://")) { // pear DB syntax
37             $parsed = parseDSN($dbparams['dsn']);
38             $this->_parsedDSN = $parsed;
39             /* Need to convert the DSN
40              *    dbtype(dbsyntax)://username:password@protocol+hostspec/database?option=value&option2=value2
41              * to dbtype:option1=value1;option2=value2
42              * PDO passes the DSN verbatim to the driver. But we need to extract the username + password
43              * and cannot rely that the parseDSN keys have the same name as needed by the driver.
44              * e.g: odbc:DSN=SAMPLE;UID=db2inst1;PWD=ibmdb2, mysql:host=127.0.0.1;dbname=testdb
45              */
46             $driver = $parsed['phptype'];
47             unset($parsed['phptype']);
48             unset($parsed['dbsyntax']);
49             $dbparams['dsn'] = $driver . ":";
50             $this->_dbh->database = $parsed['database'];
51             // mysql needs to map database=>dbname, hostspec=>host. TODO for the others.
52             $dsnmap = array('mysql' => array('database' => 'dbname', 'hostspec' => 'host')
53             );
54             foreach (array('protocol', 'hostspec', 'port', 'socket', 'database') as $option) {
55                 if (!empty($parsed[$option])) {
56                     $optionname = (isset($dsnmap[$driver][$option]) and !isset($parsed[$optionname]))
57                         ? $dsnmap[$driver][$option]
58                         : $option;
59                     $dbparams['dsn'] .= ($optionname . "=" . $parsed[$option] . ";");
60                     unset($parsed[$optionname]);
61                 }
62                 unset($parsed[$option]);
63             }
64             unset($parsed['username']);
65             unset($parsed['password']);
66             // pass the rest verbatim to the driver.
67             foreach ($parsed as $option => $value) {
68                 $dbparams['dsn'] .= ($option . "=" . $value . ";");
69             }
70         } else {
71             list($driver, $dsn) = explode(":", $dbparams['dsn'], 2);
72             foreach (explode(";", trim($dsn)) as $pair) {
73                 if ($pair) {
74                     list($option, $value) = explode("=", $pair, 2);
75                     $this->_parsedDSN[$option] = $value;
76                 }
77             }
78             $this->_dbh->database = isset($this->_parsedDSN['database'])
79                 ? $this->_parsedDSN['database']
80                 : $this->_parsedDSN['dbname'];
81         }
82         if (empty($this->_parsedDSN['password'])) $this->_parsedDSN['password'] = '';
83
84         try {
85             // try to load it dynamically (unix only)
86             if (!loadPhpExtension("pdo_$driver")) {
87                 echo $GLOBALS['php_errormsg'], "<br>\n";
88                 trigger_error(sprintf("dl() problem: Required extension '%s' could not be loaded!",
89                         "pdo_$driver"),
90                     E_USER_WARNING);
91             }
92
93             // persistent is defined as DSN option, or with a config value.
94             //   phptype://username:password@hostspec/database?persistent=false
95             $this->_dbh = new PDO($dbparams['dsn'],
96                 $this->_parsedDSN['username'],
97                 $this->_parsedDSN['password'],
98                 array(PDO_ATTR_AUTOCOMMIT => true,
99                     PDO_ATTR_TIMEOUT => DATABASE_TIMEOUT,
100                     PDO_ATTR_PERSISTENT => !empty($parsed['persistent'])
101                         or DATABASE_PERSISTENT
102                 ));
103         } catch (PDOException $e) {
104             echo "<br>\nCan't connect to database: %s" . $e->getMessage();
105             if (DEBUG & _DEBUG_VERBOSE or DEBUG & _DEBUG_SQL) {
106                 echo "<br>\nDSN: '", $dbparams['dsn'], "'";
107                 echo "<br>\n_parsedDSN: '", print_r($this->_parsedDSN), "'";
108                 echo "<br>\nparsed: '", print_r($parsed), "'";
109             }
110             if (isset($dbparams['_tryroot_from_upgrade']))
111                 trigger_error(sprintf("Can't connect to database: %s", $e->getMessage()),
112                     E_USER_WARNING);
113             else
114                 exit();
115         }
116         if (DEBUG & _DEBUG_SQL) { // not yet implemented
117             $this->_dbh->debug = true;
118         }
119         $this->_dsn = $dbparams['dsn'];
120         $this->_dbh->databaseType = $driver;
121         $this->_dbh->setAttribute(PDO_ATTR_CASE, PDO_CASE_NATURAL);
122         // Use the faster FETCH_NUM, with some special ASSOC based exceptions.
123
124         $this->_hasTransactions = true;
125         try {
126             $this->_dbh->beginTransaction();
127         } catch (PDOException $e) {
128             $this->_hasTransactions = false;
129         }
130         $sth = $this->_dbh->prepare("SELECT version()");
131         $sth->execute();
132         $this->_serverinfo['version'] = $sth->fetchSingle();
133         $this->commit(); // required to match the try catch block above!
134
135         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
136         $this->_table_names
137             = array('page_tbl' => $prefix . 'page',
138             'version_tbl' => $prefix . 'version',
139             'link_tbl' => $prefix . 'link',
140             'recent_tbl' => $prefix . 'recent',
141             'nonempty_tbl' => $prefix . 'nonempty');
142         $page_tbl = $this->_table_names['page_tbl'];
143         $version_tbl = $this->_table_names['version_tbl'];
144         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
145             . "$page_tbl.hits hits";
146         $this->page_tbl_field_list = array('id', 'pagename', 'hits');
147         $this->version_tbl_fields = "$version_tbl.version AS version, "
148             . "$version_tbl.mtime AS mtime, "
149             . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
150             . "$version_tbl.versiondata AS versiondata";
151         $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
152             'versiondata');
153
154         $this->_expressions
155             = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
156             'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
157             'maxversion' => "MAX(version)",
158             'notempty' => "<>''",
159             'iscontent' => "$version_tbl.content<>''");
160         $this->_lock_count = 0;
161     }
162
163     function beginTransaction()
164     {
165         if ($this->_hasTransactions)
166             $this->_dbh->beginTransaction();
167     }
168
169     function commit()
170     {
171         if ($this->_hasTransactions)
172             $this->_dbh->commit();
173     }
174
175     function rollback()
176     {
177         if ($this->_hasTransactions)
178             $this->_dbh->rollback();
179     }
180
181     /* no result */
182     function query($sql)
183     {
184         $sth = $this->_dbh->prepare($sql);
185         return $sth->execute();
186     }
187
188     /* with one result row */
189     function getRow($sql)
190     {
191         $sth = $this->_dbh->prepare($sql);
192         if ($sth->execute())
193             return $sth->fetch(PDO_FETCH_BOTH);
194         else
195             return false;
196     }
197
198     /**
199      * Close database connection.
200      */
201     function close()
202     {
203         if (!$this->_dbh)
204             return;
205         if ($this->_lock_count) {
206             trigger_error("WARNING: database still locked " .
207                     '(lock_count = $this->_lock_count)' . "\n<br />",
208                 E_USER_WARNING);
209         }
210         $this->unlock(false, 'force');
211
212         unset($this->_dbh);
213     }
214
215     /*
216      * Fast test for wikipage.
217      */
218     function is_wiki_page($pagename)
219     {
220         $dbh = &$this->_dbh;
221         extract($this->_table_names);
222         $sth = $dbh->prepare("SELECT $page_tbl.id AS id"
223             . " FROM $nonempty_tbl, $page_tbl"
224             . " WHERE $nonempty_tbl.id=$page_tbl.id"
225             . "   AND pagename=?");
226         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
227         if ($sth->execute())
228             return $sth->fetchSingle();
229         else
230             return false;
231     }
232
233     function get_all_pagenames()
234     {
235         $dbh = &$this->_dbh;
236         extract($this->_table_names);
237         $sth = $dbh->exec("SELECT pagename"
238             . " FROM $nonempty_tbl, $page_tbl"
239             . " WHERE $nonempty_tbl.id=$page_tbl.id"
240             . " LIMIT 1");
241         return $sth->fetchAll(PDO_FETCH_NUM);
242     }
243
244     function numPages($filter = false, $exclude = '')
245     {
246         $dbh = &$this->_dbh;
247         extract($this->_table_names);
248         $sth = $dbh->exec("SELECT count(*)"
249             . " FROM $nonempty_tbl, $page_tbl"
250             . " WHERE $nonempty_tbl.id=$page_tbl.id");
251         return $sth->fetchSingle();
252     }
253
254     function increaseHitCount($pagename)
255     {
256         $dbh = &$this->_dbh;
257         $page_tbl = $this->_table_names['page_tbl'];
258         $sth = $dbh->prepare("UPDATE $page_tbl SET hits=hits+1"
259             . " WHERE pagename=?"
260             . " LIMIT 1");
261         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
262         $sth->execute();
263     }
264
265     /**
266      * Read page information from database.
267      */
268     function get_pagedata($pagename)
269     {
270         $dbh = &$this->_dbh;
271         $page_tbl = $this->_table_names['page_tbl'];
272         $sth = $dbh->prepare("SELECT id,pagename,hits,pagedata FROM $page_tbl"
273             . " WHERE pagename=? LIMIT 1");
274         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
275         $sth->execute();
276         $row = $sth->fetch(PDO_FETCH_NUM);
277         return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
278     }
279
280     function  _extract_page_data($data, $hits)
281     {
282         if (empty($data))
283             return array('hits' => $hits);
284         else
285             return array_merge(array('hits' => $hits), $this->_unserialize($data));
286     }
287
288     function update_pagedata($pagename, $newdata)
289     {
290         $dbh = &$this->_dbh;
291         $page_tbl = $this->_table_names['page_tbl'];
292
293         // Hits is the only thing we can update in a fast manner.
294         if (count($newdata) == 1 && isset($newdata['hits'])) {
295             // Note that this will fail silently if the page does not
296             // have a record in the page table.  Since it's just the
297             // hit count, who cares?
298             $sth = $dbh->prepare("UPDATE $page_tbl SET hits=? WHERE pagename=? LIMIT 1");
299             $sth->bindParam(1, $newdata['hits'], PDO_PARAM_INT);
300             $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
301             $sth->execute();
302             return;
303         }
304         $this->beginTransaction();
305         $data = $this->get_pagedata($pagename);
306         if (!$data) {
307             $data = array();
308             $this->_get_pageid($pagename, true); // Creates page record
309         }
310
311         $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
312         unset($data['hits']);
313
314         foreach ($newdata as $key => $val) {
315             if ($key == 'hits')
316                 $hits = (int)$val;
317             else if (empty($val))
318                 unset($data[$key]);
319             else
320                 $data[$key] = $val;
321         }
322         $sth = $dbh->prepare("UPDATE $page_tbl"
323             . " SET hits=?, pagedata=?"
324             . " WHERE pagename=?"
325             . " LIMIT 1");
326         $sth->bindParam(1, $hits, PDO_PARAM_INT);
327         $sth->bindParam(2, $this->_serialize($data), PDO_PARAM_LOB);
328         $sth->bindParam(3, $pagename, PDO_PARAM_STR, 100);
329         if ($sth->execute()) {
330             $this->commit();
331             return true;
332         } else {
333             $this->rollBack();
334             return false;
335         }
336     }
337
338     function get_cached_html($pagename)
339     {
340         $dbh = &$this->_dbh;
341         $page_tbl = $this->_table_names['page_tbl'];
342         $sth = $dbh->prepare("SELECT cached_html FROM $page_tbl WHERE pagename=? LIMIT 1");
343         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
344         $sth->execute();
345         return $sth->fetchSingle(PDO_FETCH_NUM);
346     }
347
348     function set_cached_html($pagename, $data)
349     {
350         $dbh = &$this->_dbh;
351         $page_tbl = $this->_table_names['page_tbl'];
352         if (empty($data)) $data = '';
353         $sth = $dbh->prepare("UPDATE $page_tbl"
354             . " SET cached_html=?"
355             . " WHERE pagename=?"
356             . " LIMIT 1");
357         $sth->bindParam(1, $data, PDO_PARAM_STR);
358         $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
359         $sth->execute();
360     }
361
362     function _get_pageid($pagename, $create_if_missing = false)
363     {
364         // check id_cache
365         global $request;
366         $cache =& $request->_dbi->_cache->_id_cache;
367         if (isset($cache[$pagename])) {
368             if ($cache[$pagename] or !$create_if_missing) {
369                 return $cache[$pagename];
370             }
371         }
372
373         // attributes play this game.
374         if ($pagename === '') return 0;
375
376         $dbh = &$this->_dbh;
377         $page_tbl = $this->_table_names['page_tbl'];
378         $sth = $dbh->prepare("SELECT id FROM $page_tbl WHERE pagename=? LIMIT 1");
379         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
380         $id = $sth->fetchSingle();
381         if (!$create_if_missing) {
382             return $id;
383         }
384         if (!$id) {
385             //mysql, mysqli or mysqlt
386             if (substr($dbh->databaseType, 0, 5) == 'mysql') {
387                 // have auto-incrementing, atomic version
388                 $sth = $dbh->prepare("INSERT INTO $page_tbl"
389                     . " (id,pagename)"
390                     . " VALUES (NULL,?)");
391                 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
392                 $sth->execute();
393                 $id = $dbh->lastInsertId();
394             } else {
395                 $this->beginTransaction();
396                 $sth = $dbh->prepare("SELECT MAX(id) FROM $page_tbl");
397                 $sth->execute();
398                 $id = $sth->fetchSingle();
399                 $sth = $dbh->prepare("INSERT INTO $page_tbl"
400                     . " (id,pagename,hits)"
401                     . " VALUES (?,?,0)");
402                 $id++;
403                 $sth->bindParam(1, $id, PDO_PARAM_INT);
404                 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
405                 if ($sth->execute())
406                     $this->commit();
407                 else
408                     $this->rollBack();
409             }
410         }
411         assert($id);
412         return $id;
413     }
414
415     function get_latest_version($pagename)
416     {
417         $dbh = &$this->_dbh;
418         extract($this->_table_names);
419         $sth = $dbh->prepare("SELECT latestversion"
420             . " FROM $page_tbl, $recent_tbl"
421             . " WHERE $page_tbl.id=$recent_tbl.id"
422             . "  AND pagename=?"
423             . " LIMIT 1");
424         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
425         $sth->execute();
426         return $sth->fetchSingle();
427     }
428
429     function get_previous_version($pagename, $version)
430     {
431         $dbh = &$this->_dbh;
432         extract($this->_table_names);
433         $sth = $dbh->prepare("SELECT version"
434             . " FROM $version_tbl, $page_tbl"
435             . " WHERE $version_tbl.id=$page_tbl.id"
436             . "  AND pagename=?"
437             . "  AND version < ?"
438             . " ORDER BY version DESC"
439             . " LIMIT 1");
440         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
441         $sth->bindParam(2, $version, PDO_PARAM_INT);
442         $sth->execute();
443         return $sth->fetchSingle();
444     }
445
446     /**
447      * Get version data.
448      *
449      * @param $version int Which version to get.
450      *
451      * @return hash The version data, or false if specified version does not
452      *              exist.
453      */
454     function get_versiondata($pagename, $version, $want_content = false)
455     {
456         $dbh = &$this->_dbh;
457         extract($this->_table_names);
458         extract($this->_expressions);
459
460         assert(is_string($pagename) and $pagename != '');
461         assert($version > 0);
462
463         // FIXME: optimization: sometimes don't get page data?
464         if ($want_content) {
465             $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
466                 . ', ' . $this->version_tbl_fields;
467         } else {
468             $fields = $this->page_tbl_fields . ", '' AS pagedata"
469                 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
470                 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
471                 . "$version_tbl.versiondata as versiondata";
472         }
473         $sth = $dbh->prepare("SELECT $fields"
474             . " FROM $page_tbl, $version_tbl"
475             . " WHERE $page_tbl.id=$version_tbl.id"
476             . "  AND pagename=?"
477             . "  AND version=?"
478             . " LIMIT 1");
479         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
480         $sth->bindParam(2, $version, PDO_PARAM_INT);
481         $sth->execute();
482         $row = $sth->fetch(PDO_FETCH_NUM);
483         return $row ? $this->_extract_version_data_num($row, $want_content) : false;
484     }
485
486     function _extract_version_data_num($row, $want_content)
487     {
488         if (!$row)
489             return false;
490
491         //$id       &= $row[0];
492         //$pagename &= $row[1];
493         $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
494         $data['mtime'] = $row[5];
495         $data['is_minor_edit'] = !empty($row[6]);
496         if ($want_content) {
497             $data['%content'] = $row[7];
498         } else {
499             $data['%content'] = !empty($row[7]);
500         }
501         if (!empty($row[3])) {
502             $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
503         }
504         return $data;
505     }
506
507     function _extract_version_data_assoc($row)
508     {
509         if (!$row)
510             return false;
511
512         extract($row);
513         $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
514         $data['mtime'] = $mtime;
515         $data['is_minor_edit'] = !empty($minor_edit);
516         if (isset($content))
517             $data['%content'] = $content;
518         elseif ($have_content)
519             $data['%content'] = true; else
520             $data['%content'] = '';
521         if (!empty($pagedata)) {
522             $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
523         }
524         return $data;
525     }
526
527     /**
528      * Create a new revision of a page.
529      */
530     function set_versiondata($pagename, $version, $data)
531     {
532         $dbh = &$this->_dbh;
533         $version_tbl = $this->_table_names['version_tbl'];
534
535         $minor_edit = (int)!empty($data['is_minor_edit']);
536         unset($data['is_minor_edit']);
537
538         $mtime = (int)$data['mtime'];
539         unset($data['mtime']);
540         assert(!empty($mtime));
541
542         @$content = (string)$data['%content'];
543         unset($data['%content']);
544         unset($data['%pagedata']);
545
546         $this->lock(array('page', 'recent', 'version', 'nonempty'));
547         $this->beginTransaction();
548         $id = $this->_get_pageid($pagename, true);
549         $backend_type = $this->backendType();
550         // optimize: mysql can do this with one REPLACE INTO.
551         if (substr($backend_type, 0, 5) == 'mysql') {
552             $sth = $dbh->prepare("REPLACE INTO $version_tbl"
553                 . " (id,version,mtime,minor_edit,content,versiondata)"
554                 . " VALUES(?,?,?,?,?,?)");
555             $sth->bindParam(1, $id, PDO_PARAM_INT);
556             $sth->bindParam(2, $version, PDO_PARAM_INT);
557             $sth->bindParam(3, $mtime, PDO_PARAM_INT);
558             $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
559             $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
560             $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
561             $rs = $sth->execute();
562         } else {
563             $sth = $dbh->prepare("DELETE FROM $version_tbl"
564                 . " WHERE id=? AND version=?");
565             $sth->bindParam(1, $id, PDO_PARAM_INT);
566             $sth->bindParam(2, $version, PDO_PARAM_INT);
567             $sth->execute();
568             $sth = $dbh->prepare("INSERT INTO $version_tbl"
569                 . " (id,version,mtime,minor_edit,content,versiondata)"
570                 . " VALUES(?,?,?,?,?,?)");
571             $sth->bindParam(1, $id, PDO_PARAM_INT);
572             $sth->bindParam(2, $version, PDO_PARAM_INT);
573             $sth->bindParam(3, $mtime, PDO_PARAM_INT);
574             $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
575             $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
576             $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
577             $rs = $sth->execute();
578         }
579         $this->_update_recent_table($id);
580         $this->_update_nonempty_table($id);
581         if ($rs) $this->commit();
582         else $this->rollBack();
583         $this->unlock(array('page', 'recent', 'version', 'nonempty'));
584     }
585
586     /**
587      * Delete an old revision of a page.
588      */
589     function delete_versiondata($pagename, $version)
590     {
591         $dbh = &$this->_dbh;
592         extract($this->_table_names);
593
594         $this->lock(array('version'));
595         if (($id = $this->_get_pageid($pagename))) {
596             $dbh->query("DELETE FROM $version_tbl"
597                 . " WHERE id=$id AND version=$version");
598             $this->_update_recent_table($id);
599             // This shouldn't be needed (as long as the latestversion
600             // never gets deleted.)  But, let's be safe.
601             $this->_update_nonempty_table($id);
602         }
603         $this->unlock(array('version'));
604     }
605
606     /**
607      * Delete page from the database with backup possibility.
608      * i.e save_page('') and DELETE nonempty id
609      *
610      * deletePage increments latestversion in recent to a non-existent version,
611      * and removes the nonempty row,
612      * so that get_latest_version returns id+1 and get_previous_version returns prev id
613      * and page->exists returns false.
614      */
615     function delete_page($pagename)
616     {
617         $dbh = &$this->_dbh;
618         extract($this->_table_names);
619
620         $this->beginTransaction();
621         //$dbh->CommitLock($recent_tbl);
622         if (($id = $this->_get_pageid($pagename, false)) === false) {
623             $this->rollback();
624             return false;
625         }
626         $mtime = time();
627         $user =& $GLOBALS['request']->_user;
628         $meta = array('author' => $user->getId(),
629             'author_id' => $user->getAuthenticatedId(),
630             'mtime' => $mtime);
631         $this->lock(array('version', 'recent', 'nonempty', 'page', 'link'));
632         $version = $this->get_latest_version($pagename);
633         if ($dbh->query("UPDATE $recent_tbl SET latestversion=latestversion+1,"
634             . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id")
635         ) {
636             $insert = $dbh->prepare("INSERT INTO $version_tbl"
637                 . " (id,version,mtime,minor_edit,content,versiondata)"
638                 . " VALUES(?,?,?,?,?,?)");
639             $insert->bindParam(1, $id, PDO_PARAM_INT);
640             $insert->bindParam(2, $version + 1, PDO_PARAM_INT);
641             $insert->bindParam(3, $mtime, PDO_PARAM_INT);
642             $insert->bindParam(4, 0, PDO_PARAM_INT);
643             $insert->bindParam(5, '', PDO_PARAM_STR, 100);
644             $insert->bindParam(6, $this->_serialize($meta), PDO_PARAM_STR, 100);
645             if ($insert->execute()
646                 and $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id")
647                     and $this->set_links($pagename, false)
648             ) {
649                 // need to keep perms and LOCKED, otherwise you can reset the perm
650                 // by action=remove and re-create it with default perms
651                 // keep hits but delete meta-data
652                 //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id")
653                 $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
654                 $this->commit();
655                 return true;
656             }
657         } else {
658             $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
659             $this->rollBack();
660             return false;
661         }
662     }
663
664     function purge_page($pagename)
665     {
666         $dbh = &$this->_dbh;
667         extract($this->_table_names);
668
669         $this->lock(array('version', 'recent', 'nonempty', 'page', 'link'));
670         if (($id = $this->_get_pageid($pagename, false))) {
671             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
672             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
673             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
674             $this->set_links($pagename, false);
675             $sth = $dbh->prepare("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
676             $sth->execute();
677             if ($sth->fetchSingle()) {
678                 // We're still in the link table (dangling link) so we can't delete this
679                 // altogether.
680                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
681                 $result = 0;
682             } else {
683                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
684                 $result = 1;
685             }
686         } else {
687             $result = -1; // already purged or not existing
688         }
689         $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
690         return $result;
691     }
692
693     // The only thing we might be interested in updating which we can
694     // do fast in the flags (minor_edit).   I think the default
695     // update_versiondata will work fine...
696     //function update_versiondata($pagename, $version, $data) {
697     //}
698
699     function set_links($pagename, $links)
700     {
701         // Update link table.
702         // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
703
704         $dbh = &$this->_dbh;
705         extract($this->_table_names);
706
707         $this->lock(array('link'));
708         $pageid = $this->_get_pageid($pagename, true);
709
710         if ($links) {
711             $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
712             foreach ($links as $link) {
713                 if (isset($linkseen[$link]))
714                     continue;
715                 $linkseen[$link] = true;
716                 $linkid = $this->_get_pageid($link, true);
717                 assert($linkid);
718                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
719                     . " VALUES ($pageid, $linkid)");
720             }
721         } elseif (DEBUG) {
722             // purge page table: delete all non-referenced pages
723             // for all previously linked pages...
724             $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl" .
725                 " WHERE linkfrom=$pageid");
726             $sth->execute();
727             foreach ($sth->fetchAll(PDO_FETCH_NUM) as $id) {
728                 // ...check if the page is empty and has no version
729                 $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl"
730                     . " LEFT JOIN $nonempty_tbl USING (id) "
731                     . " LEFT JOIN $version_tbl USING (id)"
732                     . " WHERE ISNULL($nonempty_tbl.id) AND"
733                     . " ISNULL($version_tbl.id) AND $page_tbl.id=$id");
734                 $sth1->execute();
735                 if ($sth1->fetchSingle()) {
736                     $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
737                     $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
738                 }
739             }
740             $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
741         }
742         $this->unlock(array('link'));
743         return true;
744     }
745
746     /**
747      * Find pages which link to or are linked from a page.
748      *
749      * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
750      * (linkExistingWikiWord or linkUnknownWikiWord)
751      * This is called on every page header GleanDescription, so we can store all the existing links.
752      */
753     function get_links($pagename, $reversed = true, $include_empty = false,
754                        $sortby = '', $limit = '', $exclude = '')
755     {
756         $dbh = &$this->_dbh;
757         extract($this->_table_names);
758
759         if ($reversed)
760             list($have, $want) = array('linkee', 'linker');
761         else
762             list($have, $want) = array('linker', 'linkee');
763         $orderby = $this->sortby($sortby, 'db', array('pagename'));
764         if ($orderby) $orderby = " ORDER BY $want." . $orderby;
765         if ($exclude) // array of pagenames
766             $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude);
767         else
768             $exclude = '';
769         $limit = $this->_limit_sql($limit);
770
771         $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename,"
772             . " $want.hits AS hits"
773             . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
774             . (!$include_empty ? ", $nonempty_tbl" : '')
775             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
776             . " AND $have.pagename=?"
777             . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
778             //. " GROUP BY $want.id"
779             . $exclude
780             . $orderby
781             . $limit);
782         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
783         $sth->execute();
784         $result = $sth->fetch(PDO_FETCH_BOTH);
785         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
786     }
787
788     /**
789      * Find if a page links to another page
790      */
791     function exists_link($pagename, $link, $reversed = false)
792     {
793         $dbh = &$this->_dbh;
794         extract($this->_table_names);
795
796         if ($reversed)
797             list($have, $want) = array('linkee', 'linker');
798         else
799             list($have, $want) = array('linker', 'linkee');
800         $sth = $dbh->prepare("SELECT CASE WHEN $want.pagename THEN 1 ELSE 0 END"
801             . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
802             . " WHERE linkfrom=linker.id AND linkto=linkee.id"
803             . " AND $have.pagename=?"
804             . " AND $want.pagename=?");
805         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
806         $sth->bindParam(2, $link, PDO_PARAM_STR, 100);
807         $sth->execute();
808         return $sth->fetchSingle();
809     }
810
811     function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
812     {
813         $dbh = &$this->_dbh;
814         extract($this->_table_names);
815         $orderby = $this->sortby($sortby, 'db');
816         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
817         if ($exclude) // array of pagenames
818             $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
819         else
820             $exclude = '';
821         $limit = $this->_limit_sql($limit);
822
823         if (strstr($orderby, 'mtime ')) { // was ' mtime'
824             if ($include_empty) {
825                 $sql = "SELECT "
826                     . $this->page_tbl_fields
827                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
828                     . " WHERE $page_tbl.id=$recent_tbl.id"
829                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
830                     . $exclude
831                     . $orderby;
832             } else {
833                 $sql = "SELECT "
834                     . $this->page_tbl_fields
835                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
836                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
837                     . " AND $page_tbl.id=$recent_tbl.id"
838                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
839                     . $exclude
840                     . $orderby;
841             }
842         } else {
843             if ($include_empty) {
844                 $sql = "SELECT "
845                     . $this->page_tbl_fields
846                     . " FROM $page_tbl"
847                     . ($exclude ? " WHERE $exclude" : '')
848                     . $orderby;
849             } else {
850                 $sql = "SELECT "
851                     . $this->page_tbl_fields
852                     . " FROM $nonempty_tbl, $page_tbl"
853                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
854                     . $exclude
855                     . $orderby;
856             }
857         }
858         $sth = $dbh->prepare($sql . $limit);
859         $sth->execute();
860         $result = $sth->fetch(PDO_FETCH_BOTH);
861         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
862     }
863
864     /**
865      * Title search.
866      */
867     function text_search($search, $fullsearch = false, $sortby = '', $limit = '', $exclude = '')
868     {
869         $dbh = &$this->_dbh;
870         extract($this->_table_names);
871         $orderby = $this->sortby($sortby, 'db');
872         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
873         $limit = $this->_limit_sql($limit);
874
875         $table = "$nonempty_tbl, $page_tbl";
876         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
877         $fields = $this->page_tbl_fields;
878         $field_list = $this->page_tbl_field_list;
879         $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
880
881         if ($fullsearch) {
882             $table .= ", $recent_tbl";
883             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
884
885             $table .= ", $version_tbl";
886             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
887
888             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
889             $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
890             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
891         } else {
892             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
893         }
894
895         $search_clause = $search->makeSqlClauseObj($callback);
896         $sth = $dbh->prepare("SELECT $fields FROM $table"
897             . " WHERE $join_clause"
898             . " AND ($search_clause)"
899             . $orderby
900             . $limit);
901         $sth->execute();
902         $result = $sth->fetch(PDO_FETCH_NUM);
903         $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list);
904         $iter->stoplisted = $searchobj->stoplisted;
905         return $iter;
906     }
907
908     /*
909      * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
910      *       not sets. See above, but the above methods find too much.
911      * This is only for already resolved wildcards:
912      * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
913      */
914     function _sql_set(&$pagenames)
915     {
916         $s = '(';
917         foreach ($pagenames as $p) {
918             $s .= ($this->_dbh->qstr($p) . ",");
919         }
920         return substr($s, 0, -1) . ")";
921     }
922
923     /**
924      * Find highest or lowest hit counts.
925      */
926     function most_popular($limit = 20, $sortby = '-hits')
927     {
928         $dbh = &$this->_dbh;
929         extract($this->_table_names);
930         $order = "DESC";
931         if ($limit < 0) {
932             $order = "ASC";
933             $limit = -$limit;
934             $where = "";
935         } else {
936             $where = " AND hits > 0";
937         }
938         if ($sortby != '-hits') {
939             if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
940             else $orderby = "";
941         } else
942             $orderby = " ORDER BY hits $order";
943         $sql = "SELECT "
944             . $this->page_tbl_fields
945             . " FROM $nonempty_tbl, $page_tbl"
946             . " WHERE $nonempty_tbl.id=$page_tbl.id"
947             . $where
948             . $orderby;
949         if ($limit) {
950             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
951         } else {
952             $sth = $dbh->prepare($sql);
953         }
954         $sth->execute();
955         $result = $sth->fetch(PDO_FETCH_NUM);
956         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
957     }
958
959     /**
960      * Find recent changes.
961      */
962     function most_recent($params)
963     {
964         $limit = 0;
965         $since = 0;
966         $include_minor_revisions = false;
967         $exclude_major_revisions = false;
968         $include_all_revisions = false;
969         extract($params);
970
971         $dbh = &$this->_dbh;
972         extract($this->_table_names);
973
974         $pick = array();
975         if ($since)
976             $pick[] = "mtime >= $since";
977
978         if ($include_all_revisions) {
979             // Include all revisions of each page.
980             $table = "$page_tbl, $version_tbl";
981             $join_clause = "$page_tbl.id=$version_tbl.id";
982
983             if ($exclude_major_revisions) {
984                 // Include only minor revisions
985                 $pick[] = "minor_edit <> 0";
986             } elseif (!$include_minor_revisions) {
987                 // Include only major revisions
988                 $pick[] = "minor_edit = 0";
989             }
990         } else {
991             $table = "$page_tbl, $recent_tbl";
992             $join_clause = "$page_tbl.id=$recent_tbl.id";
993             $table .= ", $version_tbl";
994             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
995
996             if ($exclude_major_revisions) {
997                 // Include only most recent minor revision
998                 $pick[] = 'version=latestminor';
999             } elseif (!$include_minor_revisions) {
1000                 // Include only most recent major revision
1001                 $pick[] = 'version=latestmajor';
1002             } else {
1003                 // Include only the latest revision (whether major or minor).
1004                 $pick[] = 'version=latestversion';
1005             }
1006         }
1007         $order = "DESC";
1008         if ($limit < 0) {
1009             $order = "ASC";
1010             $limit = -$limit;
1011         }
1012         $where_clause = $join_clause;
1013         if ($pick)
1014             $where_clause .= " AND " . join(" AND ", $pick);
1015         $sql = "SELECT "
1016             . $this->page_tbl_fields . ", " . $this->version_tbl_fields
1017             . " FROM $table"
1018             . " WHERE $where_clause"
1019             . " ORDER BY mtime $order";
1020         if ($limit) {
1021             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1022         } else {
1023             $sth = $dbh->prepare($sql);
1024         }
1025         $sth->execute();
1026         $result = $sth->fetch(PDO_FETCH_NUM);
1027         return new WikiDB_backend_PDO_iter($this, $result,
1028             array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1029     }
1030
1031     /**
1032      * Find referenced empty pages.
1033      */
1034     function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
1035     {
1036         $dbh = &$this->_dbh;
1037         extract($this->_table_names);
1038         if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom')))
1039             $orderby = 'ORDER BY ' . $orderby;
1040
1041         if ($exclude_from) // array of pagenames
1042             $exclude_from = " AND linked.pagename NOT IN " . $this->_sql_set($exclude_from);
1043         if ($exclude) // array of pagenames
1044             $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
1045
1046         /*
1047          all empty pages, independent of linkstatus:
1048            select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1049          only all empty pages, which have a linkto:
1050            select page.pagename, linked.pagename as wantedfrom from link, page as linked
1051              left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1052              where isnull(nonempty.id) and linked.id=link.linkfrom;
1053         */
1054         $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1055             . " FROM $page_tbl p JOIN $link_tbl linked"
1056             . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
1057             . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
1058             . " WHERE ne.id is NULL"
1059             . " AND p.id = linked.linkfrom"
1060             . $exclude_from
1061             . $exclude
1062             . $orderby;
1063         if ($limit) {
1064             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1065         } else {
1066             $sth = $dbh->prepare($sql);
1067         }
1068         $sth->execute();
1069         $result = $sth->fetch(PDO_FETCH_NUM);
1070         return new WikiDB_backend_PDO_iter($this, $result, array('pagename', 'wantedfrom'));
1071     }
1072
1073     /**
1074      * Rename page in the database.
1075      */
1076     function rename_page($pagename, $to)
1077     {
1078         $dbh = &$this->_dbh;
1079         extract($this->_table_names);
1080
1081         $this->lock(array('page', 'version', 'recent', 'nonempty', 'link'));
1082         if (($id = $this->_get_pageid($pagename, false))) {
1083             if ($new = $this->_get_pageid($to, false)) {
1084                 // Cludge Alert!
1085                 // This page does not exist (already verified before), but exists in the page table.
1086                 // So we delete this page.
1087                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1088                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1089                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1090                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1091                 // We have to fix all referring tables to the old id
1092                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1093                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1094             }
1095             $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1096             $sth->bindParam(1, $to, PDO_PARAM_STR, 100);
1097             $sth->bindParam(2, $id, PDO_PARAM_INT);
1098             $sth->execute();
1099         }
1100         $this->unlock(array('page'));
1101         return $id;
1102     }
1103
1104     function _update_recent_table($pageid = false)
1105     {
1106         $dbh = &$this->_dbh;
1107         extract($this->_table_names);
1108         extract($this->_expressions);
1109
1110         $pageid = (int)$pageid;
1111
1112         // optimize: mysql can do this with one REPLACE INTO.
1113         $backend_type = $this->backendType();
1114         if (substr($backend_type, 0, 5) == 'mysql') {
1115             $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1116                 . " (id, latestversion, latestmajor, latestminor)"
1117                 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1118                 . " FROM $version_tbl"
1119                 . ($pageid ? " WHERE id=$pageid" : "")
1120                 . " GROUP BY id");
1121             $sth->execute();
1122         } else {
1123             $this->lock(array('recent'));
1124             $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1125                 . ($pageid ? " WHERE id=$pageid" : ""));
1126             $sth->execute();
1127             $sth = $dbh->prepare("INSERT INTO $recent_tbl"
1128                 . " (id, latestversion, latestmajor, latestminor)"
1129                 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1130                 . " FROM $version_tbl"
1131                 . ($pageid ? " WHERE id=$pageid" : "")
1132                 . " GROUP BY id");
1133             $sth->execute();
1134             $this->unlock(array('recent'));
1135         }
1136     }
1137
1138     function _update_nonempty_table($pageid = false)
1139     {
1140         $dbh = &$this->_dbh;
1141         extract($this->_table_names);
1142         extract($this->_expressions);
1143
1144         $pageid = (int)$pageid;
1145
1146         extract($this->_expressions);
1147         $this->lock(array('nonempty'));
1148         $dbh->query("DELETE FROM $nonempty_tbl"
1149             . ($pageid ? " WHERE id=$pageid" : ""));
1150         $dbh->query("INSERT INTO $nonempty_tbl (id)"
1151             . " SELECT $recent_tbl.id"
1152             . " FROM $recent_tbl, $version_tbl"
1153             . " WHERE $recent_tbl.id=$version_tbl.id"
1154             . "       AND version=latestversion"
1155             // We have some specifics here (Oracle)
1156             //. "  AND content<>''"
1157             . "  AND content $notempty"
1158             . ($pageid ? " AND $recent_tbl.id=$pageid" : ""));
1159         $this->unlock(array('nonempty'));
1160     }
1161
1162     /**
1163      * Grab a write lock on the tables in the SQL database.
1164      *
1165      * Calls can be nested.  The tables won't be unlocked until
1166      * _unlock_database() is called as many times as _lock_database().
1167      *
1168      * @access protected
1169      */
1170     function lock($tables, $write_lock = true)
1171     {
1172         if ($this->_lock_count++ == 0) {
1173             $this->_current_lock = $tables;
1174             if (!$this->_hasTransactions)
1175                 $this->_lock_tables($tables, $write_lock);
1176         }
1177     }
1178
1179     /**
1180      * Overridden by non-transaction safe backends.
1181      */
1182     function _lock_tables($tables, $write_lock)
1183     {
1184         $lock_type = $write_lock ? "WRITE" : "READ";
1185         foreach ($this->_table_names as $key => $table) {
1186             $locks[] = "$table $lock_type";
1187         }
1188         $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1189     }
1190
1191     /**
1192      * Release a write lock on the tables in the SQL database.
1193      *
1194      * @access protected
1195      *
1196      * @param $force boolean Unlock even if not every call to lock() has been matched
1197      * by a call to unlock().
1198      *
1199      * @see _lock_database
1200      */
1201     function unlock($tables = false, $force = false)
1202     {
1203         if ($this->_lock_count == 0) {
1204             $this->_current_lock = false;
1205             return;
1206         }
1207         if (--$this->_lock_count <= 0 || $force) {
1208             if (!$this->_hasTransactions)
1209                 $this->_unlock_tables($tables);
1210             $this->_current_lock = false;
1211             $this->_lock_count = 0;
1212         }
1213     }
1214
1215     /**
1216      * overridden by non-transaction safe backends
1217      */
1218     function _unlock_tables($tables)
1219     {
1220         $this->_dbh->query("UNLOCK TABLES");
1221     }
1222
1223     /**
1224      * Serialize data
1225      */
1226     function _serialize($data)
1227     {
1228         if (empty($data))
1229             return '';
1230         assert(is_array($data));
1231         return serialize($data);
1232     }
1233
1234     /**
1235      * Unserialize data
1236      */
1237     function _unserialize($data)
1238     {
1239         return empty($data) ? array() : unserialize($data);
1240     }
1241
1242     /* some variables and functions for DB backend abstraction (action=upgrade) */
1243     function database()
1244     {
1245         return $this->_dbh->database;
1246     }
1247
1248     function backendType()
1249     {
1250         return $this->_dbh->databaseType;
1251     }
1252
1253     function connection()
1254     {
1255         trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1256         return false;
1257     }
1258
1259     function listOfTables()
1260     {
1261         trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1262         return array();
1263     }
1264
1265     function listOfFields($database, $table)
1266     {
1267         trigger_error("PDO: virtual listOfFields", E_USER_ERROR);
1268         return array();
1269     }
1270
1271     /*
1272      * LIMIT with OFFSET is not SQL specified.
1273      *   mysql: LIMIT $offset, $count
1274      *   pgsql,sqlite: LIMIT $count OFFSET $offset
1275      *   InterBase,FireBird: ROWS $offset TO $last
1276      *   mssql: TOP $rows => TOP $last
1277      *   oci8: ROWNUM
1278      *   IBM DB2: FetchFirst
1279      * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1280
1281      SELECT field_list FROM $table X WHERE where_clause AND
1282      (
1283          SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1284      )
1285      BETWEEN $offset AND $last
1286      ORDER BY $pk $asc_desc
1287      */
1288     function _limit_sql($limit = false)
1289     {
1290         if ($limit) {
1291             list($offset, $count) = $this->limit($limit);
1292             if ($offset) {
1293                 $limit = " LIMIT $count";
1294                 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1295             } else
1296                 $limit = " LIMIT $count";
1297         } else
1298             $limit = '';
1299         return $limit;
1300     }
1301
1302     function write_accesslog(&$entry)
1303     {
1304         global $request;
1305         $dbh = &$this->_dbh;
1306         $log_tbl = $entry->_accesslog->logtable;
1307         $dbh->prepare("INSERT INTO $log_tbl"
1308             . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args,"
1309             . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)"
1310             . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
1311         // Either use unixtime as %d (long), or the native timestamp format.
1312         $sth->bindParam(1, $entry->time, PDO_PARAM_INT);
1313         $sth->bindParam(2, $entry->host, PDO_PARAM_STR, 100);
1314         $sth->bindParam(3, $entry->user, PDO_PARAM_STR, 50);
1315         $sth->bindParam(4, $entry->request_method, PDO_PARAM_STR, 10);
1316         $sth->bindParam(5, $entry->request, PDO_PARAM_STR, 255);
1317         $sth->bindParam(6, $entry->request_args, PDO_PARAM_STR, 255);
1318         $sth->bindParam(7, $entry->request_uri, PDO_PARAM_STR, 255);
1319         $sth->bindParam(8, $entry->_ncsa_time($entry->time), PDO_PARAM_STR, 28);
1320         $sth->bindParam(9, $entry->time, PDO_PARAM_INT);
1321         $sth->bindParam(10, $entry->status, PDO_PARAM_INT);
1322         $sth->bindParam(11, $entry->size, PDO_PARAM_INT);
1323         $sth->bindParam(12, $entry->referer, PDO_PARAM_STR, 255);
1324         $sth->bindParam(13, $entry->user_agent, PDO_PARAM_STR, 255);
1325         $sth->bindParam(14, $entry->duration, PDO_PARAM_FLOAT);
1326         $sth->execute();
1327     }
1328 }
1329
1330 ;
1331
1332 class WikiDB_backend_PDO_generic_iter
1333     extends WikiDB_backend_iterator
1334 {
1335     function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL)
1336     {
1337         $this->_backend = &$backend;
1338         $this->_result = $query_result;
1339         //$this->_fields = $field_list;
1340     }
1341
1342     function count()
1343     {
1344         if (!is_object($this->_result)) {
1345             return false;
1346         }
1347         $count = $this->_result->rowCount();
1348         return $count;
1349     }
1350
1351     function next()
1352     {
1353         $result = &$this->_result;
1354         if (!is_object($result)) {
1355             return false;
1356         }
1357         return $result->fetch(PDO_FETCH_BOTH);
1358     }
1359
1360     function free()
1361     {
1362         if ($this->_result) {
1363             unset($this->_result);
1364         }
1365     }
1366 }
1367
1368 class WikiDB_backend_PDO_iter
1369     extends WikiDB_backend_PDO_generic_iter
1370 {
1371     function next()
1372     {
1373         $result = &$this->_result;
1374         if (!is_object($result)) {
1375             return false;
1376         }
1377         $this->_backend = &$backend;
1378         $rec = $result->fetch(PDO_FETCH_ASSOC);
1379
1380         if (isset($rec['pagedata']))
1381             $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1382         if (!empty($rec['version'])) {
1383             $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1384         }
1385         return $rec;
1386     }
1387 }
1388
1389 class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql
1390 {
1391 }
1392
1393 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1394 // Eventually, change index.php to provide the relevant information
1395 // directly?
1396 /**
1397  * Parse a data source name.
1398  *
1399  * Additional keys can be added by appending a URI query string to the
1400  * end of the DSN.
1401  *
1402  * The format of the supplied DSN is in its fullest form:
1403  * <code>
1404  *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1405  * </code>
1406  *
1407  * Most variations are allowed:
1408  * <code>
1409  *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1410  *  phptype://username:password@hostspec/database_name
1411  *  phptype://username:password@hostspec
1412  *  phptype://username@hostspec
1413  *  phptype://hostspec/database
1414  *  phptype://hostspec
1415  *  phptype(dbsyntax)
1416  *  phptype
1417  * </code>
1418  *
1419  * @param string $dsn Data Source Name to be parsed
1420  *
1421  * @return array an associative array with the following keys:
1422  *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1423  *  + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1424  *  + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1425  *  + hostspec: Host specification (hostname[:port])
1426  *  + database: Database to use on the DBMS server
1427  *  + username: User name for login
1428  *  + password: Password for login
1429  *
1430  * @author Tomas V.V.Cox <cox@idecnet.com>
1431  */
1432 function parseDSN($dsn)
1433 {
1434     $parsed = array(
1435         'phptype' => false,
1436         'dbsyntax' => false,
1437         'username' => false,
1438         'password' => false,
1439         'protocol' => false,
1440         'hostspec' => false,
1441         'port' => false,
1442         'socket' => false,
1443         'database' => false,
1444     );
1445
1446     if (is_array($dsn)) {
1447         $dsn = array_merge($parsed, $dsn);
1448         if (!$dsn['dbsyntax']) {
1449             $dsn['dbsyntax'] = $dsn['phptype'];
1450         }
1451         return $dsn;
1452     }
1453
1454     // Find phptype and dbsyntax
1455     if (($pos = strpos($dsn, '://')) !== false) {
1456         $str = substr($dsn, 0, $pos);
1457         $dsn = substr($dsn, $pos + 3);
1458     } else {
1459         $str = $dsn;
1460         $dsn = null;
1461     }
1462
1463     // Get phptype and dbsyntax
1464     // $str => phptype(dbsyntax)
1465     if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1466         $parsed['phptype'] = $arr[1];
1467         $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1468     } else {
1469         $parsed['phptype'] = $str;
1470         $parsed['dbsyntax'] = $str;
1471     }
1472
1473     if (!count($dsn)) {
1474         return $parsed;
1475     }
1476
1477     // Get (if found): username and password
1478     // $dsn => username:password@protocol+hostspec/database
1479     if (($at = strrpos($dsn, '@')) !== false) {
1480         $str = substr($dsn, 0, $at);
1481         $dsn = substr($dsn, $at + 1);
1482         if (($pos = strpos($str, ':')) !== false) {
1483             $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1484             $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1485         } else {
1486             $parsed['username'] = rawurldecode($str);
1487         }
1488     }
1489
1490     // Find protocol and hostspec
1491
1492     // $dsn => proto(proto_opts)/database
1493     if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1494         $proto = $match[1];
1495         $proto_opts = $match[2] ? $match[2] : false;
1496         $dsn = $match[3];
1497
1498         // $dsn => protocol+hostspec/database (old format)
1499     } else {
1500         if (strpos($dsn, '+') !== false) {
1501             list($proto, $dsn) = explode('+', $dsn, 2);
1502         }
1503         if (strpos($dsn, '/') !== false) {
1504             list($proto_opts, $dsn) = explode('/', $dsn, 2);
1505         } else {
1506             $proto_opts = $dsn;
1507             $dsn = null;
1508         }
1509     }
1510
1511     // process the different protocol options
1512     $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1513     $proto_opts = rawurldecode($proto_opts);
1514     if ($parsed['protocol'] == 'tcp') {
1515         if (strpos($proto_opts, ':') !== false) {
1516             list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1517         } else {
1518             $parsed['hostspec'] = $proto_opts;
1519         }
1520     } elseif ($parsed['protocol'] == 'unix') {
1521         $parsed['socket'] = $proto_opts;
1522     }
1523
1524     // Get dabase if any
1525     // $dsn => database
1526     if ($dsn) {
1527         // /database
1528         if (($pos = strpos($dsn, '?')) === false) {
1529             $parsed['database'] = $dsn;
1530             // /database?param1=value1&param2=value2
1531         } else {
1532             $parsed['database'] = substr($dsn, 0, $pos);
1533             $dsn = substr($dsn, $pos + 1);
1534             if (strpos($dsn, '&') !== false) {
1535                 $opts = explode('&', $dsn);
1536             } else { // database?param1=value1
1537                 $opts = array($dsn);
1538             }
1539             foreach ($opts as $opt) {
1540                 list($key, $value) = explode('=', $opt);
1541                 if (!isset($parsed[$key])) {
1542                     // don't allow params overwrite
1543                     $parsed[$key] = rawurldecode($value);
1544                 }
1545             }
1546         }
1547     }
1548
1549     return $parsed;
1550 }
1551
1552 // Local Variables:
1553 // mode: php
1554 // tab-width: 8
1555 // c-basic-offset: 4
1556 // c-hanging-comment-ender-p: nil
1557 // indent-tabs-mode: nil
1558 // End: