2 rcs_id('$Id: PearDB.php,v 1.66 2004-11-10 15:29:21 rurban Exp $');
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 require_once('lib/ErrorManager.php');
7 require_once('DB.php'); // Either our local pear copy or the systems
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.
20 //TODO: check the Pear_DB version
23 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
24 $this->_pearerrhandler = true;
27 // Open connection to database
28 $this->_dsn = $dbparams['dsn'];
29 $this->_dbparams = $dbparams;
30 $dboptions = array('persistent' => true,
32 if (preg_match('/^pgsql/',$this->_dsn))
33 $dboptions['persistent'] = false;
34 $this->_dbh = DB::connect($this->_dsn, $dboptions);
36 if (DB::isError($dbh)) {
37 trigger_error(sprintf("Can't connect to database: %s",
38 $this->_pear_error_message($dbh)),
41 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
42 array($this, '_pear_error_callback'));
43 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
45 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
47 = array('page_tbl' => $prefix . 'page',
48 'version_tbl' => $prefix . 'version',
49 'link_tbl' => $prefix . 'link',
50 'recent_tbl' => $prefix . 'recent',
51 'nonempty_tbl' => $prefix . 'nonempty');
52 $page_tbl = $this->_table_names['page_tbl'];
53 $version_tbl = $this->_table_names['version_tbl'];
54 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
55 $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, ".
56 "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
59 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
60 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
61 'maxversion' => "MAX(version)",
63 'iscontent' => "content<>''");
65 $this->_lock_count = 0;
69 * Close database connection.
74 if ($this->_lock_count) {
75 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
78 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
79 $this->unlock('force');
81 $this->_dbh->disconnect();
83 if (!empty($this->_pearerrhandler)) {
84 $GLOBALS['ErrorManager']->popErrorHandler();
92 function is_wiki_page($pagename) {
94 extract($this->_table_names);
95 return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
96 . " FROM $nonempty_tbl, $page_tbl"
97 . " WHERE $nonempty_tbl.id=$page_tbl.id"
98 . " AND pagename='%s'",
99 $dbh->escapeSimple($pagename)));
102 function get_all_pagenames() {
104 extract($this->_table_names);
105 return $dbh->getCol("SELECT pagename"
106 . " FROM $nonempty_tbl, $page_tbl"
107 . " WHERE $nonempty_tbl.id=$page_tbl.id");
110 function numPages($filter=false, $exclude='') {
112 extract($this->_table_names);
113 return $dbh->getOne("SELECT count(*)"
114 . " FROM $nonempty_tbl, $page_tbl"
115 . " WHERE $nonempty_tbl.id=$page_tbl.id");
119 * Read page information from database.
121 function get_pagedata($pagename) {
123 $page_tbl = $this->_table_names['page_tbl'];
125 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
127 $result = $dbh->getRow(sprintf("SELECT %s FROM $page_tbl WHERE pagename='%s'",
128 $this->page_tbl_fields.",pagedata",
129 $dbh->escapeSimple($pagename)),
133 return $this->_extract_page_data($result);
136 function _extract_page_data($query_result) {
137 extract($query_result);
138 if (isset($query_result['pagedata'])) {
139 $data = $this->_unserialize($query_result['pagedata']);
140 // Memory optimization:
141 // Only store the cached_html for the current pagename
142 // Do it here or unset it in the Cache?
144 $data['hits'] = $query_result['hits'];
148 function update_pagedata($pagename, $newdata) {
150 $page_tbl = $this->_table_names['page_tbl'];
152 // Hits is the only thing we can update in a fast manner.
153 if (count($newdata) == 1 && isset($newdata['hits'])) {
154 // Note that this will fail silently if the page does not
155 // have a record in the page table. Since it's just the
156 // hit count, who cares?
157 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
158 $newdata['hits'], $dbh->escapeSimple($pagename)));
162 $this->lock(array($page_tbl), true);
163 $data = $this->get_pagedata($pagename);
166 $this->_get_pageid($pagename, true); // Creates page record
169 @$hits = (int)$data['hits'];
170 unset($data['hits']);
172 foreach ($newdata as $key => $val) {
175 else if (empty($val))
181 /* Portability issue -- not all DBMS supports huge strings
182 * so we need to 'bind' instead of building a SQL statment.
183 * Note that we do not need to escapeSimple when we bind
184 $dbh->query(sprintf("UPDATE $page_tbl"
185 . " SET hits=%d, pagedata='%s'"
186 . " WHERE pagename='%s'",
188 $dbh->escapeSimple($this->_serialize($data)),
189 $dbh->escapeSimple($pagename)));
191 $sth = $dbh->query("UPDATE $page_tbl"
192 . " SET hits=?, pagedata=?"
193 . " WHERE pagename=?",
194 array($hits, $this->_serialize($data), $pagename));
195 $this->unlock(array($page_tbl));
198 function _get_pageid($pagename, $create_if_missing = false) {
202 $cache =& $request->_dbi->_cache->_id_cache;
203 if (isset($cache[$pagename])) return $cache[$pagename];
206 $page_tbl = $this->_table_names['page_tbl'];
208 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
209 $dbh->escapeSimple($pagename));
211 if (!$create_if_missing)
212 return $dbh->getOne($query);
214 $id = $dbh->getOne($query);
216 $this->lock(array($page_tbl), true); // write lock
217 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
219 $dbh->query(sprintf("INSERT INTO $page_tbl"
220 . " (id,pagename,hits)"
221 . " VALUES (%d,'%s',0)",
222 $id, $dbh->escapeSimple($pagename)));
223 $this->unlock(array($page_tbl));
228 function get_latest_version($pagename) {
230 extract($this->_table_names);
232 (int)$dbh->getOne(sprintf("SELECT latestversion"
233 . " FROM $page_tbl, $recent_tbl"
234 . " WHERE $page_tbl.id=$recent_tbl.id"
235 . " AND pagename='%s'",
236 $dbh->escapeSimple($pagename)));
239 function get_previous_version($pagename, $version) {
241 extract($this->_table_names);
244 (int)$dbh->getOne(sprintf("SELECT version"
245 . " FROM $version_tbl, $page_tbl"
246 . " WHERE $version_tbl.id=$page_tbl.id"
247 . " AND pagename='%s'"
248 . " AND version < %d"
249 . " ORDER BY version DESC",
250 /* Non portable and useless anyway with getOne
253 $dbh->escapeSimple($pagename),
260 * @param $version int Which version to get.
262 * @return hash The version data, or false if specified version does not
265 function get_versiondata($pagename, $version, $want_content = false) {
267 extract($this->_table_names);
268 extract($this->_expressions);
270 assert(is_string($pagename) and $pagename != "");
271 assert($version > 0);
273 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
274 // FIXME: optimization: sometimes don't get page data?
276 $fields = $this->page_tbl_fields . ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
279 $fields = $this->page_tbl_fields . ","
280 . "mtime, minor_edit, versiondata,"
281 . "$iscontent AS have_content";
284 $result = $dbh->getRow(sprintf("SELECT $fields"
285 . " FROM $page_tbl, $version_tbl"
286 . " WHERE $page_tbl.id=$version_tbl.id"
287 . " AND pagename='%s'"
289 $dbh->escapeSimple($pagename), $version),
292 return $this->_extract_version_data($result);
295 function _extract_version_data($query_result) {
299 extract($query_result);
300 $data = $this->_unserialize($versiondata);
302 $data['mtime'] = $mtime;
303 $data['is_minor_edit'] = !empty($minor_edit);
306 $data['%content'] = $content;
307 elseif ($have_content)
308 $data['%content'] = true;
310 $data['%content'] = '';
312 // FIXME: this is ugly.
313 if (isset($pagename)) {
314 // Query also includes page data.
315 // We might as well send that back too...
316 $data['%pagedata'] = $this->_extract_page_data($query_result);
324 * Create a new revision of a page.
326 function set_versiondata($pagename, $version, $data) {
328 $version_tbl = $this->_table_names['version_tbl'];
330 $minor_edit = (int) !empty($data['is_minor_edit']);
331 unset($data['is_minor_edit']);
333 $mtime = (int)$data['mtime'];
334 unset($data['mtime']);
335 assert(!empty($mtime));
337 @$content = (string) $data['%content'];
338 unset($data['%content']);
340 unset($data['%pagedata']);
343 $id = $this->_get_pageid($pagename, true);
345 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
346 $dbh->query(sprintf("DELETE FROM $version_tbl"
347 . " WHERE id=%d AND version=%d",
350 /* mysql optimized version.
351 $dbh->query(sprintf("INSERT INTO $version_tbl"
352 . " (id,version,mtime,minor_edit,content,versiondata)"
353 . " VALUES(%d,%d,%d,%d,'%s','%s')",
354 $id, $version, $mtime, $minor_edit,
355 $dbh->quoteSmart($content),
356 $dbh->quoteSmart($this->_serialize($data))));
358 // generic slow PearDB bind eh quoting.
359 $dbh->query("INSERT INTO $version_tbl"
360 . " (id,version,mtime,minor_edit,content,versiondata)"
361 . " VALUES(?, ?, ?, ?, ?, ?)",
362 array($id, $version, $mtime, $minor_edit, $content,
363 $this->_serialize($data)));
365 $this->_update_recent_table($id);
366 $this->_update_nonempty_table($id);
372 * Delete an old revision of a page.
374 function delete_versiondata($pagename, $version) {
376 extract($this->_table_names);
379 if ( ($id = $this->_get_pageid($pagename)) ) {
380 $dbh->query("DELETE FROM $version_tbl"
381 . " WHERE id=$id AND version=$version");
382 $this->_update_recent_table($id);
383 // This shouldn't be needed (as long as the latestversion
384 // never gets deleted.) But, let's be safe.
385 $this->_update_nonempty_table($id);
391 * Delete page completely from the database.
392 * I'm not sure if this is what we want. Maybe just delete the revisions
394 function delete_page($pagename) {
396 extract($this->_table_names);
399 if ( ($id = $this->_get_pageid($pagename, false)) ) {
400 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
401 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
402 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
403 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
404 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
406 // We're still in the link table (dangling link) so we can't delete this
408 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
411 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
413 $this->_update_recent_table();
414 $this->_update_nonempty_table();
420 // The only thing we might be interested in updating which we can
421 // do fast in the flags (minor_edit). I think the default
422 // update_versiondata will work fine...
423 //function update_versiondata($pagename, $version, $data) {
426 function set_links($pagename, $links) {
427 // Update link table.
428 // FIXME: optimize: mysql can do this all in one big INSERT.
431 extract($this->_table_names);
434 $pageid = $this->_get_pageid($pagename, true);
436 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
439 foreach($links as $link) {
440 if (isset($linkseen[$link]))
442 $linkseen[$link] = true;
443 $linkid = $this->_get_pageid($link, true);
444 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
445 . " VALUES ($pageid, $linkid)");
452 * Find pages which link to or are linked from a page.
454 function get_links($pagename, $reversed=true, $include_empty=false) {
456 extract($this->_table_names);
459 list($have,$want) = array('linkee', 'linker');
461 list($have,$want) = array('linker', 'linkee');
463 $qpagename = $dbh->escapeSimple($pagename);
464 $result = $dbh->query("SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
465 // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
466 // and the PostgresSQL manual does not have it either
467 // Since it is optional in mySQL, just remove it...
468 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
469 . (!$include_empty ? ", $nonempty_tbl" : '')
470 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
471 . " AND $have.pagename='$qpagename'"
472 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
473 //. " GROUP BY $want.id"
474 . " ORDER BY $want.pagename");
476 return new WikiDB_backend_PearDB_iter($this, $result);
479 function get_all_pages($include_empty=false, $sortby=false, $limit=false) {
481 extract($this->_table_names);
482 // Limit clause is NOT portable!
483 // if ($limit) $limit = "LIMIT $limit";
485 $orderby = $this->sortby($sortby, 'db');
486 if ($orderby) $orderby = 'ORDER BY ' . $orderby;
487 if (strstr($orderby, 'mtime ')) { // multiple columns possible
488 if ($include_empty) {
490 . $this->page_tbl_fields
491 . " FROM $page_tbl, $recent_tbl, $version_tbl"
492 . " WHERE $page_tbl.id=$recent_tbl.id"
493 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
498 . $this->page_tbl_fields
499 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
500 . " WHERE $nonempty_tbl.id=$page_tbl.id"
501 . " AND $page_tbl.id=$recent_tbl.id"
502 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
506 if ($include_empty) {
508 . $this->page_tbl_fields
509 ." FROM $page_tbl $orderby";
513 . $this->page_tbl_fields
514 . " FROM $nonempty_tbl, $page_tbl"
515 . " WHERE $nonempty_tbl.id=$page_tbl.id"
520 // extract from,count from limit
521 list($from,$count) = $this->limit($limit);
522 $result = $dbh->limitQuery($sql, $from, $count);
524 $result = $dbh->query($sql);
526 return new WikiDB_backend_PearDB_iter($this, $result);
532 function text_search($search = '', $fullsearch = false) {
534 extract($this->_table_names);
536 $table = "$nonempty_tbl, $page_tbl";
537 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
538 $fields = $this->page_tbl_fields;
539 $callback = new WikiMethodCb($this, '_sql_match_clause');
542 $table .= ", $recent_tbl";
543 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
545 $table .= ", $version_tbl";
546 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
548 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
549 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
552 $search_clause = $search->makeSqlClause($callback);
554 $result = $dbh->query("SELECT $fields FROM $table"
555 . " WHERE $join_clause"
556 . " AND ($search_clause)"
557 . " ORDER BY pagename");
559 return new WikiDB_backend_PearDB_iter($this, $result);
562 //Todo: check if the better Mysql MATCH operator is supported,
563 // (ranked search) and also google like expressions.
564 function _sql_match_clause($word) {
565 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
566 $word = $this->_dbh->escapeSimple($word);
567 //$page_tbl = $this->_table_names['page_tbl'];
568 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
569 // e.g. if word is lowercased.
570 // http://bugs.mysql.com/bug.php?id=1491
571 return "LOWER(pagename) LIKE '%$word%'";
574 function _fullsearch_sql_match_clause($word) {
575 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
576 $word = $this->_dbh->escapeSimple($word);
577 //$page_tbl = $this->_table_names['page_tbl'];
578 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
579 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
583 * Find highest or lowest hit counts.
585 function most_popular($limit=0, $sortby='-hits') {
587 extract($this->_table_names);
593 $order = "hits DESC";
594 $where = " AND hits > 0";
597 if ($sortby != '-hits') {
598 if ($order = $this->sortby($sortby, 'db'))
599 $orderby = " ORDER BY " . $order;
601 $orderby = " ORDER BY $order";
603 //$limitclause = $limit ? " LIMIT $limit" : '';
605 . $this->page_tbl_fields
606 . " FROM $nonempty_tbl, $page_tbl"
607 . " WHERE $nonempty_tbl.id=$page_tbl.id"
611 list($from, $count) = $this->limit($limit);
612 $result = $dbh->limitQuery($sql, $from, $count);
614 $result = $dbh->query($sql);
617 return new WikiDB_backend_PearDB_iter($this, $result);
621 * Find recent changes.
623 function most_recent($params) {
626 $include_minor_revisions = false;
627 $exclude_major_revisions = false;
628 $include_all_revisions = false;
632 extract($this->_table_names);
636 $pick[] = "mtime >= $since";
639 if ($include_all_revisions) {
640 // Include all revisions of each page.
641 $table = "$page_tbl, $version_tbl";
642 $join_clause = "$page_tbl.id=$version_tbl.id";
644 if ($exclude_major_revisions) {
645 // Include only minor revisions
646 $pick[] = "minor_edit <> 0";
648 elseif (!$include_minor_revisions) {
649 // Include only major revisions
650 $pick[] = "minor_edit = 0";
654 $table = "$page_tbl, $recent_tbl";
655 $join_clause = "$page_tbl.id=$recent_tbl.id";
656 $table .= ", $version_tbl";
657 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
659 if ($exclude_major_revisions) {
660 // Include only most recent minor revision
661 $pick[] = 'version=latestminor';
663 elseif (!$include_minor_revisions) {
664 // Include only most recent major revision
665 $pick[] = 'version=latestmajor';
668 // Include only the latest revision (whether major or minor).
669 $pick[] ='version=latestversion';
677 // $limitclause = $limit ? " LIMIT $limit" : '';
678 $where_clause = $join_clause;
680 $where_clause .= " AND " . join(" AND ", $pick);
682 // FIXME: use SQL_BUFFER_RESULT for mysql?
684 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
686 . " WHERE $where_clause"
687 . " ORDER BY mtime $order";
690 $result = $dbh->limitQuery($sql, 0, $limit);
692 $result = $dbh->query($sql);
695 return new WikiDB_backend_PearDB_iter($this, $result);
699 * Rename page in the database.
701 function rename_page($pagename, $to) {
703 extract($this->_table_names);
706 if ( ($id = $this->_get_pageid($pagename, false)) ) {
707 if ($new = $this->_get_pageid($to, false)) {
709 //this page does not exist (already verified before), but exists in the page table.
710 //so we delete this page.
711 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
713 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
714 $dbh->escapeSimple($to)));
720 function _update_recent_table($pageid = false) {
722 extract($this->_table_names);
723 extract($this->_expressions);
725 $pageid = (int)$pageid;
728 $dbh->query("DELETE FROM $recent_tbl"
729 . ( $pageid ? " WHERE id=$pageid" : ""));
730 $dbh->query( "INSERT INTO $recent_tbl"
731 . " (id, latestversion, latestmajor, latestminor)"
732 . " SELECT id, $maxversion, $maxmajor, $maxminor"
733 . " FROM $version_tbl"
734 . ( $pageid ? " WHERE id=$pageid" : "")
739 function _update_nonempty_table($pageid = false) {
741 extract($this->_table_names);
743 $pageid = (int)$pageid;
745 extract($this->_expressions);
747 $dbh->query("DELETE FROM $nonempty_tbl"
748 . ( $pageid ? " WHERE id=$pageid" : ""));
749 $dbh->query("INSERT INTO $nonempty_tbl (id)"
750 . " SELECT $recent_tbl.id"
751 . " FROM $recent_tbl, $version_tbl"
752 . " WHERE $recent_tbl.id=$version_tbl.id"
753 . " AND version=latestversion"
754 // We have some specifics here (Oracle)
755 //. " AND content<>''"
756 . " AND content $notempty"
757 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
764 * Grab a write lock on the tables in the SQL database.
766 * Calls can be nested. The tables won't be unlocked until
767 * _unlock_database() is called as many times as _lock_database().
771 function lock($tables = false, $write_lock = true) {
772 if ($this->_lock_count++ == 0)
773 $this->_lock_tables($write_lock);
777 * Actually lock the required tables.
779 function _lock_tables($write_lock) {
780 trigger_error("virtual", E_USER_ERROR);
784 * Release a write lock on the tables in the SQL database.
788 * @param $force boolean Unlock even if not every call to lock() has been matched
789 * by a call to unlock().
791 * @see _lock_database
793 function unlock($tables = false, $force = false) {
794 if ($this->_lock_count == 0)
796 if (--$this->_lock_count <= 0 || $force) {
797 $this->_unlock_tables();
798 $this->_lock_count = 0;
803 * Actually unlock the required tables.
805 function _unlock_tables($write_lock) {
806 trigger_error("virtual", E_USER_ERROR);
813 function _serialize($data) {
816 assert(is_array($data));
817 return serialize($data);
823 function _unserialize($data) {
824 return empty($data) ? array() : unserialize($data);
828 * Callback for PEAR (DB) errors.
832 * @param A PEAR_error object.
834 function _pear_error_callback($error) {
835 if ($this->_is_false_error($error))
838 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
840 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
844 * Detect false errors messages from PEAR DB.
846 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
847 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
848 * return any data. (So when a "LOCK" command doesn't return any data,
849 * DB reports it as an error, when in fact, it's not.)
852 * @return bool True iff error is not really an error.
854 function _is_false_error($error) {
855 if ($error->getCode() != DB_ERROR)
858 $query = $this->_dbh->last_query;
860 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
861 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
862 // Last query was not of the sort which doesn't return any data.
863 //" <--kludge for brain-dead syntax coloring
867 if (! in_array('ismanip', get_class_methods('DB'))) {
868 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
869 // does not have the DB::isManip method.
873 if (DB::isManip($query)) {
874 // If Pear thinks it's an isManip then it wouldn't have thrown
875 // the error we're testing for....
882 function _pear_error_message($error) {
883 $class = get_class($this);
884 $message = "$class: fatal database error\n"
885 . "\t" . $error->getMessage() . "\n"
886 . "\t(" . $error->getDebugInfo() . ")\n";
888 // Prevent password from being exposed during a connection error
889 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
890 '\\1:XXXXXXXX', $this->_dsn);
891 return str_replace($this->_dsn, $safe_dsn, $message);
895 * Filter PHP errors notices from PEAR DB code.
897 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
898 * errors and notices. This is an error callback (for use with
899 * ErrorManager which will filter out those spurious messages.)
900 * @see _is_false_error, ErrorManager
903 function _pear_notice_filter($err) {
904 return ( $err->isNotice()
905 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
906 && $err->errline == 126
907 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
910 /* some variables and functions for DB backend abstraction (action=upgrade) */
911 function database () {
912 return $this->_dbh->dsn['database'];
914 function backendType() {
915 return $this->_dbh->phptype;
917 function connection() {
918 return $this->_dbh->connection;
921 function listOfTables() {
922 return $this->_dbh->getListOf('tables');
924 function listOfFields($database,$table) {
925 if ($this->backendType() == 'mysql') {
927 assert(!empty($database));
928 assert(!empty($table));
929 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
930 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
931 if (!$result) return array();
932 $columns = mysql_num_fields($result);
933 for ($i = 0; $i < $columns; $i++) {
934 $fields[] = mysql_field_name($result, $i);
936 mysql_free_result($result);
939 // TODO: try ADODB version?
940 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
947 * This class is a generic iterator.
949 * WikiDB_backend_PearDB_iter only iterates over things that have
950 * 'pagename', 'pagedata', etc. etc.
952 * Probably WikiDB_backend_PearDB_iter and this class should be merged
953 * (most of the code is cut-and-paste :-( ), but I am trying to make
954 * changes that could be merged easily.
956 * @author: Dan Frankowski
958 class WikiDB_backend_PearDB_generic_iter
959 extends WikiDB_backend_iterator
961 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
962 if (DB::isError($query_result)) {
963 // This shouldn't happen, I thought.
964 $backend->_pear_error_callback($query_result);
967 $this->_backend = &$backend;
968 $this->_result = $query_result;
974 return $this->_result->numRows();
978 $backend = &$this->_backend;
982 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
992 if ($this->_result) {
993 $this->_result->free();
994 $this->_result = false;
999 class WikiDB_backend_PearDB_iter
1000 extends WikiDB_backend_PearDB_generic_iter
1004 $backend = &$this->_backend;
1005 if (!$this->_result)
1008 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1014 $pagedata = $backend->_extract_page_data($record);
1015 $rec = array('pagename' => $record['pagename'],
1016 'pagedata' => $pagedata);
1018 if (!empty($record['version'])) {
1019 $rec['versiondata'] = $backend->_extract_version_data($record);
1020 $rec['version'] = $record['version'];
1027 // $Log: not supported by cvs2svn $
1028 // Revision 1.65 2004/11/09 17:11:17 rurban
1029 // * revert to the wikidb ref passing. there's no memory abuse there.
1030 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1031 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1032 // are also needed at the rendering for linkExistingWikiWord().
1033 // pass options to pageiterator.
1034 // use this cache also for _get_pageid()
1035 // This saves about 8 SELECT count per page (num all pagelinks).
1036 // * fix passing of all page fields to the pageiterator.
1037 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1039 // Revision 1.64 2004/11/07 16:02:52 rurban
1040 // new sql access log (for spam prevention), and restructured access log class
1041 // dbh->quote (generic)
1042 // pear_db: mysql specific parts seperated (using replace)
1044 // Revision 1.63 2004/11/01 10:43:58 rurban
1045 // seperate PassUser methods into seperate dir (memory usage)
1046 // fix WikiUser (old) overlarge data session
1047 // remove wikidb arg from various page class methods, use global ->_dbi instead
1050 // Revision 1.62 2004/10/14 19:19:34 rurban
1051 // loadsave: check if the dumped file will be accessible from outside.
1052 // and some other minor fixes. (cvsclient native not yet ready)
1054 // Revision 1.61 2004/10/14 17:19:17 rurban
1055 // allow most_popular sortby arguments
1057 // Revision 1.60 2004/07/09 10:06:50 rurban
1058 // Use backend specific sortby and sortable_columns method, to be able to
1059 // select between native (Db backend) and custom (PageList) sorting.
1060 // Fixed PageList::AddPageList (missed the first)
1061 // Added the author/creator.. name to AllPagesBy...
1062 // display no pages if none matched.
1063 // Improved dba and file sortby().
1064 // Use &$request reference
1066 // Revision 1.59 2004/07/08 21:32:36 rurban
1067 // Prevent from more warnings, minor db and sort optimizations
1069 // Revision 1.58 2004/07/08 16:56:16 rurban
1070 // use the backendType abstraction
1072 // Revision 1.57 2004/07/05 12:57:54 rurban
1073 // add mysql timeout
1075 // Revision 1.56 2004/07/04 10:24:43 rurban
1076 // forgot the expressions
1078 // Revision 1.55 2004/07/03 16:51:06 rurban
1079 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1080 // added atomic mysql REPLACE for PearDB as in ADODB
1081 // fixed _lock_tables typo links => link
1082 // fixes unserialize ADODB bug in line 180
1084 // Revision 1.54 2004/06/29 08:52:24 rurban
1085 // Use ...version() $need_content argument in WikiDB also:
1086 // To reduce the memory footprint for larger sets of pagelists,
1087 // we don't cache the content (only true or false) and
1088 // we purge the pagedata (_cached_html) also.
1089 // _cached_html is only cached for the current pagename.
1090 // => Vastly improved page existance check, ACL check, ...
1092 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1094 // Revision 1.53 2004/06/27 10:26:03 rurban
1095 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1097 // Revision 1.52 2004/06/25 14:15:08 rurban
1098 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1100 // Revision 1.51 2004/05/12 10:49:55 rurban
1101 // require_once fix for those libs which are loaded before FileFinder and
1102 // its automatic include_path fix, and where require_once doesn't grok
1103 // dirname(__FILE__) != './lib'
1104 // upgrade fix with PearDB
1105 // navbar.tmpl: remove spaces for IE button alignment
1107 // Revision 1.50 2004/05/06 17:30:39 rurban
1108 // CategoryGroup: oops, dos2unix eol
1109 // improved phpwiki_version:
1110 // pre -= .0001 (1.3.10pre: 1030.099)
1111 // -p1 += .001 (1.3.9-p1: 1030.091)
1112 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1113 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1114 // backend->backendType(), backend->database(),
1115 // backend->listOfFields(),
1116 // backend->listOfTables(),
1118 // Revision 1.49 2004/05/03 21:35:30 rurban
1119 // don't use persistent connections with postgres
1121 // Revision 1.48 2004/04/26 20:44:35 rurban
1122 // locking table specific for better databases
1124 // Revision 1.47 2004/04/20 00:06:04 rurban
1125 // themable paging support
1127 // Revision 1.46 2004/04/19 21:51:41 rurban
1128 // php5 compatibility: it works!
1130 // Revision 1.45 2004/04/16 14:19:39 rurban
1131 // updated ADODB notes
1134 // (c-file-style: "gnu")
1138 // c-basic-offset: 4
1139 // c-hanging-comment-ender-p: nil
1140 // indent-tabs-mode: nil