]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PDO.php
Remove rcs_id
[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
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
668     // The only thing we might be interested in updating which we can
669     // do fast in the flags (minor_edit).   I think the default
670     // update_versiondata will work fine...
671     //function update_versiondata($pagename, $version, $data) {
672     //}
673
674     function set_links($pagename, $links) {
675         // Update link table.
676         // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
677
678         $dbh = &$this->_dbh;
679         extract($this->_table_names);
680
681         $this->lock(array('link'));
682         $pageid = $this->_get_pageid($pagename, true);
683
684         if ($links) {
685             $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
686             foreach ($links as $link) {
687                 if (isset($linkseen[$link]))
688                     continue;
689                 $linkseen[$link] = true;
690                 $linkid = $this->_get_pageid($link, true);
691                 assert($linkid);
692                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
693                             . " VALUES ($pageid, $linkid)");
694             }
695         } elseif (DEBUG) {
696             // purge page table: delete all non-referenced pages
697             // for all previously linked pages...
698             $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl".
699                                  " WHERE linkfrom=$pageid");
700             $sth->execute();
701             foreach ($sth->fetchAll(PDO_FETCH_NUM) as $id) {
702                 // ...check if the page is empty and has no version
703                 $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl"
704                                       . " LEFT JOIN $nonempty_tbl USING (id) "
705                                       . " LEFT JOIN $version_tbl USING (id)"
706                                       . " WHERE ISNULL($nonempty_tbl.id) AND"
707                                       . " ISNULL($version_tbl.id) AND $page_tbl.id=$id");
708                 $sth1->execute();
709                 if ($sth1->fetchSingle()) {
710                     $dbh->query("DELETE FROM $page_tbl WHERE id=$id");   // this purges the link
711                     $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
712                 }
713             }
714             $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
715         }
716         $this->unlock(array('link'));
717         return true;
718     }
719
720     /**
721      * Find pages which link to or are linked from a page.
722      *
723      * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
724      * (linkExistingWikiWord or linkUnknownWikiWord)
725      * This is called on every page header GleanDescription, so we can store all the existing links.
726      */
727     function get_links($pagename, $reversed=true, $include_empty=false,
728                        $sortby='', $limit='', $exclude='') {
729         $dbh = &$this->_dbh;
730         extract($this->_table_names);
731
732         if ($reversed)
733             list($have,$want) = array('linkee', 'linker');
734         else
735             list($have,$want) = array('linker', 'linkee');
736         $orderby = $this->sortby($sortby, 'db', array('pagename'));
737         if ($orderby) $orderby = " ORDER BY $want." . $orderby;
738         if ($exclude) // array of pagenames
739             $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
740         else
741             $exclude='';
742         $limit = $this->_limit_sql($limit);
743
744         $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename,"
745                              . " $want.hits AS hits"
746                              . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
747                              . (!$include_empty ? ", $nonempty_tbl" : '')
748                              . " WHERE linkfrom=linker.id AND linkto=linkee.id"
749                              . " AND $have.pagename=?"
750                              . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
751                              //. " GROUP BY $want.id"
752                              . $exclude
753                              . $orderby
754                              . $limit);
755         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
756         $sth->execute();
757         $result = $sth->fetch(PDO_FETCH_BOTH);
758         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
759     }
760
761     /**
762      * Find if a page links to another page
763      */
764     function exists_link($pagename, $link, $reversed=false) {
765         $dbh = &$this->_dbh;
766         extract($this->_table_names);
767
768         if ($reversed)
769             list($have, $want) = array('linkee', 'linker');
770         else
771             list($have, $want) = array('linker', 'linkee');
772         $sth = $dbh->prepare("SELECT CASE WHEN $want.pagename THEN 1 ELSE 0 END"
773                              . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
774                              . " WHERE linkfrom=linker.id AND linkto=linkee.id"
775                              . " AND $have.pagename=?"
776                              . " AND $want.pagename=?");
777         $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
778         $sth->bindParam(2, $link, PDO_PARAM_STR, 100);
779         $sth->execute();
780         return $sth->fetchSingle();
781     }
782
783     function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
784         $dbh = &$this->_dbh;
785         extract($this->_table_names);
786         $orderby = $this->sortby($sortby, 'db');
787         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
788         if ($exclude) // array of pagenames
789             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
790         else
791             $exclude='';
792         $limit = $this->_limit_sql($limit);
793
794         if (strstr($orderby, 'mtime ')) { // was ' mtime'
795             if ($include_empty) {
796                 $sql = "SELECT "
797                     . $this->page_tbl_fields
798                     ." FROM $page_tbl, $recent_tbl, $version_tbl"
799                     . " WHERE $page_tbl.id=$recent_tbl.id"
800                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
801                     . $exclude
802                     . $orderby;
803             }
804             else {
805                 $sql = "SELECT "
806                     . $this->page_tbl_fields
807                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
808                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
809                     . " AND $page_tbl.id=$recent_tbl.id"
810                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
811                     . $exclude
812                     . $orderby;
813             }
814         } else {
815             if ($include_empty) {
816                 $sql = "SELECT "
817                     . $this->page_tbl_fields
818                     . " FROM $page_tbl"
819                     . ($exclude ? " WHERE $exclude" : '')
820                     . $orderby;
821             } else {
822                 $sql = "SELECT "
823                     . $this->page_tbl_fields
824                     . " FROM $nonempty_tbl, $page_tbl"
825                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
826                     . $exclude
827                     . $orderby;
828             }
829         }
830         $sth = $dbh->prepare($sql . $limit);
831         $sth->execute();
832         $result = $sth->fetch(PDO_FETCH_BOTH);
833         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
834     }
835
836     /**
837      * Title search.
838      */
839     function text_search($search, $fullsearch=false, $sortby='', $limit='', $exclude='') {
840         $dbh = &$this->_dbh;
841         extract($this->_table_names);
842         $orderby = $this->sortby($sortby, 'db');
843         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
844         $limit = $this->_limit_sql($limit);
845
846         $table = "$nonempty_tbl, $page_tbl";
847         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
848         $fields = $this->page_tbl_fields;
849         $field_list = $this->page_tbl_field_list;
850         $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
851
852         if ($fullsearch) {
853             $table .= ", $recent_tbl";
854             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
855
856             $table .= ", $version_tbl";
857             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
858
859             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
860             $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
861             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
862         } else {
863             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
864         }
865
866         $search_clause = $search->makeSqlClauseObj($callback);
867         $sth = $dbh->prepare("SELECT $fields FROM $table"
868                              . " WHERE $join_clause"
869                              . " AND ($search_clause)"
870                              . $orderby
871                              . $limit);
872         $sth->execute();
873         $result = $sth->fetch(PDO_FETCH_NUM);
874         $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list);
875         $iter->stoplisted = $searchobj->stoplisted;
876         return $iter;
877     }
878
879     /*
880      * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
881      *       not sets. See above, but the above methods find too much.
882      * This is only for already resolved wildcards:
883      * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
884      */
885     function _sql_set(&$pagenames) {
886         $s = '(';
887         foreach ($pagenames as $p) {
888             $s .= ($this->_dbh->qstr($p).",");
889         }
890         return substr($s,0,-1).")";
891     }
892
893     /**
894      * Find highest or lowest hit counts.
895      */
896     function most_popular($limit=20, $sortby='-hits') {
897         $dbh = &$this->_dbh;
898         extract($this->_table_names);
899         $order = "DESC";
900         if ($limit < 0){
901             $order = "ASC";
902             $limit = -$limit;
903             $where = "";
904         } else {
905             $where = " AND hits > 0";
906         }
907         if ($sortby != '-hits') {
908             if ($order = $this->sortby($sortby, 'db'))  $orderby = " ORDER BY " . $order;
909             else $orderby = "";
910         } else
911             $orderby = " ORDER BY hits $order";
912         $sql = "SELECT "
913             . $this->page_tbl_fields
914             . " FROM $nonempty_tbl, $page_tbl"
915             . " WHERE $nonempty_tbl.id=$page_tbl.id"
916             . $where
917             . $orderby;
918         if ($limit) {
919             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
920         } else {
921             $sth = $dbh->prepare($sql);
922         }
923         $sth->execute();
924         $result = $sth->fetch(PDO_FETCH_NUM);
925         return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
926     }
927
928     /**
929      * Find recent changes.
930      */
931     function most_recent($params) {
932         $limit = 0;
933         $since = 0;
934         $include_minor_revisions = false;
935         $exclude_major_revisions = false;
936         $include_all_revisions = false;
937         extract($params);
938
939         $dbh = &$this->_dbh;
940         extract($this->_table_names);
941
942         $pick = array();
943         if ($since)
944             $pick[] = "mtime >= $since";
945
946         if ($include_all_revisions) {
947             // Include all revisions of each page.
948             $table = "$page_tbl, $version_tbl";
949             $join_clause = "$page_tbl.id=$version_tbl.id";
950
951             if ($exclude_major_revisions) {
952                 // Include only minor revisions
953                 $pick[] = "minor_edit <> 0";
954             }
955             elseif (!$include_minor_revisions) {
956                 // Include only major revisions
957                 $pick[] = "minor_edit = 0";
958             }
959         }
960         else {
961             $table = "$page_tbl, $recent_tbl";
962             $join_clause = "$page_tbl.id=$recent_tbl.id";
963             $table .= ", $version_tbl";
964             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
965
966             if ($exclude_major_revisions) {
967                 // Include only most recent minor revision
968                 $pick[] = 'version=latestminor';
969             }
970             elseif (!$include_minor_revisions) {
971                 // Include only most recent major revision
972                 $pick[] = 'version=latestmajor';
973             }
974             else {
975                 // Include only the latest revision (whether major or minor).
976                 $pick[] ='version=latestversion';
977             }
978         }
979         $order = "DESC";
980         if($limit < 0){
981             $order = "ASC";
982             $limit = -$limit;
983         }
984         $where_clause = $join_clause;
985         if ($pick)
986             $where_clause .= " AND " . join(" AND ", $pick);
987         $sql = "SELECT "
988             . $this->page_tbl_fields . ", " . $this->version_tbl_fields
989             . " FROM $table"
990             . " WHERE $where_clause"
991             . " ORDER BY mtime $order";
992         if ($limit) {
993             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
994         } else {
995             $sth = $dbh->prepare($sql);
996         }
997         $sth->execute();
998         $result = $sth->fetch(PDO_FETCH_NUM);
999         return new WikiDB_backend_PDO_iter($this, $result,
1000             array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1001     }
1002
1003     /**
1004      * Find referenced empty pages.
1005      */
1006     function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
1007         $dbh = &$this->_dbh;
1008         extract($this->_table_names);
1009         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1010             $orderby = 'ORDER BY ' . $orderby;
1011
1012         if ($exclude_from) // array of pagenames
1013             $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
1014         if ($exclude) // array of pagenames
1015             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
1016
1017         /*
1018          all empty pages, independent of linkstatus:
1019            select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1020          only all empty pages, which have a linkto:
1021            select page.pagename, linked.pagename as wantedfrom from link, page as linked
1022              left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1023              where isnull(nonempty.id) and linked.id=link.linkfrom;
1024         */
1025         $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1026             . " FROM $page_tbl p JOIN $link_tbl linked"
1027             . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
1028             . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
1029             . " WHERE ne.id is NULL"
1030             .       " AND p.id = linked.linkfrom"
1031             . $exclude_from
1032             . $exclude
1033             . $orderby;
1034         if ($limit) {
1035             $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1036         } else {
1037             $sth = $dbh->prepare($sql);
1038         }
1039         $sth->execute();
1040         $result = $sth->fetch(PDO_FETCH_NUM);
1041         return new WikiDB_backend_PDO_iter($this, $result, array('pagename','wantedfrom'));
1042     }
1043
1044     /**
1045      * Rename page in the database.
1046      */
1047     function rename_page($pagename, $to) {
1048         $dbh = &$this->_dbh;
1049         extract($this->_table_names);
1050
1051         $this->lock(array('page','version','recent','nonempty','link'));
1052         if ( ($id = $this->_get_pageid($pagename, false)) ) {
1053             if ($new = $this->_get_pageid($to, false)) {
1054                 // Cludge Alert!
1055                 // This page does not exist (already verified before), but exists in the page table.
1056                 // So we delete this page.
1057                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1058                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1059                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1060                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1061                 // We have to fix all referring tables to the old id
1062                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1063                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1064             }
1065             $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1066             $sth->bindParam(1, $to, PDO_PARAM_STR, 100);
1067             $sth->bindParam(2, $id, PDO_PARAM_INT);
1068             $sth->execute();
1069         }
1070         $this->unlock(array('page'));
1071         return $id;
1072     }
1073
1074     function _update_recent_table($pageid = false) {
1075         $dbh = &$this->_dbh;
1076         extract($this->_table_names);
1077         extract($this->_expressions);
1078
1079         $pageid = (int)$pageid;
1080
1081         // optimize: mysql can do this with one REPLACE INTO.
1082         $backend_type = $this->backendType();
1083         if (substr($backend_type,0,5) == 'mysql') {
1084             $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1085                                  . " (id, latestversion, latestmajor, latestminor)"
1086                                  . " SELECT id, $maxversion, $maxmajor, $maxminor"
1087                                  . " FROM $version_tbl"
1088                                  . ( $pageid ? " WHERE id=$pageid" : "")
1089                                  . " GROUP BY id" );
1090             $sth->execute();
1091         } else {
1092             $this->lock(array('recent'));
1093             $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1094                                  . ( $pageid ? " WHERE id=$pageid" : ""));
1095             $sth->execute();
1096             $sth = $dbh->prepare( "INSERT INTO $recent_tbl"
1097                                   . " (id, latestversion, latestmajor, latestminor)"
1098                                   . " SELECT id, $maxversion, $maxmajor, $maxminor"
1099                                   . " FROM $version_tbl"
1100                                   . ( $pageid ? " WHERE id=$pageid" : "")
1101                                   . " GROUP BY id" );
1102             $sth->execute();
1103             $this->unlock(array('recent'));
1104         }
1105     }
1106
1107     function _update_nonempty_table($pageid = false) {
1108         $dbh = &$this->_dbh;
1109         extract($this->_table_names);
1110         extract($this->_expressions);
1111
1112         $pageid = (int)$pageid;
1113
1114         extract($this->_expressions);
1115         $this->lock(array('nonempty'));
1116         $dbh->query("DELETE FROM $nonempty_tbl"
1117                     . ( $pageid ? " WHERE id=$pageid" : ""));
1118         $dbh->query("INSERT INTO $nonempty_tbl (id)"
1119                     . " SELECT $recent_tbl.id"
1120                     . " FROM $recent_tbl, $version_tbl"
1121                     . " WHERE $recent_tbl.id=$version_tbl.id"
1122                     . "       AND version=latestversion"
1123                     // We have some specifics here (Oracle)
1124                     //. "  AND content<>''"
1125                     . "  AND content $notempty"
1126                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1127         $this->unlock(array('nonempty'));
1128     }
1129
1130     /**
1131      * Grab a write lock on the tables in the SQL database.
1132      *
1133      * Calls can be nested.  The tables won't be unlocked until
1134      * _unlock_database() is called as many times as _lock_database().
1135      *
1136      * @access protected
1137      */
1138     function lock($tables, $write_lock = true) {
1139         if ($this->_lock_count++ == 0) {
1140             $this->_current_lock = $tables;
1141             if (!$this->_hasTransactions)
1142                 $this->_lock_tables($tables, $write_lock);
1143         }
1144     }
1145
1146     /**
1147      * Overridden by non-transaction safe backends.
1148      */
1149     function _lock_tables($tables, $write_lock) {
1150         $lock_type = $write_lock ? "WRITE" : "READ";
1151         foreach ($this->_table_names as $key => $table) {
1152             $locks[] = "$table $lock_type";
1153         }
1154         $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1155     }
1156
1157     /**
1158      * Release a write lock on the tables in the SQL database.
1159      *
1160      * @access protected
1161      *
1162      * @param $force boolean Unlock even if not every call to lock() has been matched
1163      * by a call to unlock().
1164      *
1165      * @see _lock_database
1166      */
1167     function unlock($tables = false, $force = false) {
1168         if ($this->_lock_count == 0) {
1169             $this->_current_lock = false;
1170             return;
1171         }
1172         if (--$this->_lock_count <= 0 || $force) {
1173             if (!$this->_hasTransactions)
1174                 $this->_unlock_tables($tables);
1175             $this->_current_lock = false;
1176             $this->_lock_count = 0;
1177         }
1178     }
1179
1180     /**
1181      * overridden by non-transaction safe backends
1182      */
1183     function _unlock_tables($tables) {
1184         $this->_dbh->query("UNLOCK TABLES");
1185     }
1186
1187     /**
1188      * Serialize data
1189      */
1190     function _serialize($data) {
1191         if (empty($data))
1192             return '';
1193         assert(is_array($data));
1194         return serialize($data);
1195     }
1196
1197     /**
1198      * Unserialize data
1199      */
1200     function _unserialize($data) {
1201         return empty($data) ? array() : unserialize($data);
1202     }
1203
1204     /* some variables and functions for DB backend abstraction (action=upgrade) */
1205     function database () {
1206         return $this->_dbh->database;
1207     }
1208     function backendType() {
1209         return $this->_dbh->databaseType;
1210     }
1211     function connection() {
1212         trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1213         return false;
1214     }
1215     function listOfTables() {
1216         trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1217         return array();
1218     }
1219     function listOfFields($database, $table) {
1220         trigger_error("PDO: virtual listOfFields", E_USER_ERROR);
1221         return array();
1222     }
1223
1224     /*
1225      * LIMIT with OFFSET is not SQL specified.
1226      *   mysql: LIMIT $offset, $count
1227      *   pgsql,sqlite: LIMIT $count OFFSET $offset
1228      *   InterBase,FireBird: ROWS $offset TO $last
1229      *   mssql: TOP $rows => TOP $last
1230      *   oci8: ROWNUM
1231      *   IBM DB2: FetchFirst
1232      * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1233
1234      SELECT field_list FROM $table X WHERE where_clause AND
1235      (
1236          SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1237      )
1238      BETWEEN $offset AND $last
1239      ORDER BY $pk $asc_desc
1240      */
1241     function _limit_sql($limit = false) {
1242         if ($limit) {
1243             list($offset, $count) = $this->limit($limit);
1244             if ($offset) {
1245                 $limit = " LIMIT $count";
1246                 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1247             } else
1248                 $limit = " LIMIT $count";
1249         } else
1250             $limit = '';
1251         return $limit;
1252     }
1253
1254     function write_accesslog(&$entry) {
1255         global $request;
1256         $dbh = &$this->_dbh;
1257         $log_tbl = $entry->_accesslog->logtable;
1258         $dbh->prepare("INSERT INTO $log_tbl"
1259                       . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args,"
1260                       .   "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)"
1261                       . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
1262         // Either use unixtime as %d (long), or the native timestamp format.
1263         $sth->bindParam(1, $entry->time, PDO_PARAM_INT);
1264         $sth->bindParam(2, $entry->host, PDO_PARAM_STR, 100);
1265         $sth->bindParam(3, $entry->user, PDO_PARAM_STR, 50);
1266         $sth->bindParam(4, $entry->request_method, PDO_PARAM_STR, 10);
1267         $sth->bindParam(5, $entry->request, PDO_PARAM_STR, 255);
1268         $sth->bindParam(6, $entry->request_args, PDO_PARAM_STR, 255);
1269         $sth->bindParam(7, $entry->request_uri, PDO_PARAM_STR, 255);
1270         $sth->bindParam(8, $entry->_ncsa_time($entry->time), PDO_PARAM_STR, 28);
1271         $sth->bindParam(9, $entry->time, PDO_PARAM_INT);
1272         $sth->bindParam(10,$entry->status, PDO_PARAM_INT);
1273         $sth->bindParam(11,$entry->size, PDO_PARAM_INT);
1274         $sth->bindParam(12,$entry->referer, PDO_PARAM_STR, 255);
1275         $sth->bindParam(13,$entry->user_agent, PDO_PARAM_STR, 255);
1276         $sth->bindParam(14,$entry->duration, PDO_PARAM_FLOAT);
1277         $sth->execute();
1278     }
1279 };
1280
1281 class WikiDB_backend_PDO_generic_iter
1282 extends WikiDB_backend_iterator
1283 {
1284     function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) {
1285         $this->_backend = &$backend;
1286         $this->_result = $query_result;
1287         //$this->_fields = $field_list;
1288     }
1289
1290     function count() {
1291         if (!is_object($this->_result)) {
1292             return false;
1293         }
1294         $count = $this->_result->rowCount();
1295         return $count;
1296     }
1297
1298     function next() {
1299         $result = &$this->_result;
1300         if (!is_object($result)) {
1301             return false;
1302         }
1303         return $result->fetch(PDO_FETCH_BOTH);
1304     }
1305
1306     function free () {
1307         if ($this->_result) {
1308             unset($this->_result);
1309         }
1310     }
1311 }
1312
1313 class WikiDB_backend_PDO_iter
1314 extends WikiDB_backend_PDO_generic_iter
1315 {
1316     function next() {
1317         $result = &$this->_result;
1318         if (!is_object($result)) {
1319             return false;
1320         }
1321         $this->_backend = &$backend;
1322         $rec = $result->fetch(PDO_FETCH_ASSOC);
1323
1324         if (isset($rec['pagedata']))
1325             $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1326         if (!empty($rec['version'])) {
1327             $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1328         }
1329         return $rec;
1330     }
1331 }
1332
1333 class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql {}
1334
1335 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1336 // Eventually, change index.php to provide the relevant information
1337 // directly?
1338     /**
1339      * Parse a data source name.
1340      *
1341      * Additional keys can be added by appending a URI query string to the
1342      * end of the DSN.
1343      *
1344      * The format of the supplied DSN is in its fullest form:
1345      * <code>
1346      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1347      * </code>
1348      *
1349      * Most variations are allowed:
1350      * <code>
1351      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1352      *  phptype://username:password@hostspec/database_name
1353      *  phptype://username:password@hostspec
1354      *  phptype://username@hostspec
1355      *  phptype://hostspec/database
1356      *  phptype://hostspec
1357      *  phptype(dbsyntax)
1358      *  phptype
1359      * </code>
1360      *
1361      * @param string $dsn Data Source Name to be parsed
1362      *
1363      * @return array an associative array with the following keys:
1364      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1365      *  + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1366      *  + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1367      *  + hostspec: Host specification (hostname[:port])
1368      *  + database: Database to use on the DBMS server
1369      *  + username: User name for login
1370      *  + password: Password for login
1371      *
1372      * @author Tomas V.V.Cox <cox@idecnet.com>
1373      */
1374     function parseDSN($dsn)
1375     {
1376         $parsed = array(
1377             'phptype'  => false,
1378             'dbsyntax' => false,
1379             'username' => false,
1380             'password' => false,
1381             'protocol' => false,
1382             'hostspec' => false,
1383             'port'     => false,
1384             'socket'   => false,
1385             'database' => false,
1386         );
1387
1388         if (is_array($dsn)) {
1389             $dsn = array_merge($parsed, $dsn);
1390             if (!$dsn['dbsyntax']) {
1391                 $dsn['dbsyntax'] = $dsn['phptype'];
1392             }
1393             return $dsn;
1394         }
1395
1396         // Find phptype and dbsyntax
1397         if (($pos = strpos($dsn, '://')) !== false) {
1398             $str = substr($dsn, 0, $pos);
1399             $dsn = substr($dsn, $pos + 3);
1400         } else {
1401             $str = $dsn;
1402             $dsn = null;
1403         }
1404
1405         // Get phptype and dbsyntax
1406         // $str => phptype(dbsyntax)
1407         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1408             $parsed['phptype']  = $arr[1];
1409             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1410         } else {
1411             $parsed['phptype']  = $str;
1412             $parsed['dbsyntax'] = $str;
1413         }
1414
1415         if (!count($dsn)) {
1416             return $parsed;
1417         }
1418
1419         // Get (if found): username and password
1420         // $dsn => username:password@protocol+hostspec/database
1421         if (($at = strrpos($dsn,'@')) !== false) {
1422             $str = substr($dsn, 0, $at);
1423             $dsn = substr($dsn, $at + 1);
1424             if (($pos = strpos($str, ':')) !== false) {
1425                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1426                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1427             } else {
1428                 $parsed['username'] = rawurldecode($str);
1429             }
1430         }
1431
1432         // Find protocol and hostspec
1433
1434         // $dsn => proto(proto_opts)/database
1435         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1436             $proto       = $match[1];
1437             $proto_opts  = $match[2] ? $match[2] : false;
1438             $dsn         = $match[3];
1439
1440         // $dsn => protocol+hostspec/database (old format)
1441         } else {
1442             if (strpos($dsn, '+') !== false) {
1443                 list($proto, $dsn) = explode('+', $dsn, 2);
1444             }
1445             if (strpos($dsn, '/') !== false) {
1446                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1447             } else {
1448                 $proto_opts = $dsn;
1449                 $dsn = null;
1450             }
1451         }
1452
1453         // process the different protocol options
1454         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1455         $proto_opts = rawurldecode($proto_opts);
1456         if ($parsed['protocol'] == 'tcp') {
1457             if (strpos($proto_opts, ':') !== false) {
1458                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1459             } else {
1460                 $parsed['hostspec'] = $proto_opts;
1461             }
1462         } elseif ($parsed['protocol'] == 'unix') {
1463             $parsed['socket'] = $proto_opts;
1464         }
1465
1466         // Get dabase if any
1467         // $dsn => database
1468         if ($dsn) {
1469             // /database
1470             if (($pos = strpos($dsn, '?')) === false) {
1471                 $parsed['database'] = $dsn;
1472             // /database?param1=value1&param2=value2
1473             } else {
1474                 $parsed['database'] = substr($dsn, 0, $pos);
1475                 $dsn = substr($dsn, $pos + 1);
1476                 if (strpos($dsn, '&') !== false) {
1477                     $opts = explode('&', $dsn);
1478                 } else { // database?param1=value1
1479                     $opts = array($dsn);
1480                 }
1481                 foreach ($opts as $opt) {
1482                     list($key, $value) = explode('=', $opt);
1483                     if (!isset($parsed[$key])) {
1484                         // don't allow params overwrite
1485                         $parsed[$key] = rawurldecode($value);
1486                     }
1487                 }
1488             }
1489         }
1490
1491         return $parsed;
1492     }
1493
1494 // Local Variables:
1495 // mode: php
1496 // tab-width: 8
1497 // c-basic-offset: 4
1498 // c-hanging-comment-ender-p: nil
1499 // indent-tabs-mode: nil
1500 // End:
1501 ?>