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