2 rcs_id('$Id: PearDB.php,v 1.14 2001-12-19 12:07:53 carstenklapp 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');
9 class WikiDB_backend_PearDB
10 extends WikiDB_backend
12 function WikiDB_backend_PearDB ($dbparams) {
13 // Find and include PEAR's DB.php.
14 $pearFinder = new PearFileFinder;
15 $pearFinder->includeOnce('DB.php');
17 // Install filter to handle bogus error notices from buggy DB.php's.
19 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
21 // Open connection to database
22 $dsn = $dbparams['dsn'];
23 $this->_dbh = DB::connect($dsn, true); //FIXME: true -> persistent connection
25 if (DB::isError($dbh)) {
26 trigger_error(sprintf(_("Can't connect to database: %s"),$this->_pear_error_message($dbh)),
29 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
30 array($this, '_pear_error_callback'));
31 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
33 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
36 = array('page_tbl' => $prefix . 'page',
37 'version_tbl' => $prefix . 'version',
38 'link_tbl' => $prefix . 'link',
39 'recent_tbl' => $prefix . 'recent',
40 'nonempty_tbl' => $prefix . 'nonempty');
43 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
44 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
45 'maxversion' => "MAX(version)");
47 $this->_lock_count = 0;
51 * Close database connection.
56 if ($this->_lock_count) {
57 trigger_error( _("WARNING: database still locked") . '(lock_count = $this->_lock_count)' . "\n<br>",
60 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
61 $this->unlock('force');
63 $this->_dbh->disconnect();
71 function is_wiki_page($pagename) {
73 extract($this->_table_names);
74 return $dbh->getOne(sprintf("SELECT $page_tbl.id"
75 . " FROM $nonempty_tbl, $page_tbl"
76 . " WHERE $nonempty_tbl.id=$page_tbl.id"
77 . " AND pagename='%s'",
78 $dbh->quoteString($pagename)));
81 function get_all_pagenames() {
83 extract($this->_table_names);
84 return $dbh->getCol("SELECT pagename"
85 . " FROM $nonempty_tbl, $page_tbl"
86 . " WHERE $nonempty_tbl.id=$page_tbl.id");
90 * Read page information from database.
92 function get_pagedata($pagename) {
94 $page_tbl = $this->_table_names['page_tbl'];
96 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
98 $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
99 $dbh->quoteString($pagename)),
103 return $this->_extract_page_data($result);
106 function _extract_page_data(&$query_result) {
107 extract($query_result);
108 $data = empty($pagedata) ? array() : unserialize($pagedata);
109 $data['hits'] = $hits;
113 function update_pagedata($pagename, $newdata) {
115 $page_tbl = $this->_table_names['page_tbl'];
117 // Hits is the only thing we can update in a fast manner.
118 if (count($newdata) == 1 && isset($newdata['hits'])) {
119 // Note that this will fail silently if the page does not
120 // have a record in the page table. Since it's just the
121 // hit count, who cares?
122 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
123 $newdata['hits'], $dbh->quoteString($pagename)));
128 $data = $this->get_pagedata($pagename);
131 $this->_get_pageid($pagename, true); // Creates page record
134 @$hits = (int)$data['hits'];
135 unset($data['hits']);
137 foreach ($newdata as $key => $val) {
140 else if (empty($val))
146 $dbh->query(sprintf("UPDATE $page_tbl"
147 . " SET hits=%d, pagedata='%s'"
148 . " WHERE pagename='%s'",
150 $dbh->quoteString(serialize($data)),
151 $dbh->quoteString($pagename)));
156 function _get_pageid($pagename, $create_if_missing = false) {
159 $page_tbl = $this->_table_names['page_tbl'];
161 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
162 $dbh->quoteString($pagename));
164 if (!$create_if_missing)
165 return $dbh->getOne($query);
168 $id = $dbh->getOne($query);
170 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
172 $dbh->query(sprintf("INSERT INTO $page_tbl"
173 . " (id,pagename,hits)"
174 . " VALUES (%d,'%s',0)",
175 $id, $dbh->quoteString($pagename)));
181 function get_latest_version($pagename) {
183 extract($this->_table_names);
185 (int)$dbh->getOne(sprintf("SELECT latestversion"
186 . " FROM $page_tbl, $recent_tbl"
187 . " WHERE $page_tbl.id=$recent_tbl.id"
188 . " AND pagename='%s'",
189 $dbh->quoteString($pagename)));
192 function get_previous_version($pagename, $version) {
194 extract($this->_table_names);
197 (int)$dbh->getOne(sprintf("SELECT version"
198 . " FROM $version_tbl, $page_tbl"
199 . " WHERE $version_tbl.id=$page_tbl.id"
200 . " AND pagename='%s'"
201 . " AND version < %d"
202 . " ORDER BY version DESC"
204 $dbh->quoteString($pagename),
211 * @param $version int Which version to get.
213 * @return hash The version data, or false if specified version does not
216 function get_versiondata($pagename, $version, $want_content = false) {
218 extract($this->_table_names);
220 assert(!empty($pagename));
221 assert($version > 0);
223 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
224 // FIXME: optimization: sometimes don't get page data?
230 $fields = ("$page_tbl.*,"
231 . "mtime,minor_edit,versiondata,"
232 . "content<>'' AS have_content");
235 $result = $dbh->getRow(sprintf("SELECT $fields"
236 . " FROM $page_tbl, $version_tbl"
237 . " WHERE $page_tbl.id=$version_tbl.id"
238 . " AND pagename='%s'"
240 $dbh->quoteString($pagename), $version),
243 return $this->_extract_version_data($result);
246 function _extract_version_data(&$query_result) {
250 extract($query_result);
251 $data = empty($versiondata) ? array() : unserialize($versiondata);
253 $data['mtime'] = $mtime;
254 $data['is_minor_edit'] = !empty($minor_edit);
257 $data['%content'] = $content;
258 elseif ($have_content)
259 $data['%content'] = true;
261 $data['%content'] = '';
263 // FIXME: this is ugly.
264 if (isset($pagename)) {
265 // Query also includes page data.
266 // We might as well send that back too...
267 $data['%pagedata'] = $this->_extract_page_data($query_result);
275 * Create a new revision of a page.
277 function set_versiondata($pagename, $version, $data) {
279 $version_tbl = $this->_table_names['version_tbl'];
281 $minor_edit = (int) !empty($data['is_minor_edit']);
282 unset($data['is_minor_edit']);
284 $mtime = (int)$data['mtime'];
285 unset($data['mtime']);
286 assert(!empty($mtime));
288 @$content = (string) $data['%content'];
289 unset($data['%content']);
291 unset($data['%pagedata']);
294 $id = $this->_get_pageid($pagename, true);
296 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
297 $dbh->query(sprintf("DELETE FROM $version_tbl"
298 . " WHERE id=%d AND version=%d",
301 $dbh->query(sprintf("INSERT INTO $version_tbl"
302 . " (id,version,mtime,minor_edit,content,versiondata)"
303 . " VALUES(%d,%d,%d,%d,'%s','%s')",
304 $id, $version, $mtime, $minor_edit,
305 $dbh->quoteString($content),
306 $dbh->quoteString(serialize($data))));
308 $this->_update_recent_table($id);
309 $this->_update_nonempty_table($id);
315 * Delete an old revision of a page.
317 function delete_versiondata($pagename, $version) {
319 extract($this->_table_names);
322 if ( ($id = $this->_get_pageid($pagename)) ) {
323 $dbh->query("DELETE FROM $version_tbl"
324 . " WHERE id=$id AND version=$version");
325 $this->_update_recent_table($id);
326 // This shouldn't be needed (as long as the latestversion
327 // never gets deleted.) But, let's be safe.
328 $this->_update_nonempty_table($id);
334 * Delete page from the database.
336 function delete_page($pagename) {
338 extract($this->_table_names);
341 if ( ($id = $this->_get_pageid($pagename, 'id')) ) {
342 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
343 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
344 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
345 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
346 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
348 // We're still in the link table (dangling link) so we can't delete this
350 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
353 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
355 $this->_update_recent_table();
356 $this->_update_nonempty_table();
362 // The only thing we might be interested in updating which we can
363 // do fast in the flags (minor_edit). I think the default
364 // update_versiondata will work fine...
365 //function update_versiondata($pagename, $version, $data) {
368 function set_links($pagename, $links) {
369 // Update link table.
370 // FIXME: optimize: mysql can do this all in one big INSERT.
373 extract($this->_table_names);
376 $pageid = $this->_get_pageid($pagename, true);
378 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
381 foreach($links as $link) {
382 if (isset($linkseen[$link]))
384 $linkseen[$link] = true;
385 $linkid = $this->_get_pageid($link, true);
386 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
387 . " VALUES ($pageid, $linkid)");
394 * Find pages which link to or are linked from a page.
396 function get_links($pagename, $reversed = true) {
398 extract($this->_table_names);
401 list($have,$want) = array('linkee', 'linker');
403 list($have,$want) = array('linker', 'linkee');
405 $qpagename = $dbh->quoteString($pagename);
407 $result = $dbh->query("SELECT $want.*"
408 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
409 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
410 . " AND $have.pagename='$qpagename'"
411 //. " GROUP BY $want.id"
412 . " ORDER BY $want.pagename",
415 return new WikiDB_backend_PearDB_iter($this, $result);
418 function get_all_pages($include_deleted) {
420 extract($this->_table_names);
422 if ($include_deleted) {
423 $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY pagename");
426 $result = $dbh->query("SELECT $page_tbl.*"
427 . " FROM $nonempty_tbl, $page_tbl"
428 . " WHERE $nonempty_tbl.id=$page_tbl.id"
429 . " ORDER BY pagename");
432 return new WikiDB_backend_PearDB_iter($this, $result);
438 function text_search($search = '', $fullsearch = false) {
440 extract($this->_table_names);
442 $table = "$nonempty_tbl, $page_tbl";
443 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
444 $fields = "$page_tbl.*";
445 $callback = new WikiMethodCb($this, '_sql_match_clause');
448 $table .= ", $recent_tbl";
449 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
451 $table .= ", $version_tbl";
452 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
454 $fields .= ",$version_tbl.*";
455 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
458 $search_clause = $search->makeSqlClause($callback);
460 $result = $dbh->query("SELECT $fields FROM $table"
461 . " WHERE $join_clause"
462 . " AND ($search_clause)"
463 . " ORDER BY pagename");
465 return new WikiDB_backend_PearDB_iter($this, $result);
468 function _sql_match_clause($word) {
469 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
470 $word = $this->_dbh->quoteString($word);
471 return "LOWER(pagename) LIKE '%$word%'";
474 function _fullsearch_sql_match_clause($word) {
475 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
476 $word = $this->_dbh->quoteString($word);
477 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
481 * Find highest hit counts.
483 function most_popular($limit) {
485 extract($this->_table_names);
487 $limitclause = $limit ? " LIMIT $limit" : '';
488 $result = $dbh->query("SELECT $page_tbl.*"
489 . " FROM $nonempty_tbl, $page_tbl"
490 . " WHERE $nonempty_tbl.id=$page_tbl.id"
491 . " ORDER BY hits DESC"
494 return new WikiDB_backend_PearDB_iter($this, $result);
498 * Find recent changes.
500 function most_recent($params) {
503 $include_minor_revisions = false;
504 $exclude_major_revisions = false;
505 $include_all_revisions = false;
509 extract($this->_table_names);
513 $pick[] = "mtime >= $since";
515 if ($include_all_revisions) {
516 // Include all revisions of each page.
517 $table = "$page_tbl, $version_tbl";
518 $join_clause = "$page_tbl.id=$version_tbl.id";
520 if ($exclude_major_revisions) {
521 // Include only minor revisions
522 $pick[] = "minor_edit <> 0";
524 elseif (!$include_minor_revisions) {
525 // Include only major revisions
526 $pick[] = "minor_edit = 0";
530 $table = "$page_tbl, $recent_tbl";
531 $join_clause = "$page_tbl.id=$recent_tbl.id";
532 $table .= ", $version_tbl";
533 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
535 if ($exclude_major_revisions) {
536 // Include only most recent minor revision
537 $pick[] = 'version=latestminor';
539 elseif (!$include_minor_revisions) {
540 // Include only most recent major revision
541 $pick[] = 'version=latestmajor';
544 // Include only the latest revision (whether major or minor).
545 $pick[] ='version=latestversion';
549 $limitclause = $limit ? " LIMIT $limit" : '';
550 $where_clause = $join_clause;
552 $where_clause .= " AND " . join(" AND ", $pick);
554 // FIXME: use SQL_BUFFER_RESULT for mysql?
555 $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
557 . " WHERE $where_clause"
558 . " ORDER BY mtime DESC"
561 return new WikiDB_backend_PearDB_iter($this, $result);
564 function _update_recent_table($pageid = false) {
566 extract($this->_table_names);
567 extract($this->_expressions);
569 $pageid = (int)$pageid;
573 $dbh->query("DELETE FROM $recent_tbl"
574 . ( $pageid ? " WHERE id=$pageid" : ""));
576 $dbh->query( "INSERT INTO $recent_tbl"
577 . " (id, latestversion, latestmajor, latestminor)"
578 . " SELECT id, $maxversion, $maxmajor, $maxminor"
579 . " FROM $version_tbl"
580 . ( $pageid ? " WHERE id=$pageid" : "")
585 function _update_nonempty_table($pageid = false) {
587 extract($this->_table_names);
589 $pageid = (int)$pageid;
593 $dbh->query("DELETE FROM $nonempty_tbl"
594 . ( $pageid ? " WHERE id=$pageid" : ""));
596 $dbh->query("INSERT INTO $nonempty_tbl (id)"
597 . " SELECT $recent_tbl.id"
598 . " FROM $recent_tbl, $version_tbl"
599 . " WHERE $recent_tbl.id=$version_tbl.id"
600 . " AND version=latestversion"
602 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
609 * Grab a write lock on the tables in the SQL database.
611 * Calls can be nested. The tables won't be unlocked until
612 * _unlock_database() is called as many times as _lock_database().
616 function lock($write_lock = true) {
617 if ($this->_lock_count++ == 0)
618 $this->_lock_tables($write_lock);
622 * Actually lock the required tables.
624 function _lock_tables($write_lock) {
625 trigger_error("virtual", E_USER_ERROR);
629 * Release a write lock on the tables in the SQL database.
633 * @param $force boolean Unlock even if not every call to lock() has been matched
634 * by a call to unlock().
636 * @see _lock_database
638 function unlock($force = false) {
639 if ($this->_lock_count == 0)
641 if (--$this->_lock_count <= 0 || $force) {
642 $this->_unlock_tables();
643 $this->_lock_count = 0;
648 * Actually unlock the required tables.
650 function _unlock_tables($write_lock) {
651 trigger_error("virtual", E_USER_ERROR);
655 * Callback for PEAR (DB) errors.
659 * @param A PEAR_error object.
661 function _pear_error_callback($error) {
662 if ($this->_is_false_error($error))
665 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
667 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
671 * Detect false errors messages from PEAR DB.
673 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
674 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
675 * return any data. (So when a "LOCK" command doesn't return any data,
676 * DB reports it as an error, when in fact, it's not.)
679 * @return bool True iff error is not really an error.
681 function _is_false_error($error) {
682 if ($error->getCode() != DB_ERROR)
685 $query = $this->_dbh->last_query;
687 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
688 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
689 // Last query was not of the sort which doesn't return any data.
692 //" <--(kludge for dumb syntax coloring)
694 if (! in_array('ismanip', get_class_methods('DB'))) {
695 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
696 // does not have the DB::isManip method.
700 if (DB::isManip($query)) {
701 // If Pear thinks it's an isManip then it wouldn't have thrown
702 // the error we're testing for....
709 function _pear_error_message($error) {
710 $class = get_class($this);
711 $message = $class ": " . _("fatal database error") ."\n"
712 . "\t" . $error->getMessage() . "\n"
713 . "\t(" . $error->getDebugInfo() . ")\n";
719 * Filter PHP errors notices from PEAR DB code.
721 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
722 * errors and notices. This is an error callback (for use with
723 * ErrorManager which will filter out those spurious messages.)
724 * @see _is_false_error, ErrorManager
727 function _pear_notice_filter($err) {
728 return ( $err->isNotice()
729 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
730 && $err->errline == 126
731 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
735 class WikiDB_backend_PearDB_iter
736 extends WikiDB_backend_iterator
738 function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
739 if (DB::isError($query_result)) {
740 // This shouldn't happen, I thought.
741 $backend->_pear_error_callback($query_result);
744 $this->_backend = &$backend;
745 $this->_result = $query_result;
749 $backend = &$this->_backend;
753 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
759 $pagedata = $backend->_extract_page_data($record);
760 $rec = array('pagename' => $record['pagename'],
761 'pagedata' => $pagedata);
763 if (!empty($record['version'])) {
764 $rec['versiondata'] = $backend->_extract_version_data($record);
765 $rec['version'] = $record['version'];
772 if ($this->_result) {
773 $this->_result->free();
774 $this->_result = false;
779 // (c-file-style: "gnu")
784 // c-hanging-comment-ender-p: nil
785 // indent-tabs-mode: nil