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