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