2 rcs_id('$Id: PearDB.php,v 1.27 2002-08-17 15:52:51 rurban Exp $');
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 require_once('lib/ErrorManager.php');
7 // Try the installed pear class first. It might be newer.
8 @require_once('DB.php');
9 if (!class_exists('DB')) // >= 4.0.0
10 require_once('lib/pear/DB.php'); // Okay. our local copy
12 class WikiDB_backend_PearDB
13 extends WikiDB_backend
15 function WikiDB_backend_PearDB ($dbparams) {
16 // Find and include PEAR's DB.php.
17 //$pearFinder = new PearFileFinder;
18 //$pearFinder->includeOnce('DB.php');
20 // Install filter to handle bogus error notices from buggy DB.php's.
22 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
24 // Open connection to database
25 $this->_dsn = $dbparams['dsn'];
26 $dboptions = array('persistent' => true,
28 $this->_dbh = DB::connect($this->_dsn, $dboptions);
30 if (DB::isError($dbh)) {
31 trigger_error(sprintf("Can't connect to database: %s",
32 $this->_pear_error_message($dbh)),
35 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
36 array($this, '_pear_error_callback'));
37 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
39 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
42 = array('page_tbl' => $prefix . 'page',
43 'version_tbl' => $prefix . 'version',
44 'link_tbl' => $prefix . 'link',
45 'recent_tbl' => $prefix . 'recent',
46 'nonempty_tbl' => $prefix . 'nonempty');
49 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
50 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
51 'maxversion' => "MAX(version)");
53 $this->_lock_count = 0;
57 * Close database connection.
62 if ($this->_lock_count) {
63 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
66 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
67 $this->unlock('force');
69 $this->_dbh->disconnect();
77 function is_wiki_page($pagename) {
79 extract($this->_table_names);
80 return $dbh->getOne(sprintf("SELECT $page_tbl.id"
81 . " FROM $nonempty_tbl, $page_tbl"
82 . " WHERE $nonempty_tbl.id=$page_tbl.id"
83 . " AND pagename='%s'",
84 $dbh->quoteString($pagename)));
87 function get_all_pagenames() {
89 extract($this->_table_names);
90 return $dbh->getCol("SELECT pagename"
91 . " FROM $nonempty_tbl, $page_tbl"
92 . " WHERE $nonempty_tbl.id=$page_tbl.id");
96 * Read page information from database.
98 function get_pagedata($pagename) {
100 $page_tbl = $this->_table_names['page_tbl'];
102 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
104 $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
105 $dbh->quoteString($pagename)),
109 return $this->_extract_page_data($result);
112 function _extract_page_data(&$query_result) {
113 extract($query_result);
114 $data = empty($pagedata) ? array() : unserialize($pagedata);
115 $data['hits'] = $hits;
119 function update_pagedata($pagename, $newdata) {
121 $page_tbl = $this->_table_names['page_tbl'];
123 // Hits is the only thing we can update in a fast manner.
124 if (count($newdata) == 1 && isset($newdata['hits'])) {
125 // Note that this will fail silently if the page does not
126 // have a record in the page table. Since it's just the
127 // hit count, who cares?
128 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
129 $newdata['hits'], $dbh->quoteString($pagename)));
134 $data = $this->get_pagedata($pagename);
137 $this->_get_pageid($pagename, true); // Creates page record
140 @$hits = (int)$data['hits'];
141 unset($data['hits']);
143 foreach ($newdata as $key => $val) {
146 else if (empty($val))
152 $dbh->query(sprintf("UPDATE $page_tbl"
153 . " SET hits=%d, pagedata='%s'"
154 . " WHERE pagename='%s'",
156 $dbh->quoteString(serialize($data)),
157 $dbh->quoteString($pagename)));
162 function _get_pageid($pagename, $create_if_missing = false) {
165 $page_tbl = $this->_table_names['page_tbl'];
167 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
168 $dbh->quoteString($pagename));
170 if (!$create_if_missing)
171 return $dbh->getOne($query);
174 $id = $dbh->getOne($query);
176 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
178 $dbh->query(sprintf("INSERT INTO $page_tbl"
179 . " (id,pagename,hits)"
180 . " VALUES (%d,'%s',0)",
181 $id, $dbh->quoteString($pagename)));
187 function get_latest_version($pagename) {
189 extract($this->_table_names);
191 (int)$dbh->getOne(sprintf("SELECT latestversion"
192 . " FROM $page_tbl, $recent_tbl"
193 . " WHERE $page_tbl.id=$recent_tbl.id"
194 . " AND pagename='%s'",
195 $dbh->quoteString($pagename)));
198 function get_previous_version($pagename, $version) {
200 extract($this->_table_names);
203 (int)$dbh->getOne(sprintf("SELECT version"
204 . " FROM $version_tbl, $page_tbl"
205 . " WHERE $version_tbl.id=$page_tbl.id"
206 . " AND pagename='%s'"
207 . " AND version < %d"
208 . " ORDER BY version DESC"
210 $dbh->quoteString($pagename),
217 * @param $version int Which version to get.
219 * @return hash The version data, or false if specified version does not
222 function get_versiondata($pagename, $version, $want_content = false) {
224 extract($this->_table_names);
226 assert(!empty($pagename));
227 assert($version > 0);
229 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
230 // FIXME: optimization: sometimes don't get page data?
236 $fields = ("$page_tbl.*,"
237 . "mtime,minor_edit,versiondata,"
238 . "content<>'' AS have_content");
241 $result = $dbh->getRow(sprintf("SELECT $fields"
242 . " FROM $page_tbl, $version_tbl"
243 . " WHERE $page_tbl.id=$version_tbl.id"
244 . " AND pagename='%s'"
246 $dbh->quoteString($pagename), $version),
249 return $this->_extract_version_data($result);
252 function _extract_version_data(&$query_result) {
256 extract($query_result);
257 $data = empty($versiondata) ? array() : unserialize($versiondata);
259 $data['mtime'] = $mtime;
260 $data['is_minor_edit'] = !empty($minor_edit);
263 $data['%content'] = $content;
264 elseif ($have_content)
265 $data['%content'] = true;
267 $data['%content'] = '';
269 // FIXME: this is ugly.
270 if (isset($pagename)) {
271 // Query also includes page data.
272 // We might as well send that back too...
273 $data['%pagedata'] = $this->_extract_page_data($query_result);
281 * Create a new revision of a page.
283 function set_versiondata($pagename, $version, $data) {
285 $version_tbl = $this->_table_names['version_tbl'];
287 $minor_edit = (int) !empty($data['is_minor_edit']);
288 unset($data['is_minor_edit']);
290 $mtime = (int)$data['mtime'];
291 unset($data['mtime']);
292 assert(!empty($mtime));
294 @$content = (string) $data['%content'];
295 unset($data['%content']);
297 unset($data['%pagedata']);
300 $id = $this->_get_pageid($pagename, true);
302 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
303 $dbh->query(sprintf("DELETE FROM $version_tbl"
304 . " WHERE id=%d AND version=%d",
307 $dbh->query(sprintf("INSERT INTO $version_tbl"
308 . " (id,version,mtime,minor_edit,content,versiondata)"
309 . " VALUES(%d,%d,%d,%d,'%s','%s')",
310 $id, $version, $mtime, $minor_edit,
311 $dbh->quoteString($content),
312 $dbh->quoteString(serialize($data))));
314 $this->_update_recent_table($id);
315 $this->_update_nonempty_table($id);
321 * Delete an old revision of a page.
323 function delete_versiondata($pagename, $version) {
325 extract($this->_table_names);
328 if ( ($id = $this->_get_pageid($pagename)) ) {
329 $dbh->query("DELETE FROM $version_tbl"
330 . " WHERE id=$id AND version=$version");
331 $this->_update_recent_table($id);
332 // This shouldn't be needed (as long as the latestversion
333 // never gets deleted.) But, let's be safe.
334 $this->_update_nonempty_table($id);
340 * Delete page from the database.
342 function delete_page($pagename) {
344 extract($this->_table_names);
347 if ( ($id = $this->_get_pageid($pagename, 'id')) ) {
348 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
349 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
350 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
351 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
352 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
354 // We're still in the link table (dangling link) so we can't delete this
356 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
359 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
361 $this->_update_recent_table();
362 $this->_update_nonempty_table();
368 // The only thing we might be interested in updating which we can
369 // do fast in the flags (minor_edit). I think the default
370 // update_versiondata will work fine...
371 //function update_versiondata($pagename, $version, $data) {
374 function set_links($pagename, $links) {
375 // Update link table.
376 // FIXME: optimize: mysql can do this all in one big INSERT.
379 extract($this->_table_names);
382 $pageid = $this->_get_pageid($pagename, true);
384 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
387 foreach($links as $link) {
388 if (isset($linkseen[$link]))
390 $linkseen[$link] = true;
391 $linkid = $this->_get_pageid($link, true);
392 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
393 . " VALUES ($pageid, $linkid)");
400 * Find pages which link to or are linked from a page.
402 function get_links($pagename, $reversed = true) {
404 extract($this->_table_names);
407 list($have,$want) = array('linkee', 'linker');
409 list($have,$want) = array('linker', 'linkee');
412 $qpagename = $dbh->quoteString($pagename);
414 $result = $dbh->query("SELECT $want.*"
415 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
416 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
417 . " AND $have.pagename='$qpagename'"
418 //. " GROUP BY $want.id"
419 . " ORDER BY $want.pagename");
421 return new WikiDB_backend_PearDB_iter($this, $result);
424 function get_all_pages($include_deleted) {
426 extract($this->_table_names);
428 if ($include_deleted) {
429 $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY pagename");
432 $result = $dbh->query("SELECT $page_tbl.*"
433 . " FROM $nonempty_tbl, $page_tbl"
434 . " WHERE $nonempty_tbl.id=$page_tbl.id"
435 . " ORDER BY pagename");
438 return new WikiDB_backend_PearDB_iter($this, $result);
444 function text_search($search = '', $fullsearch = false) {
446 extract($this->_table_names);
448 $table = "$nonempty_tbl, $page_tbl";
449 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
450 $fields = "$page_tbl.*";
451 $callback = new WikiMethodCb($this, '_sql_match_clause');
454 $table .= ", $recent_tbl";
455 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
457 $table .= ", $version_tbl";
458 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
460 $fields .= ",$version_tbl.*";
461 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
464 $search_clause = $search->makeSqlClause($callback);
466 $result = $dbh->query("SELECT $fields FROM $table"
467 . " WHERE $join_clause"
468 . " AND ($search_clause)"
469 . " ORDER BY pagename");
471 return new WikiDB_backend_PearDB_iter($this, $result);
474 function _sql_match_clause($word) {
475 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
476 $word = $this->_dbh->quoteString($word);
477 return "LOWER(pagename) LIKE '%$word%'";
480 function _fullsearch_sql_match_clause($word) {
481 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
482 $word = $this->_dbh->quoteString($word);
483 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
487 * Find highest hit counts.
489 function most_popular($limit) {
491 extract($this->_table_names);
497 $limitclause = $limit ? " LIMIT $limit" : '';
498 $result = $dbh->query("SELECT $page_tbl.*"
499 . " FROM $nonempty_tbl, $page_tbl"
500 . " WHERE $nonempty_tbl.id=$page_tbl.id"
501 . " ORDER BY hits $order"
504 return new WikiDB_backend_PearDB_iter($this, $result);
508 * Find recent changes.
510 function most_recent($params) {
513 $include_minor_revisions = false;
514 $exclude_major_revisions = false;
515 $include_all_revisions = false;
519 extract($this->_table_names);
523 $pick[] = "mtime >= $since";
526 if ($include_all_revisions) {
527 // Include all revisions of each page.
528 $table = "$page_tbl, $version_tbl";
529 $join_clause = "$page_tbl.id=$version_tbl.id";
531 if ($exclude_major_revisions) {
532 // Include only minor revisions
533 $pick[] = "minor_edit <> 0";
535 elseif (!$include_minor_revisions) {
536 // Include only major revisions
537 $pick[] = "minor_edit = 0";
541 $table = "$page_tbl, $recent_tbl";
542 $join_clause = "$page_tbl.id=$recent_tbl.id";
543 $table .= ", $version_tbl";
544 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
546 if ($exclude_major_revisions) {
547 // Include only most recent minor revision
548 $pick[] = 'version=latestminor';
550 elseif (!$include_minor_revisions) {
551 // Include only most recent major revision
552 $pick[] = 'version=latestmajor';
555 // Include only the latest revision (whether major or minor).
556 $pick[] ='version=latestversion';
564 $limitclause = $limit ? " LIMIT $limit" : '';
565 $where_clause = $join_clause;
567 $where_clause .= " AND " . join(" AND ", $pick);
569 // FIXME: use SQL_BUFFER_RESULT for mysql?
570 $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
572 . " WHERE $where_clause"
573 . " ORDER BY mtime $order"
576 return new WikiDB_backend_PearDB_iter($this, $result);
579 function _update_recent_table($pageid = false) {
581 extract($this->_table_names);
582 extract($this->_expressions);
584 $pageid = (int)$pageid;
588 $dbh->query("DELETE FROM $recent_tbl"
589 . ( $pageid ? " WHERE id=$pageid" : ""));
591 $dbh->query( "INSERT INTO $recent_tbl"
592 . " (id, latestversion, latestmajor, latestminor)"
593 . " SELECT id, $maxversion, $maxmajor, $maxminor"
594 . " FROM $version_tbl"
595 . ( $pageid ? " WHERE id=$pageid" : "")
600 function _update_nonempty_table($pageid = false) {
602 extract($this->_table_names);
604 $pageid = (int)$pageid;
608 $dbh->query("DELETE FROM $nonempty_tbl"
609 . ( $pageid ? " WHERE id=$pageid" : ""));
611 $dbh->query("INSERT INTO $nonempty_tbl (id)"
612 . " SELECT $recent_tbl.id"
613 . " FROM $recent_tbl, $version_tbl"
614 . " WHERE $recent_tbl.id=$version_tbl.id"
615 . " AND version=latestversion"
617 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
624 * Grab a write lock on the tables in the SQL database.
626 * Calls can be nested. The tables won't be unlocked until
627 * _unlock_database() is called as many times as _lock_database().
631 function lock($write_lock = true) {
632 if ($this->_lock_count++ == 0)
633 $this->_lock_tables($write_lock);
637 * Actually lock the required tables.
639 function _lock_tables($write_lock) {
640 trigger_error("virtual", E_USER_ERROR);
644 * Release a write lock on the tables in the SQL database.
648 * @param $force boolean Unlock even if not every call to lock() has been matched
649 * by a call to unlock().
651 * @see _lock_database
653 function unlock($force = false) {
654 if ($this->_lock_count == 0)
656 if (--$this->_lock_count <= 0 || $force) {
657 $this->_unlock_tables();
658 $this->_lock_count = 0;
663 * Actually unlock the required tables.
665 function _unlock_tables($write_lock) {
666 trigger_error("virtual", E_USER_ERROR);
670 * Callback for PEAR (DB) errors.
674 * @param A PEAR_error object.
676 function _pear_error_callback($error) {
677 if ($this->_is_false_error($error))
680 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
682 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
686 * Detect false errors messages from PEAR DB.
688 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
689 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
690 * return any data. (So when a "LOCK" command doesn't return any data,
691 * DB reports it as an error, when in fact, it's not.)
694 * @return bool True iff error is not really an error.
696 function _is_false_error($error) {
697 if ($error->getCode() != DB_ERROR)
700 $query = $this->_dbh->last_query;
702 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
703 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
704 // Last query was not of the sort which doesn't return any data.
705 //" <--kludge for brain-dead syntax coloring
709 if (! in_array('ismanip', get_class_methods('DB'))) {
710 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
711 // does not have the DB::isManip method.
715 if (DB::isManip($query)) {
716 // If Pear thinks it's an isManip then it wouldn't have thrown
717 // the error we're testing for....
724 function _pear_error_message($error) {
725 $class = get_class($this);
726 $message = "$class: fatal database error\n"
727 . "\t" . $error->getMessage() . "\n"
728 . "\t(" . $error->getDebugInfo() . ")\n";
730 // Prevent password from being exposed during a connection error
731 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
732 '\\1:XXXXXXXX', $this->_dsn);
733 return str_replace($this->_dsn, $safe_dsn, $message);
737 * Filter PHP errors notices from PEAR DB code.
739 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
740 * errors and notices. This is an error callback (for use with
741 * ErrorManager which will filter out those spurious messages.)
742 * @see _is_false_error, ErrorManager
745 function _pear_notice_filter($err) {
746 return ( $err->isNotice()
747 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
748 && $err->errline == 126
749 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
753 class WikiDB_backend_PearDB_iter
754 extends WikiDB_backend_iterator
756 function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
757 if (DB::isError($query_result)) {
758 // This shouldn't happen, I thought.
759 $backend->_pear_error_callback($query_result);
762 $this->_backend = &$backend;
763 $this->_result = $query_result;
767 $backend = &$this->_backend;
771 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
777 $pagedata = $backend->_extract_page_data($record);
778 $rec = array('pagename' => $record['pagename'],
779 'pagedata' => $pagedata);
781 if (!empty($record['version'])) {
782 $rec['versiondata'] = $backend->_extract_version_data($record);
783 $rec['version'] = $record['version'];
790 if ($this->_result) {
791 $this->_result->free();
792 $this->_result = false;
797 // (c-file-style: "gnu")
802 // c-hanging-comment-ender-p: nil
803 // indent-tabs-mode: nil