2 rcs_id('$Id: PearDB.php,v 1.73 2004-11-26 18:39:02 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. maybe we should force our private version again...
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
294 . ",$page_tbl.pagedata as pagedata,"
295 . $this->version_tbl_fields;
298 $fields = $this->page_tbl_fields . ","
299 . "mtime, minor_edit, versiondata,"
300 . "$iscontent AS have_content";
303 $result = $dbh->getRow(sprintf("SELECT $fields"
304 . " FROM $page_tbl, $version_tbl"
305 . " WHERE $page_tbl.id=$version_tbl.id"
306 . " AND pagename='%s'"
308 $dbh->escapeSimple($pagename), $version),
311 return $this->_extract_version_data($result);
314 function _extract_version_data($query_result) {
318 extract($query_result);
319 $data = $this->_unserialize($versiondata);
321 $data['mtime'] = $mtime;
322 $data['is_minor_edit'] = !empty($minor_edit);
325 $data['%content'] = $content;
326 elseif ($have_content)
327 $data['%content'] = true;
329 $data['%content'] = '';
331 // FIXME: this is ugly.
332 if (isset($pagename)) {
333 // Query also includes page data.
334 // We might as well send that back too...
335 $data['%pagedata'] = $this->_extract_page_data($query_result);
343 * Create a new revision of a page.
345 function set_versiondata($pagename, $version, $data) {
347 $version_tbl = $this->_table_names['version_tbl'];
349 $minor_edit = (int) !empty($data['is_minor_edit']);
350 unset($data['is_minor_edit']);
352 $mtime = (int)$data['mtime'];
353 unset($data['mtime']);
354 assert(!empty($mtime));
356 @$content = (string) $data['%content'];
357 unset($data['%content']);
359 unset($data['%pagedata']);
362 $id = $this->_get_pageid($pagename, true);
364 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
365 $dbh->query(sprintf("DELETE FROM $version_tbl"
366 . " WHERE id=%d AND version=%d",
369 /* mysql optimized version.
370 $dbh->query(sprintf("INSERT INTO $version_tbl"
371 . " (id,version,mtime,minor_edit,content,versiondata)"
372 . " VALUES(%d,%d,%d,%d,'%s','%s')",
373 $id, $version, $mtime, $minor_edit,
374 $dbh->quoteSmart($content),
375 $dbh->quoteSmart($this->_serialize($data))));
377 // generic slow PearDB bind eh quoting.
378 $dbh->query("INSERT INTO $version_tbl"
379 . " (id,version,mtime,minor_edit,content,versiondata)"
380 . " VALUES(?, ?, ?, ?, ?, ?)",
381 array($id, $version, $mtime, $minor_edit, $content,
382 $this->_serialize($data)));
384 $this->_update_recent_table($id);
385 $this->_update_nonempty_table($id);
391 * Delete an old revision of a page.
393 function delete_versiondata($pagename, $version) {
395 extract($this->_table_names);
398 if ( ($id = $this->_get_pageid($pagename)) ) {
399 $dbh->query("DELETE FROM $version_tbl"
400 . " WHERE id=$id AND version=$version");
401 $this->_update_recent_table($id);
402 // This shouldn't be needed (as long as the latestversion
403 // never gets deleted.) But, let's be safe.
404 $this->_update_nonempty_table($id);
410 * Delete page completely from the database.
411 * I'm not sure if this is what we want. Maybe just delete the revisions
413 function delete_page($pagename) {
415 extract($this->_table_names);
418 if ( ($id = $this->_get_pageid($pagename, false)) ) {
419 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
420 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
421 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
422 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
423 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
425 // We're still in the link table (dangling link) so we can't delete this
427 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
430 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
432 $this->_update_recent_table();
433 $this->_update_nonempty_table();
439 // The only thing we might be interested in updating which we can
440 // do fast in the flags (minor_edit). I think the default
441 // update_versiondata will work fine...
442 //function update_versiondata($pagename, $version, $data) {
445 function set_links($pagename, $links) {
446 // Update link table.
447 // FIXME: optimize: mysql can do this all in one big INSERT.
450 extract($this->_table_names);
453 $pageid = $this->_get_pageid($pagename, true);
455 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
458 foreach($links as $link) {
459 if (isset($linkseen[$link]))
461 $linkseen[$link] = true;
462 $linkid = $this->_get_pageid($link, true);
463 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
464 . " VALUES ($pageid, $linkid)");
471 * Find pages which link to or are linked from a page.
473 function get_links($pagename, $reversed=true, $include_empty=false,
474 $sortby=false, $limit=false, $exclude='') {
476 extract($this->_table_names);
479 list($have,$want) = array('linkee', 'linker');
481 list($have,$want) = array('linker', 'linkee');
482 $orderby = $this->sortby($sortby, 'db', array('pagename'));
483 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
484 if ($exclude) // array of pagenames
485 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
489 $qpagename = $dbh->escapeSimple($pagename);
490 $sql = "SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
491 // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
492 // and the PostgresSQL manual does not have it either
493 // Since it is optional in mySQL, just remove it...
494 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
495 . (!$include_empty ? ", $nonempty_tbl" : '')
496 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
497 . " AND $have.pagename='$qpagename'"
498 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
499 //. " GROUP BY $want.id"
503 // extract from,count from limit
504 list($from,$count) = $this->limit($limit);
505 $result = $dbh->limitQuery($sql, $from, $count);
507 $result = $dbh->query($sql);
510 return new WikiDB_backend_PearDB_iter($this, $result);
513 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
515 extract($this->_table_names);
516 $orderby = $this->sortby($sortby, 'db');
517 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
518 if ($exclude) // array of pagenames
519 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
523 if (strstr($orderby, 'mtime ')) { // multiple columns possible
524 if ($include_empty) {
526 . $this->page_tbl_fields
527 . " FROM $page_tbl, $recent_tbl, $version_tbl"
528 . " WHERE $page_tbl.id=$recent_tbl.id"
529 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
535 . $this->page_tbl_fields
536 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
537 . " WHERE $nonempty_tbl.id=$page_tbl.id"
538 . " AND $page_tbl.id=$recent_tbl.id"
539 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
544 if ($include_empty) {
546 . $this->page_tbl_fields
548 . $exclude ? " WHERE $exclude" : ''
553 . $this->page_tbl_fields
554 . " FROM $nonempty_tbl, $page_tbl"
555 . " WHERE $nonempty_tbl.id=$page_tbl.id"
561 // extract from,count from limit
562 list($from,$count) = $this->limit($limit);
563 $result = $dbh->limitQuery($sql, $from, $count);
565 $result = $dbh->query($sql);
567 return new WikiDB_backend_PearDB_iter($this, $result);
573 function text_search($search, $fulltext=false) {
575 extract($this->_table_names);
577 $searchclass = get_class($this)."_search";
578 if (!class_exists($searchclass)) // no need to define it everywhere and then fallback. memory
579 $searchclass = "WikiDB_backend_PearDB_search";
580 $searchobj = new $searchclass($search, $dbh);
582 $table = "$nonempty_tbl, $page_tbl";
583 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
584 $fields = $this->page_tbl_fields;
587 $table .= ", $recent_tbl";
588 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
590 $table .= ", $version_tbl";
591 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
593 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
594 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
596 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
598 $search_clause = $search->makeSqlClauseObj($callback);
600 $result = $dbh->query("SELECT $fields FROM $table"
601 . " WHERE $join_clause"
602 . " AND ($search_clause)"
603 . " ORDER BY pagename");
605 return new WikiDB_backend_PearDB_iter($this, $result);
608 //Todo: check if the better Mysql MATCH operator is supported,
609 // (ranked search) and also google like expressions.
610 function _sql_match_clause($word) {
611 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
612 $word = $this->_dbh->escapeSimple($word);
613 //$page_tbl = $this->_table_names['page_tbl'];
614 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
615 // e.g. if word is lowercased.
616 // http://bugs.mysql.com/bug.php?id=1491
617 return "LOWER(pagename) LIKE '%$word%'";
619 function _sql_casematch_clause($word) {
620 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
621 $word = $this->_dbh->escapeSimple($word);
622 return "pagename LIKE '%$word%'";
624 function _fullsearch_sql_match_clause($word) {
625 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
626 $word = $this->_dbh->escapeSimple($word);
627 //$page_tbl = $this->_table_names['page_tbl'];
628 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
629 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
631 function _fullsearch_sql_casematch_clause($word) {
632 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
633 $word = $this->_dbh->escapeSimple($word);
634 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
638 * Find highest or lowest hit counts.
640 function most_popular($limit=0, $sortby='-hits') {
642 extract($this->_table_names);
648 $order = "hits DESC";
649 $where = " AND hits > 0";
652 if ($sortby != '-hits') {
653 if ($order = $this->sortby($sortby, 'db'))
654 $orderby = " ORDER BY " . $order;
656 $orderby = " ORDER BY $order";
658 //$limitclause = $limit ? " LIMIT $limit" : '';
660 . $this->page_tbl_fields
661 . " FROM $nonempty_tbl, $page_tbl"
662 . " WHERE $nonempty_tbl.id=$page_tbl.id"
666 list($from, $count) = $this->limit($limit);
667 $result = $dbh->limitQuery($sql, $from, $count);
669 $result = $dbh->query($sql);
672 return new WikiDB_backend_PearDB_iter($this, $result);
676 * Find recent changes.
678 function most_recent($params) {
681 $include_minor_revisions = false;
682 $exclude_major_revisions = false;
683 $include_all_revisions = false;
687 extract($this->_table_names);
691 $pick[] = "mtime >= $since";
694 if ($include_all_revisions) {
695 // Include all revisions of each page.
696 $table = "$page_tbl, $version_tbl";
697 $join_clause = "$page_tbl.id=$version_tbl.id";
699 if ($exclude_major_revisions) {
700 // Include only minor revisions
701 $pick[] = "minor_edit <> 0";
703 elseif (!$include_minor_revisions) {
704 // Include only major revisions
705 $pick[] = "minor_edit = 0";
709 $table = "$page_tbl, $recent_tbl";
710 $join_clause = "$page_tbl.id=$recent_tbl.id";
711 $table .= ", $version_tbl";
712 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
714 if ($exclude_major_revisions) {
715 // Include only most recent minor revision
716 $pick[] = 'version=latestminor';
718 elseif (!$include_minor_revisions) {
719 // Include only most recent major revision
720 $pick[] = 'version=latestmajor';
723 // Include only the latest revision (whether major or minor).
724 $pick[] ='version=latestversion';
732 // $limitclause = $limit ? " LIMIT $limit" : '';
733 $where_clause = $join_clause;
735 $where_clause .= " AND " . join(" AND ", $pick);
737 // FIXME: use SQL_BUFFER_RESULT for mysql?
739 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
741 . " WHERE $where_clause"
742 . " ORDER BY mtime $order";
744 list($from, $count) = $this->limit($limit);
745 $result = $dbh->limitQuery($sql, $from, $count);
747 $result = $dbh->query($sql);
749 return new WikiDB_backend_PearDB_iter($this, $result);
753 * Find referenced empty pages.
755 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
757 extract($this->_table_names);
758 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
759 $orderby = 'ORDER BY ' . $orderby;
761 if ($exclude_from) // array of pagenames
762 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
763 if ($exclude) // array of pagenames
764 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
766 $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
767 . " FROM $link_tbl,$page_tbl as linked "
768 . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
769 . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)"
770 . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
775 list($from, $count) = $this->limit($limit);
776 $result = $dbh->limitQuery($sql, $from, $count * 3);
778 $result = $dbh->query($sql);
780 return new WikiDB_backend_PearDB_generic_iter($this, $result);
783 function _sql_set(&$pagenames) {
785 foreach ($pagenames as $p) {
786 $s .= ("'".$this->_dbh->escapeSimple($p)."',");
788 return substr($s,0,-1).")";
792 * Rename page in the database.
794 function rename_page($pagename, $to) {
796 extract($this->_table_names);
799 if ( ($id = $this->_get_pageid($pagename, false)) ) {
800 if ($new = $this->_get_pageid($to, false)) {
802 //this page does not exist (already verified before), but exists in the page table.
803 //so we delete this page.
804 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
806 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
807 $dbh->escapeSimple($to)));
813 function _update_recent_table($pageid = false) {
815 extract($this->_table_names);
816 extract($this->_expressions);
818 $pageid = (int)$pageid;
821 $dbh->query("DELETE FROM $recent_tbl"
822 . ( $pageid ? " WHERE id=$pageid" : ""));
823 $dbh->query( "INSERT INTO $recent_tbl"
824 . " (id, latestversion, latestmajor, latestminor)"
825 . " SELECT id, $maxversion, $maxmajor, $maxminor"
826 . " FROM $version_tbl"
827 . ( $pageid ? " WHERE id=$pageid" : "")
832 function _update_nonempty_table($pageid = false) {
834 extract($this->_table_names);
836 $pageid = (int)$pageid;
838 extract($this->_expressions);
840 $dbh->query("DELETE FROM $nonempty_tbl"
841 . ( $pageid ? " WHERE id=$pageid" : ""));
842 $dbh->query("INSERT INTO $nonempty_tbl (id)"
843 . " SELECT $recent_tbl.id"
844 . " FROM $recent_tbl, $version_tbl"
845 . " WHERE $recent_tbl.id=$version_tbl.id"
846 . " AND version=latestversion"
847 // We have some specifics here (Oracle)
848 //. " AND content<>''"
849 . " AND content $notempty"
850 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
857 * Grab a write lock on the tables in the SQL database.
859 * Calls can be nested. The tables won't be unlocked until
860 * _unlock_database() is called as many times as _lock_database().
864 function lock($tables = false, $write_lock = true) {
865 if ($this->_lock_count++ == 0)
866 $this->_lock_tables($write_lock);
870 * Actually lock the required tables.
872 function _lock_tables($write_lock) {
873 trigger_error("virtual", E_USER_ERROR);
877 * Release a write lock on the tables in the SQL database.
881 * @param $force boolean Unlock even if not every call to lock() has been matched
882 * by a call to unlock().
884 * @see _lock_database
886 function unlock($tables = false, $force = false) {
887 if ($this->_lock_count == 0)
889 if (--$this->_lock_count <= 0 || $force) {
890 $this->_unlock_tables();
891 $this->_lock_count = 0;
896 * Actually unlock the required tables.
898 function _unlock_tables($write_lock) {
899 trigger_error("virtual", E_USER_ERROR);
906 function _serialize($data) {
909 assert(is_array($data));
910 return serialize($data);
916 function _unserialize($data) {
917 return empty($data) ? array() : unserialize($data);
921 * Callback for PEAR (DB) errors.
925 * @param A PEAR_error object.
927 function _pear_error_callback($error) {
928 if ($this->_is_false_error($error))
931 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
933 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
937 * Detect false errors messages from PEAR DB.
939 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
940 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
941 * return any data. (So when a "LOCK" command doesn't return any data,
942 * DB reports it as an error, when in fact, it's not.)
945 * @return bool True iff error is not really an error.
947 function _is_false_error($error) {
948 if ($error->getCode() != DB_ERROR)
951 $query = $this->_dbh->last_query;
953 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
954 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
955 // Last query was not of the sort which doesn't return any data.
956 //" <--kludge for brain-dead syntax coloring
960 if (! in_array('ismanip', get_class_methods('DB'))) {
961 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
962 // does not have the DB::isManip method.
966 if (DB::isManip($query)) {
967 // If Pear thinks it's an isManip then it wouldn't have thrown
968 // the error we're testing for....
975 function _pear_error_message($error) {
976 $class = get_class($this);
977 $message = "$class: fatal database error\n"
978 . "\t" . $error->getMessage() . "\n"
979 . "\t(" . $error->getDebugInfo() . ")\n";
981 // Prevent password from being exposed during a connection error
982 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
983 '\\1:XXXXXXXX', $this->_dsn);
984 return str_replace($this->_dsn, $safe_dsn, $message);
988 * Filter PHP errors notices from PEAR DB code.
990 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
991 * errors and notices. This is an error callback (for use with
992 * ErrorManager which will filter out those spurious messages.)
993 * @see _is_false_error, ErrorManager
996 function _pear_notice_filter($err) {
997 return ( $err->isNotice()
998 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
999 && $err->errline == 126
1000 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1003 /* some variables and functions for DB backend abstraction (action=upgrade) */
1004 function database () {
1005 return $this->_dbh->dsn['database'];
1007 function backendType() {
1008 return $this->_dbh->phptype;
1010 function connection() {
1011 return $this->_dbh->connection;
1014 function listOfTables() {
1015 return $this->_dbh->getListOf('tables');
1017 function listOfFields($database,$table) {
1018 if ($this->backendType() == 'mysql') {
1020 assert(!empty($database));
1021 assert(!empty($table));
1022 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1023 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1024 if (!$result) return array();
1025 $columns = mysql_num_fields($result);
1026 for ($i = 0; $i < $columns; $i++) {
1027 $fields[] = mysql_field_name($result, $i);
1029 mysql_free_result($result);
1032 // TODO: try ADODB version?
1033 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1040 * This class is a generic iterator.
1042 * WikiDB_backend_PearDB_iter only iterates over things that have
1043 * 'pagename', 'pagedata', etc. etc.
1045 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1046 * (most of the code is cut-and-paste :-( ), but I am trying to make
1047 * changes that could be merged easily.
1049 * @author: Dan Frankowski
1051 class WikiDB_backend_PearDB_generic_iter
1052 extends WikiDB_backend_iterator
1054 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1055 if (DB::isError($query_result)) {
1056 // This shouldn't happen, I thought.
1057 $backend->_pear_error_callback($query_result);
1060 $this->_backend = &$backend;
1061 $this->_result = $query_result;
1065 if (!$this->_result)
1067 return $this->_result->numRows();
1071 $backend = &$this->_backend;
1072 if (!$this->_result)
1075 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1085 if ($this->_result) {
1086 $this->_result->free();
1087 $this->_result = false;
1092 class WikiDB_backend_PearDB_iter
1093 extends WikiDB_backend_PearDB_generic_iter
1097 $backend = &$this->_backend;
1098 if (!$this->_result)
1101 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1107 $pagedata = $backend->_extract_page_data($record);
1108 $rec = array('pagename' => $record['pagename'],
1109 'pagedata' => $pagedata);
1111 if (!empty($record['version'])) {
1112 $rec['versiondata'] = $backend->_extract_version_data($record);
1113 $rec['version'] = $record['version'];
1121 class WikiDB_backend_PearDB_search
1122 extends WikiDB_backend_search
1124 function WikiDB_backend_PearDB_search(&$search, &$dbh) {
1126 $this->_case_exact = $search->_case_exact;
1128 function _quote($word) {
1129 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
1130 return $this->_dbh->escapeSimple($this->_case_exact ? $word : strtolower($word));
1132 function EXACT($word) { return $this->_quote($word); }
1133 function STARTS_WITH($word) { return $this->_quote($word)."%"; }
1134 function ENDS_WITH($word) { return "%".$this->_quote($word); }
1135 function WORD($word) { return "%".$this->_quote($word)."%"; } // substring
1136 function REGEX($word) { // posix regex
1137 // we really must know if the backend supports posix REGEXP
1138 // or if it has to be converted to SQL matching. * => %, ? => _
1139 return $this->_dbh->escapeSimple($word);
1142 function _pagename_match_clause($node) {
1143 $method = $node->op;
1144 $word = $this->$method($node->word);
1145 if ($method == 'REGEX') { // posix regex extensions
1146 if (preg_match("/mysql/i", $this->_dbh->phptype))
1147 return "pagename REGEXP '$word'";
1148 elseif (preg_match("/pgsql/i", $this->_dbh->phptype))
1149 return $this->_case_exact ? "pagename ~* '$word'"
1150 : "pagename ~ '$word'";
1152 return $this->_case_exact ? "pagename LIKE '$word'"
1153 : "LOWER(pagename) LIKE '$word'";
1156 function _fulltext_match_clause($node) {
1157 $method = $node->op;
1158 $word = $this->WORD($node->word);
1159 return $this->_pagename_match_clause($node)
1160 // probably convert this MATCH AGAINST or SUBSTR/POSITION without wildcards
1161 . ($this->_case_exact ? " OR content LIKE '$word'"
1162 : " OR LOWER(content) LIKE '$word'");
1166 // $Log: not supported by cvs2svn $
1167 // Revision 1.72 2004/11/25 17:20:51 rurban
1168 // and again a couple of more native db args: backlinks
1170 // Revision 1.71 2004/11/23 13:35:48 rurban
1171 // add case_exact search
1173 // Revision 1.70 2004/11/21 11:59:26 rurban
1174 // remove final \n to be ob_cache independent
1176 // Revision 1.69 2004/11/20 17:49:39 rurban
1177 // add fast exclude support to SQL get_all_pages
1179 // Revision 1.68 2004/11/20 17:35:58 rurban
1180 // improved WantedPages SQL backends
1181 // PageList::sortby new 3rd arg valid_fields (override db fields)
1182 // WantedPages sql pager inexact for performance reasons:
1183 // assume 3 wantedfrom per page, to be correct, no getTotal()
1184 // support exclude argument for get_all_pages, new _sql_set()
1186 // Revision 1.67 2004/11/10 19:32:24 rurban
1187 // * optimize increaseHitCount, esp. for mysql.
1188 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1189 // * Pear_DB version logic (awful but needed)
1190 // * fix broken ADODB quote
1191 // * _extract_page_data simplification
1193 // Revision 1.66 2004/11/10 15:29:21 rurban
1194 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1195 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1196 // * WikiDB: moved SQL specific methods upwards
1197 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1198 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1200 // Revision 1.65 2004/11/09 17:11:17 rurban
1201 // * revert to the wikidb ref passing. there's no memory abuse there.
1202 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1203 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1204 // are also needed at the rendering for linkExistingWikiWord().
1205 // pass options to pageiterator.
1206 // use this cache also for _get_pageid()
1207 // This saves about 8 SELECT count per page (num all pagelinks).
1208 // * fix passing of all page fields to the pageiterator.
1209 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1211 // Revision 1.64 2004/11/07 16:02:52 rurban
1212 // new sql access log (for spam prevention), and restructured access log class
1213 // dbh->quote (generic)
1214 // pear_db: mysql specific parts seperated (using replace)
1216 // Revision 1.63 2004/11/01 10:43:58 rurban
1217 // seperate PassUser methods into seperate dir (memory usage)
1218 // fix WikiUser (old) overlarge data session
1219 // remove wikidb arg from various page class methods, use global ->_dbi instead
1222 // Revision 1.62 2004/10/14 19:19:34 rurban
1223 // loadsave: check if the dumped file will be accessible from outside.
1224 // and some other minor fixes. (cvsclient native not yet ready)
1226 // Revision 1.61 2004/10/14 17:19:17 rurban
1227 // allow most_popular sortby arguments
1229 // Revision 1.60 2004/07/09 10:06:50 rurban
1230 // Use backend specific sortby and sortable_columns method, to be able to
1231 // select between native (Db backend) and custom (PageList) sorting.
1232 // Fixed PageList::AddPageList (missed the first)
1233 // Added the author/creator.. name to AllPagesBy...
1234 // display no pages if none matched.
1235 // Improved dba and file sortby().
1236 // Use &$request reference
1238 // Revision 1.59 2004/07/08 21:32:36 rurban
1239 // Prevent from more warnings, minor db and sort optimizations
1241 // Revision 1.58 2004/07/08 16:56:16 rurban
1242 // use the backendType abstraction
1244 // Revision 1.57 2004/07/05 12:57:54 rurban
1245 // add mysql timeout
1247 // Revision 1.56 2004/07/04 10:24:43 rurban
1248 // forgot the expressions
1250 // Revision 1.55 2004/07/03 16:51:06 rurban
1251 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1252 // added atomic mysql REPLACE for PearDB as in ADODB
1253 // fixed _lock_tables typo links => link
1254 // fixes unserialize ADODB bug in line 180
1256 // Revision 1.54 2004/06/29 08:52:24 rurban
1257 // Use ...version() $need_content argument in WikiDB also:
1258 // To reduce the memory footprint for larger sets of pagelists,
1259 // we don't cache the content (only true or false) and
1260 // we purge the pagedata (_cached_html) also.
1261 // _cached_html is only cached for the current pagename.
1262 // => Vastly improved page existance check, ACL check, ...
1264 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1266 // Revision 1.53 2004/06/27 10:26:03 rurban
1267 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1269 // Revision 1.52 2004/06/25 14:15:08 rurban
1270 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1272 // Revision 1.51 2004/05/12 10:49:55 rurban
1273 // require_once fix for those libs which are loaded before FileFinder and
1274 // its automatic include_path fix, and where require_once doesn't grok
1275 // dirname(__FILE__) != './lib'
1276 // upgrade fix with PearDB
1277 // navbar.tmpl: remove spaces for IE button alignment
1279 // Revision 1.50 2004/05/06 17:30:39 rurban
1280 // CategoryGroup: oops, dos2unix eol
1281 // improved phpwiki_version:
1282 // pre -= .0001 (1.3.10pre: 1030.099)
1283 // -p1 += .001 (1.3.9-p1: 1030.091)
1284 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1285 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1286 // backend->backendType(), backend->database(),
1287 // backend->listOfFields(),
1288 // backend->listOfTables(),
1290 // Revision 1.49 2004/05/03 21:35:30 rurban
1291 // don't use persistent connections with postgres
1293 // Revision 1.48 2004/04/26 20:44:35 rurban
1294 // locking table specific for better databases
1296 // Revision 1.47 2004/04/20 00:06:04 rurban
1297 // themable paging support
1299 // Revision 1.46 2004/04/19 21:51:41 rurban
1300 // php5 compatibility: it works!
1302 // Revision 1.45 2004/04/16 14:19:39 rurban
1303 // updated ADODB notes
1306 // (c-file-style: "gnu")
1310 // c-basic-offset: 4
1311 // c-hanging-comment-ender-p: nil
1312 // indent-tabs-mode: nil