2 rcs_id('$Id: PearDB.php,v 1.67 2004-11-10 19:32:24 rurban Exp $');
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 //require_once('lib/ErrorManager.php');
8 class WikiDB_backend_PearDB
13 function WikiDB_backend_PearDB ($dbparams) {
14 // Find and include PEAR's DB.php.
15 // if DB would have exported its version number, it would be easier.
16 @require_once('DB/common.php'); // Either our local pear copy or the system one
18 $name = check_php_version(5) ? "escapeSimple" : strtolower("escapeSimple");
19 if (!in_array($name, get_class_methods("DB_common"))) {
20 $finder = new FileFinder;
21 $dir = dirname(__FILE__)."/../../pear";
22 $finder->_prepend_to_include_path($dir);
23 include_once("$dir/DB/common.php"); // use our version instead.
24 if (!in_array($name, get_class_methods("DB_common"))) {
25 $pearFinder = new PearFileFinder("lib/pear");
26 $pearFinder->includeOnce('DB.php');
28 include_once("$dir/DB.php");
31 include_once("DB.php");
34 // Install filter to handle bogus error notices from buggy DB.php's.
35 //TODO: check the Pear_DB version, but how?
38 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
39 $this->_pearerrhandler = true;
42 // Open connection to database
43 $this->_dsn = $dbparams['dsn'];
44 $this->_dbparams = $dbparams;
45 $dboptions = array('persistent' => true,
47 if (preg_match('/^pgsql/',$this->_dsn))
48 $dboptions['persistent'] = false;
49 $this->_dbh = DB::connect($this->_dsn, $dboptions);
51 if (DB::isError($dbh)) {
52 trigger_error(sprintf("Can't connect to database: %s",
53 $this->_pear_error_message($dbh)),
56 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
57 array($this, '_pear_error_callback'));
58 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
60 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
62 = array('page_tbl' => $prefix . 'page',
63 'version_tbl' => $prefix . 'version',
64 'link_tbl' => $prefix . 'link',
65 'recent_tbl' => $prefix . 'recent',
66 'nonempty_tbl' => $prefix . 'nonempty');
67 $page_tbl = $this->_table_names['page_tbl'];
68 $version_tbl = $this->_table_names['version_tbl'];
69 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
70 $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, ".
71 "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
74 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
75 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
76 'maxversion' => "MAX(version)",
78 'iscontent' => "content<>''");
80 $this->_lock_count = 0;
84 * Close database connection.
89 if ($this->_lock_count) {
90 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
93 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
94 $this->unlock('force');
96 $this->_dbh->disconnect();
98 if (!empty($this->_pearerrhandler)) {
99 $GLOBALS['ErrorManager']->popErrorHandler();
105 * Test fast wikipage.
107 function is_wiki_page($pagename) {
109 extract($this->_table_names);
110 return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
111 . " FROM $nonempty_tbl, $page_tbl"
112 . " WHERE $nonempty_tbl.id=$page_tbl.id"
113 . " AND pagename='%s'",
114 $dbh->escapeSimple($pagename)));
117 function get_all_pagenames() {
119 extract($this->_table_names);
120 return $dbh->getCol("SELECT pagename"
121 . " FROM $nonempty_tbl, $page_tbl"
122 . " WHERE $nonempty_tbl.id=$page_tbl.id");
125 function numPages($filter=false, $exclude='') {
127 extract($this->_table_names);
128 return $dbh->getOne("SELECT count(*)"
129 . " FROM $nonempty_tbl, $page_tbl"
130 . " WHERE $nonempty_tbl.id=$page_tbl.id");
133 function increaseHitCount($pagename) {
135 // Hits is the only thing we can update in a fast manner.
136 // Note that this will fail silently if the page does not
137 // have a record in the page table. Since it's just the
138 // hit count, who cares?
139 $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
140 $this->_table_names['page_tbl'],
141 $dbh->escapeSimple($pagename)));
146 * Read page information from database.
148 function get_pagedata($pagename) {
150 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
151 $result = $dbh->getRow(sprintf("SELECT %s FROM %s WHERE pagename='%s'",
153 $this->_table_names['page_tbl'],
154 $dbh->escapeSimple($pagename)),
156 return $result ? $this->_extract_page_data($result) : false;
159 function _extract_page_data($data) {
160 if (empty($data)) return array();
161 elseif (empty($data['pagedata'])) return $data;
162 else return array_merge($data, $this->_unserialize($data['pagedata']));
165 function update_pagedata($pagename, $newdata) {
167 $page_tbl = $this->_table_names['page_tbl'];
169 // Hits is the only thing we can update in a fast manner.
170 if (count($newdata) == 1 && isset($newdata['hits'])) {
171 // Note that this will fail silently if the page does not
172 // have a record in the page table. Since it's just the
173 // hit count, who cares?
174 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
175 $newdata['hits'], $dbh->escapeSimple($pagename)));
179 $this->lock(array($page_tbl), true);
180 $data = $this->get_pagedata($pagename);
183 $this->_get_pageid($pagename, true); // Creates page record
186 @$hits = (int)$data['hits'];
187 unset($data['hits']);
189 foreach ($newdata as $key => $val) {
192 else if (empty($val))
198 /* Portability issue -- not all DBMS supports huge strings
199 * so we need to 'bind' instead of building a SQL statment.
200 * Note that we do not need to escapeSimple when we bind
201 $dbh->query(sprintf("UPDATE $page_tbl"
202 . " SET hits=%d, pagedata='%s'"
203 . " WHERE pagename='%s'",
205 $dbh->escapeSimple($this->_serialize($data)),
206 $dbh->escapeSimple($pagename)));
208 $sth = $dbh->query("UPDATE $page_tbl"
209 . " SET hits=?, pagedata=?"
210 . " WHERE pagename=?",
211 array($hits, $this->_serialize($data), $pagename));
212 $this->unlock(array($page_tbl));
215 function _get_pageid($pagename, $create_if_missing = false) {
219 $cache =& $request->_dbi->_cache->_id_cache;
220 if (isset($cache[$pagename])) return $cache[$pagename];
223 $page_tbl = $this->_table_names['page_tbl'];
225 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
226 $dbh->escapeSimple($pagename));
228 if (!$create_if_missing)
229 return $dbh->getOne($query);
231 $id = $dbh->getOne($query);
233 $this->lock(array($page_tbl), true); // write lock
234 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
236 $dbh->query(sprintf("INSERT INTO $page_tbl"
237 . " (id,pagename,hits)"
238 . " VALUES (%d,'%s',0)",
239 $id, $dbh->escapeSimple($pagename)));
240 $this->unlock(array($page_tbl));
245 function get_latest_version($pagename) {
247 extract($this->_table_names);
249 (int)$dbh->getOne(sprintf("SELECT latestversion"
250 . " FROM $page_tbl, $recent_tbl"
251 . " WHERE $page_tbl.id=$recent_tbl.id"
252 . " AND pagename='%s'",
253 $dbh->escapeSimple($pagename)));
256 function get_previous_version($pagename, $version) {
258 extract($this->_table_names);
261 (int)$dbh->getOne(sprintf("SELECT version"
262 . " FROM $version_tbl, $page_tbl"
263 . " WHERE $version_tbl.id=$page_tbl.id"
264 . " AND pagename='%s'"
265 . " AND version < %d"
266 . " ORDER BY version DESC",
267 /* Non portable and useless anyway with getOne
270 $dbh->escapeSimple($pagename),
277 * @param $version int Which version to get.
279 * @return hash The version data, or false if specified version does not
282 function get_versiondata($pagename, $version, $want_content = false) {
284 extract($this->_table_names);
285 extract($this->_expressions);
287 assert(is_string($pagename) and $pagename != "");
288 assert($version > 0);
290 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
291 // FIXME: optimization: sometimes don't get page data?
293 $fields = $this->page_tbl_fields . ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
296 $fields = $this->page_tbl_fields . ","
297 . "mtime, minor_edit, versiondata,"
298 . "$iscontent AS have_content";
301 $result = $dbh->getRow(sprintf("SELECT $fields"
302 . " FROM $page_tbl, $version_tbl"
303 . " WHERE $page_tbl.id=$version_tbl.id"
304 . " AND pagename='%s'"
306 $dbh->escapeSimple($pagename), $version),
309 return $this->_extract_version_data($result);
312 function _extract_version_data($query_result) {
316 extract($query_result);
317 $data = $this->_unserialize($versiondata);
319 $data['mtime'] = $mtime;
320 $data['is_minor_edit'] = !empty($minor_edit);
323 $data['%content'] = $content;
324 elseif ($have_content)
325 $data['%content'] = true;
327 $data['%content'] = '';
329 // FIXME: this is ugly.
330 if (isset($pagename)) {
331 // Query also includes page data.
332 // We might as well send that back too...
333 $data['%pagedata'] = $this->_extract_page_data($query_result);
341 * Create a new revision of a page.
343 function set_versiondata($pagename, $version, $data) {
345 $version_tbl = $this->_table_names['version_tbl'];
347 $minor_edit = (int) !empty($data['is_minor_edit']);
348 unset($data['is_minor_edit']);
350 $mtime = (int)$data['mtime'];
351 unset($data['mtime']);
352 assert(!empty($mtime));
354 @$content = (string) $data['%content'];
355 unset($data['%content']);
357 unset($data['%pagedata']);
360 $id = $this->_get_pageid($pagename, true);
362 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
363 $dbh->query(sprintf("DELETE FROM $version_tbl"
364 . " WHERE id=%d AND version=%d",
367 /* mysql optimized version.
368 $dbh->query(sprintf("INSERT INTO $version_tbl"
369 . " (id,version,mtime,minor_edit,content,versiondata)"
370 . " VALUES(%d,%d,%d,%d,'%s','%s')",
371 $id, $version, $mtime, $minor_edit,
372 $dbh->quoteSmart($content),
373 $dbh->quoteSmart($this->_serialize($data))));
375 // generic slow PearDB bind eh quoting.
376 $dbh->query("INSERT INTO $version_tbl"
377 . " (id,version,mtime,minor_edit,content,versiondata)"
378 . " VALUES(?, ?, ?, ?, ?, ?)",
379 array($id, $version, $mtime, $minor_edit, $content,
380 $this->_serialize($data)));
382 $this->_update_recent_table($id);
383 $this->_update_nonempty_table($id);
389 * Delete an old revision of a page.
391 function delete_versiondata($pagename, $version) {
393 extract($this->_table_names);
396 if ( ($id = $this->_get_pageid($pagename)) ) {
397 $dbh->query("DELETE FROM $version_tbl"
398 . " WHERE id=$id AND version=$version");
399 $this->_update_recent_table($id);
400 // This shouldn't be needed (as long as the latestversion
401 // never gets deleted.) But, let's be safe.
402 $this->_update_nonempty_table($id);
408 * Delete page completely from the database.
409 * I'm not sure if this is what we want. Maybe just delete the revisions
411 function delete_page($pagename) {
413 extract($this->_table_names);
416 if ( ($id = $this->_get_pageid($pagename, false)) ) {
417 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
418 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
419 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
420 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
421 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
423 // We're still in the link table (dangling link) so we can't delete this
425 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
428 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
430 $this->_update_recent_table();
431 $this->_update_nonempty_table();
437 // The only thing we might be interested in updating which we can
438 // do fast in the flags (minor_edit). I think the default
439 // update_versiondata will work fine...
440 //function update_versiondata($pagename, $version, $data) {
443 function set_links($pagename, $links) {
444 // Update link table.
445 // FIXME: optimize: mysql can do this all in one big INSERT.
448 extract($this->_table_names);
451 $pageid = $this->_get_pageid($pagename, true);
453 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
456 foreach($links as $link) {
457 if (isset($linkseen[$link]))
459 $linkseen[$link] = true;
460 $linkid = $this->_get_pageid($link, true);
461 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
462 . " VALUES ($pageid, $linkid)");
469 * Find pages which link to or are linked from a page.
471 function get_links($pagename, $reversed=true, $include_empty=false) {
473 extract($this->_table_names);
476 list($have,$want) = array('linkee', 'linker');
478 list($have,$want) = array('linker', 'linkee');
480 $qpagename = $dbh->escapeSimple($pagename);
481 $result = $dbh->query("SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
482 // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
483 // and the PostgresSQL manual does not have it either
484 // Since it is optional in mySQL, just remove it...
485 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
486 . (!$include_empty ? ", $nonempty_tbl" : '')
487 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
488 . " AND $have.pagename='$qpagename'"
489 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
490 //. " GROUP BY $want.id"
491 . " ORDER BY $want.pagename");
493 return new WikiDB_backend_PearDB_iter($this, $result);
496 function get_all_pages($include_empty=false, $sortby=false, $limit=false) {
498 extract($this->_table_names);
499 // Limit clause is NOT portable!
500 // if ($limit) $limit = "LIMIT $limit";
502 $orderby = $this->sortby($sortby, 'db');
503 if ($orderby) $orderby = 'ORDER BY ' . $orderby;
504 if (strstr($orderby, 'mtime ')) { // multiple columns possible
505 if ($include_empty) {
507 . $this->page_tbl_fields
508 . " FROM $page_tbl, $recent_tbl, $version_tbl"
509 . " WHERE $page_tbl.id=$recent_tbl.id"
510 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
515 . $this->page_tbl_fields
516 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
517 . " WHERE $nonempty_tbl.id=$page_tbl.id"
518 . " AND $page_tbl.id=$recent_tbl.id"
519 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
523 if ($include_empty) {
525 . $this->page_tbl_fields
526 ." FROM $page_tbl $orderby";
530 . $this->page_tbl_fields
531 . " FROM $nonempty_tbl, $page_tbl"
532 . " WHERE $nonempty_tbl.id=$page_tbl.id"
537 // extract from,count from limit
538 list($from,$count) = $this->limit($limit);
539 $result = $dbh->limitQuery($sql, $from, $count);
541 $result = $dbh->query($sql);
543 return new WikiDB_backend_PearDB_iter($this, $result);
549 function text_search($search = '', $fullsearch = false) {
551 extract($this->_table_names);
553 $table = "$nonempty_tbl, $page_tbl";
554 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
555 $fields = $this->page_tbl_fields;
556 $callback = new WikiMethodCb($this, '_sql_match_clause');
559 $table .= ", $recent_tbl";
560 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
562 $table .= ", $version_tbl";
563 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
565 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
566 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
569 $search_clause = $search->makeSqlClause($callback);
571 $result = $dbh->query("SELECT $fields FROM $table"
572 . " WHERE $join_clause"
573 . " AND ($search_clause)"
574 . " ORDER BY pagename");
576 return new WikiDB_backend_PearDB_iter($this, $result);
579 //Todo: check if the better Mysql MATCH operator is supported,
580 // (ranked search) and also google like expressions.
581 function _sql_match_clause($word) {
582 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
583 $word = $this->_dbh->escapeSimple($word);
584 //$page_tbl = $this->_table_names['page_tbl'];
585 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
586 // e.g. if word is lowercased.
587 // http://bugs.mysql.com/bug.php?id=1491
588 return "LOWER(pagename) LIKE '%$word%'";
591 function _fullsearch_sql_match_clause($word) {
592 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
593 $word = $this->_dbh->escapeSimple($word);
594 //$page_tbl = $this->_table_names['page_tbl'];
595 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
596 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
600 * Find highest or lowest hit counts.
602 function most_popular($limit=0, $sortby='-hits') {
604 extract($this->_table_names);
610 $order = "hits DESC";
611 $where = " AND hits > 0";
614 if ($sortby != '-hits') {
615 if ($order = $this->sortby($sortby, 'db'))
616 $orderby = " ORDER BY " . $order;
618 $orderby = " ORDER BY $order";
620 //$limitclause = $limit ? " LIMIT $limit" : '';
622 . $this->page_tbl_fields
623 . " FROM $nonempty_tbl, $page_tbl"
624 . " WHERE $nonempty_tbl.id=$page_tbl.id"
628 list($from, $count) = $this->limit($limit);
629 $result = $dbh->limitQuery($sql, $from, $count);
631 $result = $dbh->query($sql);
634 return new WikiDB_backend_PearDB_iter($this, $result);
638 * Find recent changes.
640 function most_recent($params) {
643 $include_minor_revisions = false;
644 $exclude_major_revisions = false;
645 $include_all_revisions = false;
649 extract($this->_table_names);
653 $pick[] = "mtime >= $since";
656 if ($include_all_revisions) {
657 // Include all revisions of each page.
658 $table = "$page_tbl, $version_tbl";
659 $join_clause = "$page_tbl.id=$version_tbl.id";
661 if ($exclude_major_revisions) {
662 // Include only minor revisions
663 $pick[] = "minor_edit <> 0";
665 elseif (!$include_minor_revisions) {
666 // Include only major revisions
667 $pick[] = "minor_edit = 0";
671 $table = "$page_tbl, $recent_tbl";
672 $join_clause = "$page_tbl.id=$recent_tbl.id";
673 $table .= ", $version_tbl";
674 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
676 if ($exclude_major_revisions) {
677 // Include only most recent minor revision
678 $pick[] = 'version=latestminor';
680 elseif (!$include_minor_revisions) {
681 // Include only most recent major revision
682 $pick[] = 'version=latestmajor';
685 // Include only the latest revision (whether major or minor).
686 $pick[] ='version=latestversion';
694 // $limitclause = $limit ? " LIMIT $limit" : '';
695 $where_clause = $join_clause;
697 $where_clause .= " AND " . join(" AND ", $pick);
699 // FIXME: use SQL_BUFFER_RESULT for mysql?
701 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
703 . " WHERE $where_clause"
704 . " ORDER BY mtime $order";
707 $result = $dbh->limitQuery($sql, 0, $limit);
709 $result = $dbh->query($sql);
712 return new WikiDB_backend_PearDB_iter($this, $result);
716 * Rename page in the database.
718 function rename_page($pagename, $to) {
720 extract($this->_table_names);
723 if ( ($id = $this->_get_pageid($pagename, false)) ) {
724 if ($new = $this->_get_pageid($to, false)) {
726 //this page does not exist (already verified before), but exists in the page table.
727 //so we delete this page.
728 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
730 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
731 $dbh->escapeSimple($to)));
737 function _update_recent_table($pageid = false) {
739 extract($this->_table_names);
740 extract($this->_expressions);
742 $pageid = (int)$pageid;
745 $dbh->query("DELETE FROM $recent_tbl"
746 . ( $pageid ? " WHERE id=$pageid" : ""));
747 $dbh->query( "INSERT INTO $recent_tbl"
748 . " (id, latestversion, latestmajor, latestminor)"
749 . " SELECT id, $maxversion, $maxmajor, $maxminor"
750 . " FROM $version_tbl"
751 . ( $pageid ? " WHERE id=$pageid" : "")
756 function _update_nonempty_table($pageid = false) {
758 extract($this->_table_names);
760 $pageid = (int)$pageid;
762 extract($this->_expressions);
764 $dbh->query("DELETE FROM $nonempty_tbl"
765 . ( $pageid ? " WHERE id=$pageid" : ""));
766 $dbh->query("INSERT INTO $nonempty_tbl (id)"
767 . " SELECT $recent_tbl.id"
768 . " FROM $recent_tbl, $version_tbl"
769 . " WHERE $recent_tbl.id=$version_tbl.id"
770 . " AND version=latestversion"
771 // We have some specifics here (Oracle)
772 //. " AND content<>''"
773 . " AND content $notempty"
774 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
781 * Grab a write lock on the tables in the SQL database.
783 * Calls can be nested. The tables won't be unlocked until
784 * _unlock_database() is called as many times as _lock_database().
788 function lock($tables = false, $write_lock = true) {
789 if ($this->_lock_count++ == 0)
790 $this->_lock_tables($write_lock);
794 * Actually lock the required tables.
796 function _lock_tables($write_lock) {
797 trigger_error("virtual", E_USER_ERROR);
801 * Release a write lock on the tables in the SQL database.
805 * @param $force boolean Unlock even if not every call to lock() has been matched
806 * by a call to unlock().
808 * @see _lock_database
810 function unlock($tables = false, $force = false) {
811 if ($this->_lock_count == 0)
813 if (--$this->_lock_count <= 0 || $force) {
814 $this->_unlock_tables();
815 $this->_lock_count = 0;
820 * Actually unlock the required tables.
822 function _unlock_tables($write_lock) {
823 trigger_error("virtual", E_USER_ERROR);
830 function _serialize($data) {
833 assert(is_array($data));
834 return serialize($data);
840 function _unserialize($data) {
841 return empty($data) ? array() : unserialize($data);
845 * Callback for PEAR (DB) errors.
849 * @param A PEAR_error object.
851 function _pear_error_callback($error) {
852 if ($this->_is_false_error($error))
855 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
857 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
861 * Detect false errors messages from PEAR DB.
863 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
864 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
865 * return any data. (So when a "LOCK" command doesn't return any data,
866 * DB reports it as an error, when in fact, it's not.)
869 * @return bool True iff error is not really an error.
871 function _is_false_error($error) {
872 if ($error->getCode() != DB_ERROR)
875 $query = $this->_dbh->last_query;
877 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
878 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
879 // Last query was not of the sort which doesn't return any data.
880 //" <--kludge for brain-dead syntax coloring
884 if (! in_array('ismanip', get_class_methods('DB'))) {
885 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
886 // does not have the DB::isManip method.
890 if (DB::isManip($query)) {
891 // If Pear thinks it's an isManip then it wouldn't have thrown
892 // the error we're testing for....
899 function _pear_error_message($error) {
900 $class = get_class($this);
901 $message = "$class: fatal database error\n"
902 . "\t" . $error->getMessage() . "\n"
903 . "\t(" . $error->getDebugInfo() . ")\n";
905 // Prevent password from being exposed during a connection error
906 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
907 '\\1:XXXXXXXX', $this->_dsn);
908 return str_replace($this->_dsn, $safe_dsn, $message);
912 * Filter PHP errors notices from PEAR DB code.
914 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
915 * errors and notices. This is an error callback (for use with
916 * ErrorManager which will filter out those spurious messages.)
917 * @see _is_false_error, ErrorManager
920 function _pear_notice_filter($err) {
921 return ( $err->isNotice()
922 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
923 && $err->errline == 126
924 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
927 /* some variables and functions for DB backend abstraction (action=upgrade) */
928 function database () {
929 return $this->_dbh->dsn['database'];
931 function backendType() {
932 return $this->_dbh->phptype;
934 function connection() {
935 return $this->_dbh->connection;
938 function listOfTables() {
939 return $this->_dbh->getListOf('tables');
941 function listOfFields($database,$table) {
942 if ($this->backendType() == 'mysql') {
944 assert(!empty($database));
945 assert(!empty($table));
946 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
947 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
948 if (!$result) return array();
949 $columns = mysql_num_fields($result);
950 for ($i = 0; $i < $columns; $i++) {
951 $fields[] = mysql_field_name($result, $i);
953 mysql_free_result($result);
956 // TODO: try ADODB version?
957 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
964 * This class is a generic iterator.
966 * WikiDB_backend_PearDB_iter only iterates over things that have
967 * 'pagename', 'pagedata', etc. etc.
969 * Probably WikiDB_backend_PearDB_iter and this class should be merged
970 * (most of the code is cut-and-paste :-( ), but I am trying to make
971 * changes that could be merged easily.
973 * @author: Dan Frankowski
975 class WikiDB_backend_PearDB_generic_iter
976 extends WikiDB_backend_iterator
978 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
979 if (DB::isError($query_result)) {
980 // This shouldn't happen, I thought.
981 $backend->_pear_error_callback($query_result);
984 $this->_backend = &$backend;
985 $this->_result = $query_result;
991 return $this->_result->numRows();
995 $backend = &$this->_backend;
999 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1009 if ($this->_result) {
1010 $this->_result->free();
1011 $this->_result = false;
1016 class WikiDB_backend_PearDB_iter
1017 extends WikiDB_backend_PearDB_generic_iter
1021 $backend = &$this->_backend;
1022 if (!$this->_result)
1025 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1031 $pagedata = $backend->_extract_page_data($record);
1032 $rec = array('pagename' => $record['pagename'],
1033 'pagedata' => $pagedata);
1035 if (!empty($record['version'])) {
1036 $rec['versiondata'] = $backend->_extract_version_data($record);
1037 $rec['version'] = $record['version'];
1044 // $Log: not supported by cvs2svn $
1045 // Revision 1.66 2004/11/10 15:29:21 rurban
1046 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1047 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1048 // * WikiDB: moved SQL specific methods upwards
1049 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1050 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1052 // Revision 1.65 2004/11/09 17:11:17 rurban
1053 // * revert to the wikidb ref passing. there's no memory abuse there.
1054 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1055 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1056 // are also needed at the rendering for linkExistingWikiWord().
1057 // pass options to pageiterator.
1058 // use this cache also for _get_pageid()
1059 // This saves about 8 SELECT count per page (num all pagelinks).
1060 // * fix passing of all page fields to the pageiterator.
1061 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1063 // Revision 1.64 2004/11/07 16:02:52 rurban
1064 // new sql access log (for spam prevention), and restructured access log class
1065 // dbh->quote (generic)
1066 // pear_db: mysql specific parts seperated (using replace)
1068 // Revision 1.63 2004/11/01 10:43:58 rurban
1069 // seperate PassUser methods into seperate dir (memory usage)
1070 // fix WikiUser (old) overlarge data session
1071 // remove wikidb arg from various page class methods, use global ->_dbi instead
1074 // Revision 1.62 2004/10/14 19:19:34 rurban
1075 // loadsave: check if the dumped file will be accessible from outside.
1076 // and some other minor fixes. (cvsclient native not yet ready)
1078 // Revision 1.61 2004/10/14 17:19:17 rurban
1079 // allow most_popular sortby arguments
1081 // Revision 1.60 2004/07/09 10:06:50 rurban
1082 // Use backend specific sortby and sortable_columns method, to be able to
1083 // select between native (Db backend) and custom (PageList) sorting.
1084 // Fixed PageList::AddPageList (missed the first)
1085 // Added the author/creator.. name to AllPagesBy...
1086 // display no pages if none matched.
1087 // Improved dba and file sortby().
1088 // Use &$request reference
1090 // Revision 1.59 2004/07/08 21:32:36 rurban
1091 // Prevent from more warnings, minor db and sort optimizations
1093 // Revision 1.58 2004/07/08 16:56:16 rurban
1094 // use the backendType abstraction
1096 // Revision 1.57 2004/07/05 12:57:54 rurban
1097 // add mysql timeout
1099 // Revision 1.56 2004/07/04 10:24:43 rurban
1100 // forgot the expressions
1102 // Revision 1.55 2004/07/03 16:51:06 rurban
1103 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1104 // added atomic mysql REPLACE for PearDB as in ADODB
1105 // fixed _lock_tables typo links => link
1106 // fixes unserialize ADODB bug in line 180
1108 // Revision 1.54 2004/06/29 08:52:24 rurban
1109 // Use ...version() $need_content argument in WikiDB also:
1110 // To reduce the memory footprint for larger sets of pagelists,
1111 // we don't cache the content (only true or false) and
1112 // we purge the pagedata (_cached_html) also.
1113 // _cached_html is only cached for the current pagename.
1114 // => Vastly improved page existance check, ACL check, ...
1116 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1118 // Revision 1.53 2004/06/27 10:26:03 rurban
1119 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1121 // Revision 1.52 2004/06/25 14:15:08 rurban
1122 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1124 // Revision 1.51 2004/05/12 10:49:55 rurban
1125 // require_once fix for those libs which are loaded before FileFinder and
1126 // its automatic include_path fix, and where require_once doesn't grok
1127 // dirname(__FILE__) != './lib'
1128 // upgrade fix with PearDB
1129 // navbar.tmpl: remove spaces for IE button alignment
1131 // Revision 1.50 2004/05/06 17:30:39 rurban
1132 // CategoryGroup: oops, dos2unix eol
1133 // improved phpwiki_version:
1134 // pre -= .0001 (1.3.10pre: 1030.099)
1135 // -p1 += .001 (1.3.9-p1: 1030.091)
1136 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1137 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1138 // backend->backendType(), backend->database(),
1139 // backend->listOfFields(),
1140 // backend->listOfTables(),
1142 // Revision 1.49 2004/05/03 21:35:30 rurban
1143 // don't use persistent connections with postgres
1145 // Revision 1.48 2004/04/26 20:44:35 rurban
1146 // locking table specific for better databases
1148 // Revision 1.47 2004/04/20 00:06:04 rurban
1149 // themable paging support
1151 // Revision 1.46 2004/04/19 21:51:41 rurban
1152 // php5 compatibility: it works!
1154 // Revision 1.45 2004/04/16 14:19:39 rurban
1155 // updated ADODB notes
1158 // (c-file-style: "gnu")
1162 // c-basic-offset: 4
1163 // c-hanging-comment-ender-p: nil
1164 // indent-tabs-mode: nil