2 rcs_id('$Id: PearDB.php,v 1.24 2002-02-08 22:51:26 lakka Exp $');
4 //require_once('DB.php');
5 require_once('lib/WikiDB/backend.php');
6 //require_once('lib/FileFinder.php');
7 require_once('lib/ErrorManager.php');
8 require_once('lib/pear/DB.php');
10 class WikiDB_backend_PearDB
11 extends WikiDB_backend
13 function WikiDB_backend_PearDB ($dbparams) {
14 // Find and include PEAR's DB.php.
15 //$pearFinder = new PearFileFinder;
16 //$pearFinder->includeOnce('DB.php');
18 // Install filter to handle bogus error notices from buggy DB.php's.
20 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
22 // Open connection to database
23 $this->_dsn = $dbparams['dsn'];
24 $dboptions = array('persistent' => true,
26 $this->_dbh = DB::connect($this->_dsn, $dboptions);
28 if (DB::isError($dbh)) {
29 trigger_error(sprintf("Can't connect to database: %s",
30 $this->_pear_error_message($dbh)),
33 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
34 array($this, '_pear_error_callback'));
35 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
37 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
40 = array('page_tbl' => $prefix . 'page',
41 'version_tbl' => $prefix . 'version',
42 'link_tbl' => $prefix . 'link',
43 'recent_tbl' => $prefix . 'recent',
44 'nonempty_tbl' => $prefix . 'nonempty');
47 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
48 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
49 'maxversion' => "MAX(version)");
51 $this->_lock_count = 0;
55 * Close database connection.
60 if ($this->_lock_count) {
61 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
64 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
65 $this->unlock('force');
67 $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 = empty($pagedata) ? array() : 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(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 = empty($versiondata) ? array() : 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(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 from the database.
340 function delete_page($pagename) {
342 extract($this->_table_names);
345 if ( ($id = $this->_get_pageid($pagename, 'id')) ) {
346 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
347 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
348 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
349 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
350 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
352 // We're still in the link table (dangling link) so we can't delete this
354 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
357 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
359 $this->_update_recent_table();
360 $this->_update_nonempty_table();
366 // The only thing we might be interested in updating which we can
367 // do fast in the flags (minor_edit). I think the default
368 // update_versiondata will work fine...
369 //function update_versiondata($pagename, $version, $data) {
372 function set_links($pagename, $links) {
373 // Update link table.
374 // FIXME: optimize: mysql can do this all in one big INSERT.
377 extract($this->_table_names);
380 $pageid = $this->_get_pageid($pagename, true);
382 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
385 foreach($links as $link) {
386 if (isset($linkseen[$link]))
388 $linkseen[$link] = true;
389 $linkid = $this->_get_pageid($link, true);
390 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
391 . " VALUES ($pageid, $linkid)");
398 * Find pages which link to or are linked from a page.
400 function get_links($pagename, $reversed = true) {
402 extract($this->_table_names);
405 list($have,$want) = array('linkee', 'linker');
407 list($have,$want) = array('linker', 'linkee');
409 $qpagename = $dbh->quoteString($pagename);
411 $result = $dbh->query("SELECT $want.*"
412 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
413 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
414 . " AND $have.pagename='$qpagename'"
415 //. " GROUP BY $want.id"
416 . " ORDER BY $want.pagename",
419 return new WikiDB_backend_PearDB_iter($this, $result);
422 function get_all_pages($include_deleted) {
424 extract($this->_table_names);
426 if ($include_deleted) {
427 $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY pagename");
430 $result = $dbh->query("SELECT $page_tbl.*"
431 . " FROM $nonempty_tbl, $page_tbl"
432 . " WHERE $nonempty_tbl.id=$page_tbl.id"
433 . " ORDER BY pagename");
436 return new WikiDB_backend_PearDB_iter($this, $result);
442 function text_search($search = '', $fullsearch = false) {
444 extract($this->_table_names);
446 $table = "$nonempty_tbl, $page_tbl";
447 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
448 $fields = "$page_tbl.*";
449 $callback = new WikiMethodCb($this, '_sql_match_clause');
452 $table .= ", $recent_tbl";
453 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
455 $table .= ", $version_tbl";
456 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
458 $fields .= ",$version_tbl.*";
459 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
462 $search_clause = $search->makeSqlClause($callback);
464 $result = $dbh->query("SELECT $fields FROM $table"
465 . " WHERE $join_clause"
466 . " AND ($search_clause)"
467 . " ORDER BY pagename");
469 return new WikiDB_backend_PearDB_iter($this, $result);
472 function _sql_match_clause($word) {
473 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
474 $word = $this->_dbh->quoteString($word);
475 return "LOWER(pagename) LIKE '%$word%'";
478 function _fullsearch_sql_match_clause($word) {
479 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
480 $word = $this->_dbh->quoteString($word);
481 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
485 * Find highest hit counts.
487 function most_popular($limit) {
489 extract($this->_table_names);
495 $limitclause = $limit ? " LIMIT $limit" : '';
496 $result = $dbh->query("SELECT $page_tbl.*"
497 . " FROM $nonempty_tbl, $page_tbl"
498 . " WHERE $nonempty_tbl.id=$page_tbl.id"
499 . " ORDER BY hits $order"
502 return new WikiDB_backend_PearDB_iter($this, $result);
506 * Find recent changes.
508 function most_recent($params) {
511 $include_minor_revisions = false;
512 $exclude_major_revisions = false;
513 $include_all_revisions = false;
517 extract($this->_table_names);
524 $pick[] = "mtime <= $since";
527 $pick[] = "mtime >= $since";
530 if ($include_all_revisions) {
531 // Include all revisions of each page.
532 $table = "$page_tbl, $version_tbl";
533 $join_clause = "$page_tbl.id=$version_tbl.id";
535 if ($exclude_major_revisions) {
536 // Include only minor revisions
537 $pick[] = "minor_edit <> 0";
539 elseif (!$include_minor_revisions) {
540 // Include only major revisions
541 $pick[] = "minor_edit = 0";
545 $table = "$page_tbl, $recent_tbl";
546 $join_clause = "$page_tbl.id=$recent_tbl.id";
547 $table .= ", $version_tbl";
548 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
550 if ($exclude_major_revisions) {
551 // Include only most recent minor revision
552 $pick[] = 'version=latestminor';
554 elseif (!$include_minor_revisions) {
555 // Include only most recent major revision
556 $pick[] = 'version=latestmajor';
559 // Include only the latest revision (whether major or minor).
560 $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