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