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