2 rcs_id('$Id: PDO.php,v 1.5 2005-09-14 06:04:43 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 IF($want.pagename,1,0)"
766 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
767 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
768 . " AND $have.pagename=?"
769 . " AND $want.pagename=?"
771 $sth->bindParam(1, $pagename, PDO_PARAM_STR, 100);
772 $sth->bindParam(2, $link, PDO_PARAM_STR, 100);
774 return $sth->fetchSingle();
777 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
779 extract($this->_table_names);
780 $orderby = $this->sortby($sortby, 'db');
781 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
782 if ($exclude) // array of pagenames
783 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
786 $limit = $this->_limit_sql($limit);
788 if (strstr($orderby, 'mtime ')) { // was ' mtime'
789 if ($include_empty) {
791 . $this->page_tbl_fields
792 ." FROM $page_tbl, $recent_tbl, $version_tbl"
793 . " WHERE $page_tbl.id=$recent_tbl.id"
794 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
800 . $this->page_tbl_fields
801 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
802 . " WHERE $nonempty_tbl.id=$page_tbl.id"
803 . " AND $page_tbl.id=$recent_tbl.id"
804 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
809 if ($include_empty) {
811 . $this->page_tbl_fields
813 . ($exclude ? " WHERE $exclude" : '')
817 . $this->page_tbl_fields
818 . " FROM $nonempty_tbl, $page_tbl"
819 . " WHERE $nonempty_tbl.id=$page_tbl.id"
824 $sth = $dbh->prepare($sql . $limit);
826 $result = $sth->fetch(PDO_FETCH_BOTH);
827 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
833 function text_search($search, $fullsearch=false, $sortby=false, $limit=false, $exclude=false) {
835 extract($this->_table_names);
836 $orderby = $this->sortby($sortby, 'db');
837 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
838 $limit = $this->_limit_sql($limit);
840 $table = "$nonempty_tbl, $page_tbl";
841 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
842 $fields = $this->page_tbl_fields;
843 $field_list = $this->page_tbl_field_list;
844 $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
847 $table .= ", $recent_tbl";
848 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
850 $table .= ", $version_tbl";
851 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
853 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
854 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
855 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
857 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
860 $search_clause = $search->makeSqlClauseObj($callback);
861 $sth = $dbh->prepare("SELECT $fields FROM $table"
862 . " WHERE $join_clause"
863 . " AND ($search_clause)"
867 $result = $sth->fetch(PDO_FETCH_NUM);
868 return new WikiDB_backend_PDO_iter($this, $result, $field_list);
872 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
873 * not sets. See above, but the above methods find too much.
874 * This is only for already resolved wildcards:
875 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
877 function _sql_set(&$pagenames) {
879 foreach ($pagenames as $p) {
880 $s .= ($this->_dbh->qstr($p).",");
882 return substr($s,0,-1).")";
886 * Find highest or lowest hit counts.
888 function most_popular($limit=20, $sortby='-hits') {
890 extract($this->_table_names);
897 $where = " AND hits > 0";
899 if ($sortby != '-hits') {
900 if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
903 $orderby = " ORDER BY hits $order";
905 . $this->page_tbl_fields
906 . " FROM $nonempty_tbl, $page_tbl"
907 . " WHERE $nonempty_tbl.id=$page_tbl.id"
911 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
913 $sth = $dbh->prepare($sql);
916 $result = $sth->fetch(PDO_FETCH_NUM);
917 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
921 * Find recent changes.
923 function most_recent($params) {
926 $include_minor_revisions = false;
927 $exclude_major_revisions = false;
928 $include_all_revisions = false;
932 extract($this->_table_names);
936 $pick[] = "mtime >= $since";
938 if ($include_all_revisions) {
939 // Include all revisions of each page.
940 $table = "$page_tbl, $version_tbl";
941 $join_clause = "$page_tbl.id=$version_tbl.id";
943 if ($exclude_major_revisions) {
944 // Include only minor revisions
945 $pick[] = "minor_edit <> 0";
947 elseif (!$include_minor_revisions) {
948 // Include only major revisions
949 $pick[] = "minor_edit = 0";
953 $table = "$page_tbl, $recent_tbl";
954 $join_clause = "$page_tbl.id=$recent_tbl.id";
955 $table .= ", $version_tbl";
956 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
958 if ($exclude_major_revisions) {
959 // Include only most recent minor revision
960 $pick[] = 'version=latestminor';
962 elseif (!$include_minor_revisions) {
963 // Include only most recent major revision
964 $pick[] = 'version=latestmajor';
967 // Include only the latest revision (whether major or minor).
968 $pick[] ='version=latestversion';
976 $where_clause = $join_clause;
978 $where_clause .= " AND " . join(" AND ", $pick);
980 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
982 . " WHERE $where_clause"
983 . " ORDER BY mtime $order";
985 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
987 $sth = $dbh->prepare($sql);
990 $result = $sth->fetch(PDO_FETCH_NUM);
991 return new WikiDB_backend_PDO_iter($this, $result,
992 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
996 * Find referenced empty pages.
998 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
1000 extract($this->_table_names);
1001 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1002 $orderby = 'ORDER BY ' . $orderby;
1004 if ($exclude_from) // array of pagenames
1005 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
1006 if ($exclude) // array of pagenames
1007 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
1010 all empty pages, independent of linkstatus:
1011 select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1012 only all empty pages, which have a linkto:
1013 select page.pagename, linked.pagename as wantedfrom from link, page as linked
1014 left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1015 where isnull(nonempty.id) and linked.id=link.linkfrom;
1017 $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
1018 . " FROM $link_tbl,$page_tbl as linked "
1019 . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
1020 . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)"
1021 . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
1026 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1028 $sth = $dbh->prepare($sql);
1031 $result = $sth->fetch(PDO_FETCH_NUM);
1032 return new WikiDB_backend_PDO_iter($this, $result, array('pagename','wantedfrom'));
1036 * Rename page in the database.
1038 function rename_page($pagename, $to) {
1039 $dbh = &$this->_dbh;
1040 extract($this->_table_names);
1042 $this->lock(array('page','version','recent','nonempty','link'));
1043 if ( ($id = $this->_get_pageid($pagename, false)) ) {
1044 if ($new = $this->_get_pageid($to, false)) {
1046 // This page does not exist (already verified before), but exists in the page table.
1047 // So we delete this page.
1048 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1049 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1050 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1051 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1052 // We have to fix all referring tables to the old id
1053 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1054 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1056 $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1057 $sth->bindParam(1, $to, PDO_PARAM_STR, 100);
1058 $sth->bindParam(2, $id, PDO_PARAM_INT);
1061 $this->unlock(array('page'));
1065 function _update_recent_table($pageid = false) {
1066 $dbh = &$this->_dbh;
1067 extract($this->_table_names);
1068 extract($this->_expressions);
1070 $pageid = (int)$pageid;
1072 // optimize: mysql can do this with one REPLACE INTO.
1073 $backend_type = $this->backendType();
1074 if (substr($backend_type,0,5) == 'mysql') {
1075 $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1076 . " (id, latestversion, latestmajor, latestminor)"
1077 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1078 . " FROM $version_tbl"
1079 . ( $pageid ? " WHERE id=$pageid" : "")
1083 $this->lock(array('recent'));
1084 $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1085 . ( $pageid ? " WHERE id=$pageid" : ""));
1087 $sth = $dbh->prepare( "INSERT INTO $recent_tbl"
1088 . " (id, latestversion, latestmajor, latestminor)"
1089 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1090 . " FROM $version_tbl"
1091 . ( $pageid ? " WHERE id=$pageid" : "")
1094 $this->unlock(array('recent'));
1098 function _update_nonempty_table($pageid = false) {
1099 $dbh = &$this->_dbh;
1100 extract($this->_table_names);
1101 extract($this->_expressions);
1103 $pageid = (int)$pageid;
1105 extract($this->_expressions);
1106 $this->lock(array('nonempty'));
1107 $dbh->query("DELETE FROM $nonempty_tbl"
1108 . ( $pageid ? " WHERE id=$pageid" : ""));
1109 $dbh->query("INSERT INTO $nonempty_tbl (id)"
1110 . " SELECT $recent_tbl.id"
1111 . " FROM $recent_tbl, $version_tbl"
1112 . " WHERE $recent_tbl.id=$version_tbl.id"
1113 . " AND version=latestversion"
1114 // We have some specifics here (Oracle)
1115 //. " AND content<>''"
1116 . " AND content $notempty"
1117 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1118 $this->unlock(array('nonempty'));
1122 * Grab a write lock on the tables in the SQL database.
1124 * Calls can be nested. The tables won't be unlocked until
1125 * _unlock_database() is called as many times as _lock_database().
1129 function lock($tables, $write_lock = true) {
1130 if ($this->_lock_count++ == 0) {
1131 $this->_current_lock = $tables;
1132 if (!$this->_hasTransactions)
1133 $this->_lock_tables($tables, $write_lock);
1138 * Overridden by non-transaction safe backends.
1140 function _lock_tables($tables, $write_lock) {
1141 $lock_type = $write_lock ? "WRITE" : "READ";
1142 foreach ($this->_table_names as $key => $table) {
1143 $locks[] = "$table $lock_type";
1145 $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1149 * Release a write lock on the tables in the SQL database.
1153 * @param $force boolean Unlock even if not every call to lock() has been matched
1154 * by a call to unlock().
1156 * @see _lock_database
1158 function unlock($tables = false, $force = false) {
1159 if ($this->_lock_count == 0) {
1160 $this->_current_lock = false;
1163 if (--$this->_lock_count <= 0 || $force) {
1164 if (!$this->_hasTransactions)
1165 $this->_unlock_tables($tables);
1166 $this->_current_lock = false;
1167 $this->_lock_count = 0;
1172 * overridden by non-transaction safe backends
1174 function _unlock_tables($tables) {
1175 $this->_dbh->query("UNLOCK TABLES");
1181 function _serialize($data) {
1184 assert(is_array($data));
1185 return serialize($data);
1191 function _unserialize($data) {
1192 return empty($data) ? array() : unserialize($data);
1195 /* some variables and functions for DB backend abstraction (action=upgrade) */
1196 function database () {
1197 return $this->_dbh->database;
1199 function backendType() {
1200 return $this->_dbh->databaseType;
1202 function connection() {
1203 trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1206 function listOfTables() {
1207 trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1210 function listOfFields($database, $table) {
1211 trigger_error("PDO: virtual listOfFields", E_USER_ERROR);
1216 * LIMIT with OFFSET is not SQL specified.
1217 * mysql: LIMIT $offset, $count
1218 * pgsql,sqlite: LIMIT $count OFFSET $offset
1219 * InterBase,FireBird: ROWS $offset TO $last
1220 * mssql: TOP $rows => TOP $last
1222 * IBM DB2: FetchFirst
1223 * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1225 SELECT field_list FROM $table X WHERE where_clause AND
1227 SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1229 BETWEEN $offset AND $last
1230 ORDER BY $pk $asc_desc
1232 function _limit_sql($limit = false) {
1234 list($offset, $count) = $this->limit($limit);
1236 $limit = " LIMIT $count";
1237 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1239 $limit = " LIMIT $count";
1246 class WikiDB_backend_PDO_generic_iter
1247 extends WikiDB_backend_iterator
1249 function WikiDB_backend_PDO_generic_iter($backend, $query_result, $field_list = NULL) {
1250 $this->_backend = &$backend;
1251 $this->_result = $query_result;
1252 //$this->_fields = $field_list;
1256 if (!is_object($this->_result)) {
1259 $count = $this->_result->rowCount();
1264 $result = &$this->_result;
1265 if (!is_object($result)) {
1268 return $result->fetch(PDO_FETCH_BOTH);
1272 if ($this->_result) {
1273 unset($this->_result);
1278 class WikiDB_backend_PDO_iter
1279 extends WikiDB_backend_PDO_generic_iter
1282 $result = &$this->_result;
1283 if (!is_object($result)) {
1286 $this->_backend = &$backend;
1287 $rec = $result->fetch(PDO_FETCH_ASSOC);
1289 if (isset($rec['pagedata']))
1290 $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1291 if (!empty($rec['version'])) {
1292 $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1298 class WikiDB_backend_PDO_search
1299 extends WikiDB_backend_search
1301 function WikiDB_backend_PDO_search(&$search, &$dbh) {
1302 $this->_dbh =& $dbh;
1303 $this->_case_exact = $search->_case_exact;
1305 function _pagename_match_clause($node) {
1306 // word already quoted by TextSearchQuery_node_word::_sql_quote()
1307 $word = $node->sql();
1311 return ($this->_case_exact
1312 ? "pagename LIKE '$word'"
1313 : "LOWER(pagename) LIKE '$word'");
1315 function _fulltext_match_clause($node) {
1316 $word = $node->sql();
1319 // eliminate stoplist words
1320 if (preg_match("/^%".$this->_stoplist."%/i", $word)
1321 or preg_match("/^".$this->_stoplist."$/i", $word))
1322 return $this->_pagename_match_clause($node);
1324 return $this->_pagename_match_clause($node)
1325 . ($this->_case_exact ? " OR content LIKE '$word'"
1326 : " OR LOWER(content) LIKE '$word'");
1330 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1331 // Eventually, change index.php to provide the relevant information
1334 * Parse a data source name.
1336 * Additional keys can be added by appending a URI query string to the
1339 * The format of the supplied DSN is in its fullest form:
1341 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1344 * Most variations are allowed:
1346 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1347 * phptype://username:password@hostspec/database_name
1348 * phptype://username:password@hostspec
1349 * phptype://username@hostspec
1350 * phptype://hostspec/database
1351 * phptype://hostspec
1356 * @param string $dsn Data Source Name to be parsed
1358 * @return array an associative array with the following keys:
1359 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1360 * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1361 * + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1362 * + hostspec: Host specification (hostname[:port])
1363 * + database: Database to use on the DBMS server
1364 * + username: User name for login
1365 * + password: Password for login
1367 * @author Tomas V.V.Cox <cox@idecnet.com>
1369 function parseDSN($dsn)
1373 'dbsyntax' => false,
1374 'username' => false,
1375 'password' => false,
1376 'protocol' => false,
1377 'hostspec' => false,
1380 'database' => false,
1383 if (is_array($dsn)) {
1384 $dsn = array_merge($parsed, $dsn);
1385 if (!$dsn['dbsyntax']) {
1386 $dsn['dbsyntax'] = $dsn['phptype'];
1391 // Find phptype and dbsyntax
1392 if (($pos = strpos($dsn, '://')) !== false) {
1393 $str = substr($dsn, 0, $pos);
1394 $dsn = substr($dsn, $pos + 3);
1400 // Get phptype and dbsyntax
1401 // $str => phptype(dbsyntax)
1402 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1403 $parsed['phptype'] = $arr[1];
1404 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1406 $parsed['phptype'] = $str;
1407 $parsed['dbsyntax'] = $str;
1414 // Get (if found): username and password
1415 // $dsn => username:password@protocol+hostspec/database
1416 if (($at = strrpos($dsn,'@')) !== false) {
1417 $str = substr($dsn, 0, $at);
1418 $dsn = substr($dsn, $at + 1);
1419 if (($pos = strpos($str, ':')) !== false) {
1420 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1421 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1423 $parsed['username'] = rawurldecode($str);
1427 // Find protocol and hostspec
1429 // $dsn => proto(proto_opts)/database
1430 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1432 $proto_opts = $match[2] ? $match[2] : false;
1435 // $dsn => protocol+hostspec/database (old format)
1437 if (strpos($dsn, '+') !== false) {
1438 list($proto, $dsn) = explode('+', $dsn, 2);
1440 if (strpos($dsn, '/') !== false) {
1441 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1448 // process the different protocol options
1449 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1450 $proto_opts = rawurldecode($proto_opts);
1451 if ($parsed['protocol'] == 'tcp') {
1452 if (strpos($proto_opts, ':') !== false) {
1453 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1455 $parsed['hostspec'] = $proto_opts;
1457 } elseif ($parsed['protocol'] == 'unix') {
1458 $parsed['socket'] = $proto_opts;
1461 // Get dabase if any
1465 if (($pos = strpos($dsn, '?')) === false) {
1466 $parsed['database'] = $dsn;
1467 // /database?param1=value1¶m2=value2
1469 $parsed['database'] = substr($dsn, 0, $pos);
1470 $dsn = substr($dsn, $pos + 1);
1471 if (strpos($dsn, '&') !== false) {
1472 $opts = explode('&', $dsn);
1473 } else { // database?param1=value1
1474 $opts = array($dsn);
1476 foreach ($opts as $opt) {
1477 list($key, $value) = explode('=', $opt);
1478 if (!isset($parsed[$key])) {
1479 // don't allow params overwrite
1480 $parsed[$key] = rawurldecode($value);
1489 // $Log: not supported by cvs2svn $
1490 // Revision 1.4 2005/09/11 13:25:12 rurban
1491 // enhance LIMIT support
1493 // Revision 1.3 2005/09/10 21:30:16 rurban
1494 // enhance titleSearch
1496 // Revision 1.2 2005/02/11 14:45:45 rurban
1497 // support ENABLE_LIVESEARCH, enable PDO sessions
1499 // Revision 1.1 2005/02/10 19:01:22 rurban
1503 // (c-file-style: "gnu")
1507 // c-basic-offset: 4
1508 // c-hanging-comment-ender-p: nil
1509 // indent-tabs-mode: nil