2 rcs_id('$Id: PearDB.php,v 1.40 2004-03-01 13:48:45 rurban Exp $');
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 require_once('lib/ErrorManager.php');
7 require_once('lib/pear/DB.php'); // Always favor use our local pear copy
9 class WikiDB_backend_PearDB
10 extends WikiDB_backend
14 function WikiDB_backend_PearDB ($dbparams) {
15 // Find and include PEAR's DB.php.
16 //$pearFinder = new PearFileFinder;
17 //$pearFinder->includeOnce('DB.php');
19 // Install filter to handle bogus error notices from buggy DB.php's.
21 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
23 // Open connection to database
24 $this->_dsn = $dbparams['dsn'];
25 $dboptions = array('persistent' => true,
27 $this->_dbh = DB::connect($this->_dsn, $dboptions);
29 if (DB::isError($dbh)) {
30 trigger_error(sprintf("Can't connect to database: %s",
31 $this->_pear_error_message($dbh)),
34 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
35 array(&$this, '_pear_error_callback'));
36 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
38 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
41 = array('page_tbl' => $prefix . 'page',
42 'version_tbl' => $prefix . 'version',
43 'link_tbl' => $prefix . 'link',
44 'recent_tbl' => $prefix . 'recent',
45 'nonempty_tbl' => $prefix . 'nonempty');
48 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
49 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
50 'maxversion' => "MAX(version)");
52 $this->_lock_count = 0;
56 * Close database connection.
61 if ($this->_lock_count) {
62 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
65 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
66 $this->unlock('force');
68 $this->_dbh->disconnect();
75 function is_wiki_page($pagename) {
77 extract($this->_table_names);
78 return $dbh->getOne(sprintf("SELECT $page_tbl.id"
79 . " FROM $nonempty_tbl, $page_tbl"
80 . " WHERE $nonempty_tbl.id=$page_tbl.id"
81 . " AND pagename='%s'",
82 $dbh->quoteString($pagename)));
85 function get_all_pagenames() {
87 extract($this->_table_names);
88 return $dbh->getCol("SELECT pagename"
89 . " FROM $nonempty_tbl, $page_tbl"
90 . " WHERE $nonempty_tbl.id=$page_tbl.id");
94 * Read page information from database.
96 function get_pagedata($pagename) {
98 $page_tbl = $this->_table_names['page_tbl'];
100 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
102 $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
103 $dbh->quoteString($pagename)),
107 return $this->_extract_page_data($result);
110 function _extract_page_data(&$query_result) {
111 extract($query_result);
112 $data = $this->_unserialize($pagedata);
113 $data['hits'] = $hits;
117 function update_pagedata($pagename, $newdata) {
119 $page_tbl = $this->_table_names['page_tbl'];
121 // Hits is the only thing we can update in a fast manner.
122 if (count($newdata) == 1 && isset($newdata['hits'])) {
123 // Note that this will fail silently if the page does not
124 // have a record in the page table. Since it's just the
125 // hit count, who cares?
126 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
127 $newdata['hits'], $dbh->quoteString($pagename)));
132 $data = $this->get_pagedata($pagename);
135 $this->_get_pageid($pagename, true); // Creates page record
138 @$hits = (int)$data['hits'];
139 unset($data['hits']);
141 foreach ($newdata as $key => $val) {
144 else if (empty($val))
150 $dbh->query(sprintf("UPDATE $page_tbl"
151 . " SET hits=%d, pagedata='%s'"
152 . " WHERE pagename='%s'",
154 $dbh->quoteString($this->_serialize($data)),
155 $dbh->quoteString($pagename)));
160 function _get_pageid($pagename, $create_if_missing = false) {
163 $page_tbl = $this->_table_names['page_tbl'];
165 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
166 $dbh->quoteString($pagename));
168 if (!$create_if_missing)
169 return $dbh->getOne($query);
172 $id = $dbh->getOne($query);
174 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
176 $dbh->query(sprintf("INSERT INTO $page_tbl"
177 . " (id,pagename,hits)"
178 . " VALUES (%d,'%s',0)",
179 $id, $dbh->quoteString($pagename)));
185 function get_latest_version($pagename) {
187 extract($this->_table_names);
189 (int)$dbh->getOne(sprintf("SELECT latestversion"
190 . " FROM $page_tbl, $recent_tbl"
191 . " WHERE $page_tbl.id=$recent_tbl.id"
192 . " AND pagename='%s'",
193 $dbh->quoteString($pagename)));
196 function get_previous_version($pagename, $version) {
198 extract($this->_table_names);
201 (int)$dbh->getOne(sprintf("SELECT version"
202 . " FROM $version_tbl, $page_tbl"
203 . " WHERE $version_tbl.id=$page_tbl.id"
204 . " AND pagename='%s'"
205 . " AND version < %d"
206 . " ORDER BY version DESC"
208 $dbh->quoteString($pagename),
215 * @param $version int Which version to get.
217 * @return hash The version data, or false if specified version does not
220 function get_versiondata($pagename, $version, $want_content = false) {
222 extract($this->_table_names);
224 assert(!empty($pagename));
225 assert($version > 0);
227 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
228 // FIXME: optimization: sometimes don't get page data?
234 $fields = ("$page_tbl.*,"
235 . "mtime,minor_edit,versiondata,"
236 . "content<>'' AS have_content");
239 $result = $dbh->getRow(sprintf("SELECT $fields"
240 . " FROM $page_tbl, $version_tbl"
241 . " WHERE $page_tbl.id=$version_tbl.id"
242 . " AND pagename='%s'"
244 $dbh->quoteString($pagename), $version),
247 return $this->_extract_version_data($result);
250 function _extract_version_data(&$query_result) {
254 extract($query_result);
255 $data = $this->_unserialize($versiondata);
257 $data['mtime'] = $mtime;
258 $data['is_minor_edit'] = !empty($minor_edit);
261 $data['%content'] = $content;
262 elseif ($have_content)
263 $data['%content'] = true;
265 $data['%content'] = '';
267 // FIXME: this is ugly.
268 if (isset($pagename)) {
269 // Query also includes page data.
270 // We might as well send that back too...
271 $data['%pagedata'] = $this->_extract_page_data($query_result);
279 * Create a new revision of a page.
281 function set_versiondata($pagename, $version, $data) {
283 $version_tbl = $this->_table_names['version_tbl'];
285 $minor_edit = (int) !empty($data['is_minor_edit']);
286 unset($data['is_minor_edit']);
288 $mtime = (int)$data['mtime'];
289 unset($data['mtime']);
290 assert(!empty($mtime));
292 @$content = (string) $data['%content'];
293 unset($data['%content']);
295 unset($data['%pagedata']);
298 $id = $this->_get_pageid($pagename, true);
300 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
301 $dbh->query(sprintf("DELETE FROM $version_tbl"
302 . " WHERE id=%d AND version=%d",
305 $dbh->query(sprintf("INSERT INTO $version_tbl"
306 . " (id,version,mtime,minor_edit,content,versiondata)"
307 . " VALUES(%d,%d,%d,%d,'%s','%s')",
308 $id, $version, $mtime, $minor_edit,
309 $dbh->quoteString($content),
310 $dbh->quoteString($this->_serialize($data))));
312 $this->_update_recent_table($id);
313 $this->_update_nonempty_table($id);
319 * Delete an old revision of a page.
321 function delete_versiondata($pagename, $version) {
323 extract($this->_table_names);
326 if ( ($id = $this->_get_pageid($pagename)) ) {
327 $dbh->query("DELETE FROM $version_tbl"
328 . " WHERE id=$id AND version=$version");
329 $this->_update_recent_table($id);
330 // This shouldn't be needed (as long as the latestversion
331 // never gets deleted.) But, let's be safe.
332 $this->_update_nonempty_table($id);
338 * Delete page completely from the database.
339 * I'm not sure if this is what we want. Maybe just delete the revisions
341 function delete_page($pagename) {
343 extract($this->_table_names);
346 if ( ($id = $this->_get_pageid($pagename, false)) ) {
347 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
348 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
349 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
350 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
351 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
353 // We're still in the link table (dangling link) so we can't delete this
355 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
358 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
360 $this->_update_recent_table();
361 $this->_update_nonempty_table();
367 // The only thing we might be interested in updating which we can
368 // do fast in the flags (minor_edit). I think the default
369 // update_versiondata will work fine...
370 //function update_versiondata($pagename, $version, $data) {
373 function set_links($pagename, $links) {
374 // Update link table.
375 // FIXME: optimize: mysql can do this all in one big INSERT.
378 extract($this->_table_names);
381 $pageid = $this->_get_pageid($pagename, true);
383 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
386 foreach($links as $link) {
387 if (isset($linkseen[$link]))
389 $linkseen[$link] = true;
390 $linkid = $this->_get_pageid($link, true);
391 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
392 . " VALUES ($pageid, $linkid)");
399 * Find pages which link to or are linked from a page.
401 function get_links($pagename, $reversed = true) {
403 extract($this->_table_names);
406 list($have,$want) = array('linkee', 'linker');
408 list($have,$want) = array('linker', 'linkee');
411 $qpagename = $dbh->quoteString($pagename);
413 $result = $dbh->query("SELECT $want.*"
414 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
415 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
416 . " AND $have.pagename='$qpagename'"
417 //. " GROUP BY $want.id"
418 . " ORDER BY $want.pagename");
420 return new WikiDB_backend_PearDB_iter($this, $result);
423 function get_all_pages($include_deleted=false,$sortby=false,$limit=false) {
425 extract($this->_table_names);
426 if ($limit) $limit = "LIMIT $limit";
428 if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
430 if (strstr($orderby,' mtime')) {
431 if ($include_deleted) {
432 $result = $dbh->query("SELECT * FROM $page_tbl, $recent_tbl, $version_tbl"
433 . " WHERE $page_tbl.id=$recent_tbl.id"
434 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
435 . " $orderby $limit");
438 $result = $dbh->query("SELECT $page_tbl.*"
439 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
440 . " WHERE $nonempty_tbl.id=$page_tbl.id"
441 . " AND $page_tbl.id=$recent_tbl.id"
442 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
443 . " $orderby $limit");
446 if ($include_deleted) {
447 $result = $dbh->query("SELECT * FROM $page_tbl $orderby $limit");
450 $result = $dbh->query("SELECT $page_tbl.*"
451 . " FROM $nonempty_tbl, $page_tbl"
452 . " WHERE $nonempty_tbl.id=$page_tbl.id"
453 . " $orderby $limit");
456 return new WikiDB_backend_PearDB_iter($this, $result);
462 function text_search($search = '', $fullsearch = false) {
464 extract($this->_table_names);
466 $table = "$nonempty_tbl, $page_tbl";
467 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
468 $fields = "$page_tbl.*";
469 $callback = new WikiMethodCb($this, '_sql_match_clause');
472 $table .= ", $recent_tbl";
473 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
475 $table .= ", $version_tbl";
476 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
478 $fields .= ",$version_tbl.*";
479 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
482 $search_clause = $search->makeSqlClause($callback);
484 $result = $dbh->query("SELECT $fields FROM $table"
485 . " WHERE $join_clause"
486 . " AND ($search_clause)"
487 . " ORDER BY pagename");
489 return new WikiDB_backend_PearDB_iter($this, $result);
492 //Todo: check if the better Mysql MATCH operator is supported,
493 // (ranked search) and also google like expressions.
494 function _sql_match_clause($word) {
495 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
496 $word = $this->_dbh->quoteString($word);
497 //$page_tbl = $this->_table_names['page_tbl'];
498 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
499 // e.g. if word is lowercased.
500 // http://bugs.mysql.com/bug.php?id=1491
501 return "LOWER(pagename) LIKE '%$word%'";
504 function _fullsearch_sql_match_clause($word) {
505 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
506 $word = $this->_dbh->quoteString($word);
507 //$page_tbl = $this->_table_names['page_tbl'];
508 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
509 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
513 * Find highest or lowest hit counts.
515 function most_popular($limit,$sortby = '') {
517 extract($this->_table_names);
523 if ($limit) $limit = "LIMIT $limit";
524 else $limit = 'LIMIT 20';
525 if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
526 else $orderby = "ORDER BY hits $order";
527 //$limitclause = $limit ? " LIMIT $limit" : '';
528 $result = $dbh->query("SELECT $page_tbl.*"
529 . " FROM $nonempty_tbl, $page_tbl"
530 . " WHERE $nonempty_tbl.id=$page_tbl.id"
534 return new WikiDB_backend_PearDB_iter($this, $result);
538 * Find recent changes.
540 function most_recent($params) {
543 $include_minor_revisions = false;
544 $exclude_major_revisions = false;
545 $include_all_revisions = false;
549 extract($this->_table_names);
553 $pick[] = "mtime >= $since";
556 if ($include_all_revisions) {
557 // Include all revisions of each page.
558 $table = "$page_tbl, $version_tbl";
559 $join_clause = "$page_tbl.id=$version_tbl.id";
561 if ($exclude_major_revisions) {
562 // Include only minor revisions
563 $pick[] = "minor_edit <> 0";
565 elseif (!$include_minor_revisions) {
566 // Include only major revisions
567 $pick[] = "minor_edit = 0";
571 $table = "$page_tbl, $recent_tbl";
572 $join_clause = "$page_tbl.id=$recent_tbl.id";
573 $table .= ", $version_tbl";
574 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
576 if ($exclude_major_revisions) {
577 // Include only most recent minor revision
578 $pick[] = 'version=latestminor';
580 elseif (!$include_minor_revisions) {
581 // Include only most recent major revision
582 $pick[] = 'version=latestmajor';
585 // Include only the latest revision (whether major or minor).
586 $pick[] ='version=latestversion';
594 $limitclause = $limit ? " LIMIT $limit" : '';
595 $where_clause = $join_clause;
597 $where_clause .= " AND " . join(" AND ", $pick);
599 // FIXME: use SQL_BUFFER_RESULT for mysql?
600 $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
602 . " WHERE $where_clause"
603 . " ORDER BY mtime $order"
606 return new WikiDB_backend_PearDB_iter($this, $result);
610 * Rename page in the database.
612 function rename_page($pagename, $to) {
614 extract($this->_table_names);
617 if ( ($id = $this->_get_pageid($pagename, false)) ) {
618 if ($new = $this->_get_pageid($to, false)) {
620 //this page does not exist (already verified before), but exists in the page table.
621 //so we delete this page.
622 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
623 $dbh->quoteString($to)));
625 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
626 $dbh->quoteString($to)));
632 function _update_recent_table($pageid = false) {
634 extract($this->_table_names);
635 extract($this->_expressions);
637 $pageid = (int)$pageid;
641 $dbh->query("DELETE FROM $recent_tbl"
642 . ( $pageid ? " WHERE id=$pageid" : ""));
644 $dbh->query( "INSERT INTO $recent_tbl"
645 . " (id, latestversion, latestmajor, latestminor)"
646 . " SELECT id, $maxversion, $maxmajor, $maxminor"
647 . " FROM $version_tbl"
648 . ( $pageid ? " WHERE id=$pageid" : "")
653 function _update_nonempty_table($pageid = false) {
655 extract($this->_table_names);
657 $pageid = (int)$pageid;
661 $dbh->query("DELETE FROM $nonempty_tbl"
662 . ( $pageid ? " WHERE id=$pageid" : ""));
664 $dbh->query("INSERT INTO $nonempty_tbl (id)"
665 . " SELECT $recent_tbl.id"
666 . " FROM $recent_tbl, $version_tbl"
667 . " WHERE $recent_tbl.id=$version_tbl.id"
668 . " AND version=latestversion"
670 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
677 * Grab a write lock on the tables in the SQL database.
679 * Calls can be nested. The tables won't be unlocked until
680 * _unlock_database() is called as many times as _lock_database().
684 function lock($write_lock = true) {
685 if ($this->_lock_count++ == 0)
686 $this->_lock_tables($write_lock);
690 * Actually lock the required tables.
692 function _lock_tables($write_lock) {
693 trigger_error("virtual", E_USER_ERROR);
697 * Release a write lock on the tables in the SQL database.
701 * @param $force boolean Unlock even if not every call to lock() has been matched
702 * by a call to unlock().
704 * @see _lock_database
706 function unlock($force = false) {
707 if ($this->_lock_count == 0)
709 if (--$this->_lock_count <= 0 || $force) {
710 $this->_unlock_tables();
711 $this->_lock_count = 0;
716 * Actually unlock the required tables.
718 function _unlock_tables($write_lock) {
719 trigger_error("virtual", E_USER_ERROR);
726 function _serialize($data) {
729 assert(is_array($data));
730 return serialize($data);
736 function _unserialize($data) {
737 return empty($data) ? array() : unserialize($data);
741 * Callback for PEAR (DB) errors.
745 * @param A PEAR_error object.
747 function _pear_error_callback($error) {
748 if ($this->_is_false_error($error))
751 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
753 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
757 * Detect false errors messages from PEAR DB.
759 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
760 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
761 * return any data. (So when a "LOCK" command doesn't return any data,
762 * DB reports it as an error, when in fact, it's not.)
765 * @return bool True iff error is not really an error.
767 function _is_false_error($error) {
768 if ($error->getCode() != DB_ERROR)
771 $query = $this->_dbh->last_query;
773 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
774 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
775 // Last query was not of the sort which doesn't return any data.
776 //" <--kludge for brain-dead syntax coloring
780 if (! in_array('ismanip', get_class_methods('DB'))) {
781 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
782 // does not have the DB::isManip method.
786 if (DB::isManip($query)) {
787 // If Pear thinks it's an isManip then it wouldn't have thrown
788 // the error we're testing for....
795 function _pear_error_message($error) {
796 $class = get_class($this);
797 $message = "$class: fatal database error\n"
798 . "\t" . $error->getMessage() . "\n"
799 . "\t(" . $error->getDebugInfo() . ")\n";
801 // Prevent password from being exposed during a connection error
802 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
803 '\\1:XXXXXXXX', $this->_dsn);
804 return str_replace($this->_dsn, $safe_dsn, $message);
808 * Filter PHP errors notices from PEAR DB code.
810 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
811 * errors and notices. This is an error callback (for use with
812 * ErrorManager which will filter out those spurious messages.)
813 * @see _is_false_error, ErrorManager
816 function _pear_notice_filter($err) {
817 return ( $err->isNotice()
818 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
819 && $err->errline == 126
820 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
824 class WikiDB_backend_PearDB_iter
825 extends WikiDB_backend_iterator
827 function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
828 if (DB::isError($query_result)) {
829 // This shouldn't happen, I thought.
830 $backend->_pear_error_callback($query_result);
833 $this->_backend = &$backend;
834 $this->_result = $query_result;
838 $backend = &$this->_backend;
842 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
848 $pagedata = $backend->_extract_page_data($record);
849 $rec = array('pagename' => $record['pagename'],
850 'pagedata' => $pagedata);
852 if (!empty($record['version'])) {
853 $rec['versiondata'] = $backend->_extract_version_data($record);
854 $rec['version'] = $record['version'];
861 if ($this->_result) {
862 $this->_result->free();
863 $this->_result = false;
868 // (c-file-style: "gnu")
873 // c-hanging-comment-ender-p: nil
874 // indent-tabs-mode: nil