2 rcs_id('$Id: PearDB.php,v 1.76 2004-11-30 17:45:53 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 hits,pagedata FROM %s WHERE pagename='%s'",
152 $this->_table_names['page_tbl'],
153 $dbh->escapeSimple($pagename)),
155 return $result ? $this->_extract_page_data($result) : false;
158 function _extract_page_data($data) {
159 if (empty($data)) return array();
160 elseif (empty($data['pagedata'])) return $data;
162 $data = array_merge($data, $this->_unserialize($data['pagedata']));
163 unset($data['pagedata']);
168 function update_pagedata($pagename, $newdata) {
170 $page_tbl = $this->_table_names['page_tbl'];
172 // Hits is the only thing we can update in a fast manner.
173 if (count($newdata) == 1 && isset($newdata['hits'])) {
174 // Note that this will fail silently if the page does not
175 // have a record in the page table. Since it's just the
176 // hit count, who cares?
177 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
178 $newdata['hits'], $dbh->escapeSimple($pagename)));
182 $this->lock(array($page_tbl), true);
183 $data = $this->get_pagedata($pagename);
186 $this->_get_pageid($pagename, true); // Creates page record
189 @$hits = (int)$data['hits'];
190 unset($data['hits']);
192 foreach ($newdata as $key => $val) {
195 else if (empty($val))
201 /* Portability issue -- not all DBMS supports huge strings
202 * so we need to 'bind' instead of building a simple SQL statment.
203 * Note that we do not need to escapeSimple when we bind
204 $dbh->query(sprintf("UPDATE $page_tbl"
205 . " SET hits=%d, pagedata='%s'"
206 . " WHERE pagename='%s'",
208 $dbh->escapeSimple($this->_serialize($data)),
209 $dbh->escapeSimple($pagename)));
211 $sth = $dbh->query("UPDATE $page_tbl"
212 . " SET hits=?, pagedata=?"
213 . " WHERE pagename=?",
214 array($hits, $this->_serialize($data), $pagename));
215 $this->unlock(array($page_tbl));
218 function _get_pageid($pagename, $create_if_missing = false) {
222 $cache =& $request->_dbi->_cache->_id_cache;
223 if (isset($cache[$pagename])) return $cache[$pagename];
226 $page_tbl = $this->_table_names['page_tbl'];
228 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
229 $dbh->escapeSimple($pagename));
231 if (!$create_if_missing)
232 return $dbh->getOne($query);
234 $id = $dbh->getOne($query);
236 $this->lock(array($page_tbl), true); // write lock
237 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
239 $dbh->query(sprintf("INSERT INTO $page_tbl"
240 . " (id,pagename,hits)"
241 . " VALUES (%d,'%s',0)",
242 $id, $dbh->escapeSimple($pagename)));
243 $this->unlock(array($page_tbl));
248 function get_latest_version($pagename) {
250 extract($this->_table_names);
252 (int)$dbh->getOne(sprintf("SELECT latestversion"
253 . " FROM $page_tbl, $recent_tbl"
254 . " WHERE $page_tbl.id=$recent_tbl.id"
255 . " AND pagename='%s'",
256 $dbh->escapeSimple($pagename)));
259 function get_previous_version($pagename, $version) {
261 extract($this->_table_names);
264 (int)$dbh->getOne(sprintf("SELECT version"
265 . " FROM $version_tbl, $page_tbl"
266 . " WHERE $version_tbl.id=$page_tbl.id"
267 . " AND pagename='%s'"
268 . " AND version < %d"
269 . " ORDER BY version DESC",
270 /* Non portable and useless anyway with getOne
273 $dbh->escapeSimple($pagename),
280 * @param $version int Which version to get.
282 * @return hash The version data, or false if specified version does not
285 function get_versiondata($pagename, $version, $want_content = false) {
287 extract($this->_table_names);
288 extract($this->_expressions);
290 assert(is_string($pagename) and $pagename != "");
291 assert($version > 0);
293 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
294 // FIXME: optimization: sometimes don't get page data?
296 $fields = $this->page_tbl_fields
297 . ",$page_tbl.pagedata as pagedata,"
298 . $this->version_tbl_fields;
301 $fields = $this->page_tbl_fields . ","
302 . "mtime, minor_edit, versiondata,"
303 . "$iscontent AS have_content";
306 $result = $dbh->getRow(sprintf("SELECT $fields"
307 . " FROM $page_tbl, $version_tbl"
308 . " WHERE $page_tbl.id=$version_tbl.id"
309 . " AND pagename='%s'"
311 $dbh->escapeSimple($pagename), $version),
314 return $this->_extract_version_data($result);
317 function _extract_version_data($query_result) {
321 $data = $this->_unserialize($query_result['versiondata']);
323 $data['mtime'] = $query_result['mtime'];
324 $data['is_minor_edit'] = !empty($query_result['minor_edit']);
326 if (isset($query_result['content']))
327 $data['%content'] = $query_result['content'];
328 elseif ($query_result['have_content'])
329 $data['%content'] = true;
331 $data['%content'] = '';
333 // FIXME: this is ugly.
334 if (isset($query_result['pagename'])) {
335 // Query also includes page data.
336 // We might as well send that back too...
337 unset($query_result['versiondata']);
338 $data['%pagedata'] = $this->_extract_page_data($query_result);
346 * Create a new revision of a page.
348 function set_versiondata($pagename, $version, $data) {
350 $version_tbl = $this->_table_names['version_tbl'];
352 $minor_edit = (int) !empty($data['is_minor_edit']);
353 unset($data['is_minor_edit']);
355 $mtime = (int)$data['mtime'];
356 unset($data['mtime']);
357 assert(!empty($mtime));
359 @$content = (string) $data['%content'];
360 unset($data['%content']);
362 unset($data['%pagedata']);
365 $id = $this->_get_pageid($pagename, true);
367 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
368 $dbh->query(sprintf("DELETE FROM $version_tbl"
369 . " WHERE id=%d AND version=%d",
372 /* mysql optimized version.
373 $dbh->query(sprintf("INSERT INTO $version_tbl"
374 . " (id,version,mtime,minor_edit,content,versiondata)"
375 . " VALUES(%d,%d,%d,%d,'%s','%s')",
376 $id, $version, $mtime, $minor_edit,
377 $dbh->quoteSmart($content),
378 $dbh->quoteSmart($this->_serialize($data))));
380 // generic slow PearDB bind eh quoting.
381 $dbh->query("INSERT INTO $version_tbl"
382 . " (id,version,mtime,minor_edit,content,versiondata)"
383 . " VALUES(?, ?, ?, ?, ?, ?)",
384 array($id, $version, $mtime, $minor_edit, $content,
385 $this->_serialize($data)));
387 $this->_update_recent_table($id);
388 $this->_update_nonempty_table($id);
394 * Delete an old revision of a page.
396 function delete_versiondata($pagename, $version) {
398 extract($this->_table_names);
401 if ( ($id = $this->_get_pageid($pagename)) ) {
402 $dbh->query("DELETE FROM $version_tbl"
403 . " WHERE id=$id AND version=$version");
404 $this->_update_recent_table($id);
405 // This shouldn't be needed (as long as the latestversion
406 // never gets deleted.) But, let's be safe.
407 $this->_update_nonempty_table($id);
413 * Delete page completely from the database.
414 * I'm not sure if this is what we want. Maybe just delete the revisions
416 function delete_page($pagename) {
418 extract($this->_table_names);
421 if ( ($id = $this->_get_pageid($pagename, false)) ) {
422 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
423 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
424 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
425 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
426 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
428 // We're still in the link table (dangling link) so we can't delete this
430 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
433 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
435 $this->_update_recent_table();
436 $this->_update_nonempty_table();
442 // The only thing we might be interested in updating which we can
443 // do fast in the flags (minor_edit). I think the default
444 // update_versiondata will work fine...
445 //function update_versiondata($pagename, $version, $data) {
448 function set_links($pagename, $links) {
449 // Update link table.
450 // FIXME: optimize: mysql can do this all in one big INSERT.
453 extract($this->_table_names);
456 $pageid = $this->_get_pageid($pagename, true);
458 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
461 foreach($links as $link) {
462 if (isset($linkseen[$link]))
464 $linkseen[$link] = true;
465 $linkid = $this->_get_pageid($link, true);
466 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
467 . " VALUES ($pageid, $linkid)");
474 * Find pages which link to or are linked from a page.
476 function get_links($pagename, $reversed=true, $include_empty=false,
477 $sortby=false, $limit=false, $exclude='') {
479 extract($this->_table_names);
482 list($have,$want) = array('linkee', 'linker');
484 list($have,$want) = array('linker', 'linkee');
485 $orderby = $this->sortby($sortby, 'db', array('pagename'));
486 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
487 if ($exclude) // array of pagenames
488 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
492 $qpagename = $dbh->escapeSimple($pagename);
493 $sql = "SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
494 // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
495 // and the PostgresSQL manual does not have it either
496 // Since it is optional in mySQL, just remove it...
497 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
498 . (!$include_empty ? ", $nonempty_tbl" : '')
499 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
500 . " AND $have.pagename='$qpagename'"
501 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
502 //. " GROUP BY $want.id"
506 // extract from,count from limit
507 list($from,$count) = $this->limit($limit);
508 $result = $dbh->limitQuery($sql, $from, $count);
510 $result = $dbh->query($sql);
513 return new WikiDB_backend_PearDB_iter($this, $result);
517 * Find if a page links to another page
519 function exists_link($pagename, $link, $reversed=false) {
521 extract($this->_table_names);
524 list($have, $want) = array('linkee', 'linker');
526 list($have, $want) = array('linker', 'linkee');
527 $qpagename = $dbh->escapeSimple($pagename);
528 $qlink = $dbh->escapeSimple($link);
529 $row = $dbh->GetRow("SELECT IF($want.pagename,1,0) as result"
530 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
531 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
532 . " AND $have.pagename=$qpagename"
533 . " AND $want.pagename=$qlink"
535 return $row['result'];
538 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
540 extract($this->_table_names);
541 $orderby = $this->sortby($sortby, 'db');
542 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
543 if ($exclude) // array of pagenames
544 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
548 if (strstr($orderby, 'mtime ')) { // multiple columns possible
549 if ($include_empty) {
551 . $this->page_tbl_fields
552 . " FROM $page_tbl, $recent_tbl, $version_tbl"
553 . " WHERE $page_tbl.id=$recent_tbl.id"
554 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
560 . $this->page_tbl_fields
561 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
562 . " WHERE $nonempty_tbl.id=$page_tbl.id"
563 . " AND $page_tbl.id=$recent_tbl.id"
564 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
569 if ($include_empty) {
571 . $this->page_tbl_fields
573 . $exclude ? " WHERE $exclude" : ''
578 . $this->page_tbl_fields
579 . " FROM $nonempty_tbl, $page_tbl"
580 . " WHERE $nonempty_tbl.id=$page_tbl.id"
586 // extract from,count from limit
587 list($from,$count) = $this->limit($limit);
588 $result = $dbh->limitQuery($sql, $from, $count);
590 $result = $dbh->query($sql);
592 return new WikiDB_backend_PearDB_iter($this, $result);
598 function text_search($search, $fulltext=false) {
600 extract($this->_table_names);
602 $searchclass = get_class($this)."_search";
603 // no need to define it everywhere and then fallback. memory!
604 if (!class_exists($searchclass))
605 $searchclass = "WikiDB_backend_PearDB_search";
606 $searchobj = new $searchclass($search, $dbh);
608 $table = "$nonempty_tbl, $page_tbl";
609 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
610 $fields = $this->page_tbl_fields;
613 $table .= ", $recent_tbl";
614 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
616 $table .= ", $version_tbl";
617 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
619 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
620 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
622 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
624 $search_clause = $search->makeSqlClauseObj($callback);
626 $result = $dbh->query("SELECT $fields FROM $table"
627 . " WHERE $join_clause"
628 . " AND ($search_clause)"
629 . " ORDER BY pagename");
631 return new WikiDB_backend_PearDB_iter($this, $result);
634 //Todo: check if the better Mysql MATCH operator is supported,
635 // (ranked search) and also google like expressions.
636 function _sql_match_clause($word) {
637 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
638 $word = $this->_dbh->escapeSimple($word);
639 //$page_tbl = $this->_table_names['page_tbl'];
640 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
641 // e.g. if word is lowercased.
642 // http://bugs.mysql.com/bug.php?id=1491
643 return "LOWER(pagename) LIKE '%$word%'";
645 function _sql_casematch_clause($word) {
646 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
647 $word = $this->_dbh->escapeSimple($word);
648 return "pagename LIKE '%$word%'";
650 function _fullsearch_sql_match_clause($word) {
651 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
652 $word = $this->_dbh->escapeSimple($word);
653 //$page_tbl = $this->_table_names['page_tbl'];
654 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
655 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
657 function _fullsearch_sql_casematch_clause($word) {
658 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
659 $word = $this->_dbh->escapeSimple($word);
660 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
664 * Find highest or lowest hit counts.
666 function most_popular($limit=0, $sortby='-hits') {
668 extract($this->_table_names);
674 $order = "hits DESC";
675 $where = " AND hits > 0";
678 if ($sortby != '-hits') {
679 if ($order = $this->sortby($sortby, 'db'))
680 $orderby = " ORDER BY " . $order;
682 $orderby = " ORDER BY $order";
684 //$limitclause = $limit ? " LIMIT $limit" : '';
686 . $this->page_tbl_fields
687 . " FROM $nonempty_tbl, $page_tbl"
688 . " WHERE $nonempty_tbl.id=$page_tbl.id"
692 list($from, $count) = $this->limit($limit);
693 $result = $dbh->limitQuery($sql, $from, $count);
695 $result = $dbh->query($sql);
698 return new WikiDB_backend_PearDB_iter($this, $result);
702 * Find recent changes.
704 function most_recent($params) {
707 $include_minor_revisions = false;
708 $exclude_major_revisions = false;
709 $include_all_revisions = false;
713 extract($this->_table_names);
717 $pick[] = "mtime >= $since";
720 if ($include_all_revisions) {
721 // Include all revisions of each page.
722 $table = "$page_tbl, $version_tbl";
723 $join_clause = "$page_tbl.id=$version_tbl.id";
725 if ($exclude_major_revisions) {
726 // Include only minor revisions
727 $pick[] = "minor_edit <> 0";
729 elseif (!$include_minor_revisions) {
730 // Include only major revisions
731 $pick[] = "minor_edit = 0";
735 $table = "$page_tbl, $recent_tbl";
736 $join_clause = "$page_tbl.id=$recent_tbl.id";
737 $table .= ", $version_tbl";
738 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
740 if ($exclude_major_revisions) {
741 // Include only most recent minor revision
742 $pick[] = 'version=latestminor';
744 elseif (!$include_minor_revisions) {
745 // Include only most recent major revision
746 $pick[] = 'version=latestmajor';
749 // Include only the latest revision (whether major or minor).
750 $pick[] ='version=latestversion';
758 // $limitclause = $limit ? " LIMIT $limit" : '';
759 $where_clause = $join_clause;
761 $where_clause .= " AND " . join(" AND ", $pick);
763 // FIXME: use SQL_BUFFER_RESULT for mysql?
765 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
767 . " WHERE $where_clause"
768 . " ORDER BY mtime $order";
770 list($from, $count) = $this->limit($limit);
771 $result = $dbh->limitQuery($sql, $from, $count);
773 $result = $dbh->query($sql);
775 return new WikiDB_backend_PearDB_iter($this, $result);
779 * Find referenced empty pages.
781 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
783 extract($this->_table_names);
784 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
785 $orderby = 'ORDER BY ' . $orderby;
787 if ($exclude_from) // array of pagenames
788 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
789 if ($exclude) // array of pagenames
790 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
792 $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
793 . " FROM $link_tbl,$page_tbl as linked "
794 . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
795 . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)"
796 . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
801 list($from, $count) = $this->limit($limit);
802 $result = $dbh->limitQuery($sql, $from, $count * 3);
804 $result = $dbh->query($sql);
806 return new WikiDB_backend_PearDB_generic_iter($this, $result);
809 function _sql_set(&$pagenames) {
811 foreach ($pagenames as $p) {
812 $s .= ("'".$this->_dbh->escapeSimple($p)."',");
814 return substr($s,0,-1).")";
818 * Rename page in the database.
820 function rename_page($pagename, $to) {
822 extract($this->_table_names);
825 if ( ($id = $this->_get_pageid($pagename, false)) ) {
826 if ($new = $this->_get_pageid($to, false)) {
828 //this page does not exist (already verified before), but exists in the page table.
829 //so we delete this page.
830 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
832 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
833 $dbh->escapeSimple($to)));
839 function _update_recent_table($pageid = false) {
841 extract($this->_table_names);
842 extract($this->_expressions);
844 $pageid = (int)$pageid;
847 $dbh->query("DELETE FROM $recent_tbl"
848 . ( $pageid ? " WHERE id=$pageid" : ""));
849 $dbh->query( "INSERT INTO $recent_tbl"
850 . " (id, latestversion, latestmajor, latestminor)"
851 . " SELECT id, $maxversion, $maxmajor, $maxminor"
852 . " FROM $version_tbl"
853 . ( $pageid ? " WHERE id=$pageid" : "")
858 function _update_nonempty_table($pageid = false) {
860 extract($this->_table_names);
862 $pageid = (int)$pageid;
864 extract($this->_expressions);
866 $dbh->query("DELETE FROM $nonempty_tbl"
867 . ( $pageid ? " WHERE id=$pageid" : ""));
868 $dbh->query("INSERT INTO $nonempty_tbl (id)"
869 . " SELECT $recent_tbl.id"
870 . " FROM $recent_tbl, $version_tbl"
871 . " WHERE $recent_tbl.id=$version_tbl.id"
872 . " AND version=latestversion"
873 // We have some specifics here (Oracle)
874 //. " AND content<>''"
875 . " AND content $notempty"
876 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
883 * Grab a write lock on the tables in the SQL database.
885 * Calls can be nested. The tables won't be unlocked until
886 * _unlock_database() is called as many times as _lock_database().
890 function lock($tables = false, $write_lock = true) {
891 if ($this->_lock_count++ == 0)
892 $this->_lock_tables($write_lock);
896 * Actually lock the required tables.
898 function _lock_tables($write_lock) {
899 trigger_error("virtual", E_USER_ERROR);
903 * Release a write lock on the tables in the SQL database.
907 * @param $force boolean Unlock even if not every call to lock() has been matched
908 * by a call to unlock().
910 * @see _lock_database
912 function unlock($tables = false, $force = false) {
913 if ($this->_lock_count == 0)
915 if (--$this->_lock_count <= 0 || $force) {
916 $this->_unlock_tables();
917 $this->_lock_count = 0;
922 * Actually unlock the required tables.
924 function _unlock_tables($write_lock) {
925 trigger_error("virtual", E_USER_ERROR);
932 function _serialize($data) {
935 assert(is_array($data));
936 return serialize($data);
942 function _unserialize($data) {
943 return empty($data) ? array() : unserialize($data);
947 * Callback for PEAR (DB) errors.
951 * @param A PEAR_error object.
953 function _pear_error_callback($error) {
954 if ($this->_is_false_error($error))
957 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
959 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
963 * Detect false errors messages from PEAR DB.
965 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
966 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
967 * return any data. (So when a "LOCK" command doesn't return any data,
968 * DB reports it as an error, when in fact, it's not.)
971 * @return bool True iff error is not really an error.
973 function _is_false_error($error) {
974 if ($error->getCode() != DB_ERROR)
977 $query = $this->_dbh->last_query;
979 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
980 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
981 // Last query was not of the sort which doesn't return any data.
982 //" <--kludge for brain-dead syntax coloring
986 if (! in_array('ismanip', get_class_methods('DB'))) {
987 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
988 // does not have the DB::isManip method.
992 if (DB::isManip($query)) {
993 // If Pear thinks it's an isManip then it wouldn't have thrown
994 // the error we're testing for....
1001 function _pear_error_message($error) {
1002 $class = get_class($this);
1003 $message = "$class: fatal database error\n"
1004 . "\t" . $error->getMessage() . "\n"
1005 . "\t(" . $error->getDebugInfo() . ")\n";
1007 // Prevent password from being exposed during a connection error
1008 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1009 '\\1:XXXXXXXX', $this->_dsn);
1010 return str_replace($this->_dsn, $safe_dsn, $message);
1014 * Filter PHP errors notices from PEAR DB code.
1016 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1017 * errors and notices. This is an error callback (for use with
1018 * ErrorManager which will filter out those spurious messages.)
1019 * @see _is_false_error, ErrorManager
1022 function _pear_notice_filter($err) {
1023 return ( $err->isNotice()
1024 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1025 && $err->errline == 126
1026 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1029 /* some variables and functions for DB backend abstraction (action=upgrade) */
1030 function database () {
1031 return $this->_dbh->dsn['database'];
1033 function backendType() {
1034 return $this->_dbh->phptype;
1036 function connection() {
1037 return $this->_dbh->connection;
1040 function listOfTables() {
1041 return $this->_dbh->getListOf('tables');
1043 function listOfFields($database,$table) {
1044 if ($this->backendType() == 'mysql') {
1046 assert(!empty($database));
1047 assert(!empty($table));
1048 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1049 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1050 if (!$result) return array();
1051 $columns = mysql_num_fields($result);
1052 for ($i = 0; $i < $columns; $i++) {
1053 $fields[] = mysql_field_name($result, $i);
1055 mysql_free_result($result);
1058 // TODO: try ADODB version?
1059 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1066 * This class is a generic iterator.
1068 * WikiDB_backend_PearDB_iter only iterates over things that have
1069 * 'pagename', 'pagedata', etc. etc.
1071 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1072 * (most of the code is cut-and-paste :-( ), but I am trying to make
1073 * changes that could be merged easily.
1075 * @author: Dan Frankowski
1077 class WikiDB_backend_PearDB_generic_iter
1078 extends WikiDB_backend_iterator
1080 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1081 if (DB::isError($query_result)) {
1082 // This shouldn't happen, I thought.
1083 $backend->_pear_error_callback($query_result);
1086 $this->_backend = &$backend;
1087 $this->_result = $query_result;
1091 if (!$this->_result)
1093 return $this->_result->numRows();
1097 $backend = &$this->_backend;
1098 if (!$this->_result)
1101 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1111 if ($this->_result) {
1112 $this->_result->free();
1113 $this->_result = false;
1118 class WikiDB_backend_PearDB_iter
1119 extends WikiDB_backend_PearDB_generic_iter
1123 $backend = &$this->_backend;
1124 if (!$this->_result)
1127 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1133 $pagedata = $backend->_extract_page_data($record);
1134 $rec = array('pagename' => $record['pagename'],
1135 'pagedata' => $pagedata);
1137 if (!empty($record['version'])) {
1138 $rec['versiondata'] = $backend->_extract_version_data($record);
1139 $rec['version'] = $record['version'];
1147 class WikiDB_backend_PearDB_search
1148 extends WikiDB_backend_search
1150 function WikiDB_backend_PearDB_search(&$search, &$dbh) {
1152 $this->_case_exact = $search->_case_exact;
1154 function _pagename_match_clause($node) {
1155 $word = $node->sql();
1156 if ($node->op == 'REGEX') { // posix regex extensions
1157 if (preg_match("/mysql/i", $this->_dbh->phptype))
1158 return "pagename REGEXP '$word'";
1160 return $this->_case_exact ? "pagename LIKE '$word'"
1161 : "LOWER(pagename) LIKE '$word'";
1164 function _fulltext_match_clause($node) {
1165 $word = $node->sql();
1166 return $this->_pagename_match_clause($node)
1167 // probably convert this MATCH AGAINST or SUBSTR/POSITION without wildcards
1168 . ($this->_case_exact ? " OR content LIKE '$word'"
1169 : " OR LOWER(content) LIKE '$word'");
1173 // $Log: not supported by cvs2svn $
1174 // Revision 1.75 2004/11/28 20:42:33 rurban
1175 // Optimize PearDB _extract_version_data and _extract_page_data.
1177 // Revision 1.74 2004/11/27 14:39:05 rurban
1178 // simpified regex search architecture:
1179 // no db specific node methods anymore,
1180 // new sql() method for each node
1181 // parallel to regexp() (which returns pcre)
1182 // regex types bitmasked (op's not yet)
1184 // clarified WikiDB::quote() backend methods:
1185 // ->quote() adds surrounsing quotes
1186 // ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1187 // pear and adodb have now unified quote methods for all generic queries.
1189 // Revision 1.73 2004/11/26 18:39:02 rurban
1190 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1192 // Revision 1.72 2004/11/25 17:20:51 rurban
1193 // and again a couple of more native db args: backlinks
1195 // Revision 1.71 2004/11/23 13:35:48 rurban
1196 // add case_exact search
1198 // Revision 1.70 2004/11/21 11:59:26 rurban
1199 // remove final \n to be ob_cache independent
1201 // Revision 1.69 2004/11/20 17:49:39 rurban
1202 // add fast exclude support to SQL get_all_pages
1204 // Revision 1.68 2004/11/20 17:35:58 rurban
1205 // improved WantedPages SQL backends
1206 // PageList::sortby new 3rd arg valid_fields (override db fields)
1207 // WantedPages sql pager inexact for performance reasons:
1208 // assume 3 wantedfrom per page, to be correct, no getTotal()
1209 // support exclude argument for get_all_pages, new _sql_set()
1211 // Revision 1.67 2004/11/10 19:32:24 rurban
1212 // * optimize increaseHitCount, esp. for mysql.
1213 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1214 // * Pear_DB version logic (awful but needed)
1215 // * fix broken ADODB quote
1216 // * _extract_page_data simplification
1218 // Revision 1.66 2004/11/10 15:29:21 rurban
1219 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1220 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1221 // * WikiDB: moved SQL specific methods upwards
1222 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1223 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1225 // Revision 1.65 2004/11/09 17:11:17 rurban
1226 // * revert to the wikidb ref passing. there's no memory abuse there.
1227 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1228 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1229 // are also needed at the rendering for linkExistingWikiWord().
1230 // pass options to pageiterator.
1231 // use this cache also for _get_pageid()
1232 // This saves about 8 SELECT count per page (num all pagelinks).
1233 // * fix passing of all page fields to the pageiterator.
1234 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1236 // Revision 1.64 2004/11/07 16:02:52 rurban
1237 // new sql access log (for spam prevention), and restructured access log class
1238 // dbh->quote (generic)
1239 // pear_db: mysql specific parts seperated (using replace)
1241 // Revision 1.63 2004/11/01 10:43:58 rurban
1242 // seperate PassUser methods into seperate dir (memory usage)
1243 // fix WikiUser (old) overlarge data session
1244 // remove wikidb arg from various page class methods, use global ->_dbi instead
1247 // Revision 1.62 2004/10/14 19:19:34 rurban
1248 // loadsave: check if the dumped file will be accessible from outside.
1249 // and some other minor fixes. (cvsclient native not yet ready)
1251 // Revision 1.61 2004/10/14 17:19:17 rurban
1252 // allow most_popular sortby arguments
1254 // Revision 1.60 2004/07/09 10:06:50 rurban
1255 // Use backend specific sortby and sortable_columns method, to be able to
1256 // select between native (Db backend) and custom (PageList) sorting.
1257 // Fixed PageList::AddPageList (missed the first)
1258 // Added the author/creator.. name to AllPagesBy...
1259 // display no pages if none matched.
1260 // Improved dba and file sortby().
1261 // Use &$request reference
1263 // Revision 1.59 2004/07/08 21:32:36 rurban
1264 // Prevent from more warnings, minor db and sort optimizations
1266 // Revision 1.58 2004/07/08 16:56:16 rurban
1267 // use the backendType abstraction
1269 // Revision 1.57 2004/07/05 12:57:54 rurban
1270 // add mysql timeout
1272 // Revision 1.56 2004/07/04 10:24:43 rurban
1273 // forgot the expressions
1275 // Revision 1.55 2004/07/03 16:51:06 rurban
1276 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1277 // added atomic mysql REPLACE for PearDB as in ADODB
1278 // fixed _lock_tables typo links => link
1279 // fixes unserialize ADODB bug in line 180
1281 // Revision 1.54 2004/06/29 08:52:24 rurban
1282 // Use ...version() $need_content argument in WikiDB also:
1283 // To reduce the memory footprint for larger sets of pagelists,
1284 // we don't cache the content (only true or false) and
1285 // we purge the pagedata (_cached_html) also.
1286 // _cached_html is only cached for the current pagename.
1287 // => Vastly improved page existance check, ACL check, ...
1289 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1291 // Revision 1.53 2004/06/27 10:26:03 rurban
1292 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1294 // Revision 1.52 2004/06/25 14:15:08 rurban
1295 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1297 // Revision 1.51 2004/05/12 10:49:55 rurban
1298 // require_once fix for those libs which are loaded before FileFinder and
1299 // its automatic include_path fix, and where require_once doesn't grok
1300 // dirname(__FILE__) != './lib'
1301 // upgrade fix with PearDB
1302 // navbar.tmpl: remove spaces for IE button alignment
1304 // Revision 1.50 2004/05/06 17:30:39 rurban
1305 // CategoryGroup: oops, dos2unix eol
1306 // improved phpwiki_version:
1307 // pre -= .0001 (1.3.10pre: 1030.099)
1308 // -p1 += .001 (1.3.9-p1: 1030.091)
1309 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1310 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1311 // backend->backendType(), backend->database(),
1312 // backend->listOfFields(),
1313 // backend->listOfTables(),
1315 // Revision 1.49 2004/05/03 21:35:30 rurban
1316 // don't use persistent connections with postgres
1318 // Revision 1.48 2004/04/26 20:44:35 rurban
1319 // locking table specific for better databases
1321 // Revision 1.47 2004/04/20 00:06:04 rurban
1322 // themable paging support
1324 // Revision 1.46 2004/04/19 21:51:41 rurban
1325 // php5 compatibility: it works!
1327 // Revision 1.45 2004/04/16 14:19:39 rurban
1328 // updated ADODB notes
1331 // (c-file-style: "gnu")
1335 // c-basic-offset: 4
1336 // c-hanging-comment-ender-p: nil
1337 // indent-tabs-mode: nil