2 rcs_id('$Id: PearDB.php,v 1.77 2004-12-06 19:50:04 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 * See ADODB for a better delete_page(), which can be undone and is seen in RecentChanges.
415 function delete_page($pagename) {
416 $this->purge_page($pagename);
420 * Delete page completely from the database.
421 * I'm not sure if this is what we want. Maybe just delete the revisions
423 function purge_page($pagename) {
425 extract($this->_table_names);
428 if ( ($id = $this->_get_pageid($pagename, false)) ) {
429 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
430 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
431 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
432 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
433 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
435 // We're still in the link table (dangling link) so we can't delete this
437 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
441 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
444 $this->_update_recent_table();
445 $this->_update_nonempty_table();
447 $result = -1; // already purged or not existing
453 // The only thing we might be interested in updating which we can
454 // do fast in the flags (minor_edit). I think the default
455 // update_versiondata will work fine...
456 //function update_versiondata($pagename, $version, $data) {
459 function set_links($pagename, $links) {
460 // Update link table.
461 // FIXME: optimize: mysql can do this all in one big INSERT.
464 extract($this->_table_names);
467 $pageid = $this->_get_pageid($pagename, true);
469 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
472 foreach($links as $link) {
473 if (isset($linkseen[$link]))
475 $linkseen[$link] = true;
476 $linkid = $this->_get_pageid($link, true);
477 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
478 . " VALUES ($pageid, $linkid)");
485 * Find pages which link to or are linked from a page.
487 function get_links($pagename, $reversed=true, $include_empty=false,
488 $sortby=false, $limit=false, $exclude='') {
490 extract($this->_table_names);
493 list($have,$want) = array('linkee', 'linker');
495 list($have,$want) = array('linker', 'linkee');
496 $orderby = $this->sortby($sortby, 'db', array('pagename'));
497 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
498 if ($exclude) // array of pagenames
499 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
503 $qpagename = $dbh->escapeSimple($pagename);
504 $sql = "SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
505 // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
506 // and the PostgresSQL manual does not have it either
507 // Since it is optional in mySQL, just remove it...
508 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
509 . (!$include_empty ? ", $nonempty_tbl" : '')
510 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
511 . " AND $have.pagename='$qpagename'"
512 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
513 //. " GROUP BY $want.id"
517 // extract from,count from limit
518 list($from,$count) = $this->limit($limit);
519 $result = $dbh->limitQuery($sql, $from, $count);
521 $result = $dbh->query($sql);
524 return new WikiDB_backend_PearDB_iter($this, $result);
528 * Find if a page links to another page
530 function exists_link($pagename, $link, $reversed=false) {
532 extract($this->_table_names);
535 list($have, $want) = array('linkee', 'linker');
537 list($have, $want) = array('linker', 'linkee');
538 $qpagename = $dbh->escapeSimple($pagename);
539 $qlink = $dbh->escapeSimple($link);
540 $row = $dbh->GetRow("SELECT IF($want.pagename,1,0) as result"
541 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
542 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
543 . " AND $have.pagename=$qpagename"
544 . " AND $want.pagename=$qlink"
546 return $row['result'];
549 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
551 extract($this->_table_names);
552 $orderby = $this->sortby($sortby, 'db');
553 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
554 if ($exclude) // array of pagenames
555 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
559 if (strstr($orderby, 'mtime ')) { // multiple columns possible
560 if ($include_empty) {
562 . $this->page_tbl_fields
563 . " FROM $page_tbl, $recent_tbl, $version_tbl"
564 . " WHERE $page_tbl.id=$recent_tbl.id"
565 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
571 . $this->page_tbl_fields
572 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
573 . " WHERE $nonempty_tbl.id=$page_tbl.id"
574 . " AND $page_tbl.id=$recent_tbl.id"
575 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
580 if ($include_empty) {
582 . $this->page_tbl_fields
584 . $exclude ? " WHERE $exclude" : ''
589 . $this->page_tbl_fields
590 . " FROM $nonempty_tbl, $page_tbl"
591 . " WHERE $nonempty_tbl.id=$page_tbl.id"
597 // extract from,count from limit
598 list($from,$count) = $this->limit($limit);
599 $result = $dbh->limitQuery($sql, $from, $count);
601 $result = $dbh->query($sql);
603 return new WikiDB_backend_PearDB_iter($this, $result);
609 function text_search($search, $fulltext=false) {
611 extract($this->_table_names);
613 $searchclass = get_class($this)."_search";
614 // no need to define it everywhere and then fallback. memory!
615 if (!class_exists($searchclass))
616 $searchclass = "WikiDB_backend_PearDB_search";
617 $searchobj = new $searchclass($search, $dbh);
619 $table = "$nonempty_tbl, $page_tbl";
620 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
621 $fields = $this->page_tbl_fields;
624 $table .= ", $recent_tbl";
625 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
627 $table .= ", $version_tbl";
628 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
630 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
631 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
633 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
635 $search_clause = $search->makeSqlClauseObj($callback);
637 $result = $dbh->query("SELECT $fields FROM $table"
638 . " WHERE $join_clause"
639 . " AND ($search_clause)"
640 . " ORDER BY pagename");
642 return new WikiDB_backend_PearDB_iter($this, $result);
645 //Todo: check if the better Mysql MATCH operator is supported,
646 // (ranked search) and also google like expressions.
647 function _sql_match_clause($word) {
648 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
649 $word = $this->_dbh->escapeSimple($word);
650 //$page_tbl = $this->_table_names['page_tbl'];
651 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
652 // e.g. if word is lowercased.
653 // http://bugs.mysql.com/bug.php?id=1491
654 return "LOWER(pagename) LIKE '%$word%'";
656 function _sql_casematch_clause($word) {
657 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
658 $word = $this->_dbh->escapeSimple($word);
659 return "pagename LIKE '%$word%'";
661 function _fullsearch_sql_match_clause($word) {
662 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
663 $word = $this->_dbh->escapeSimple($word);
664 //$page_tbl = $this->_table_names['page_tbl'];
665 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
666 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
668 function _fullsearch_sql_casematch_clause($word) {
669 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
670 $word = $this->_dbh->escapeSimple($word);
671 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
675 * Find highest or lowest hit counts.
677 function most_popular($limit=0, $sortby='-hits') {
679 extract($this->_table_names);
685 $order = "hits DESC";
686 $where = " AND hits > 0";
689 if ($sortby != '-hits') {
690 if ($order = $this->sortby($sortby, 'db'))
691 $orderby = " ORDER BY " . $order;
693 $orderby = " ORDER BY $order";
695 //$limitclause = $limit ? " LIMIT $limit" : '';
697 . $this->page_tbl_fields
698 . " FROM $nonempty_tbl, $page_tbl"
699 . " WHERE $nonempty_tbl.id=$page_tbl.id"
703 list($from, $count) = $this->limit($limit);
704 $result = $dbh->limitQuery($sql, $from, $count);
706 $result = $dbh->query($sql);
709 return new WikiDB_backend_PearDB_iter($this, $result);
713 * Find recent changes.
715 function most_recent($params) {
718 $include_minor_revisions = false;
719 $exclude_major_revisions = false;
720 $include_all_revisions = false;
724 extract($this->_table_names);
728 $pick[] = "mtime >= $since";
731 if ($include_all_revisions) {
732 // Include all revisions of each page.
733 $table = "$page_tbl, $version_tbl";
734 $join_clause = "$page_tbl.id=$version_tbl.id";
736 if ($exclude_major_revisions) {
737 // Include only minor revisions
738 $pick[] = "minor_edit <> 0";
740 elseif (!$include_minor_revisions) {
741 // Include only major revisions
742 $pick[] = "minor_edit = 0";
746 $table = "$page_tbl, $recent_tbl";
747 $join_clause = "$page_tbl.id=$recent_tbl.id";
748 $table .= ", $version_tbl";
749 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
751 if ($exclude_major_revisions) {
752 // Include only most recent minor revision
753 $pick[] = 'version=latestminor';
755 elseif (!$include_minor_revisions) {
756 // Include only most recent major revision
757 $pick[] = 'version=latestmajor';
760 // Include only the latest revision (whether major or minor).
761 $pick[] ='version=latestversion';
769 // $limitclause = $limit ? " LIMIT $limit" : '';
770 $where_clause = $join_clause;
772 $where_clause .= " AND " . join(" AND ", $pick);
774 // FIXME: use SQL_BUFFER_RESULT for mysql?
776 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
778 . " WHERE $where_clause"
779 . " ORDER BY mtime $order";
781 list($from, $count) = $this->limit($limit);
782 $result = $dbh->limitQuery($sql, $from, $count);
784 $result = $dbh->query($sql);
786 return new WikiDB_backend_PearDB_iter($this, $result);
790 * Find referenced empty pages.
792 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
794 extract($this->_table_names);
795 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
796 $orderby = 'ORDER BY ' . $orderby;
798 if ($exclude_from) // array of pagenames
799 $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
800 if ($exclude) // array of pagenames
801 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
803 $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
804 . " FROM $link_tbl,$page_tbl as linked "
805 . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
806 . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)"
807 . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
812 list($from, $count) = $this->limit($limit);
813 $result = $dbh->limitQuery($sql, $from, $count * 3);
815 $result = $dbh->query($sql);
817 return new WikiDB_backend_PearDB_generic_iter($this, $result);
820 function _sql_set(&$pagenames) {
822 foreach ($pagenames as $p) {
823 $s .= ("'".$this->_dbh->escapeSimple($p)."',");
825 return substr($s,0,-1).")";
829 * Rename page in the database.
831 function rename_page($pagename, $to) {
833 extract($this->_table_names);
836 if ( ($id = $this->_get_pageid($pagename, false)) ) {
837 if ($new = $this->_get_pageid($to, false)) {
839 //this page does not exist (already verified before), but exists in the page table.
840 //so we delete this page.
841 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
843 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
844 $dbh->escapeSimple($to)));
850 function _update_recent_table($pageid = false) {
852 extract($this->_table_names);
853 extract($this->_expressions);
855 $pageid = (int)$pageid;
858 $dbh->query("DELETE FROM $recent_tbl"
859 . ( $pageid ? " WHERE id=$pageid" : ""));
860 $dbh->query( "INSERT INTO $recent_tbl"
861 . " (id, latestversion, latestmajor, latestminor)"
862 . " SELECT id, $maxversion, $maxmajor, $maxminor"
863 . " FROM $version_tbl"
864 . ( $pageid ? " WHERE id=$pageid" : "")
869 function _update_nonempty_table($pageid = false) {
871 extract($this->_table_names);
873 $pageid = (int)$pageid;
875 extract($this->_expressions);
877 $dbh->query("DELETE FROM $nonempty_tbl"
878 . ( $pageid ? " WHERE id=$pageid" : ""));
879 $dbh->query("INSERT INTO $nonempty_tbl (id)"
880 . " SELECT $recent_tbl.id"
881 . " FROM $recent_tbl, $version_tbl"
882 . " WHERE $recent_tbl.id=$version_tbl.id"
883 . " AND version=latestversion"
884 // We have some specifics here (Oracle)
885 //. " AND content<>''"
886 . " AND content $notempty"
887 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
894 * Grab a write lock on the tables in the SQL database.
896 * Calls can be nested. The tables won't be unlocked until
897 * _unlock_database() is called as many times as _lock_database().
901 function lock($tables = false, $write_lock = true) {
902 if ($this->_lock_count++ == 0)
903 $this->_lock_tables($write_lock);
907 * Actually lock the required tables.
909 function _lock_tables($write_lock) {
910 trigger_error("virtual", E_USER_ERROR);
914 * Release a write lock on the tables in the SQL database.
918 * @param $force boolean Unlock even if not every call to lock() has been matched
919 * by a call to unlock().
921 * @see _lock_database
923 function unlock($tables = false, $force = false) {
924 if ($this->_lock_count == 0)
926 if (--$this->_lock_count <= 0 || $force) {
927 $this->_unlock_tables();
928 $this->_lock_count = 0;
933 * Actually unlock the required tables.
935 function _unlock_tables($write_lock) {
936 trigger_error("virtual", E_USER_ERROR);
943 function _serialize($data) {
946 assert(is_array($data));
947 return serialize($data);
953 function _unserialize($data) {
954 return empty($data) ? array() : unserialize($data);
958 * Callback for PEAR (DB) errors.
962 * @param A PEAR_error object.
964 function _pear_error_callback($error) {
965 if ($this->_is_false_error($error))
968 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
970 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
974 * Detect false errors messages from PEAR DB.
976 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
977 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
978 * return any data. (So when a "LOCK" command doesn't return any data,
979 * DB reports it as an error, when in fact, it's not.)
982 * @return bool True iff error is not really an error.
984 function _is_false_error($error) {
985 if ($error->getCode() != DB_ERROR)
988 $query = $this->_dbh->last_query;
990 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
991 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
992 // Last query was not of the sort which doesn't return any data.
993 //" <--kludge for brain-dead syntax coloring
997 if (! in_array('ismanip', get_class_methods('DB'))) {
998 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
999 // does not have the DB::isManip method.
1003 if (DB::isManip($query)) {
1004 // If Pear thinks it's an isManip then it wouldn't have thrown
1005 // the error we're testing for....
1012 function _pear_error_message($error) {
1013 $class = get_class($this);
1014 $message = "$class: fatal database error\n"
1015 . "\t" . $error->getMessage() . "\n"
1016 . "\t(" . $error->getDebugInfo() . ")\n";
1018 // Prevent password from being exposed during a connection error
1019 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1020 '\\1:XXXXXXXX', $this->_dsn);
1021 return str_replace($this->_dsn, $safe_dsn, $message);
1025 * Filter PHP errors notices from PEAR DB code.
1027 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1028 * errors and notices. This is an error callback (for use with
1029 * ErrorManager which will filter out those spurious messages.)
1030 * @see _is_false_error, ErrorManager
1033 function _pear_notice_filter($err) {
1034 return ( $err->isNotice()
1035 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1036 && $err->errline == 126
1037 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1040 /* some variables and functions for DB backend abstraction (action=upgrade) */
1041 function database () {
1042 return $this->_dbh->dsn['database'];
1044 function backendType() {
1045 return $this->_dbh->phptype;
1047 function connection() {
1048 return $this->_dbh->connection;
1051 function listOfTables() {
1052 return $this->_dbh->getListOf('tables');
1054 function listOfFields($database,$table) {
1055 if ($this->backendType() == 'mysql') {
1057 assert(!empty($database));
1058 assert(!empty($table));
1059 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1060 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1061 if (!$result) return array();
1062 $columns = mysql_num_fields($result);
1063 for ($i = 0; $i < $columns; $i++) {
1064 $fields[] = mysql_field_name($result, $i);
1066 mysql_free_result($result);
1069 // TODO: try ADODB version?
1070 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1077 * This class is a generic iterator.
1079 * WikiDB_backend_PearDB_iter only iterates over things that have
1080 * 'pagename', 'pagedata', etc. etc.
1082 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1083 * (most of the code is cut-and-paste :-( ), but I am trying to make
1084 * changes that could be merged easily.
1086 * @author: Dan Frankowski
1088 class WikiDB_backend_PearDB_generic_iter
1089 extends WikiDB_backend_iterator
1091 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1092 if (DB::isError($query_result)) {
1093 // This shouldn't happen, I thought.
1094 $backend->_pear_error_callback($query_result);
1097 $this->_backend = &$backend;
1098 $this->_result = $query_result;
1102 if (!$this->_result)
1104 return $this->_result->numRows();
1108 $backend = &$this->_backend;
1109 if (!$this->_result)
1112 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1122 if ($this->_result) {
1123 $this->_result->free();
1124 $this->_result = false;
1129 class WikiDB_backend_PearDB_iter
1130 extends WikiDB_backend_PearDB_generic_iter
1134 $backend = &$this->_backend;
1135 if (!$this->_result)
1138 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1144 $pagedata = $backend->_extract_page_data($record);
1145 $rec = array('pagename' => $record['pagename'],
1146 'pagedata' => $pagedata);
1148 if (!empty($record['version'])) {
1149 $rec['versiondata'] = $backend->_extract_version_data($record);
1150 $rec['version'] = $record['version'];
1158 class WikiDB_backend_PearDB_search
1159 extends WikiDB_backend_search
1161 function WikiDB_backend_PearDB_search(&$search, &$dbh) {
1163 $this->_case_exact = $search->_case_exact;
1165 function _pagename_match_clause($node) {
1166 $word = $node->sql();
1167 if ($node->op == 'REGEX') { // posix regex extensions
1168 if (preg_match("/mysql/i", $this->_dbh->phptype))
1169 return "pagename REGEXP '$word'";
1171 return $this->_case_exact ? "pagename LIKE '$word'"
1172 : "LOWER(pagename) LIKE '$word'";
1175 function _fulltext_match_clause($node) {
1176 $word = $node->sql();
1177 return $this->_pagename_match_clause($node)
1178 // probably convert this MATCH AGAINST or SUBSTR/POSITION without wildcards
1179 . ($this->_case_exact ? " OR content LIKE '$word'"
1180 : " OR LOWER(content) LIKE '$word'");
1184 // $Log: not supported by cvs2svn $
1185 // Revision 1.76 2004/11/30 17:45:53 rurban
1186 // exists_links backend implementation
1188 // Revision 1.75 2004/11/28 20:42:33 rurban
1189 // Optimize PearDB _extract_version_data and _extract_page_data.
1191 // Revision 1.74 2004/11/27 14:39:05 rurban
1192 // simpified regex search architecture:
1193 // no db specific node methods anymore,
1194 // new sql() method for each node
1195 // parallel to regexp() (which returns pcre)
1196 // regex types bitmasked (op's not yet)
1198 // clarified WikiDB::quote() backend methods:
1199 // ->quote() adds surrounsing quotes
1200 // ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1201 // pear and adodb have now unified quote methods for all generic queries.
1203 // Revision 1.73 2004/11/26 18:39:02 rurban
1204 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1206 // Revision 1.72 2004/11/25 17:20:51 rurban
1207 // and again a couple of more native db args: backlinks
1209 // Revision 1.71 2004/11/23 13:35:48 rurban
1210 // add case_exact search
1212 // Revision 1.70 2004/11/21 11:59:26 rurban
1213 // remove final \n to be ob_cache independent
1215 // Revision 1.69 2004/11/20 17:49:39 rurban
1216 // add fast exclude support to SQL get_all_pages
1218 // Revision 1.68 2004/11/20 17:35:58 rurban
1219 // improved WantedPages SQL backends
1220 // PageList::sortby new 3rd arg valid_fields (override db fields)
1221 // WantedPages sql pager inexact for performance reasons:
1222 // assume 3 wantedfrom per page, to be correct, no getTotal()
1223 // support exclude argument for get_all_pages, new _sql_set()
1225 // Revision 1.67 2004/11/10 19:32:24 rurban
1226 // * optimize increaseHitCount, esp. for mysql.
1227 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1228 // * Pear_DB version logic (awful but needed)
1229 // * fix broken ADODB quote
1230 // * _extract_page_data simplification
1232 // Revision 1.66 2004/11/10 15:29:21 rurban
1233 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1234 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1235 // * WikiDB: moved SQL specific methods upwards
1236 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1237 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1239 // Revision 1.65 2004/11/09 17:11:17 rurban
1240 // * revert to the wikidb ref passing. there's no memory abuse there.
1241 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1242 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1243 // are also needed at the rendering for linkExistingWikiWord().
1244 // pass options to pageiterator.
1245 // use this cache also for _get_pageid()
1246 // This saves about 8 SELECT count per page (num all pagelinks).
1247 // * fix passing of all page fields to the pageiterator.
1248 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1250 // Revision 1.64 2004/11/07 16:02:52 rurban
1251 // new sql access log (for spam prevention), and restructured access log class
1252 // dbh->quote (generic)
1253 // pear_db: mysql specific parts seperated (using replace)
1255 // Revision 1.63 2004/11/01 10:43:58 rurban
1256 // seperate PassUser methods into seperate dir (memory usage)
1257 // fix WikiUser (old) overlarge data session
1258 // remove wikidb arg from various page class methods, use global ->_dbi instead
1261 // Revision 1.62 2004/10/14 19:19:34 rurban
1262 // loadsave: check if the dumped file will be accessible from outside.
1263 // and some other minor fixes. (cvsclient native not yet ready)
1265 // Revision 1.61 2004/10/14 17:19:17 rurban
1266 // allow most_popular sortby arguments
1268 // Revision 1.60 2004/07/09 10:06:50 rurban
1269 // Use backend specific sortby and sortable_columns method, to be able to
1270 // select between native (Db backend) and custom (PageList) sorting.
1271 // Fixed PageList::AddPageList (missed the first)
1272 // Added the author/creator.. name to AllPagesBy...
1273 // display no pages if none matched.
1274 // Improved dba and file sortby().
1275 // Use &$request reference
1277 // Revision 1.59 2004/07/08 21:32:36 rurban
1278 // Prevent from more warnings, minor db and sort optimizations
1280 // Revision 1.58 2004/07/08 16:56:16 rurban
1281 // use the backendType abstraction
1283 // Revision 1.57 2004/07/05 12:57:54 rurban
1284 // add mysql timeout
1286 // Revision 1.56 2004/07/04 10:24:43 rurban
1287 // forgot the expressions
1289 // Revision 1.55 2004/07/03 16:51:06 rurban
1290 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1291 // added atomic mysql REPLACE for PearDB as in ADODB
1292 // fixed _lock_tables typo links => link
1293 // fixes unserialize ADODB bug in line 180
1295 // Revision 1.54 2004/06/29 08:52:24 rurban
1296 // Use ...version() $need_content argument in WikiDB also:
1297 // To reduce the memory footprint for larger sets of pagelists,
1298 // we don't cache the content (only true or false) and
1299 // we purge the pagedata (_cached_html) also.
1300 // _cached_html is only cached for the current pagename.
1301 // => Vastly improved page existance check, ACL check, ...
1303 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1305 // Revision 1.53 2004/06/27 10:26:03 rurban
1306 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1308 // Revision 1.52 2004/06/25 14:15:08 rurban
1309 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1311 // Revision 1.51 2004/05/12 10:49:55 rurban
1312 // require_once fix for those libs which are loaded before FileFinder and
1313 // its automatic include_path fix, and where require_once doesn't grok
1314 // dirname(__FILE__) != './lib'
1315 // upgrade fix with PearDB
1316 // navbar.tmpl: remove spaces for IE button alignment
1318 // Revision 1.50 2004/05/06 17:30:39 rurban
1319 // CategoryGroup: oops, dos2unix eol
1320 // improved phpwiki_version:
1321 // pre -= .0001 (1.3.10pre: 1030.099)
1322 // -p1 += .001 (1.3.9-p1: 1030.091)
1323 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1324 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1325 // backend->backendType(), backend->database(),
1326 // backend->listOfFields(),
1327 // backend->listOfTables(),
1329 // Revision 1.49 2004/05/03 21:35:30 rurban
1330 // don't use persistent connections with postgres
1332 // Revision 1.48 2004/04/26 20:44:35 rurban
1333 // locking table specific for better databases
1335 // Revision 1.47 2004/04/20 00:06:04 rurban
1336 // themable paging support
1338 // Revision 1.46 2004/04/19 21:51:41 rurban
1339 // php5 compatibility: it works!
1341 // Revision 1.45 2004/04/16 14:19:39 rurban
1342 // updated ADODB notes
1345 // (c-file-style: "gnu")
1349 // c-basic-offset: 4
1350 // c-hanging-comment-ender-p: nil
1351 // indent-tabs-mode: nil