2 rcs_id('$Id: PDO.php,v 1.11 2007-01-04 16:57:32 rurban Exp $');
5 Copyright 2005 $ThePhpWikiProgrammingTeam
7 This file is part of PhpWiki.
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.
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.
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
25 * @author: Reini Urban
28 require_once('lib/WikiDB/backend.php');
30 class WikiDB_backend_PDO
31 extends WikiDB_backend
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
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')
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]
59 $dbparams['dsn'] .= ($optionname . "=" . $parsed[$option] . ";");
60 unset($parsed[$optionname]);
62 unset($parsed[$option]);
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 . ";");
71 list($driver, $dsn) = explode(":", $dbparams['dsn'], 2);
72 foreach (explode(";", trim($dsn)) as $pair) {
74 list($option, $value) = explode("=", $pair, 2);
75 $this->_parsedDSN[$option] = $value;
78 $this->_dbh->database = isset($this->_parsedDSN['database'])
79 ? $this->_parsedDSN['database']
80 : $this->_parsedDSN['dbname'];
82 if (empty($this->_parsedDSN['password'])) $this->_parsedDSN['password'] = '';
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!",
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
104 catch (PDOException $e) {
105 echo "<br>\nCan't connect to database: %s" . $e->getMessage();
106 if (DEBUG & _DEBUG_VERBOSE or DEBUG & _DEBUG_SQL) {
107 echo "<br>\nDSN: '", $dbparams['dsn'], "'";
108 echo "<br>\n_parsedDSN: '", print_r($this->_parsedDSN), "'";
109 echo "<br>\nparsed: '", print_r($parsed), "'";
111 if (isset($dbparams['_tryroot_from_upgrade']))
112 trigger_error(sprintf("Can't connect to database: %s", $e->getMessage()),
117 if (DEBUG & _DEBUG_SQL) { // not yet implemented
118 $this->_dbh->debug = true;
120 $this->_dsn = $dbparams['dsn'];
121 $this->_dbh->databaseType = $driver;
122 $this->_dbh->setAttribute(PDO_ATTR_CASE, PDO_CASE_NATURAL);
123 // Use the faster FETCH_NUM, with some special ASSOC based exceptions.
125 $this->_hasTransactions = true;
127 $this->_dbh->beginTransaction();
129 catch (PDOException $e) {
130 $this->_hasTransactions = false;
132 $sth = $this->_dbh->prepare("SELECT version()");
134 $this->_serverinfo['version'] = $sth->fetchSingle();
135 $this->commit(); // required to match the try catch block above!
137 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
139 = array('page_tbl' => $prefix . 'page',
140 'version_tbl' => $prefix . 'version',
141 'link_tbl' => $prefix . 'link',
142 'recent_tbl' => $prefix . 'recent',
143 'nonempty_tbl' => $prefix . 'nonempty');
144 $page_tbl = $this->_table_names['page_tbl'];
145 $version_tbl = $this->_table_names['version_tbl'];
146 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
147 . "$page_tbl.hits hits";
148 $this->page_tbl_field_list = array('id', 'pagename', 'hits');
149 $this->version_tbl_fields = "$version_tbl.version AS version, "
150 . "$version_tbl.mtime AS mtime, "
151 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
152 . "$version_tbl.versiondata AS versiondata";
153 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
157 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
158 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
159 'maxversion' => "MAX(version)",
160 'notempty' => "<>''",
161 'iscontent' => "$version_tbl.content<>''");
162 $this->_lock_count = 0;
165 function beginTransaction() {
166 if ($this->_hasTransactions)
167 $this->_dbh->beginTransaction();
170 if ($this->_hasTransactions)
171 $this->_dbh->commit();
173 function rollback() {
174 if ($this->_hasTransactions)
175 $this->_dbh->rollback();
178 function query($sql) {
179 $sth = $this->_dbh->prepare($sql);
180 return $sth->execute();
182 /* with one result row */
183 function getRow($sql) {
184 $sth = $this->_dbh->prepare($sql);
186 return $sth->fetch(PDO_FETCH_BOTH);
192 * Close database connection.
197 if ($this->_lock_count) {
198 trigger_error("WARNING: database still locked " .
199 '(lock_count = $this->_lock_count)' . "\n<br />",
202 $this->unlock(false, 'force');
208 * Fast test for wikipage.
210 function is_wiki_page($pagename) {
212 extract($this->_table_names);
213 $sth = $dbh->prepare("SELECT $page_tbl.id AS id"
214 . " FROM $nonempty_tbl, $page_tbl"
215 . " WHERE $nonempty_tbl.id=$page_tbl.id"
216 . " AND pagename=?");
217 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
219 return $sth->fetchSingle();
224 function get_all_pagenames() {
226 extract($this->_table_names);
227 $sth = $dbh->exec("SELECT pagename"
228 . " FROM $nonempty_tbl, $page_tbl"
229 . " WHERE $nonempty_tbl.id=$page_tbl.id"
231 return $sth->fetchAll(PDO_FETCH_NUM);
234 function numPages($filter=false, $exclude='') {
236 extract($this->_table_names);
237 $sth = $dbh->exec("SELECT count(*)"
238 . " FROM $nonempty_tbl, $page_tbl"
239 . " WHERE $nonempty_tbl.id=$page_tbl.id");
240 return $sth->fetchSingle();
243 function increaseHitCount($pagename) {
245 $page_tbl = $this->_table_names['page_tbl'];
246 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=hits+1"
247 . " WHERE pagename=?"
249 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
254 * Read page information from database.
256 function get_pagedata($pagename) {
258 $page_tbl = $this->_table_names['page_tbl'];
259 $sth = $dbh->prepare("SELECT id,pagename,hits,pagedata FROM $page_tbl"
260 ." WHERE pagename=? LIMIT 1");
261 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
263 $row = $sth->fetch(PDO_FETCH_NUM);
264 return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
267 function _extract_page_data($data, $hits) {
269 return array('hits' => $hits);
271 return array_merge(array('hits' => $hits), $this->_unserialize($data));
274 function update_pagedata($pagename, $newdata) {
276 $page_tbl = $this->_table_names['page_tbl'];
278 // Hits is the only thing we can update in a fast manner.
279 if (count($newdata) == 1 && isset($newdata['hits'])) {
280 // Note that this will fail silently if the page does not
281 // have a record in the page table. Since it's just the
282 // hit count, who cares?
283 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=? WHERE pagename=? LIMIT 1");
284 $sth->bindParam(1, $newdata['hits'], PDO_PARAM_INT);
285 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
289 $this->beginTransaction();
290 $data = $this->get_pagedata($pagename);
293 $this->_get_pageid($pagename, true); // Creates page record
296 $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
297 unset($data['hits']);
299 foreach ($newdata as $key => $val) {
302 else if (empty($val))
307 $sth = $dbh->prepare("UPDATE $page_tbl"
308 . " SET hits=?, pagedata=?"
309 . " WHERE pagename=?"
311 $sth->bindParam(1, $hits, PDO_PARAM_INT);
312 $sth->bindParam(2, $this->_serialize($data), PDO_PARAM_LOB);
313 $sth->bindParam(3, $pagename, PDO_PARAM_STR, 100);
314 if ($sth->execute()) {
323 function get_cached_html($pagename) {
325 $page_tbl = $this->_table_names['page_tbl'];
326 $sth = $dbh->prepare("SELECT cached_html FROM $page_tbl WHERE pagename=? LIMIT 1");
327 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
329 return $sth->fetchSingle(PDO_FETCH_NUM);
332 function set_cached_html($pagename, $data) {
334 $page_tbl = $this->_table_names['page_tbl'];
335 if (empty($data)) $data = '';
336 $sth = $dbh->prepare("UPDATE $page_tbl"
337 . " SET cached_html=?"
338 . " WHERE pagename=?"
340 $sth->bindParam(1, $data, PDO_PARAM_STR);
341 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
345 function _get_pageid($pagename, $create_if_missing = false) {
348 $cache =& $request->_dbi->_cache->_id_cache;
349 if (isset($cache[$pagename])) {
350 if ($cache[$pagename] or !$create_if_missing) {
351 return $cache[$pagename];
355 // attributes play this game.
356 if ($pagename === '') return 0;
359 $page_tbl = $this->_table_names['page_tbl'];
360 $sth = $dbh->prepare("SELECT id FROM $page_tbl WHERE pagename=? LIMIT 1");
361 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
362 $id = $sth->fetchSingle();
363 if (! $create_if_missing ) {
367 //mysql, mysqli or mysqlt
368 if (substr($dbh->databaseType,0,5) == 'mysql') {
369 // have auto-incrementing, atomic version
370 $sth = $dbh->prepare("INSERT INTO $page_tbl"
372 . " VALUES (NULL,?)");
373 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
375 $id = $dbh->lastInsertId();
377 $this->beginTransaction();
378 $sth = $dbh->prepare("SELECT MAX(id) FROM $page_tbl");
380 $id = $sth->fetchSingle();
381 $sth = $dbh->prepare("INSERT INTO $page_tbl"
382 . " (id,pagename,hits)"
383 . " VALUES (?,?,0)");
385 $sth->bindParam(1, $id, PDO_PARAM_INT);
386 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
397 function get_latest_version($pagename) {
399 extract($this->_table_names);
400 $sth = $dbh->prepare("SELECT latestversion"
401 . " FROM $page_tbl, $recent_tbl"
402 . " WHERE $page_tbl.id=$recent_tbl.id"
405 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
407 return $sth->fetchSingle();
410 function get_previous_version($pagename, $version) {
412 extract($this->_table_names);
413 $sth = $dbh->prepare("SELECT version"
414 . " FROM $version_tbl, $page_tbl"
415 . " WHERE $version_tbl.id=$page_tbl.id"
418 . " ORDER BY version DESC"
420 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
421 $sth->bindParam(2, $version, PDO_PARAM_INT);
423 return $sth->fetchSingle();
429 * @param $version int Which version to get.
431 * @return hash The version data, or false if specified version does not
434 function get_versiondata($pagename, $version, $want_content = false) {
436 extract($this->_table_names);
437 extract($this->_expressions);
439 assert(is_string($pagename) and $pagename != '');
440 assert($version > 0);
442 // FIXME: optimization: sometimes don't get page data?
444 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
445 . ', ' . $this->version_tbl_fields;
447 $fields = $this->page_tbl_fields . ", '' AS pagedata"
448 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
449 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
450 . "$version_tbl.versiondata as versiondata";
452 $sth = $dbh->prepare("SELECT $fields"
453 . " FROM $page_tbl, $version_tbl"
454 . " WHERE $page_tbl.id=$version_tbl.id"
458 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
459 $sth->bindParam(2, $version, PDO_PARAM_INT);
461 $row = $sth->fetch(PDO_FETCH_NUM);
462 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
465 function _extract_version_data_num($row, $want_content) {
470 //$pagename &= $row[1];
471 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
472 $data['mtime'] = $row[5];
473 $data['is_minor_edit'] = !empty($row[6]);
475 $data['%content'] = $row[7];
477 $data['%content'] = !empty($row[7]);
479 if (!empty($row[3])) {
480 $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
485 function _extract_version_data_assoc($row) {
490 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
491 $data['mtime'] = $mtime;
492 $data['is_minor_edit'] = !empty($minor_edit);
494 $data['%content'] = $content;
495 elseif ($have_content)
496 $data['%content'] = true;
498 $data['%content'] = '';
499 if (!empty($pagedata)) {
500 $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
506 * Create a new revision of a page.
508 function set_versiondata($pagename, $version, $data) {
510 $version_tbl = $this->_table_names['version_tbl'];
512 $minor_edit = (int) !empty($data['is_minor_edit']);
513 unset($data['is_minor_edit']);
515 $mtime = (int)$data['mtime'];
516 unset($data['mtime']);
517 assert(!empty($mtime));
519 @$content = (string) $data['%content'];
520 unset($data['%content']);
521 unset($data['%pagedata']);
523 $this->lock(array('page','recent','version','nonempty'));
524 $this->beginTransaction();
525 $id = $this->_get_pageid($pagename, true);
526 $backend_type = $this->backendType();
527 // optimize: mysql can do this with one REPLACE INTO.
528 if (substr($backend_type,0,5) == 'mysql') {
529 $sth = $dbh->prepare("REPLACE INTO $version_tbl"
530 . " (id,version,mtime,minor_edit,content,versiondata)"
531 . " VALUES(?,?,?,?,?,?)");
532 $sth->bindParam(1, $id, PDO_PARAM_INT);
533 $sth->bindParam(2, $version, PDO_PARAM_INT);
534 $sth->bindParam(3, $mtime, PDO_PARAM_INT);
535 $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
536 $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
537 $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
538 $rs = $sth->execute();
540 $sth = $dbh->prepare("DELETE FROM $version_tbl"
541 . " WHERE id=? AND version=?");
542 $sth->bindParam(1, $id, PDO_PARAM_INT);
543 $sth->bindParam(2, $version, PDO_PARAM_INT);
545 $sth = $dbh->prepare("INSERT INTO $version_tbl"
546 . " (id,version,mtime,minor_edit,content,versiondata)"
547 . " VALUES(?,?,?,?,?,?)");
548 $sth->bindParam(1, $id, PDO_PARAM_INT);
549 $sth->bindParam(2, $version, PDO_PARAM_INT);
550 $sth->bindParam(3, $mtime, PDO_PARAM_INT);
551 $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
552 $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
553 $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
554 $rs = $sth->execute();
556 $this->_update_recent_table($id);
557 $this->_update_nonempty_table($id);
558 if ($rs) $this->commit( );
559 else $this->rollBack( );
560 $this->unlock(array('page','recent','version','nonempty'));
564 * Delete an old revision of a page.
566 function delete_versiondata($pagename, $version) {
568 extract($this->_table_names);
570 $this->lock(array('version'));
571 if ( ($id = $this->_get_pageid($pagename)) ) {
572 $dbh->query("DELETE FROM $version_tbl"
573 . " WHERE id=$id AND version=$version");
574 $this->_update_recent_table($id);
575 // This shouldn't be needed (as long as the latestversion
576 // never gets deleted.) But, let's be safe.
577 $this->_update_nonempty_table($id);
579 $this->unlock(array('version'));
583 * Delete page from the database with backup possibility.
584 * i.e save_page('') and DELETE nonempty id
586 * deletePage increments latestversion in recent to a non-existent version,
587 * and removes the nonempty row,
588 * so that get_latest_version returns id+1 and get_previous_version returns prev id
589 * and page->exists returns false.
591 function delete_page($pagename) {
593 extract($this->_table_names);
595 $this->beginTransaction();
596 //$dbh->CommitLock($recent_tbl);
597 if (($id = $this->_get_pageid($pagename, false)) === false) {
602 $user =& $GLOBALS['request']->_user;
603 $meta = array('author' => $user->getId(),
604 'author_id' => $user->getAuthenticatedId(),
606 $this->lock(array('version','recent','nonempty','page','link'));
607 $version = $this->get_latest_version($pagename);
608 if ($dbh->query("UPDATE $recent_tbl SET latestversion=latestversion+1,"
609 . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id"))
611 $insert = $dbh->prepare("INSERT INTO $version_tbl"
612 . " (id,version,mtime,minor_edit,content,versiondata)"
613 . " VALUES(?,?,?,?,?,?)");
614 $insert->bindParam(1, $id, PDO_PARAM_INT);
615 $insert->bindParam(2, $version + 1, PDO_PARAM_INT);
616 $insert->bindParam(3, $mtime, PDO_PARAM_INT);
617 $insert->bindParam(4, 0, PDO_PARAM_INT);
618 $insert->bindParam(5, '', PDO_PARAM_STR, 100);
619 $insert->bindParam(6, $this->_serialize($meta), PDO_PARAM_STR, 100);
620 if ($insert->execute()
621 and $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id")
622 and $this->set_links($pagename, false)) {
623 // need to keep perms and LOCKED, otherwise you can reset the perm
624 // by action=remove and re-create it with default perms
625 // keep hits but delete meta-data
626 //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id")
627 $this->unlock(array('version','recent','nonempty','page','link'));
632 $this->unlock(array('version','recent','nonempty','page','link'));
638 function purge_page($pagename) {
640 extract($this->_table_names);
642 $this->lock(array('version','recent','nonempty','page','link'));
643 if ( ($id = $this->_get_pageid($pagename, false)) ) {
644 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
645 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
646 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
647 $this->set_links($pagename, false);
648 $sth = $dbh->prepare("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
650 if ($sth->fetchSingle()) {
651 // We're still in the link table (dangling link) so we can't delete this
653 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
657 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
661 $result = -1; // already purged or not existing
663 $this->unlock(array('version','recent','nonempty','page','link'));
668 // The only thing we might be interested in updating which we can
669 // do fast in the flags (minor_edit). I think the default
670 // update_versiondata will work fine...
671 //function update_versiondata($pagename, $version, $data) {
674 function set_links($pagename, $links) {
675 // Update link table.
676 // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
679 extract($this->_table_names);
681 $this->lock(array('link'));
682 $pageid = $this->_get_pageid($pagename, true);
685 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
686 foreach ($links as $link) {
687 if (isset($linkseen[$link]))
689 $linkseen[$link] = true;
690 $linkid = $this->_get_pageid($link, true);
692 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
693 . " VALUES ($pageid, $linkid)");
696 // purge page table: delete all non-referenced pages
697 // for all previously linked pages...
698 $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl".
699 " WHERE linkfrom=$pageid");
701 foreach ($sth->fetchAll(PDO_FETCH_NUM) as $id) {
702 // ...check if the page is empty and has no version
703 $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl"
704 . " LEFT JOIN $nonempty_tbl USING (id) "
705 . " LEFT JOIN $version_tbl USING (id)"
706 . " WHERE ISNULL($nonempty_tbl.id) AND"
707 . " ISNULL($version_tbl.id) AND $page_tbl.id=$id");
709 if ($sth1->fetchSingle()) {
710 $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
711 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
714 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
716 $this->unlock(array('link'));
721 * Find pages which link to or are linked from a page.
723 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
724 * (linkExistingWikiWord or linkUnknownWikiWord)
725 * This is called on every page header GleanDescription, so we can store all the existing links.
727 function get_links($pagename, $reversed=true, $include_empty=false,
728 $sortby='', $limit='', $exclude='') {
730 extract($this->_table_names);
733 list($have,$want) = array('linkee', 'linker');
735 list($have,$want) = array('linker', 'linkee');
736 $orderby = $this->sortby($sortby, 'db', array('pagename'));
737 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
738 if ($exclude) // array of pagenames
739 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
742 $limit = $this->_limit_sql($limit);
744 $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename,"
745 . " $want.hits AS hits"
746 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
747 . (!$include_empty ? ", $nonempty_tbl" : '')
748 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
749 . " AND $have.pagename=?"
750 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
751 //. " GROUP BY $want.id"
755 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
757 $result = $sth->fetch(PDO_FETCH_BOTH);
758 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
762 * Find if a page links to another page
764 function exists_link($pagename, $link, $reversed=false) {
766 extract($this->_table_names);
769 list($have, $want) = array('linkee', 'linker');
771 list($have, $want) = array('linker', 'linkee');
772 $sth = $dbh->prepare("SELECT CASE WHEN $want.pagename THEN 1 ELSE 0 END"
773 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
774 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
775 . " AND $have.pagename=?"
776 . " AND $want.pagename=?");
777 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
778 $sth->bindParam(2, $link, PDO_PARAM_STR, 100);
780 return $sth->fetchSingle();
783 function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
785 extract($this->_table_names);
786 $orderby = $this->sortby($sortby, 'db');
787 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
788 if ($exclude) // array of pagenames
789 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
792 $limit = $this->_limit_sql($limit);
794 if (strstr($orderby, 'mtime ')) { // was ' mtime'
795 if ($include_empty) {
797 . $this->page_tbl_fields
798 ." FROM $page_tbl, $recent_tbl, $version_tbl"
799 . " WHERE $page_tbl.id=$recent_tbl.id"
800 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
806 . $this->page_tbl_fields
807 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
808 . " WHERE $nonempty_tbl.id=$page_tbl.id"
809 . " AND $page_tbl.id=$recent_tbl.id"
810 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
815 if ($include_empty) {
817 . $this->page_tbl_fields
819 . ($exclude ? " WHERE $exclude" : '')
823 . $this->page_tbl_fields
824 . " FROM $nonempty_tbl, $page_tbl"
825 . " WHERE $nonempty_tbl.id=$page_tbl.id"
830 $sth = $dbh->prepare($sql . $limit);
832 $result = $sth->fetch(PDO_FETCH_BOTH);
833 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
839 function text_search($search, $fullsearch=false, $sortby='', $limit='', $exclude='') {
841 extract($this->_table_names);
842 $orderby = $this->sortby($sortby, 'db');
843 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
844 $limit = $this->_limit_sql($limit);
846 $table = "$nonempty_tbl, $page_tbl";
847 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
848 $fields = $this->page_tbl_fields;
849 $field_list = $this->page_tbl_field_list;
850 $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
853 $table .= ", $recent_tbl";
854 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
856 $table .= ", $version_tbl";
857 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
859 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
860 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
861 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
863 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
866 $search_clause = $search->makeSqlClauseObj($callback);
867 $sth = $dbh->prepare("SELECT $fields FROM $table"
868 . " WHERE $join_clause"
869 . " AND ($search_clause)"
873 $result = $sth->fetch(PDO_FETCH_NUM);
874 $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list);
875 $iter->stoplisted = $searchobj->stoplisted;
880 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
881 * not sets. See above, but the above methods find too much.
882 * This is only for already resolved wildcards:
883 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
885 function _sql_set(&$pagenames) {
887 foreach ($pagenames as $p) {
888 $s .= ($this->_dbh->qstr($p).",");
890 return substr($s,0,-1).")";
894 * Find highest or lowest hit counts.
896 function most_popular($limit=20, $sortby='-hits') {
898 extract($this->_table_names);
905 $where = " AND hits > 0";
907 if ($sortby != '-hits') {
908 if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
911 $orderby = " ORDER BY hits $order";
913 . $this->page_tbl_fields
914 . " FROM $nonempty_tbl, $page_tbl"
915 . " WHERE $nonempty_tbl.id=$page_tbl.id"
919 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
921 $sth = $dbh->prepare($sql);
924 $result = $sth->fetch(PDO_FETCH_NUM);
925 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
929 * Find recent changes.
931 function most_recent($params) {
934 $include_minor_revisions = false;
935 $exclude_major_revisions = false;
936 $include_all_revisions = false;
940 extract($this->_table_names);
944 $pick[] = "mtime >= $since";
946 if ($include_all_revisions) {
947 // Include all revisions of each page.
948 $table = "$page_tbl, $version_tbl";
949 $join_clause = "$page_tbl.id=$version_tbl.id";
951 if ($exclude_major_revisions) {
952 // Include only minor revisions
953 $pick[] = "minor_edit <> 0";
955 elseif (!$include_minor_revisions) {
956 // Include only major revisions
957 $pick[] = "minor_edit = 0";
961 $table = "$page_tbl, $recent_tbl";
962 $join_clause = "$page_tbl.id=$recent_tbl.id";
963 $table .= ", $version_tbl";
964 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
966 if ($exclude_major_revisions) {
967 // Include only most recent minor revision
968 $pick[] = 'version=latestminor';
970 elseif (!$include_minor_revisions) {
971 // Include only most recent major revision
972 $pick[] = 'version=latestmajor';
975 // Include only the latest revision (whether major or minor).
976 $pick[] ='version=latestversion';
984 $where_clause = $join_clause;
986 $where_clause .= " AND " . join(" AND ", $pick);
988 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
990 . " WHERE $where_clause"
991 . " ORDER BY mtime $order";
993 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
995 $sth = $dbh->prepare($sql);
998 $result = $sth->fetch(PDO_FETCH_NUM);
999 return new WikiDB_backend_PDO_iter($this, $result,
1000 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1004 * Find referenced empty pages.
1006 function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
1007 $dbh = &$this->_dbh;
1008 extract($this->_table_names);
1009 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1010 $orderby = 'ORDER BY ' . $orderby;
1012 if ($exclude_from) // array of pagenames
1013 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
1014 if ($exclude) // array of pagenames
1015 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
1018 all empty pages, independent of linkstatus:
1019 select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1020 only all empty pages, which have a linkto:
1021 select page.pagename, linked.pagename as wantedfrom from link, page as linked
1022 left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1023 where isnull(nonempty.id) and linked.id=link.linkfrom;
1025 $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1026 . " FROM $page_tbl p JOIN $link_tbl linked"
1027 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
1028 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
1029 . " WHERE ne.id is NULL"
1030 . " AND p.id = linked.linkfrom"
1035 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1037 $sth = $dbh->prepare($sql);
1040 $result = $sth->fetch(PDO_FETCH_NUM);
1041 return new WikiDB_backend_PDO_iter($this, $result, array('pagename','wantedfrom'));
1045 * Rename page in the database.
1047 function rename_page($pagename, $to) {
1048 $dbh = &$this->_dbh;
1049 extract($this->_table_names);
1051 $this->lock(array('page','version','recent','nonempty','link'));
1052 if ( ($id = $this->_get_pageid($pagename, false)) ) {
1053 if ($new = $this->_get_pageid($to, false)) {
1055 // This page does not exist (already verified before), but exists in the page table.
1056 // So we delete this page.
1057 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1058 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1059 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1060 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1061 // We have to fix all referring tables to the old id
1062 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1063 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1065 $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1066 $sth->bindParam(1, $to, PDO_PARAM_STR, 100);
1067 $sth->bindParam(2, $id, PDO_PARAM_INT);
1070 $this->unlock(array('page'));
1074 function _update_recent_table($pageid = false) {
1075 $dbh = &$this->_dbh;
1076 extract($this->_table_names);
1077 extract($this->_expressions);
1079 $pageid = (int)$pageid;
1081 // optimize: mysql can do this with one REPLACE INTO.
1082 $backend_type = $this->backendType();
1083 if (substr($backend_type,0,5) == 'mysql') {
1084 $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1085 . " (id, latestversion, latestmajor, latestminor)"
1086 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1087 . " FROM $version_tbl"
1088 . ( $pageid ? " WHERE id=$pageid" : "")
1092 $this->lock(array('recent'));
1093 $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1094 . ( $pageid ? " WHERE id=$pageid" : ""));
1096 $sth = $dbh->prepare( "INSERT INTO $recent_tbl"
1097 . " (id, latestversion, latestmajor, latestminor)"
1098 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1099 . " FROM $version_tbl"
1100 . ( $pageid ? " WHERE id=$pageid" : "")
1103 $this->unlock(array('recent'));
1107 function _update_nonempty_table($pageid = false) {
1108 $dbh = &$this->_dbh;
1109 extract($this->_table_names);
1110 extract($this->_expressions);
1112 $pageid = (int)$pageid;
1114 extract($this->_expressions);
1115 $this->lock(array('nonempty'));
1116 $dbh->query("DELETE FROM $nonempty_tbl"
1117 . ( $pageid ? " WHERE id=$pageid" : ""));
1118 $dbh->query("INSERT INTO $nonempty_tbl (id)"
1119 . " SELECT $recent_tbl.id"
1120 . " FROM $recent_tbl, $version_tbl"
1121 . " WHERE $recent_tbl.id=$version_tbl.id"
1122 . " AND version=latestversion"
1123 // We have some specifics here (Oracle)
1124 //. " AND content<>''"
1125 . " AND content $notempty"
1126 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1127 $this->unlock(array('nonempty'));
1131 * Grab a write lock on the tables in the SQL database.
1133 * Calls can be nested. The tables won't be unlocked until
1134 * _unlock_database() is called as many times as _lock_database().
1138 function lock($tables, $write_lock = true) {
1139 if ($this->_lock_count++ == 0) {
1140 $this->_current_lock = $tables;
1141 if (!$this->_hasTransactions)
1142 $this->_lock_tables($tables, $write_lock);
1147 * Overridden by non-transaction safe backends.
1149 function _lock_tables($tables, $write_lock) {
1150 $lock_type = $write_lock ? "WRITE" : "READ";
1151 foreach ($this->_table_names as $key => $table) {
1152 $locks[] = "$table $lock_type";
1154 $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1158 * Release a write lock on the tables in the SQL database.
1162 * @param $force boolean Unlock even if not every call to lock() has been matched
1163 * by a call to unlock().
1165 * @see _lock_database
1167 function unlock($tables = false, $force = false) {
1168 if ($this->_lock_count == 0) {
1169 $this->_current_lock = false;
1172 if (--$this->_lock_count <= 0 || $force) {
1173 if (!$this->_hasTransactions)
1174 $this->_unlock_tables($tables);
1175 $this->_current_lock = false;
1176 $this->_lock_count = 0;
1181 * overridden by non-transaction safe backends
1183 function _unlock_tables($tables) {
1184 $this->_dbh->query("UNLOCK TABLES");
1190 function _serialize($data) {
1193 assert(is_array($data));
1194 return serialize($data);
1200 function _unserialize($data) {
1201 return empty($data) ? array() : unserialize($data);
1204 /* some variables and functions for DB backend abstraction (action=upgrade) */
1205 function database () {
1206 return $this->_dbh->database;
1208 function backendType() {
1209 return $this->_dbh->databaseType;
1211 function connection() {
1212 trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1215 function listOfTables() {
1216 trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1219 function listOfFields($database, $table) {
1220 trigger_error("PDO: virtual listOfFields", E_USER_ERROR);
1225 * LIMIT with OFFSET is not SQL specified.
1226 * mysql: LIMIT $offset, $count
1227 * pgsql,sqlite: LIMIT $count OFFSET $offset
1228 * InterBase,FireBird: ROWS $offset TO $last
1229 * mssql: TOP $rows => TOP $last
1231 * IBM DB2: FetchFirst
1232 * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1234 SELECT field_list FROM $table X WHERE where_clause AND
1236 SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1238 BETWEEN $offset AND $last
1239 ORDER BY $pk $asc_desc
1241 function _limit_sql($limit = false) {
1243 list($offset, $count) = $this->limit($limit);
1245 $limit = " LIMIT $count";
1246 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1248 $limit = " LIMIT $count";
1255 class WikiDB_backend_PDO_generic_iter
1256 extends WikiDB_backend_iterator
1258 function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) {
1259 $this->_backend = &$backend;
1260 $this->_result = $query_result;
1261 //$this->_fields = $field_list;
1265 if (!is_object($this->_result)) {
1268 $count = $this->_result->rowCount();
1273 $result = &$this->_result;
1274 if (!is_object($result)) {
1277 return $result->fetch(PDO_FETCH_BOTH);
1281 if ($this->_result) {
1282 unset($this->_result);
1287 class WikiDB_backend_PDO_iter
1288 extends WikiDB_backend_PDO_generic_iter
1291 $result = &$this->_result;
1292 if (!is_object($result)) {
1295 $this->_backend = &$backend;
1296 $rec = $result->fetch(PDO_FETCH_ASSOC);
1298 if (isset($rec['pagedata']))
1299 $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1300 if (!empty($rec['version'])) {
1301 $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1307 class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql {}
1309 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1310 // Eventually, change index.php to provide the relevant information
1313 * Parse a data source name.
1315 * Additional keys can be added by appending a URI query string to the
1318 * The format of the supplied DSN is in its fullest form:
1320 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1323 * Most variations are allowed:
1325 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1326 * phptype://username:password@hostspec/database_name
1327 * phptype://username:password@hostspec
1328 * phptype://username@hostspec
1329 * phptype://hostspec/database
1330 * phptype://hostspec
1335 * @param string $dsn Data Source Name to be parsed
1337 * @return array an associative array with the following keys:
1338 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1339 * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1340 * + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1341 * + hostspec: Host specification (hostname[:port])
1342 * + database: Database to use on the DBMS server
1343 * + username: User name for login
1344 * + password: Password for login
1346 * @author Tomas V.V.Cox <cox@idecnet.com>
1348 function parseDSN($dsn)
1352 'dbsyntax' => false,
1353 'username' => false,
1354 'password' => false,
1355 'protocol' => false,
1356 'hostspec' => false,
1359 'database' => false,
1362 if (is_array($dsn)) {
1363 $dsn = array_merge($parsed, $dsn);
1364 if (!$dsn['dbsyntax']) {
1365 $dsn['dbsyntax'] = $dsn['phptype'];
1370 // Find phptype and dbsyntax
1371 if (($pos = strpos($dsn, '://')) !== false) {
1372 $str = substr($dsn, 0, $pos);
1373 $dsn = substr($dsn, $pos + 3);
1379 // Get phptype and dbsyntax
1380 // $str => phptype(dbsyntax)
1381 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1382 $parsed['phptype'] = $arr[1];
1383 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1385 $parsed['phptype'] = $str;
1386 $parsed['dbsyntax'] = $str;
1393 // Get (if found): username and password
1394 // $dsn => username:password@protocol+hostspec/database
1395 if (($at = strrpos($dsn,'@')) !== false) {
1396 $str = substr($dsn, 0, $at);
1397 $dsn = substr($dsn, $at + 1);
1398 if (($pos = strpos($str, ':')) !== false) {
1399 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1400 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1402 $parsed['username'] = rawurldecode($str);
1406 // Find protocol and hostspec
1408 // $dsn => proto(proto_opts)/database
1409 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1411 $proto_opts = $match[2] ? $match[2] : false;
1414 // $dsn => protocol+hostspec/database (old format)
1416 if (strpos($dsn, '+') !== false) {
1417 list($proto, $dsn) = explode('+', $dsn, 2);
1419 if (strpos($dsn, '/') !== false) {
1420 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1427 // process the different protocol options
1428 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1429 $proto_opts = rawurldecode($proto_opts);
1430 if ($parsed['protocol'] == 'tcp') {
1431 if (strpos($proto_opts, ':') !== false) {
1432 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1434 $parsed['hostspec'] = $proto_opts;
1436 } elseif ($parsed['protocol'] == 'unix') {
1437 $parsed['socket'] = $proto_opts;
1440 // Get dabase if any
1444 if (($pos = strpos($dsn, '?')) === false) {
1445 $parsed['database'] = $dsn;
1446 // /database?param1=value1¶m2=value2
1448 $parsed['database'] = substr($dsn, 0, $pos);
1449 $dsn = substr($dsn, $pos + 1);
1450 if (strpos($dsn, '&') !== false) {
1451 $opts = explode('&', $dsn);
1452 } else { // database?param1=value1
1453 $opts = array($dsn);
1455 foreach ($opts as $opt) {
1456 list($key, $value) = explode('=', $opt);
1457 if (!isset($parsed[$key])) {
1458 // don't allow params overwrite
1459 $parsed[$key] = rawurldecode($value);
1468 // $Log: not supported by cvs2svn $
1469 // Revision 1.10 2006/12/22 01:04:12 rurban
1472 // Revision 1.9 2006/11/19 14:04:39 rurban
1473 // Oops. Syntax error in prev commit
1475 // Revision 1.8 2006/11/19 14:03:32 rurban
1476 // Replace IF by CASE in exists_link()
1478 // Revision 1.7 2006/05/14 12:28:03 rurban
1479 // mysql 5.x fix for wantedpages join
1481 // Revision 1.6 2005/11/14 22:24:33 rurban
1482 // fix fulltext search,
1483 // Eliminate stoplist words,
1484 // don't extract %pagedate twice in ADODB,
1485 // add SemanticWeb support: link(relation),
1486 // major postgresql update: stored procedures, tsearch2 for fulltext
1488 // Revision 1.5 2005/09/14 06:04:43 rurban
1489 // optimize searching for ALL (ie %), use the stoplist on PDO
1491 // Revision 1.4 2005/09/11 13:25:12 rurban
1492 // enhance LIMIT support
1494 // Revision 1.3 2005/09/10 21:30:16 rurban
1495 // enhance titleSearch
1497 // Revision 1.2 2005/02/11 14:45:45 rurban
1498 // support ENABLE_LIVESEARCH, enable PDO sessions
1500 // Revision 1.1 2005/02/10 19:01:22 rurban
1504 // (c-file-style: "gnu")
1508 // c-basic-offset: 4
1509 // c-hanging-comment-ender-p: nil
1510 // indent-tabs-mode: nil