2 rcs_id('$Id: PDO.php,v 1.8 2006-11-19 14:03: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>\nDB Connection failed: " . $e->getMessage();
106 if (DEBUG & _DEBUG_VERBOSE or DEBUG & _DEBUG_SQL) {
107 echo "<br>\nDSN: '", $dbparams['dsn'], "'";
108 echo "<br>\n_parsedDSN: '", print_r($this->_parsedDSN), "'";
109 echo "<br>\nparsed: '", print_r($parsed), "'";
113 if (DEBUG & _DEBUG_SQL) { // not yet implemented
114 $this->_dbh->debug = true;
116 $this->_dsn = $dbparams['dsn'];
117 $this->_dbh->databaseType = $driver;
118 $this->_dbh->setAttribute(PDO_ATTR_CASE, PDO_CASE_NATURAL);
119 // Use the faster FETCH_NUM, with some special ASSOC based exceptions.
121 $this->_hasTransactions = true;
123 $this->_dbh->beginTransaction();
125 catch (PDOException $e) {
126 $this->_hasTransactions = false;
128 $sth = $this->_dbh->prepare("SELECT version()");
130 $this->_serverinfo['version'] = $sth->fetchSingle();
131 $this->commit(); // required to match the try catch block above!
133 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
135 = array('page_tbl' => $prefix . 'page',
136 'version_tbl' => $prefix . 'version',
137 'link_tbl' => $prefix . 'link',
138 'recent_tbl' => $prefix . 'recent',
139 'nonempty_tbl' => $prefix . 'nonempty');
140 $page_tbl = $this->_table_names['page_tbl'];
141 $version_tbl = $this->_table_names['version_tbl'];
142 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
143 . "$page_tbl.hits hits";
144 $this->page_tbl_field_list = array('id', 'pagename', 'hits');
145 $this->version_tbl_fields = "$version_tbl.version AS version, "
146 . "$version_tbl.mtime AS mtime, "
147 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
148 . "$version_tbl.versiondata AS versiondata";
149 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
153 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
154 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
155 'maxversion' => "MAX(version)",
156 'notempty' => "<>''",
157 'iscontent' => "$version_tbl.content<>''");
158 $this->_lock_count = 0;
161 function beginTransaction() {
162 if ($this->_hasTransactions)
163 $this->_dbh->beginTransaction();
166 if ($this->_hasTransactions)
167 $this->_dbh->commit();
169 function rollback() {
170 if ($this->_hasTransactions)
171 $this->_dbh->rollback();
174 function query($sql) {
175 $sth = $this->_dbh->prepare($sql);
176 return $sth->execute();
178 /* with one result row */
179 function getRow($sql) {
180 $sth = $this->_dbh->prepare($sql);
182 return $sth->fetch(PDO_FETCH_BOTH);
188 * Close database connection.
193 if ($this->_lock_count) {
194 trigger_error("WARNING: database still locked " .
195 '(lock_count = $this->_lock_count)' . "\n<br />",
198 $this->unlock(false, 'force');
204 * Fast test for wikipage.
206 function is_wiki_page($pagename) {
208 extract($this->_table_names);
209 $sth = $dbh->prepare("SELECT $page_tbl.id AS id"
210 . " FROM $nonempty_tbl, $page_tbl"
211 . " WHERE $nonempty_tbl.id=$page_tbl.id"
212 . " AND pagename=?");
213 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
215 return $sth->fetchSingle();
220 function get_all_pagenames() {
222 extract($this->_table_names);
223 $sth = $dbh->exec("SELECT pagename"
224 . " FROM $nonempty_tbl, $page_tbl"
225 . " WHERE $nonempty_tbl.id=$page_tbl.id"
227 return $sth->fetchAll(PDO_FETCH_NUM);
230 function numPages($filter=false, $exclude='') {
232 extract($this->_table_names);
233 $sth = $dbh->exec("SELECT count(*)"
234 . " FROM $nonempty_tbl, $page_tbl"
235 . " WHERE $nonempty_tbl.id=$page_tbl.id");
236 return $sth->fetchSingle();
239 function increaseHitCount($pagename) {
241 $page_tbl = $this->_table_names['page_tbl'];
242 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=hits+1"
243 . " WHERE pagename=?"
245 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
250 * Read page information from database.
252 function get_pagedata($pagename) {
254 $page_tbl = $this->_table_names['page_tbl'];
255 $sth = $dbh->prepare("SELECT id,pagename,hits,pagedata FROM $page_tbl"
256 ." WHERE pagename=? LIMIT 1");
257 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
259 $row = $sth->fetch(PDO_FETCH_NUM);
260 return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
263 function _extract_page_data($data, $hits) {
265 return array('hits' => $hits);
267 return array_merge(array('hits' => $hits), $this->_unserialize($data));
270 function update_pagedata($pagename, $newdata) {
272 $page_tbl = $this->_table_names['page_tbl'];
274 // Hits is the only thing we can update in a fast manner.
275 if (count($newdata) == 1 && isset($newdata['hits'])) {
276 // Note that this will fail silently if the page does not
277 // have a record in the page table. Since it's just the
278 // hit count, who cares?
279 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=? WHERE pagename=? LIMIT 1");
280 $sth->bindParam(1, $newdata['hits'], PDO_PARAM_INT);
281 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
285 $this->beginTransaction();
286 $data = $this->get_pagedata($pagename);
289 $this->_get_pageid($pagename, true); // Creates page record
292 $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
293 unset($data['hits']);
295 foreach ($newdata as $key => $val) {
298 else if (empty($val))
303 $sth = $dbh->prepare("UPDATE $page_tbl"
304 . " SET hits=?, pagedata=?"
305 . " WHERE pagename=?"
307 $sth->bindParam(1, $hits, PDO_PARAM_INT);
308 $sth->bindParam(2, $this->_serialize($data), PDO_PARAM_LOB);
309 $sth->bindParam(3, $pagename, PDO_PARAM_STR, 100);
310 if ($sth->execute()) {
319 function get_cached_html($pagename) {
321 $page_tbl = $this->_table_names['page_tbl'];
322 $sth = $dbh->prepare("SELECT cached_html FROM $page_tbl WHERE pagename=? LIMIT 1");
323 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
325 return $sth->fetchSingle(PDO_FETCH_NUM);
328 function set_cached_html($pagename, $data) {
330 $page_tbl = $this->_table_names['page_tbl'];
331 if (empty($data)) $data = '';
332 $sth = $dbh->prepare("UPDATE $page_tbl"
333 . " SET cached_html=?"
334 . " WHERE pagename=?"
336 $sth->bindParam(1, $data, PDO_PARAM_STR);
337 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
341 function _get_pageid($pagename, $create_if_missing = false) {
344 $cache =& $request->_dbi->_cache->_id_cache;
345 if (isset($cache[$pagename])) {
346 if ($cache[$pagename] or !$create_if_missing) {
347 return $cache[$pagename];
352 $page_tbl = $this->_table_names['page_tbl'];
353 $sth = $dbh->prepare("SELECT id FROM $page_tbl WHERE pagename=? LIMIT 1");
354 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
355 $id = $sth->fetchSingle();
356 if (! $create_if_missing ) {
360 //mysql, mysqli or mysqlt
361 if (substr($dbh->databaseType,0,5) == 'mysql') {
362 // have auto-incrementing, atomic version
363 $sth = $dbh->prepare("INSERT INTO $page_tbl"
365 . " VALUES (NULL,?)");
366 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
368 $id = $dbh->lastInsertId();
370 $this->beginTransaction();
371 $sth = $dbh->prepare("SELECT MAX(id) FROM $page_tbl");
373 $id = $sth->fetchSingle();
374 $sth = $dbh->prepare("INSERT INTO $page_tbl"
375 . " (id,pagename,hits)"
376 . " VALUES (?,?,0)");
378 $sth->bindParam(1, $id, PDO_PARAM_INT);
379 $sth->bindParam(2, $pagename, PDO_PARAM_STR, 100);
390 function get_latest_version($pagename) {
392 extract($this->_table_names);
393 $sth = $dbh->prepare("SELECT latestversion"
394 . " FROM $page_tbl, $recent_tbl"
395 . " WHERE $page_tbl.id=$recent_tbl.id"
398 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
400 return $sth->fetchSingle();
403 function get_previous_version($pagename, $version) {
405 extract($this->_table_names);
406 $sth = $dbh->prepare("SELECT version"
407 . " FROM $version_tbl, $page_tbl"
408 . " WHERE $version_tbl.id=$page_tbl.id"
411 . " ORDER BY version DESC"
413 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
414 $sth->bindParam(2, $version, PDO_PARAM_INT);
416 return $sth->fetchSingle();
422 * @param $version int Which version to get.
424 * @return hash The version data, or false if specified version does not
427 function get_versiondata($pagename, $version, $want_content = false) {
429 extract($this->_table_names);
430 extract($this->_expressions);
432 assert(is_string($pagename) and $pagename != '');
433 assert($version > 0);
435 // FIXME: optimization: sometimes don't get page data?
437 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
438 . ', ' . $this->version_tbl_fields;
440 $fields = $this->page_tbl_fields . ", '' AS pagedata"
441 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
442 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
443 . "$version_tbl.versiondata as versiondata";
445 $sth = $dbh->prepare("SELECT $fields"
446 . " FROM $page_tbl, $version_tbl"
447 . " WHERE $page_tbl.id=$version_tbl.id"
451 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
452 $sth->bindParam(2, $version, PDO_PARAM_INT);
454 $row = $sth->fetch(PDO_FETCH_NUM);
455 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
458 function _extract_version_data_num($row, $want_content) {
463 //$pagename &= $row[1];
464 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
465 $data['mtime'] = $row[5];
466 $data['is_minor_edit'] = !empty($row[6]);
468 $data['%content'] = $row[7];
470 $data['%content'] = !empty($row[7]);
472 if (!empty($row[3])) {
473 $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
478 function _extract_version_data_assoc($row) {
483 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
484 $data['mtime'] = $mtime;
485 $data['is_minor_edit'] = !empty($minor_edit);
487 $data['%content'] = $content;
488 elseif ($have_content)
489 $data['%content'] = true;
491 $data['%content'] = '';
492 if (!empty($pagedata)) {
493 $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
499 * Create a new revision of a page.
501 function set_versiondata($pagename, $version, $data) {
503 $version_tbl = $this->_table_names['version_tbl'];
505 $minor_edit = (int) !empty($data['is_minor_edit']);
506 unset($data['is_minor_edit']);
508 $mtime = (int)$data['mtime'];
509 unset($data['mtime']);
510 assert(!empty($mtime));
512 @$content = (string) $data['%content'];
513 unset($data['%content']);
514 unset($data['%pagedata']);
516 $this->lock(array('page','recent','version','nonempty'));
517 $this->beginTransaction();
518 $id = $this->_get_pageid($pagename, true);
519 $backend_type = $this->backendType();
520 // optimize: mysql can do this with one REPLACE INTO.
521 if (substr($backend_type,0,5) == 'mysql') {
522 $sth = $dbh->prepare("REPLACE INTO $version_tbl"
523 . " (id,version,mtime,minor_edit,content,versiondata)"
524 . " VALUES(?,?,?,?,?,?)");
525 $sth->bindParam(1, $id, PDO_PARAM_INT);
526 $sth->bindParam(2, $version, PDO_PARAM_INT);
527 $sth->bindParam(3, $mtime, PDO_PARAM_INT);
528 $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
529 $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
530 $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
531 $rs = $sth->execute();
533 $sth = $dbh->prepare("DELETE FROM $version_tbl"
534 . " WHERE id=? AND version=?");
535 $sth->bindParam(1, $id, PDO_PARAM_INT);
536 $sth->bindParam(2, $version, PDO_PARAM_INT);
538 $sth = $dbh->prepare("INSERT INTO $version_tbl"
539 . " (id,version,mtime,minor_edit,content,versiondata)"
540 . " VALUES(?,?,?,?,?,?)");
541 $sth->bindParam(1, $id, PDO_PARAM_INT);
542 $sth->bindParam(2, $version, PDO_PARAM_INT);
543 $sth->bindParam(3, $mtime, PDO_PARAM_INT);
544 $sth->bindParam(4, $minor_edit, PDO_PARAM_INT);
545 $sth->bindParam(5, $content, PDO_PARAM_STR, 100);
546 $sth->bindParam(6, $this->_serialize($data), PDO_PARAM_STR, 100);
547 $rs = $sth->execute();
549 $this->_update_recent_table($id);
550 $this->_update_nonempty_table($id);
551 if ($rs) $this->commit( );
552 else $this->rollBack( );
553 $this->unlock(array('page','recent','version','nonempty'));
557 * Delete an old revision of a page.
559 function delete_versiondata($pagename, $version) {
561 extract($this->_table_names);
563 $this->lock(array('version'));
564 if ( ($id = $this->_get_pageid($pagename)) ) {
565 $dbh->query("DELETE FROM $version_tbl"
566 . " WHERE id=$id AND version=$version");
567 $this->_update_recent_table($id);
568 // This shouldn't be needed (as long as the latestversion
569 // never gets deleted.) But, let's be safe.
570 $this->_update_nonempty_table($id);
572 $this->unlock(array('version'));
576 * Delete page from the database with backup possibility.
577 * i.e save_page('') and DELETE nonempty id
579 * deletePage increments latestversion in recent to a non-existent version,
580 * and removes the nonempty row,
581 * so that get_latest_version returns id+1 and get_previous_version returns prev id
582 * and page->exists returns false.
584 function delete_page($pagename) {
586 extract($this->_table_names);
588 $this->beginTransaction();
589 //$dbh->CommitLock($recent_tbl);
590 if (($id = $this->_get_pageid($pagename, false)) === false) {
595 $user =& $GLOBALS['request']->_user;
596 $meta = array('author' => $user->getId(),
597 'author_id' => $user->getAuthenticatedId(),
599 $this->lock(array('version','recent','nonempty','page','link'));
600 $version = $this->get_latest_version($pagename);
601 if ($dbh->query("UPDATE $recent_tbl SET latestversion=latestversion+1,"
602 . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id"))
604 $insert = $dbh->prepare("INSERT INTO $version_tbl"
605 . " (id,version,mtime,minor_edit,content,versiondata)"
606 . " VALUES(?,?,?,?,?,?)");
607 $insert->bindParam(1, $id, PDO_PARAM_INT);
608 $insert->bindParam(2, $version + 1, PDO_PARAM_INT);
609 $insert->bindParam(3, $mtime, PDO_PARAM_INT);
610 $insert->bindParam(4, 0, PDO_PARAM_INT);
611 $insert->bindParam(5, '', PDO_PARAM_STR, 100);
612 $insert->bindParam(6, $this->_serialize($meta), PDO_PARAM_STR, 100);
613 if ($insert->execute()
614 and $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id")
615 and $this->set_links($pagename, false)) {
616 // need to keep perms and LOCKED, otherwise you can reset the perm
617 // by action=remove and re-create it with default perms
618 // keep hits but delete meta-data
619 //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id")
620 $this->unlock(array('version','recent','nonempty','page','link'));
625 $this->unlock(array('version','recent','nonempty','page','link'));
631 function purge_page($pagename) {
633 extract($this->_table_names);
635 $this->lock(array('version','recent','nonempty','page','link'));
636 if ( ($id = $this->_get_pageid($pagename, false)) ) {
637 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
638 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
639 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
640 $this->set_links($pagename, false);
641 $sth = $dbh->prepare("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
643 if ($sth->fetchSingle()) {
644 // We're still in the link table (dangling link) so we can't delete this
646 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
650 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
654 $result = -1; // already purged or not existing
656 $this->unlock(array('version','recent','nonempty','page','link'));
661 // The only thing we might be interested in updating which we can
662 // do fast in the flags (minor_edit). I think the default
663 // update_versiondata will work fine...
664 //function update_versiondata($pagename, $version, $data) {
667 function set_links($pagename, $links) {
668 // Update link table.
669 // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
672 extract($this->_table_names);
674 $this->lock(array('link'));
675 $pageid = $this->_get_pageid($pagename, true);
678 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
679 foreach ($links as $link) {
680 if (isset($linkseen[$link]))
682 $linkseen[$link] = true;
683 $linkid = $this->_get_pageid($link, true);
685 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
686 . " VALUES ($pageid, $linkid)");
689 // purge page table: delete all non-referenced pages
690 // for all previously linked pages...
691 $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl".
692 " WHERE linkfrom=$pageid");
694 foreach ($sth->fetchAll(PDO_FETCH_NUM) as $id) {
695 // ...check if the page is empty and has no version
696 $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl"
697 . " LEFT JOIN $nonempty_tbl USING (id) "
698 . " LEFT JOIN $version_tbl USING (id)"
699 . " WHERE ISNULL($nonempty_tbl.id) AND"
700 . " ISNULL($version_tbl.id) AND $page_tbl.id=$id");
702 if ($sth1->fetchSingle()) {
703 $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
704 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
707 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
709 $this->unlock(array('link'));
714 * Find pages which link to or are linked from a page.
716 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
717 * (linkExistingWikiWord or linkUnknownWikiWord)
718 * This is called on every page header GleanDescription, so we can store all the existing links.
720 function get_links($pagename, $reversed=true, $include_empty=false,
721 $sortby=false, $limit=false, $exclude='') {
723 extract($this->_table_names);
726 list($have,$want) = array('linkee', 'linker');
728 list($have,$want) = array('linker', 'linkee');
729 $orderby = $this->sortby($sortby, 'db', array('pagename'));
730 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
731 if ($exclude) // array of pagenames
732 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
735 $limit = $this->_limit_sql($limit);
737 $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename,"
738 . " $want.hits AS hits"
739 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
740 . (!$include_empty ? ", $nonempty_tbl" : '')
741 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
742 . " AND $have.pagename=?"
743 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
744 //. " GROUP BY $want.id"
748 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
750 $result = $sth->fetch(PDO_FETCH_BOTH);
751 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
755 * Find if a page links to another page
757 function exists_link($pagename, $link, $reversed=false) {
759 extract($this->_table_names);
762 list($have, $want) = array('linkee', 'linker');
764 list($have, $want) = array('linker', 'linkee');
765 $sth = $dbh->prepare("SELECT CASE $want.pagename WHEN 1 ELSE 0 END"
766 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
767 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
768 . " AND $have.pagename=?"
769 . " AND $want.pagename=?);
770 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
771 $sth->bindParam(2, $link, PDO_PARAM_STR, 100);
773 return $sth->fetchSingle();
776 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
778 extract($this->_table_names);
779 $orderby = $this->sortby($sortby, 'db');
780 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
781 if ($exclude) // array of pagenames
782 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
785 $limit = $this->_limit_sql($limit);
787 if (strstr($orderby, 'mtime ')) { // was ' mtime'
788 if ($include_empty) {
790 . $this->page_tbl_fields
791 ." FROM $page_tbl, $recent_tbl, $version_tbl"
792 . " WHERE $page_tbl.id=$recent_tbl.id"
793 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
799 . $this->page_tbl_fields
800 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
801 . " WHERE $nonempty_tbl.id=$page_tbl.id"
802 . " AND $page_tbl.id=$recent_tbl.id"
803 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
808 if ($include_empty) {
810 . $this->page_tbl_fields
812 . ($exclude ? " WHERE $exclude" : '')
816 . $this->page_tbl_fields
817 . " FROM $nonempty_tbl, $page_tbl"
818 . " WHERE $nonempty_tbl.id=$page_tbl.id"
823 $sth = $dbh->prepare($sql . $limit);
825 $result = $sth->fetch(PDO_FETCH_BOTH);
826 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
832 function text_search($search, $fullsearch=false, $sortby=false, $limit=false, $exclude=false) {
834 extract($this->_table_names);
835 $orderby = $this->sortby($sortby, 'db');
836 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
837 $limit = $this->_limit_sql($limit);
839 $table = "$nonempty_tbl, $page_tbl";
840 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
841 $fields = $this->page_tbl_fields;
842 $field_list = $this->page_tbl_field_list;
843 $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
846 $table .= ", $recent_tbl";
847 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
849 $table .= ", $version_tbl";
850 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
852 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
853 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
854 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
856 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
859 $search_clause = $search->makeSqlClauseObj($callback);
860 $sth = $dbh->prepare("SELECT $fields FROM $table"
861 . " WHERE $join_clause"
862 . " AND ($search_clause)"
866 $result = $sth->fetch(PDO_FETCH_NUM);
867 $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list);
868 $iter->stoplisted = $searchobj->stoplisted;
873 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
874 * not sets. See above, but the above methods find too much.
875 * This is only for already resolved wildcards:
876 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
878 function _sql_set(&$pagenames) {
880 foreach ($pagenames as $p) {
881 $s .= ($this->_dbh->qstr($p).",");
883 return substr($s,0,-1).")";
887 * Find highest or lowest hit counts.
889 function most_popular($limit=20, $sortby='-hits') {
891 extract($this->_table_names);
898 $where = " AND hits > 0";
900 if ($sortby != '-hits') {
901 if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
904 $orderby = " ORDER BY hits $order";
906 . $this->page_tbl_fields
907 . " FROM $nonempty_tbl, $page_tbl"
908 . " WHERE $nonempty_tbl.id=$page_tbl.id"
912 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
914 $sth = $dbh->prepare($sql);
917 $result = $sth->fetch(PDO_FETCH_NUM);
918 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
922 * Find recent changes.
924 function most_recent($params) {
927 $include_minor_revisions = false;
928 $exclude_major_revisions = false;
929 $include_all_revisions = false;
933 extract($this->_table_names);
937 $pick[] = "mtime >= $since";
939 if ($include_all_revisions) {
940 // Include all revisions of each page.
941 $table = "$page_tbl, $version_tbl";
942 $join_clause = "$page_tbl.id=$version_tbl.id";
944 if ($exclude_major_revisions) {
945 // Include only minor revisions
946 $pick[] = "minor_edit <> 0";
948 elseif (!$include_minor_revisions) {
949 // Include only major revisions
950 $pick[] = "minor_edit = 0";
954 $table = "$page_tbl, $recent_tbl";
955 $join_clause = "$page_tbl.id=$recent_tbl.id";
956 $table .= ", $version_tbl";
957 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
959 if ($exclude_major_revisions) {
960 // Include only most recent minor revision
961 $pick[] = 'version=latestminor';
963 elseif (!$include_minor_revisions) {
964 // Include only most recent major revision
965 $pick[] = 'version=latestmajor';
968 // Include only the latest revision (whether major or minor).
969 $pick[] ='version=latestversion';
977 $where_clause = $join_clause;
979 $where_clause .= " AND " . join(" AND ", $pick);
981 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
983 . " WHERE $where_clause"
984 . " ORDER BY mtime $order";
986 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
988 $sth = $dbh->prepare($sql);
991 $result = $sth->fetch(PDO_FETCH_NUM);
992 return new WikiDB_backend_PDO_iter($this, $result,
993 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
997 * Find referenced empty pages.
999 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
1000 $dbh = &$this->_dbh;
1001 extract($this->_table_names);
1002 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1003 $orderby = 'ORDER BY ' . $orderby;
1005 if ($exclude_from) // array of pagenames
1006 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
1007 if ($exclude) // array of pagenames
1008 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
1011 all empty pages, independent of linkstatus:
1012 select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1013 only all empty pages, which have a linkto:
1014 select page.pagename, linked.pagename as wantedfrom from link, page as linked
1015 left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1016 where isnull(nonempty.id) and linked.id=link.linkfrom;
1018 $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1019 . " FROM $page_tbl p JOIN $link_tbl linked"
1020 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
1021 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
1022 . " WHERE ne.id is NULL"
1023 . " AND p.id = linked.linkfrom"
1028 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1030 $sth = $dbh->prepare($sql);
1033 $result = $sth->fetch(PDO_FETCH_NUM);
1034 return new WikiDB_backend_PDO_iter($this, $result, array('pagename','wantedfrom'));
1038 * Rename page in the database.
1040 function rename_page($pagename, $to) {
1041 $dbh = &$this->_dbh;
1042 extract($this->_table_names);
1044 $this->lock(array('page','version','recent','nonempty','link'));
1045 if ( ($id = $this->_get_pageid($pagename, false)) ) {
1046 if ($new = $this->_get_pageid($to, false)) {
1048 // This page does not exist (already verified before), but exists in the page table.
1049 // So we delete this page.
1050 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1051 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1052 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1053 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1054 // We have to fix all referring tables to the old id
1055 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1056 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1058 $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1059 $sth->bindParam(1, $to, PDO_PARAM_STR, 100);
1060 $sth->bindParam(2, $id, PDO_PARAM_INT);
1063 $this->unlock(array('page'));
1067 function _update_recent_table($pageid = false) {
1068 $dbh = &$this->_dbh;
1069 extract($this->_table_names);
1070 extract($this->_expressions);
1072 $pageid = (int)$pageid;
1074 // optimize: mysql can do this with one REPLACE INTO.
1075 $backend_type = $this->backendType();
1076 if (substr($backend_type,0,5) == 'mysql') {
1077 $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1078 . " (id, latestversion, latestmajor, latestminor)"
1079 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1080 . " FROM $version_tbl"
1081 . ( $pageid ? " WHERE id=$pageid" : "")
1085 $this->lock(array('recent'));
1086 $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1087 . ( $pageid ? " WHERE id=$pageid" : ""));
1089 $sth = $dbh->prepare( "INSERT INTO $recent_tbl"
1090 . " (id, latestversion, latestmajor, latestminor)"
1091 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1092 . " FROM $version_tbl"
1093 . ( $pageid ? " WHERE id=$pageid" : "")
1096 $this->unlock(array('recent'));
1100 function _update_nonempty_table($pageid = false) {
1101 $dbh = &$this->_dbh;
1102 extract($this->_table_names);
1103 extract($this->_expressions);
1105 $pageid = (int)$pageid;
1107 extract($this->_expressions);
1108 $this->lock(array('nonempty'));
1109 $dbh->query("DELETE FROM $nonempty_tbl"
1110 . ( $pageid ? " WHERE id=$pageid" : ""));
1111 $dbh->query("INSERT INTO $nonempty_tbl (id)"
1112 . " SELECT $recent_tbl.id"
1113 . " FROM $recent_tbl, $version_tbl"
1114 . " WHERE $recent_tbl.id=$version_tbl.id"
1115 . " AND version=latestversion"
1116 // We have some specifics here (Oracle)
1117 //. " AND content<>''"
1118 . " AND content $notempty"
1119 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1120 $this->unlock(array('nonempty'));
1124 * Grab a write lock on the tables in the SQL database.
1126 * Calls can be nested. The tables won't be unlocked until
1127 * _unlock_database() is called as many times as _lock_database().
1131 function lock($tables, $write_lock = true) {
1132 if ($this->_lock_count++ == 0) {
1133 $this->_current_lock = $tables;
1134 if (!$this->_hasTransactions)
1135 $this->_lock_tables($tables, $write_lock);
1140 * Overridden by non-transaction safe backends.
1142 function _lock_tables($tables, $write_lock) {
1143 $lock_type = $write_lock ? "WRITE" : "READ";
1144 foreach ($this->_table_names as $key => $table) {
1145 $locks[] = "$table $lock_type";
1147 $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1151 * Release a write lock on the tables in the SQL database.
1155 * @param $force boolean Unlock even if not every call to lock() has been matched
1156 * by a call to unlock().
1158 * @see _lock_database
1160 function unlock($tables = false, $force = false) {
1161 if ($this->_lock_count == 0) {
1162 $this->_current_lock = false;
1165 if (--$this->_lock_count <= 0 || $force) {
1166 if (!$this->_hasTransactions)
1167 $this->_unlock_tables($tables);
1168 $this->_current_lock = false;
1169 $this->_lock_count = 0;
1174 * overridden by non-transaction safe backends
1176 function _unlock_tables($tables) {
1177 $this->_dbh->query("UNLOCK TABLES");
1183 function _serialize($data) {
1186 assert(is_array($data));
1187 return serialize($data);
1193 function _unserialize($data) {
1194 return empty($data) ? array() : unserialize($data);
1197 /* some variables and functions for DB backend abstraction (action=upgrade) */
1198 function database () {
1199 return $this->_dbh->database;
1201 function backendType() {
1202 return $this->_dbh->databaseType;
1204 function connection() {
1205 trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1208 function listOfTables() {
1209 trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1212 function listOfFields($database, $table) {
1213 trigger_error("PDO: virtual listOfFields", E_USER_ERROR);
1218 * LIMIT with OFFSET is not SQL specified.
1219 * mysql: LIMIT $offset, $count
1220 * pgsql,sqlite: LIMIT $count OFFSET $offset
1221 * InterBase,FireBird: ROWS $offset TO $last
1222 * mssql: TOP $rows => TOP $last
1224 * IBM DB2: FetchFirst
1225 * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1227 SELECT field_list FROM $table X WHERE where_clause AND
1229 SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1231 BETWEEN $offset AND $last
1232 ORDER BY $pk $asc_desc
1234 function _limit_sql($limit = false) {
1236 list($offset, $count) = $this->limit($limit);
1238 $limit = " LIMIT $count";
1239 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1241 $limit = " LIMIT $count";
1248 class WikiDB_backend_PDO_generic_iter
1249 extends WikiDB_backend_iterator
1251 function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) {
1252 $this->_backend = &$backend;
1253 $this->_result = $query_result;
1254 //$this->_fields = $field_list;
1258 if (!is_object($this->_result)) {
1261 $count = $this->_result->rowCount();
1266 $result = &$this->_result;
1267 if (!is_object($result)) {
1270 return $result->fetch(PDO_FETCH_BOTH);
1274 if ($this->_result) {
1275 unset($this->_result);
1280 class WikiDB_backend_PDO_iter
1281 extends WikiDB_backend_PDO_generic_iter
1284 $result = &$this->_result;
1285 if (!is_object($result)) {
1288 $this->_backend = &$backend;
1289 $rec = $result->fetch(PDO_FETCH_ASSOC);
1291 if (isset($rec['pagedata']))
1292 $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1293 if (!empty($rec['version'])) {
1294 $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1300 class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql {}
1302 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1303 // Eventually, change index.php to provide the relevant information
1306 * Parse a data source name.
1308 * Additional keys can be added by appending a URI query string to the
1311 * The format of the supplied DSN is in its fullest form:
1313 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1316 * Most variations are allowed:
1318 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1319 * phptype://username:password@hostspec/database_name
1320 * phptype://username:password@hostspec
1321 * phptype://username@hostspec
1322 * phptype://hostspec/database
1323 * phptype://hostspec
1328 * @param string $dsn Data Source Name to be parsed
1330 * @return array an associative array with the following keys:
1331 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1332 * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1333 * + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1334 * + hostspec: Host specification (hostname[:port])
1335 * + database: Database to use on the DBMS server
1336 * + username: User name for login
1337 * + password: Password for login
1339 * @author Tomas V.V.Cox <cox@idecnet.com>
1341 function parseDSN($dsn)
1345 'dbsyntax' => false,
1346 'username' => false,
1347 'password' => false,
1348 'protocol' => false,
1349 'hostspec' => false,
1352 'database' => false,
1355 if (is_array($dsn)) {
1356 $dsn = array_merge($parsed, $dsn);
1357 if (!$dsn['dbsyntax']) {
1358 $dsn['dbsyntax'] = $dsn['phptype'];
1363 // Find phptype and dbsyntax
1364 if (($pos = strpos($dsn, '://')) !== false) {
1365 $str = substr($dsn, 0, $pos);
1366 $dsn = substr($dsn, $pos + 3);
1372 // Get phptype and dbsyntax
1373 // $str => phptype(dbsyntax)
1374 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1375 $parsed['phptype'] = $arr[1];
1376 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1378 $parsed['phptype'] = $str;
1379 $parsed['dbsyntax'] = $str;
1386 // Get (if found): username and password
1387 // $dsn => username:password@protocol+hostspec/database
1388 if (($at = strrpos($dsn,'@')) !== false) {
1389 $str = substr($dsn, 0, $at);
1390 $dsn = substr($dsn, $at + 1);
1391 if (($pos = strpos($str, ':')) !== false) {
1392 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1393 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1395 $parsed['username'] = rawurldecode($str);
1399 // Find protocol and hostspec
1401 // $dsn => proto(proto_opts)/database
1402 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1404 $proto_opts = $match[2] ? $match[2] : false;
1407 // $dsn => protocol+hostspec/database (old format)
1409 if (strpos($dsn, '+') !== false) {
1410 list($proto, $dsn) = explode('+', $dsn, 2);
1412 if (strpos($dsn, '/') !== false) {
1413 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1420 // process the different protocol options
1421 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1422 $proto_opts = rawurldecode($proto_opts);
1423 if ($parsed['protocol'] == 'tcp') {
1424 if (strpos($proto_opts, ':') !== false) {
1425 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1427 $parsed['hostspec'] = $proto_opts;
1429 } elseif ($parsed['protocol'] == 'unix') {
1430 $parsed['socket'] = $proto_opts;
1433 // Get dabase if any
1437 if (($pos = strpos($dsn, '?')) === false) {
1438 $parsed['database'] = $dsn;
1439 // /database?param1=value1¶m2=value2
1441 $parsed['database'] = substr($dsn, 0, $pos);
1442 $dsn = substr($dsn, $pos + 1);
1443 if (strpos($dsn, '&') !== false) {
1444 $opts = explode('&', $dsn);
1445 } else { // database?param1=value1
1446 $opts = array($dsn);
1448 foreach ($opts as $opt) {
1449 list($key, $value) = explode('=', $opt);
1450 if (!isset($parsed[$key])) {
1451 // don't allow params overwrite
1452 $parsed[$key] = rawurldecode($value);
1461 // $Log: not supported by cvs2svn $
1462 // Revision 1.7 2006/05/14 12:28:03 rurban
1463 // mysql 5.x fix for wantedpages join
1465 // Revision 1.6 2005/11/14 22:24:33 rurban
1466 // fix fulltext search,
1467 // Eliminate stoplist words,
1468 // don't extract %pagedate twice in ADODB,
1469 // add SemanticWeb support: link(relation),
1470 // major postgresql update: stored procedures, tsearch2 for fulltext
1472 // Revision 1.5 2005/09/14 06:04:43 rurban
1473 // optimize searching for ALL (ie %), use the stoplist on PDO
1475 // Revision 1.4 2005/09/11 13:25:12 rurban
1476 // enhance LIMIT support
1478 // Revision 1.3 2005/09/10 21:30:16 rurban
1479 // enhance titleSearch
1481 // Revision 1.2 2005/02/11 14:45:45 rurban
1482 // support ENABLE_LIVESEARCH, enable PDO sessions
1484 // Revision 1.1 2005/02/10 19:01:22 rurban
1488 // (c-file-style: "gnu")
1492 // c-basic-offset: 4
1493 // c-hanging-comment-ender-p: nil
1494 // indent-tabs-mode: nil