2 rcs_id('$Id: PearDB.php,v 1.103 2006-12-03 17:11: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 // TODO: apparently some Pear::Db version adds LIMIT 1,0 to getOne(),
20 // which is invalid for "select version()"
21 if (!in_array($name, get_class_methods("DB_common"))) {
22 $finder = new FileFinder;
23 $dir = dirname(__FILE__)."/../../pear";
24 $finder->_prepend_to_include_path($dir);
25 include_once("$dir/DB/common.php"); // use our version instead.
26 if (!in_array($name, get_class_methods("DB_common"))) {
27 $pearFinder = new PearFileFinder("lib/pear");
28 $pearFinder->includeOnce('DB.php');
30 include_once("$dir/DB.php");
33 include_once("DB.php");
36 // Install filter to handle bogus error notices from buggy DB.php's.
37 // TODO: check the Pear_DB version, but how?
40 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
41 $this->_pearerrhandler = true;
44 // Open connection to database
45 $this->_dsn = $dbparams['dsn'];
46 $this->_dbparams = $dbparams;
47 $this->_lock_count = 0;
49 // persistent is usually a DSN option: we override it with a config value.
50 // phptype://username:password@hostspec/database?persistent=false
51 $dboptions = array('persistent' => DATABASE_PERSISTENT,
53 //if (preg_match('/^pgsql/', $this->_dsn)) $dboptions['persistent'] = false;
54 $this->_dbh = DB::connect($this->_dsn, $dboptions);
56 if (DB::isError($dbh)) {
57 trigger_error(sprintf("Can't connect to database: %s",
58 $this->_pear_error_message($dbh)),
61 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
62 array($this, '_pear_error_callback'));
63 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
65 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
67 = array('page_tbl' => $prefix . 'page',
68 'version_tbl' => $prefix . 'version',
69 'link_tbl' => $prefix . 'link',
70 'recent_tbl' => $prefix . 'recent',
71 'nonempty_tbl' => $prefix . 'nonempty');
72 $page_tbl = $this->_table_names['page_tbl'];
73 $version_tbl = $this->_table_names['version_tbl'];
74 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
75 $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, ".
76 "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
79 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
80 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
81 'maxversion' => "MAX(version)",
83 'iscontent' => "content<>''");
88 * Close database connection.
93 if ($this->_lock_count) {
94 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
97 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
98 $this->unlock('force');
100 $this->_dbh->disconnect();
102 if (!empty($this->_pearerrhandler)) {
103 $GLOBALS['ErrorManager']->popErrorHandler();
109 * Test fast wikipage.
111 function is_wiki_page($pagename) {
113 extract($this->_table_names);
114 return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
115 . " FROM $nonempty_tbl, $page_tbl"
116 . " WHERE $nonempty_tbl.id=$page_tbl.id"
117 . " AND pagename='%s'",
118 $dbh->escapeSimple($pagename)));
121 function get_all_pagenames() {
123 extract($this->_table_names);
124 return $dbh->getCol("SELECT pagename"
125 . " FROM $nonempty_tbl, $page_tbl"
126 . " WHERE $nonempty_tbl.id=$page_tbl.id");
129 function numPages($filter=false, $exclude='') {
131 extract($this->_table_names);
132 return $dbh->getOne("SELECT count(*)"
133 . " FROM $nonempty_tbl, $page_tbl"
134 . " WHERE $nonempty_tbl.id=$page_tbl.id");
137 function increaseHitCount($pagename) {
139 // Hits is the only thing we can update in a fast manner.
140 // Note that this will fail silently if the page does not
141 // have a record in the page table. Since it's just the
142 // hit count, who cares?
143 $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
144 $this->_table_names['page_tbl'],
145 $dbh->escapeSimple($pagename)));
150 * Read page information from database.
152 function get_pagedata($pagename) {
154 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
155 $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'",
156 $this->_table_names['page_tbl'],
157 $dbh->escapeSimple($pagename)),
159 return $result ? $this->_extract_page_data($result) : false;
162 function _extract_page_data($data) {
163 if (empty($data)) return array();
164 elseif (empty($data['pagedata'])) return $data;
166 $data = array_merge($data, $this->_unserialize($data['pagedata']));
167 unset($data['pagedata']);
172 function update_pagedata($pagename, $newdata) {
174 $page_tbl = $this->_table_names['page_tbl'];
176 // Hits is the only thing we can update in a fast manner.
177 if (count($newdata) == 1 && isset($newdata['hits'])) {
178 // Note that this will fail silently if the page does not
179 // have a record in the page table. Since it's just the
180 // hit count, who cares?
181 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
182 $newdata['hits'], $dbh->escapeSimple($pagename)));
186 $this->lock(array($page_tbl), true);
187 $data = $this->get_pagedata($pagename);
190 $this->_get_pageid($pagename, true); // Creates page record
193 @$hits = (int)$data['hits'];
194 unset($data['hits']);
196 foreach ($newdata as $key => $val) {
199 else if (empty($val))
205 /* Portability issue -- not all DBMS supports huge strings
206 * so we need to 'bind' instead of building a simple SQL statment.
207 * Note that we do not need to escapeSimple when we bind
208 $dbh->query(sprintf("UPDATE $page_tbl"
209 . " SET hits=%d, pagedata='%s'"
210 . " WHERE pagename='%s'",
212 $dbh->escapeSimple($this->_serialize($data)),
213 $dbh->escapeSimple($pagename)));
215 $dbh->query("UPDATE $page_tbl"
216 . " SET hits=?, pagedata=?"
217 . " WHERE pagename=?",
218 array($hits, $this->_serialize($data), $pagename));
219 $this->unlock(array($page_tbl));
222 function get_cached_html($pagename) {
224 $page_tbl = $this->_table_names['page_tbl'];
225 return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'",
226 $dbh->escapeSimple($pagename)));
229 function set_cached_html($pagename, $data) {
231 $page_tbl = $this->_table_names['page_tbl'];
232 $dbh->query("UPDATE $page_tbl"
233 . " SET cached_html=?"
234 . " WHERE pagename=?",
235 array($data, $pagename));
238 function _get_pageid($pagename, $create_if_missing = false) {
242 $cache =& $request->_dbi->_cache->_id_cache;
243 if (isset($cache[$pagename])) {
244 if ($cache[$pagename] or !$create_if_missing) {
245 return $cache[$pagename];
250 $page_tbl = $this->_table_names['page_tbl'];
252 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
253 $dbh->escapeSimple($pagename));
255 if (!$create_if_missing)
256 return $dbh->getOne($query);
258 $id = $dbh->getOne($query);
260 $this->lock(array($page_tbl), true); // write lock
261 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
263 // requires createSequence and on mysql lock the interim table ->getSequenceName
264 //$id = $dbh->nextId($page_tbl . "_id");
265 $dbh->query(sprintf("INSERT INTO $page_tbl"
266 . " (id,pagename,hits)"
267 . " VALUES (%d,'%s',0)",
268 $id, $dbh->escapeSimple($pagename)));
269 $this->unlock(array($page_tbl));
274 function get_latest_version($pagename) {
276 extract($this->_table_names);
278 (int)$dbh->getOne(sprintf("SELECT latestversion"
279 . " FROM $page_tbl, $recent_tbl"
280 . " WHERE $page_tbl.id=$recent_tbl.id"
281 . " AND pagename='%s'",
282 $dbh->escapeSimple($pagename)));
285 function get_previous_version($pagename, $version) {
287 extract($this->_table_names);
290 (int)$dbh->getOne(sprintf("SELECT version"
291 . " FROM $version_tbl, $page_tbl"
292 . " WHERE $version_tbl.id=$page_tbl.id"
293 . " AND pagename='%s'"
294 . " AND version < %d"
295 . " ORDER BY version DESC",
296 /* Non portable and useless anyway with getOne
299 $dbh->escapeSimple($pagename),
306 * @param $version int Which version to get.
308 * @return hash The version data, or false if specified version does not
311 function get_versiondata($pagename, $version, $want_content = false) {
313 extract($this->_table_names);
314 extract($this->_expressions);
316 assert(is_string($pagename) and $pagename != "");
317 assert($version > 0);
319 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
320 // FIXME: optimization: sometimes don't get page data?
322 $fields = $this->page_tbl_fields
323 . ",$page_tbl.pagedata as pagedata,"
324 . $this->version_tbl_fields;
327 $fields = $this->page_tbl_fields . ","
328 . "mtime, minor_edit, versiondata,"
329 . "$iscontent AS have_content";
332 $result = $dbh->getRow(sprintf("SELECT $fields"
333 . " FROM $page_tbl, $version_tbl"
334 . " WHERE $page_tbl.id=$version_tbl.id"
335 . " AND pagename='%s'"
337 $dbh->escapeSimple($pagename), $version),
340 return $this->_extract_version_data($result);
343 function _extract_version_data($query_result) {
347 /* Earlier versions (<= 1.3.7) stored the version data in base64.
348 This could be done here or in upgrade.
350 if (!strstr($query_result['versiondata'], ":")) {
351 $query_result['versiondata'] =
352 base64_decode($query_result['versiondata']);
354 $data = $this->_unserialize($query_result['versiondata']);
356 $data['mtime'] = $query_result['mtime'];
357 $data['is_minor_edit'] = !empty($query_result['minor_edit']);
359 if (isset($query_result['content']))
360 $data['%content'] = $query_result['content'];
361 elseif ($query_result['have_content'])
362 $data['%content'] = true;
364 $data['%content'] = '';
366 // FIXME: this is ugly.
367 if (isset($query_result['pagedata'])) {
368 // Query also includes page data.
369 // We might as well send that back too...
370 unset($query_result['versiondata']);
371 $data['%pagedata'] = $this->_extract_page_data($query_result);
379 * Create a new revision of a page.
381 function set_versiondata($pagename, $version, $data) {
383 $version_tbl = $this->_table_names['version_tbl'];
385 $minor_edit = (int) !empty($data['is_minor_edit']);
386 unset($data['is_minor_edit']);
388 $mtime = (int)$data['mtime'];
389 unset($data['mtime']);
390 assert(!empty($mtime));
392 @$content = (string) $data['%content'];
393 unset($data['%content']);
395 unset($data['%pagedata']);
398 $id = $this->_get_pageid($pagename, true);
400 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
401 $dbh->query(sprintf("DELETE FROM $version_tbl"
402 . " WHERE id=%d AND version=%d",
405 /* mysql optimized version.
406 $dbh->query(sprintf("INSERT INTO $version_tbl"
407 . " (id,version,mtime,minor_edit,content,versiondata)"
408 . " VALUES(%d,%d,%d,%d,'%s','%s')",
409 $id, $version, $mtime, $minor_edit,
410 $dbh->quoteSmart($content),
411 $dbh->quoteSmart($this->_serialize($data))));
413 // generic slow PearDB bind eh quoting.
414 $dbh->query("INSERT INTO $version_tbl"
415 . " (id,version,mtime,minor_edit,content,versiondata)"
416 . " VALUES(?, ?, ?, ?, ?, ?)",
417 array($id, $version, $mtime, $minor_edit, $content,
418 $this->_serialize($data)));
420 $this->_update_recent_table($id);
421 $this->_update_nonempty_table($id);
427 * Delete an old revision of a page.
429 function delete_versiondata($pagename, $version) {
431 extract($this->_table_names);
434 if ( ($id = $this->_get_pageid($pagename)) ) {
435 $dbh->query("DELETE FROM $version_tbl"
436 . " WHERE id=$id AND version=$version");
437 $this->_update_recent_table($id);
438 // This shouldn't be needed (as long as the latestversion
439 // never gets deleted.) But, let's be safe.
440 $this->_update_nonempty_table($id);
446 * Delete page from the database with backup possibility.
447 * i.e save_page('') and DELETE nonempty id
448 * Can be undone and is seen in RecentChanges.
450 /* // see parent backend.php
451 function delete_page($pagename) {
453 $user =& $GLOBALS['request']->_user;
454 $vdata = array('author' => $user->getId(),
455 'author_id' => $user->getAuthenticatedId(),
459 $version = $this->get_latest_version($pagename);
460 $this->set_versiondata($pagename, $version+1, $vdata);
461 $this->set_links($pagename, false);
462 $pagedata = get_pagedata($pagename);
463 $this->update_pagedata($pagename, array('hits' => $pagedata['hits']));
469 * Delete page completely from the database.
470 * I'm not sure if this is what we want. Maybe just delete the revisions
472 function purge_page($pagename) {
474 extract($this->_table_names);
477 if ( ($id = $this->_get_pageid($pagename, false)) ) {
478 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
479 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
480 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
481 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
482 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
484 // We're still in the link table (dangling link) so we can't delete this
486 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
490 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
493 $this->_update_recent_table();
494 $this->_update_nonempty_table();
496 $result = -1; // already purged or not existing
502 // The only thing we might be interested in updating which we can
503 // do fast in the flags (minor_edit). I think the default
504 // update_versiondata will work fine...
505 //function update_versiondata($pagename, $version, $data) {
508 function set_links($pagename, $links) {
509 // Update link table.
510 // FIXME: optimize: mysql can do this all in one big INSERT.
513 extract($this->_table_names);
516 $pageid = $this->_get_pageid($pagename, true);
518 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
521 foreach ($links as $link) {
522 $linkto = $link['linkto'];
523 if ($link['relation'])
524 $relation = $this->_get_pageid($link['relation'], true);
528 if (isset($linkseen[$linkto]) and !$relation)
531 $linkseen[$linkto] = true;
532 $linkid = $this->_get_pageid($linkto, true);
534 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
535 . " VALUES ($pageid, $linkid, $relation)");
542 * Find pages which link to or are linked from a page.
544 * TESTME relations: get_links is responsible to add the relation to the pagehash
545 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
546 * if (isset($next['linkrelation']))
548 function get_links($pagename, $reversed=true, $include_empty=false,
549 $sortby=false, $limit=false, $exclude='',
550 $want_relations = false)
553 extract($this->_table_names);
556 list($have,$want) = array('linkee', 'linker');
558 list($have,$want) = array('linker', 'linkee');
559 $orderby = $this->sortby($sortby, 'db', array('pagename'));
560 if ($orderby) $orderby = ' ORDER BY $want.' . $orderby;
561 if ($exclude) // array of pagenames
562 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
566 $qpagename = $dbh->escapeSimple($pagename);
567 $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
568 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
570 . (!$include_empty ? "$nonempty_tbl, " : '')
571 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
572 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
573 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
574 . " AND $have.pagename='$qpagename'"
575 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
576 //. " GROUP BY $want.id"
580 // extract from,count from limit
581 list($from,$count) = $this->limit($limit);
582 $result = $dbh->limitQuery($sql, $from, $count);
584 $result = $dbh->query($sql);
587 return new WikiDB_backend_PearDB_iter($this, $result);
591 * Find if a page links to another page
593 function exists_link($pagename, $link, $reversed=false) {
595 extract($this->_table_names);
598 list($have, $want) = array('linkee', 'linker');
600 list($have, $want) = array('linker', 'linkee');
601 $qpagename = $dbh->escapeSimple($pagename);
602 $qlink = $dbh->escapeSimple($link);
603 $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result"
604 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
605 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
606 . " AND $have.pagename='$qpagename'"
607 . " AND $want.pagename='$qlink'");
608 return $row['result'];
611 function get_all_pages($include_empty=false, $sortby=false, $limit=false, $exclude='') {
613 extract($this->_table_names);
614 $orderby = $this->sortby($sortby, 'db');
615 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
616 if ($exclude) // array of pagenames
617 $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
621 if (strstr($orderby, 'mtime ')) { // multiple columns possible
622 if ($include_empty) {
624 . $this->page_tbl_fields
625 . " FROM $page_tbl, $recent_tbl, $version_tbl"
626 . " WHERE $page_tbl.id=$recent_tbl.id"
627 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
633 . $this->page_tbl_fields
634 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
635 . " WHERE $nonempty_tbl.id=$page_tbl.id"
636 . " AND $page_tbl.id=$recent_tbl.id"
637 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
642 if ($include_empty) {
644 . $this->page_tbl_fields
646 . ($exclude ? " WHERE $exclude" : '')
651 . $this->page_tbl_fields
652 . " FROM $nonempty_tbl, $page_tbl"
653 . " WHERE $nonempty_tbl.id=$page_tbl.id"
659 // extract from,count from limit
660 list($from,$count) = $this->limit($limit);
661 $result = $dbh->limitQuery($sql, $from, $count);
663 $result = $dbh->query($sql);
665 return new WikiDB_backend_PearDB_iter($this, $result);
672 function text_search($search, $fulltext=false, $sortby=false, $limit=false,
676 extract($this->_table_names);
677 $orderby = $this->sortby($sortby, 'db');
678 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
679 //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
681 $searchclass = get_class($this)."_search";
682 // no need to define it everywhere and then fallback. memory!
683 if (!class_exists($searchclass))
684 $searchclass = "WikiDB_backend_PearDB_search";
685 $searchobj = new $searchclass($search, $dbh);
687 $table = "$nonempty_tbl, $page_tbl";
688 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
689 $fields = $this->page_tbl_fields;
692 $table .= ", $recent_tbl";
693 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
695 $table .= ", $version_tbl";
696 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
698 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
699 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
701 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
703 $search_clause = $search->makeSqlClauseObj($callback);
705 $sql = "SELECT $fields FROM $table"
706 . " WHERE $join_clause"
707 . " AND ($search_clause)"
710 list($from, $count) = $this->limit($limit);
711 $result = $dbh->limitQuery($sql, $from, $count);
713 $result = $dbh->query($sql);
716 $iter = new WikiDB_backend_PearDB_iter($this, $result);
717 $iter->stoplisted = @$searchobj->stoplisted;
721 //Todo: check if the better Mysql MATCH operator is supported,
722 // (ranked search) and also google like expressions.
723 function _sql_match_clause($word) {
724 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
725 $word = $this->_dbh->escapeSimple($word);
726 //$page_tbl = $this->_table_names['page_tbl'];
727 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
728 // e.g. if word is lowercased.
729 // http://bugs.mysql.com/bug.php?id=1491
730 return "LOWER(pagename) LIKE '%$word%'";
732 function _sql_casematch_clause($word) {
733 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
734 $word = $this->_dbh->escapeSimple($word);
735 return "pagename LIKE '%$word%'";
737 function _fullsearch_sql_match_clause($word) {
738 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
739 $word = $this->_dbh->escapeSimple($word);
740 //$page_tbl = $this->_table_names['page_tbl'];
741 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
742 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
744 function _fullsearch_sql_casematch_clause($word) {
745 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
746 $word = $this->_dbh->escapeSimple($word);
747 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
751 * Find highest or lowest hit counts.
753 function most_popular($limit=20, $sortby='-hits') {
755 extract($this->_table_names);
761 $order = "hits DESC";
762 $where = " AND hits > 0";
765 if ($sortby != '-hits') {
766 if ($order = $this->sortby($sortby, 'db'))
767 $orderby = " ORDER BY " . $order;
769 $orderby = " ORDER BY $order";
771 //$limitclause = $limit ? " LIMIT $limit" : '';
773 . $this->page_tbl_fields
774 . " FROM $nonempty_tbl, $page_tbl"
775 . " WHERE $nonempty_tbl.id=$page_tbl.id"
779 list($from, $count) = $this->limit($limit);
780 $result = $dbh->limitQuery($sql, $from, $count);
782 $result = $dbh->query($sql);
785 return new WikiDB_backend_PearDB_iter($this, $result);
789 * Find recent changes.
791 function most_recent($params) {
794 $include_minor_revisions = false;
795 $exclude_major_revisions = false;
796 $include_all_revisions = false;
800 extract($this->_table_names);
804 $pick[] = "mtime >= $since";
807 if ($include_all_revisions) {
808 // Include all revisions of each page.
809 $table = "$page_tbl, $version_tbl";
810 $join_clause = "$page_tbl.id=$version_tbl.id";
812 if ($exclude_major_revisions) {
813 // Include only minor revisions
814 $pick[] = "minor_edit <> 0";
816 elseif (!$include_minor_revisions) {
817 // Include only major revisions
818 $pick[] = "minor_edit = 0";
822 $table = "$page_tbl, $recent_tbl";
823 $join_clause = "$page_tbl.id=$recent_tbl.id";
824 $table .= ", $version_tbl";
825 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
827 if ($exclude_major_revisions) {
828 // Include only most recent minor revision
829 $pick[] = 'version=latestminor';
831 elseif (!$include_minor_revisions) {
832 // Include only most recent major revision
833 $pick[] = 'version=latestmajor';
836 // Include only the latest revision (whether major or minor).
837 $pick[] ='version=latestversion';
845 // $limitclause = $limit ? " LIMIT $limit" : '';
846 $where_clause = $join_clause;
848 $where_clause .= " AND " . join(" AND ", $pick);
850 // FIXME: use SQL_BUFFER_RESULT for mysql?
852 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
854 . " WHERE $where_clause"
855 . " ORDER BY mtime $order";
857 list($from, $count) = $this->limit($limit);
858 $result = $dbh->limitQuery($sql, $from, $count);
860 $result = $dbh->query($sql);
862 return new WikiDB_backend_PearDB_iter($this, $result);
866 * Find referenced empty pages.
868 function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
870 extract($this->_table_names);
871 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
872 $orderby = 'ORDER BY ' . $orderby;
874 if ($exclude_from) // array of pagenames
875 $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
876 if ($exclude) // array of pagenames
877 $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
878 $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
879 . " FROM $page_tbl p, $link_tbl linked"
880 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
881 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
882 . " WHERE ne.id IS NULL"
883 . " AND p.id = linked.linkfrom"
888 // oci8 error: WHERE NULL = NULL appended
889 list($from, $count) = $this->limit($limit);
890 $result = $dbh->limitQuery($sql, $from, $count * 3);
892 $result = $dbh->query($sql);
894 return new WikiDB_backend_PearDB_generic_iter($this, $result);
897 function _sql_set(&$pagenames) {
899 foreach ($pagenames as $p) {
900 $s .= ("'".$this->_dbh->escapeSimple($p)."',");
902 return substr($s,0,-1).")";
906 * Rename page in the database.
908 function rename_page ($pagename, $to) {
910 extract($this->_table_names);
913 if (($id = $this->_get_pageid($pagename, false)) ) {
914 if ($new = $this->_get_pageid($to, false)) {
916 // This page does not exist (already verified before), but exists in the page table.
917 // So we delete this page.
918 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
919 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
920 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
921 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
922 // We have to fix all referring tables to the old id
923 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
924 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
926 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
927 $dbh->escapeSimple($to)));
933 function _update_recent_table($pageid = false) {
935 extract($this->_table_names);
936 extract($this->_expressions);
938 $pageid = (int)$pageid;
941 $dbh->query("DELETE FROM $recent_tbl"
942 . ( $pageid ? " WHERE id=$pageid" : ""));
943 $dbh->query( "INSERT INTO $recent_tbl"
944 . " (id, latestversion, latestmajor, latestminor)"
945 . " SELECT id, $maxversion, $maxmajor, $maxminor"
946 . " FROM $version_tbl"
947 . ( $pageid ? " WHERE id=$pageid" : "")
952 function _update_nonempty_table($pageid = false) {
954 extract($this->_table_names);
956 $pageid = (int)$pageid;
958 extract($this->_expressions);
960 $dbh->query("DELETE FROM $nonempty_tbl"
961 . ( $pageid ? " WHERE id=$pageid" : ""));
962 $dbh->query("INSERT INTO $nonempty_tbl (id)"
963 . " SELECT $recent_tbl.id"
964 . " FROM $recent_tbl, $version_tbl"
965 . " WHERE $recent_tbl.id=$version_tbl.id"
966 . " AND version=latestversion"
967 // We have some specifics here (Oracle)
968 //. " AND content<>''"
969 . " AND content $notempty"
970 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
977 * Grab a write lock on the tables in the SQL database.
979 * Calls can be nested. The tables won't be unlocked until
980 * _unlock_database() is called as many times as _lock_database().
984 function lock($tables = false, $write_lock = true) {
985 if ($this->_lock_count++ == 0)
986 $this->_lock_tables($write_lock);
990 * Actually lock the required tables.
992 function _lock_tables($write_lock) {
993 trigger_error("virtual", E_USER_ERROR);
997 * Release a write lock on the tables in the SQL database.
1001 * @param $force boolean Unlock even if not every call to lock() has been matched
1002 * by a call to unlock().
1004 * @see _lock_database
1006 function unlock($tables = false, $force = false) {
1007 if ($this->_lock_count == 0)
1009 if (--$this->_lock_count <= 0 || $force) {
1010 $this->_unlock_tables();
1011 $this->_lock_count = 0;
1016 * Actually unlock the required tables.
1018 function _unlock_tables($write_lock) {
1019 trigger_error("virtual", E_USER_ERROR);
1026 function _serialize($data) {
1029 assert(is_array($data));
1030 return serialize($data);
1036 function _unserialize($data) {
1037 return empty($data) ? array() : unserialize($data);
1041 * Callback for PEAR (DB) errors.
1045 * @param A PEAR_error object.
1047 function _pear_error_callback($error) {
1048 if ($this->_is_false_error($error))
1051 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
1053 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1057 * Detect false errors messages from PEAR DB.
1059 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1060 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1061 * return any data. (So when a "LOCK" command doesn't return any data,
1062 * DB reports it as an error, when in fact, it's not.)
1065 * @return bool True iff error is not really an error.
1067 function _is_false_error($error) {
1068 if ($error->getCode() != DB_ERROR)
1071 $query = $this->_dbh->last_query;
1073 if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1074 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
1075 // Last query was not of the sort which doesn't return any data.
1076 //" <--kludge for brain-dead syntax coloring
1080 if (! in_array('ismanip', get_class_methods('DB'))) {
1081 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1082 // does not have the DB::isManip method.
1086 if (DB::isManip($query)) {
1087 // If Pear thinks it's an isManip then it wouldn't have thrown
1088 // the error we're testing for....
1095 function _pear_error_message($error) {
1096 $class = get_class($this);
1097 $message = "$class: fatal database error\n"
1098 . "\t" . $error->getMessage() . "\n"
1099 . "\t(" . $error->getDebugInfo() . ")\n";
1101 // Prevent password from being exposed during a connection error
1102 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1103 '\\1:XXXXXXXX', $this->_dsn);
1104 return str_replace($this->_dsn, $safe_dsn, $message);
1108 * Filter PHP errors notices from PEAR DB code.
1110 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1111 * errors and notices. This is an error callback (for use with
1112 * ErrorManager which will filter out those spurious messages.)
1113 * @see _is_false_error, ErrorManager
1116 function _pear_notice_filter($err) {
1117 return ( $err->isNotice()
1118 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1119 && $err->errline == 126
1120 && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1123 /* some variables and functions for DB backend abstraction (action=upgrade) */
1124 function database () {
1125 return $this->_dbh->dsn['database'];
1127 function backendType() {
1128 return $this->_dbh->phptype;
1130 function connection() {
1131 return $this->_dbh->connection;
1133 function getRow($query) {
1134 return $this->_dbh->getRow($query);
1137 function listOfTables() {
1138 return $this->_dbh->getListOf('tables');
1140 function listOfFields($database,$table) {
1141 if ($this->backendType() == 'mysql') {
1143 assert(!empty($database));
1144 assert(!empty($table));
1145 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1146 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1147 if (!$result) return array();
1148 $columns = mysql_num_fields($result);
1149 for ($i = 0; $i < $columns; $i++) {
1150 $fields[] = mysql_field_name($result, $i);
1152 mysql_free_result($result);
1155 // TODO: try ADODB version?
1156 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1163 * This class is a generic iterator.
1165 * WikiDB_backend_PearDB_iter only iterates over things that have
1166 * 'pagename', 'pagedata', etc. etc.
1168 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1169 * (most of the code is cut-and-paste :-( ), but I am trying to make
1170 * changes that could be merged easily.
1172 * @author: Dan Frankowski
1174 class WikiDB_backend_PearDB_generic_iter
1175 extends WikiDB_backend_iterator
1177 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1178 if (DB::isError($query_result)) {
1179 // This shouldn't happen, I thought.
1180 $backend->_pear_error_callback($query_result);
1183 $this->_backend = &$backend;
1184 $this->_result = $query_result;
1188 if (!$this->_result)
1190 return $this->_result->numRows();
1194 if (!$this->_result)
1197 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1207 if ($this->_result) {
1208 $this->_result->free();
1209 $this->_result = false;
1214 class WikiDB_backend_PearDB_iter
1215 extends WikiDB_backend_PearDB_generic_iter
1219 $backend = &$this->_backend;
1220 if (!$this->_result)
1223 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1229 $pagedata = $backend->_extract_page_data($record);
1230 $rec = array('pagename' => $record['pagename'],
1231 'pagedata' => $pagedata);
1233 if (!empty($record['version'])) {
1234 $rec['versiondata'] = $backend->_extract_version_data($record);
1235 $rec['version'] = $record['version'];
1242 class WikiDB_backend_PearDB_search extends WikiDB_backend_search_sql
1244 // no surrounding quotes because we know it's a string
1245 // function _quote($word) { return $this->_dbh->addq($word); }
1248 // $Log: not supported by cvs2svn $
1249 // Revision 1.102 2006/12/02 21:57:27 rurban
1250 // fix WantedPages SQL: no JOIN
1251 // clarify first condition in CASE WHEN
1253 // Revision 1.101 2006/11/29 19:49:05 rurban
1254 // fix CASE WHEN SQL syntax error from previous commit
1256 // Revision 1.100 2006/11/19 13:59:11 rurban
1257 // Replace IF by CASE in exists_link()
1259 // Revision 1.99 2006/10/08 12:40:51 rurban
1260 // minor cleanup: remove unused vars
1262 // Revision 1.98 2006/06/03 08:50:41 rurban
1263 // revert wrong pear DB nextID() usage, our old is easier
1265 // Revision 1.97 2006/05/14 12:28:03 rurban
1266 // mysql 5.x fix for wantedpages join
1268 // Revision 1.96 2006/04/15 12:28:53 rurban
1271 // Revision 1.95 2006/02/22 21:52:28 rurban
1274 // Revision 1.94 2005/11/14 22:24:33 rurban
1275 // fix fulltext search,
1276 // Eliminate stoplist words,
1277 // don't extract %pagedate twice in ADODB,
1278 // add SemanticWeb support: link(relation),
1279 // major postgresql update: stored procedures, tsearch2 for fulltext
1281 // Revision 1.93 2005/10/10 19:42:15 rurban
1282 // fix wanted_pages SQL syntax
1284 // Revision 1.92 2005/09/14 06:04:43 rurban
1285 // optimize searching for ALL (ie %), use the stoplist on PDO
1287 // Revision 1.91 2005/09/11 14:55:05 rurban
1288 // implement fulltext stoplist
1290 // Revision 1.90 2005/09/11 13:25:12 rurban
1291 // enhance LIMIT support
1293 // Revision 1.89 2005/09/10 21:30:16 rurban
1294 // enhance titleSearch
1296 // Revision 1.88 2005/08/06 13:20:05 rurban
1299 // Revision 1.87 2005/02/10 19:04:24 rurban
1300 // move getRow up one level to our backend class
1302 // Revision 1.86 2005/01/29 19:51:02 rurban
1303 // Bugs item #1077769 fixed by frugal.
1304 // Deleted the wrong page. Fix all other tables also.
1306 // Revision 1.85 2005/01/25 08:03:35 rurban
1307 // support DATABASE_PERSISTENT besides dsn database?persistent=false; move lock_count up (per Charles Corrigan)
1309 // Revision 1.84 2005/01/18 20:55:47 rurban
1310 // reformatting and two bug fixes: adding missing parens
1312 // Revision 1.83 2005/01/18 10:11:29 rurban
1313 // Oops. Again thanks to Charles Corrigan
1315 // Revision 1.82 2005/01/18 08:55:51 rurban
1318 // Revision 1.81 2005/01/17 08:53:09 rurban
1319 // pagedata fix by Charles Corrigan
1321 // Revision 1.80 2004/12/22 18:33:31 rurban
1322 // fix page _id_cache logic for _get_pageid create_if_missing
1324 // Revision 1.79 2004/12/10 02:45:27 rurban
1325 // SQL optimization:
1326 // put _cached_html from pagedata into a new seperate blob, not huge serialized string.
1327 // it is only rarelely needed: for current page only, if-not-modified
1328 // but was extracted for every simple page iteration.
1330 // Revision 1.78 2004/12/08 12:55:51 rurban
1331 // support new non-destructive delete_page via generic backend method
1333 // Revision 1.77 2004/12/06 19:50:04 rurban
1334 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1335 // renamed delete_page to purge_page.
1336 // enable action=edit&version=-1 to force creation of a new version.
1337 // added BABYCART_PATH config
1338 // fixed magiqc in adodb.inc.php
1339 // and some more docs
1341 // Revision 1.76 2004/11/30 17:45:53 rurban
1342 // exists_links backend implementation
1344 // Revision 1.75 2004/11/28 20:42:33 rurban
1345 // Optimize PearDB _extract_version_data and _extract_page_data.
1347 // Revision 1.74 2004/11/27 14:39:05 rurban
1348 // simpified regex search architecture:
1349 // no db specific node methods anymore,
1350 // new sql() method for each node
1351 // parallel to regexp() (which returns pcre)
1352 // regex types bitmasked (op's not yet)
1354 // clarified WikiDB::quote() backend methods:
1355 // ->quote() adds surrounsing quotes
1356 // ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1357 // pear and adodb have now unified quote methods for all generic queries.
1359 // Revision 1.73 2004/11/26 18:39:02 rurban
1360 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
1362 // Revision 1.72 2004/11/25 17:20:51 rurban
1363 // and again a couple of more native db args: backlinks
1365 // Revision 1.71 2004/11/23 13:35:48 rurban
1366 // add case_exact search
1368 // Revision 1.70 2004/11/21 11:59:26 rurban
1369 // remove final \n to be ob_cache independent
1371 // Revision 1.69 2004/11/20 17:49:39 rurban
1372 // add fast exclude support to SQL get_all_pages
1374 // Revision 1.68 2004/11/20 17:35:58 rurban
1375 // improved WantedPages SQL backends
1376 // PageList::sortby new 3rd arg valid_fields (override db fields)
1377 // WantedPages sql pager inexact for performance reasons:
1378 // assume 3 wantedfrom per page, to be correct, no getTotal()
1379 // support exclude argument for get_all_pages, new _sql_set()
1381 // Revision 1.67 2004/11/10 19:32:24 rurban
1382 // * optimize increaseHitCount, esp. for mysql.
1383 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1384 // * Pear_DB version logic (awful but needed)
1385 // * fix broken ADODB quote
1386 // * _extract_page_data simplification
1388 // Revision 1.66 2004/11/10 15:29:21 rurban
1389 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1390 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1391 // * WikiDB: moved SQL specific methods upwards
1392 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1393 // fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1395 // Revision 1.65 2004/11/09 17:11:17 rurban
1396 // * revert to the wikidb ref passing. there's no memory abuse there.
1397 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1398 // store page ids with getPageLinks (GleanDescription) of all existing pages, which
1399 // are also needed at the rendering for linkExistingWikiWord().
1400 // pass options to pageiterator.
1401 // use this cache also for _get_pageid()
1402 // This saves about 8 SELECT count per page (num all pagelinks).
1403 // * fix passing of all page fields to the pageiterator.
1404 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1406 // Revision 1.64 2004/11/07 16:02:52 rurban
1407 // new sql access log (for spam prevention), and restructured access log class
1408 // dbh->quote (generic)
1409 // pear_db: mysql specific parts seperated (using replace)
1411 // Revision 1.63 2004/11/01 10:43:58 rurban
1412 // seperate PassUser methods into seperate dir (memory usage)
1413 // fix WikiUser (old) overlarge data session
1414 // remove wikidb arg from various page class methods, use global ->_dbi instead
1417 // Revision 1.62 2004/10/14 19:19:34 rurban
1418 // loadsave: check if the dumped file will be accessible from outside.
1419 // and some other minor fixes. (cvsclient native not yet ready)
1421 // Revision 1.61 2004/10/14 17:19:17 rurban
1422 // allow most_popular sortby arguments
1424 // Revision 1.60 2004/07/09 10:06:50 rurban
1425 // Use backend specific sortby and sortable_columns method, to be able to
1426 // select between native (Db backend) and custom (PageList) sorting.
1427 // Fixed PageList::AddPageList (missed the first)
1428 // Added the author/creator.. name to AllPagesBy...
1429 // display no pages if none matched.
1430 // Improved dba and file sortby().
1431 // Use &$request reference
1433 // Revision 1.59 2004/07/08 21:32:36 rurban
1434 // Prevent from more warnings, minor db and sort optimizations
1436 // Revision 1.58 2004/07/08 16:56:16 rurban
1437 // use the backendType abstraction
1439 // Revision 1.57 2004/07/05 12:57:54 rurban
1440 // add mysql timeout
1442 // Revision 1.56 2004/07/04 10:24:43 rurban
1443 // forgot the expressions
1445 // Revision 1.55 2004/07/03 16:51:06 rurban
1446 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1447 // added atomic mysql REPLACE for PearDB as in ADODB
1448 // fixed _lock_tables typo links => link
1449 // fixes unserialize ADODB bug in line 180
1451 // Revision 1.54 2004/06/29 08:52:24 rurban
1452 // Use ...version() $need_content argument in WikiDB also:
1453 // To reduce the memory footprint for larger sets of pagelists,
1454 // we don't cache the content (only true or false) and
1455 // we purge the pagedata (_cached_html) also.
1456 // _cached_html is only cached for the current pagename.
1457 // => Vastly improved page existance check, ACL check, ...
1459 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1461 // Revision 1.53 2004/06/27 10:26:03 rurban
1462 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1464 // Revision 1.52 2004/06/25 14:15:08 rurban
1465 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1467 // Revision 1.51 2004/05/12 10:49:55 rurban
1468 // require_once fix for those libs which are loaded before FileFinder and
1469 // its automatic include_path fix, and where require_once doesn't grok
1470 // dirname(__FILE__) != './lib'
1471 // upgrade fix with PearDB
1472 // navbar.tmpl: remove spaces for IE button alignment
1474 // Revision 1.50 2004/05/06 17:30:39 rurban
1475 // CategoryGroup: oops, dos2unix eol
1476 // improved phpwiki_version:
1477 // pre -= .0001 (1.3.10pre: 1030.099)
1478 // -p1 += .001 (1.3.9-p1: 1030.091)
1479 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1480 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1481 // backend->backendType(), backend->database(),
1482 // backend->listOfFields(),
1483 // backend->listOfTables(),
1485 // Revision 1.49 2004/05/03 21:35:30 rurban
1486 // don't use persistent connections with postgres
1488 // Revision 1.48 2004/04/26 20:44:35 rurban
1489 // locking table specific for better databases
1491 // Revision 1.47 2004/04/20 00:06:04 rurban
1492 // themable paging support
1494 // Revision 1.46 2004/04/19 21:51:41 rurban
1495 // php5 compatibility: it works!
1497 // Revision 1.45 2004/04/16 14:19:39 rurban
1498 // updated ADODB notes
1501 // (c-file-style: "gnu")
1505 // c-basic-offset: 4
1506 // c-hanging-comment-ender-p: nil
1507 // indent-tabs-mode: nil