2 rcs_id('$Id: PearDB.php,v 1.29 2003-02-22 00:28:34 dairiki 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();
76 function is_wiki_page($pagename) {
78 extract($this->_table_names);
79 return $dbh->getOne(sprintf("SELECT $page_tbl.id"
80 . " FROM $nonempty_tbl, $page_tbl"
81 . " WHERE $nonempty_tbl.id=$page_tbl.id"
82 . " AND pagename='%s'",
83 $dbh->quoteString($pagename)));
86 function get_all_pagenames() {
88 extract($this->_table_names);
89 return $dbh->getCol("SELECT pagename"
90 . " FROM $nonempty_tbl, $page_tbl"
91 . " WHERE $nonempty_tbl.id=$page_tbl.id");
95 * Read page information from database.
97 function get_pagedata($pagename) {
99 $page_tbl = $this->_table_names['page_tbl'];
101 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
103 $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
104 $dbh->quoteString($pagename)),
108 return $this->_extract_page_data($result);
111 function _extract_page_data(&$query_result) {
112 extract($query_result);
113 $data = empty($pagedata) ? array() : unserialize($pagedata);
114 $data['hits'] = $hits;
118 function update_pagedata($pagename, $newdata) {
120 $page_tbl = $this->_table_names['page_tbl'];
122 // Hits is the only thing we can update in a fast manner.
123 if (count($newdata) == 1 && isset($newdata['hits'])) {
124 // Note that this will fail silently if the page does not
125 // have a record in the page table. Since it's just the
126 // hit count, who cares?
127 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
128 $newdata['hits'], $dbh->quoteString($pagename)));
133 $data = $this->get_pagedata($pagename);
136 $this->_get_pageid($pagename, true); // Creates page record
139 @$hits = (int)$data['hits'];
140 unset($data['hits']);
142 foreach ($newdata as $key => $val) {
145 else if (empty($val))
151 $dbh->query(sprintf("UPDATE $page_tbl"
152 . " SET hits=%d, pagedata='%s'"
153 . " WHERE pagename='%s'",
155 $dbh->quoteString(serialize($data)),
156 $dbh->quoteString($pagename)));
161 function _get_pageid($pagename, $create_if_missing = false) {
164 $page_tbl = $this->_table_names['page_tbl'];
166 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
167 $dbh->quoteString($pagename));
169 if (!$create_if_missing)
170 return $dbh->getOne($query);
173 $id = $dbh->getOne($query);
175 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
177 $dbh->query(sprintf("INSERT INTO $page_tbl"
178 . " (id,pagename,hits)"
179 . " VALUES (%d,'%s',0)",
180 $id, $dbh->quoteString($pagename)));
186 function get_latest_version($pagename) {
188 extract($this->_table_names);
190 (int)$dbh->getOne(sprintf("SELECT latestversion"
191 . " FROM $page_tbl, $recent_tbl"
192 . " WHERE $page_tbl.id=$recent_tbl.id"
193 . " AND pagename='%s'",
194 $dbh->quoteString($pagename)));
197 function get_previous_version($pagename, $version) {
199 extract($this->_table_names);
202 (int)$dbh->getOne(sprintf("SELECT version"
203 . " FROM $version_tbl, $page_tbl"
204 . " WHERE $version_tbl.id=$page_tbl.id"
205 . " AND pagename='%s'"
206 . " AND version < %d"
207 . " ORDER BY version DESC"
209 $dbh->quoteString($pagename),
216 * @param $version int Which version to get.
218 * @return hash The version data, or false if specified version does not
221 function get_versiondata($pagename, $version, $want_content = false) {
223 extract($this->_table_names);
225 assert(!empty($pagename));
226 assert($version > 0);
228 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
229 // FIXME: optimization: sometimes don't get page data?
235 $fields = ("$page_tbl.*,"
236 . "mtime,minor_edit,versiondata,"
237 . "content<>'' AS have_content");
240 $result = $dbh->getRow(sprintf("SELECT $fields"
241 . " FROM $page_tbl, $version_tbl"
242 . " WHERE $page_tbl.id=$version_tbl.id"
243 . " AND pagename='%s'"
245 $dbh->quoteString($pagename), $version),
248 return $this->_extract_version_data($result);
251 function _extract_version_data(&$query_result) {
255 extract($query_result);
256 $data = empty($versiondata) ? array() : unserialize($versiondata);
258 $data['mtime'] = $mtime;
259 $data['is_minor_edit'] = !empty($minor_edit);
262 $data['%content'] = $content;
263 elseif ($have_content)
264 $data['%content'] = true;
266 $data['%content'] = '';
268 // FIXME: this is ugly.
269 if (isset($pagename)) {
270 // Query also includes page data.
271 // We might as well send that back too...
272 $data['%pagedata'] = $this->_extract_page_data($query_result);
280 * Create a new revision of a page.
282 function set_versiondata($pagename, $version, $data) {
284 $version_tbl = $this->_table_names['version_tbl'];
286 $minor_edit = (int) !empty($data['is_minor_edit']);
287 unset($data['is_minor_edit']);
289 $mtime = (int)$data['mtime'];
290 unset($data['mtime']);
291 assert(!empty($mtime));
293 @$content = (string) $data['%content'];
294 unset($data['%content']);
296 unset($data['%pagedata']);
299 $id = $this->_get_pageid($pagename, true);
301 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
302 $dbh->query(sprintf("DELETE FROM $version_tbl"
303 . " WHERE id=%d AND version=%d",
306 $dbh->query(sprintf("INSERT INTO $version_tbl"
307 . " (id,version,mtime,minor_edit,content,versiondata)"
308 . " VALUES(%d,%d,%d,%d,'%s','%s')",
309 $id, $version, $mtime, $minor_edit,
310 $dbh->quoteString($content),
311 $dbh->quoteString(serialize($data))));
313 $this->_update_recent_table($id);
314 $this->_update_nonempty_table($id);
320 * Delete an old revision of a page.
322 function delete_versiondata($pagename, $version) {
324 extract($this->_table_names);
327 if ( ($id = $this->_get_pageid($pagename)) ) {
328 $dbh->query("DELETE FROM $version_tbl"
329 . " WHERE id=$id AND version=$version");
330 $this->_update_recent_table($id);
331 // This shouldn't be needed (as long as the latestversion
332 // never gets deleted.) But, let's be safe.
333 $this->_update_nonempty_table($id);
339 * Delete page from the database.
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) {
425 extract($this->_table_names);
427 if ($include_deleted) {
428 $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY pagename");
431 $result = $dbh->query("SELECT $page_tbl.*"
432 . " FROM $nonempty_tbl, $page_tbl"
433 . " WHERE $nonempty_tbl.id=$page_tbl.id"
434 . " ORDER BY pagename");
437 return new WikiDB_backend_PearDB_iter($this, $result);
443 function text_search($search = '', $fullsearch = false) {
445 extract($this->_table_names);
447 $table = "$nonempty_tbl, $page_tbl";
448 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
449 $fields = "$page_tbl.*";
450 $callback = new WikiMethodCb($this, '_sql_match_clause');
453 $table .= ", $recent_tbl";
454 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
456 $table .= ", $version_tbl";
457 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
459 $fields .= ",$version_tbl.*";
460 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
463 $search_clause = $search->makeSqlClause($callback);
465 $result = $dbh->query("SELECT $fields FROM $table"
466 . " WHERE $join_clause"
467 . " AND ($search_clause)"
468 . " ORDER BY pagename");
470 return new WikiDB_backend_PearDB_iter($this, $result);
473 function _sql_match_clause($word) {
474 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
475 $word = $this->_dbh->quoteString($word);
476 return "LOWER(pagename) LIKE '%$word%'";
479 function _fullsearch_sql_match_clause($word) {
480 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
481 $word = $this->_dbh->quoteString($word);
482 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
486 * Find highest hit counts.
488 function most_popular($limit) {
490 extract($this->_table_names);
496 $limitclause = $limit ? " LIMIT $limit" : '';
497 $result = $dbh->query("SELECT $page_tbl.*"
498 . " FROM $nonempty_tbl, $page_tbl"
499 . " WHERE $nonempty_tbl.id=$page_tbl.id"
500 . " ORDER BY hits $order"
503 return new WikiDB_backend_PearDB_iter($this, $result);
507 * Find recent changes.
509 function most_recent($params) {
512 $include_minor_revisions = false;
513 $exclude_major_revisions = false;
514 $include_all_revisions = false;
518 extract($this->_table_names);
522 $pick[] = "mtime >= $since";
525 if ($include_all_revisions) {
526 // Include all revisions of each page.
527 $table = "$page_tbl, $version_tbl";
528 $join_clause = "$page_tbl.id=$version_tbl.id";
530 if ($exclude_major_revisions) {
531 // Include only minor revisions
532 $pick[] = "minor_edit <> 0";
534 elseif (!$include_minor_revisions) {
535 // Include only major revisions
536 $pick[] = "minor_edit = 0";
540 $table = "$page_tbl, $recent_tbl";
541 $join_clause = "$page_tbl.id=$recent_tbl.id";
542 $table .= ", $version_tbl";
543 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
545 if ($exclude_major_revisions) {
546 // Include only most recent minor revision
547 $pick[] = 'version=latestminor';
549 elseif (!$include_minor_revisions) {
550 // Include only most recent major revision
551 $pick[] = 'version=latestmajor';
554 // Include only the latest revision (whether major or minor).
555 $pick[] ='version=latestversion';
563 $limitclause = $limit ? " LIMIT $limit" : '';
564 $where_clause = $join_clause;
566 $where_clause .= " AND " . join(" AND ", $pick);
568 // FIXME: use SQL_BUFFER_RESULT for mysql?
569 $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
571 . " WHERE $where_clause"
572 . " ORDER BY mtime $order"
575 return new WikiDB_backend_PearDB_iter($this, $result);
578 function _update_recent_table($pageid = false) {
580 extract($this->_table_names);
581 extract($this->_expressions);
583 $pageid = (int)$pageid;
587 $dbh->query("DELETE FROM $recent_tbl"
588 . ( $pageid ? " WHERE id=$pageid" : ""));
590 $dbh->query( "INSERT INTO $recent_tbl"
591 . " (id, latestversion, latestmajor, latestminor)"
592 . " SELECT id, $maxversion, $maxmajor, $maxminor"
593 . " FROM $version_tbl"
594 . ( $pageid ? " WHERE id=$pageid" : "")
599 function _update_nonempty_table($pageid = false) {
601 extract($this->_table_names);
603 $pageid = (int)$pageid;
607 $dbh->query("DELETE FROM $nonempty_tbl"
608 . ( $pageid ? " WHERE id=$pageid" : ""));
610 $dbh->query("INSERT INTO $nonempty_tbl (id)"
611 . " SELECT $recent_tbl.id"
612 . " FROM $recent_tbl, $version_tbl"
613 . " WHERE $recent_tbl.id=$version_tbl.id"
614 . " AND version=latestversion"
616 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
623 * Grab a write lock on the tables in the SQL database.
625 * Calls can be nested. The tables won't be unlocked until
626 * _unlock_database() is called as many times as _lock_database().
630 function lock($write_lock = true) {
631 if ($this->_lock_count++ == 0)
632 $this->_lock_tables($write_lock);
636 * Actually lock the required tables.
638 function _lock_tables($write_lock) {
639 trigger_error("virtual", E_USER_ERROR);
643 * Release a write lock on the tables in the SQL database.
647 * @param $force boolean Unlock even if not every call to lock() has been matched
648 * by a call to unlock().
650 * @see _lock_database
652 function unlock($force = false) {
653 if ($this->_lock_count == 0)
655 if (--$this->_lock_count <= 0 || $force) {
656 $this->_unlock_tables();
657 $this->_lock_count = 0;
662 * Actually unlock the required tables.
664 function _unlock_tables($write_lock) {
665 trigger_error("virtual", E_USER_ERROR);
669 * Callback for PEAR (DB) errors.
673 * @param A PEAR_error object.
675 function _pear_error_callback($error) {
676 if ($this->_is_false_error($error))
679 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
681 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
685 * Detect false errors messages from PEAR DB.
687 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
688 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
689 * return any data. (So when a "LOCK" command doesn't return any data,
690 * DB reports it as an error, when in fact, it's not.)
693 * @return bool True iff error is not really an error.
695 function _is_false_error($error) {
696 if ($error->getCode() != DB_ERROR)
699 $query = $this->_dbh->last_query;
701 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
702 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
703 // Last query was not of the sort which doesn't return any data.
704 //" <--kludge for brain-dead syntax coloring
708 if (! in_array('ismanip', get_class_methods('DB'))) {
709 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
710 // does not have the DB::isManip method.
714 if (DB::isManip($query)) {
715 // If Pear thinks it's an isManip then it wouldn't have thrown
716 // the error we're testing for....
723 function _pear_error_message($error) {
724 $class = get_class($this);
725 $message = "$class: fatal database error\n"
726 . "\t" . $error->getMessage() . "\n"
727 . "\t(" . $error->getDebugInfo() . ")\n";
729 // Prevent password from being exposed during a connection error
730 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
731 '\\1:XXXXXXXX', $this->_dsn);
732 return str_replace($this->_dsn, $safe_dsn, $message);
736 * Filter PHP errors notices from PEAR DB code.
738 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
739 * errors and notices. This is an error callback (for use with
740 * ErrorManager which will filter out those spurious messages.)
741 * @see _is_false_error, ErrorManager
744 function _pear_notice_filter($err) {
745 return ( $err->isNotice()
746 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
747 && $err->errline == 126
748 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
752 class WikiDB_backend_PearDB_iter
753 extends WikiDB_backend_iterator
755 function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
756 if (DB::isError($query_result)) {
757 // This shouldn't happen, I thought.
758 $backend->_pear_error_callback($query_result);
761 $this->_backend = &$backend;
762 $this->_result = $query_result;
766 $backend = &$this->_backend;
770 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
776 $pagedata = $backend->_extract_page_data($record);
777 $rec = array('pagename' => $record['pagename'],
778 'pagedata' => $pagedata);
780 if (!empty($record['version'])) {
781 $rec['versiondata'] = $backend->_extract_version_data($record);
782 $rec['version'] = $record['version'];
789 if ($this->_result) {
790 $this->_result->free();
791 $this->_result = false;
796 // (c-file-style: "gnu")
801 // c-hanging-comment-ender-p: nil
802 // indent-tabs-mode: nil