3 require_once 'lib/WikiDB/backend.php';
5 class WikiDB_backend_PearDB
10 function WikiDB_backend_PearDB($dbparams)
12 // Find and include PEAR's DB.php. maybe we should force our private version again...
13 // if DB would have exported its version number, it would be easier.
14 @require_once('DB/common.php'); // Either our local pear copy or the system one
15 $name = "escapeSimple";
16 // TODO: apparently some Pear::Db version adds LIMIT 1,0 to getOne(),
17 // which is invalid for "select version()"
18 if (!in_array($name, get_class_methods("DB_common"))) {
19 $finder = new FileFinder;
20 $dir = dirname(__FILE__) . "/../../pear";
21 $finder->_prepend_to_include_path($dir);
22 include_once("$dir/DB/common.php"); // use our version instead.
23 if (!in_array($name, get_class_methods("DB_common"))) {
24 $pearFinder = new PearFileFinder("lib/pear");
25 $pearFinder->includeOnce('DB.php');
27 include_once("$dir/DB.php");
30 include_once 'DB.php';
33 // Install filter to handle bogus error notices from buggy DB.php's.
34 // TODO: check the Pear_DB version, but how?
37 $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
38 $this->_pearerrhandler = true;
41 // Open connection to database
42 $this->_dsn = $dbparams['dsn'];
43 $this->_dbparams = $dbparams;
44 $this->_lock_count = 0;
46 // persistent is usually a DSN option: we override it with a config value.
47 // phptype://username:password@hostspec/database?persistent=false
48 $dboptions = array('persistent' => DATABASE_PERSISTENT,
50 //if (preg_match('/^pgsql/', $this->_dsn)) $dboptions['persistent'] = false;
51 $this->_dbh = DB::connect($this->_dsn, $dboptions);
53 if (DB::isError($dbh)) {
54 trigger_error(sprintf("Can't connect to database: %s",
55 $this->_pear_error_message($dbh)),
56 isset($dbparams['_tryroot_from_upgrade']) // hack!
57 ? E_USER_WARNING : E_USER_ERROR);
58 if (isset($dbparams['_tryroot_from_upgrade']))
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.
94 if ($this->_lock_count) {
95 trigger_error("WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
98 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
99 $this->unlock('force');
101 $this->_dbh->disconnect();
103 if (!empty($this->_pearerrhandler)) {
104 $GLOBALS['ErrorManager']->popErrorHandler();
109 * Test fast wikipage.
111 function is_wiki_page($pagename)
114 extract($this->_table_names);
115 return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
116 . " FROM $nonempty_tbl, $page_tbl"
117 . " WHERE $nonempty_tbl.id=$page_tbl.id"
118 . " AND pagename='%s'",
119 $dbh->escapeSimple($pagename)));
122 function get_all_pagenames()
125 extract($this->_table_names);
126 return $dbh->getCol("SELECT pagename"
127 . " FROM $nonempty_tbl, $page_tbl"
128 . " WHERE $nonempty_tbl.id=$page_tbl.id");
131 function numPages($filter = false, $exclude = '')
134 extract($this->_table_names);
135 return $dbh->getOne("SELECT count(*)"
136 . " FROM $nonempty_tbl, $page_tbl"
137 . " WHERE $nonempty_tbl.id=$page_tbl.id");
140 function increaseHitCount($pagename)
143 // Hits is the only thing we can update in a fast manner.
144 // Note that this will fail silently if the page does not
145 // have a record in the page table. Since it's just the
146 // hit count, who cares?
147 $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
148 $this->_table_names['page_tbl'],
149 $dbh->escapeSimple($pagename)));
154 * Read page information from database.
156 function get_pagedata($pagename)
159 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
160 $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'",
161 $this->_table_names['page_tbl'],
162 $dbh->escapeSimple($pagename)),
164 return $result ? $this->_extract_page_data($result) : false;
167 function _extract_page_data($data)
169 if (empty($data)) return array();
170 elseif (empty($data['pagedata'])) return $data; else {
171 $data = array_merge($data, $this->_unserialize($data['pagedata']));
172 unset($data['pagedata']);
177 function update_pagedata($pagename, $newdata)
180 $page_tbl = $this->_table_names['page_tbl'];
182 // Hits is the only thing we can update in a fast manner.
183 if (count($newdata) == 1 && isset($newdata['hits'])) {
184 // Note that this will fail silently if the page does not
185 // have a record in the page table. Since it's just the
186 // hit count, who cares?
187 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
188 $newdata['hits'], $dbh->escapeSimple($pagename)));
192 $this->lock(array($page_tbl), true);
193 $data = $this->get_pagedata($pagename);
196 $this->_get_pageid($pagename, true); // Creates page record
199 $hits = !empty($data['hits']) ? (int)$data['hits'] : 0;
200 unset($data['hits']);
202 foreach ($newdata as $key => $val) {
205 else if (empty($val))
211 /* Portability issue -- not all DBMS supports huge strings
212 * so we need to 'bind' instead of building a simple SQL statment.
213 * Note that we do not need to escapeSimple when we bind
214 $dbh->query(sprintf("UPDATE $page_tbl"
215 . " SET hits=%d, pagedata='%s'"
216 . " WHERE pagename='%s'",
218 $dbh->escapeSimple($this->_serialize($data)),
219 $dbh->escapeSimple($pagename)));
221 $dbh->query("UPDATE $page_tbl"
222 . " SET hits=?, pagedata=?"
223 . " WHERE pagename=?",
224 array($hits, $this->_serialize($data), $pagename));
225 $this->unlock(array($page_tbl));
228 function get_cached_html($pagename)
231 $page_tbl = $this->_table_names['page_tbl'];
232 return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'",
233 $dbh->escapeSimple($pagename)));
236 function set_cached_html($pagename, $data)
239 $page_tbl = $this->_table_names['page_tbl'];
240 $dbh->query("UPDATE $page_tbl"
241 . " SET cached_html=?"
242 . " WHERE pagename=?",
243 array($data, $pagename));
246 function _get_pageid($pagename, $create_if_missing = false)
251 $cache =& $request->_dbi->_cache->_id_cache;
252 if (isset($cache[$pagename])) {
253 if ($cache[$pagename] or !$create_if_missing) {
254 return $cache[$pagename];
258 // attributes play this game.
259 if ($pagename === '') return 0;
262 $page_tbl = $this->_table_names['page_tbl'];
264 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
265 $dbh->escapeSimple($pagename));
267 if (!$create_if_missing)
268 return $dbh->getOne($query);
270 $id = $dbh->getOne($query);
272 $this->lock(array($page_tbl), true); // write lock
273 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
275 // requires createSequence and on mysql lock the interim table ->getSequenceName
276 //$id = $dbh->nextId($page_tbl . "_id");
277 $dbh->query(sprintf("INSERT INTO $page_tbl"
278 . " (id,pagename,hits)"
279 . " VALUES (%d,'%s',0)",
280 $id, $dbh->escapeSimple($pagename)));
281 $this->unlock(array($page_tbl));
286 function get_latest_version($pagename)
289 extract($this->_table_names);
291 (int)$dbh->getOne(sprintf("SELECT latestversion"
292 . " FROM $page_tbl, $recent_tbl"
293 . " WHERE $page_tbl.id=$recent_tbl.id"
294 . " AND pagename='%s'",
295 $dbh->escapeSimple($pagename)));
298 function get_previous_version($pagename, $version)
301 extract($this->_table_names);
304 (int)$dbh->getOne(sprintf("SELECT version"
305 . " FROM $version_tbl, $page_tbl"
306 . " WHERE $version_tbl.id=$page_tbl.id"
307 . " AND pagename='%s'"
308 . " AND version < %d"
309 . " ORDER BY version DESC",
310 /* Non portable and useless anyway with getOne
313 $dbh->escapeSimple($pagename),
320 * @param $version int Which version to get.
322 * @return hash The version data, or false if specified version does not
325 function get_versiondata($pagename, $version, $want_content = false)
328 extract($this->_table_names);
329 extract($this->_expressions);
331 assert(is_string($pagename) and $pagename != "");
332 assert($version > 0);
334 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
335 // FIXME: optimization: sometimes don't get page data?
337 $fields = $this->page_tbl_fields
338 . ",$page_tbl.pagedata as pagedata,"
339 . $this->version_tbl_fields;
341 $fields = $this->page_tbl_fields . ","
342 . "mtime, minor_edit, versiondata,"
343 . "$iscontent AS have_content";
346 $result = $dbh->getRow(sprintf("SELECT $fields"
347 . " FROM $page_tbl, $version_tbl"
348 . " WHERE $page_tbl.id=$version_tbl.id"
349 . " AND pagename='%s'"
351 $dbh->escapeSimple($pagename), $version),
354 return $this->_extract_version_data($result);
357 function _extract_version_data($query_result)
362 /* Earlier versions (<= 1.3.7) stored the version data in base64.
363 This could be done here or in upgrade.
365 if (!strstr($query_result['versiondata'], ":")) {
366 $query_result['versiondata'] =
367 base64_decode($query_result['versiondata']);
369 $data = $this->_unserialize($query_result['versiondata']);
371 $data['mtime'] = $query_result['mtime'];
372 $data['is_minor_edit'] = !empty($query_result['minor_edit']);
374 if (isset($query_result['content']))
375 $data['%content'] = $query_result['content'];
376 elseif ($query_result['have_content'])
377 $data['%content'] = true; else
378 $data['%content'] = '';
380 // FIXME: this is ugly.
381 if (isset($query_result['pagedata'])) {
382 // Query also includes page data.
383 // We might as well send that back too...
384 unset($query_result['versiondata']);
385 $data['%pagedata'] = $this->_extract_page_data($query_result);
393 * Create a new revision of a page.
395 function set_versiondata($pagename, $version, $data)
398 $version_tbl = $this->_table_names['version_tbl'];
400 $minor_edit = (int)!empty($data['is_minor_edit']);
401 unset($data['is_minor_edit']);
403 $mtime = (int)$data['mtime'];
404 unset($data['mtime']);
405 assert(!empty($mtime));
407 $content = isset($data['%content']) ? (string)$data['%content'] : '';
408 unset($data['%content']);
410 unset($data['%pagedata']);
413 $id = $this->_get_pageid($pagename, true);
415 $dbh->query(sprintf("DELETE FROM $version_tbl"
416 . " WHERE id=%d AND version=%d",
418 // generic slow PearDB bind eh quoting.
419 $dbh->query("INSERT INTO $version_tbl"
420 . " (id,version,mtime,minor_edit,content,versiondata)"
421 . " VALUES(?, ?, ?, ?, ?, ?)",
422 array($id, $version, $mtime, $minor_edit, $content,
423 $this->_serialize($data)));
425 $this->_update_recent_table($id);
426 $this->_update_nonempty_table($id);
432 * Delete an old revision of a page.
434 function delete_versiondata($pagename, $version)
437 extract($this->_table_names);
440 if (($id = $this->_get_pageid($pagename))) {
441 $dbh->query("DELETE FROM $version_tbl"
442 . " WHERE id=$id AND version=$version");
444 $this->_update_recent_table($id);
445 // This shouldn't be needed (as long as the latestversion
446 // never gets deleted.) But, let's be safe.
447 $this->_update_nonempty_table($id);
453 * Delete page from the database with backup possibility.
454 * i.e save_page('') and DELETE nonempty id
455 * Can be undone and is seen in RecentChanges.
457 /* // see parent backend.php
458 function delete_page($pagename) {
460 $user =& $GLOBALS['request']->_user;
461 $vdata = array('author' => $user->getId(),
462 'author_id' => $user->getAuthenticatedId(),
466 $version = $this->get_latest_version($pagename);
467 $this->set_versiondata($pagename, $version+1, $vdata);
468 $this->set_links($pagename, false);
469 $pagedata = get_pagedata($pagename);
470 $this->update_pagedata($pagename, array('hits' => $pagedata['hits']));
476 * Delete page completely from the database.
477 * I'm not sure if this is what we want. Maybe just delete the revisions
479 function purge_page($pagename)
482 extract($this->_table_names);
485 if (($id = $this->_get_pageid($pagename, false))) {
486 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
487 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
488 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
489 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
490 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
492 // We're still in the link table (dangling link) so we can't delete this
494 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
497 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
500 $this->_update_recent_table();
501 $this->_update_nonempty_table();
503 $result = -1; // already purged or not existing
509 // The only thing we might be interested in updating which we can
510 // do fast in the flags (minor_edit). I think the default
511 // update_versiondata will work fine...
512 //function update_versiondata($pagename, $version, $data) {
515 function set_links($pagename, $links)
517 // Update link table.
518 // FIXME: optimize: mysql can do this all in one big INSERT.
521 extract($this->_table_names);
524 $pageid = $this->_get_pageid($pagename, true);
526 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
529 foreach ($links as $link) {
530 $linkto = $link['linkto'];
531 if ($linkto === "") { // ignore attributes
534 if (isset($link['relation']))
535 $relation = $this->_get_pageid($link['relation'], true);
539 if (isset($linkseen[$linkto]) and !$relation)
542 $linkseen[$linkto] = true;
543 $linkid = $this->_get_pageid($linkto, true);
545 echo("No link for $linkto on page $pagename");
546 //printSimpleTrace(debug_backtrace());
547 trigger_error("No link for $linkto on page $pagename");
550 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
551 . " VALUES ($pageid, $linkid, $relation)");
559 * Find pages which link to or are linked from a page.
561 * TESTME relations: get_links is responsible to add the relation to the pagehash
562 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
563 * if (isset($next['linkrelation']))
565 function get_links($pagename, $reversed = true, $include_empty = false,
566 $sortby = '', $limit = '', $exclude = '',
567 $want_relations = false)
570 extract($this->_table_names);
573 list($have, $want) = array('linkee', 'linker');
575 list($have, $want) = array('linker', 'linkee');
576 $orderby = $this->sortby($sortby, 'db', array('pagename'));
577 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
578 if ($exclude) // array of pagenames
579 $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude);
583 $qpagename = $dbh->escapeSimple($pagename);
584 $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
585 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
587 . (!$include_empty ? "$nonempty_tbl, " : '')
588 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
589 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
590 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
591 . " AND $have.pagename='$qpagename'"
592 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
593 //. " GROUP BY $want.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);
604 return new WikiDB_backend_PearDB_iter($this, $result);
608 * Find if a page links to another page
610 function exists_link($pagename, $link, $reversed = false)
613 extract($this->_table_names);
616 list($have, $want) = array('linkee', 'linker');
618 list($have, $want) = array('linker', 'linkee');
619 $qpagename = $dbh->escapeSimple($pagename);
620 $qlink = $dbh->escapeSimple($link);
621 $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result"
622 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
623 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
624 . " AND $have.pagename='$qpagename'"
625 . " AND $want.pagename='$qlink'");
626 return $row['result'];
629 function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
632 extract($this->_table_names);
633 $orderby = $this->sortby($sortby, 'db');
634 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
635 if ($exclude) // array of pagenames
636 $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
640 if (strstr($orderby, 'mtime ')) { // multiple columns possible
641 if ($include_empty) {
643 . $this->page_tbl_fields
644 . " FROM $page_tbl, $recent_tbl, $version_tbl"
645 . " WHERE $page_tbl.id=$recent_tbl.id"
646 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
651 . $this->page_tbl_fields
652 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
653 . " WHERE $nonempty_tbl.id=$page_tbl.id"
654 . " AND $page_tbl.id=$recent_tbl.id"
655 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
660 if ($include_empty) {
662 . $this->page_tbl_fields
664 . ($exclude ? " WHERE $exclude" : '')
668 . $this->page_tbl_fields
669 . " FROM $nonempty_tbl, $page_tbl"
670 . " WHERE $nonempty_tbl.id=$page_tbl.id"
675 if ($limit && $orderby) {
676 // extract from,count from limit
677 list($from, $count) = $this->limit($limit);
678 $result = $dbh->limitQuery($sql, $from, $count);
679 $options = array('limit_by_db' => 1);
681 $result = $dbh->query($sql);
682 $options = array('limit_by_db' => 0);
684 return new WikiDB_backend_PearDB_iter($this, $result, $options);
691 function text_search($search, $fulltext = false, $sortby = '', $limit = '',
695 extract($this->_table_names);
696 $orderby = $this->sortby($sortby, 'db');
697 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
698 //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
700 $searchclass = get_class($this) . "_search";
701 // no need to define it everywhere and then fallback. memory!
702 if (!class_exists($searchclass))
703 $searchclass = "WikiDB_backend_PearDB_search";
704 $searchobj = new $searchclass($search, $dbh);
706 $table = "$nonempty_tbl, $page_tbl";
707 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
708 $fields = $this->page_tbl_fields;
711 $table .= ", $recent_tbl";
712 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
714 $table .= ", $version_tbl";
715 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
717 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
718 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
720 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
722 $search_clause = $search->makeSqlClauseObj($callback);
724 $sql = "SELECT $fields FROM $table"
725 . " WHERE $join_clause"
726 . " AND ($search_clause)"
729 list($from, $count) = $this->limit($limit);
730 $result = $dbh->limitQuery($sql, $from, $count);
732 $result = $dbh->query($sql);
735 $iter = new WikiDB_backend_PearDB_iter($this, $result);
736 $iter->stoplisted = @$searchobj->stoplisted;
740 //Todo: check if the better Mysql MATCH operator is supported,
741 // (ranked search) and also google like expressions.
742 function _sql_match_clause($word)
744 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
745 $word = $this->_dbh->escapeSimple($word);
746 //$page_tbl = $this->_table_names['page_tbl'];
747 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
748 // e.g. if word is lowercased.
749 // http://bugs.mysql.com/bug.php?id=1491
750 return "LOWER(pagename) LIKE '%$word%'";
753 function _sql_casematch_clause($word)
755 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
756 $word = $this->_dbh->escapeSimple($word);
757 return "pagename LIKE '%$word%'";
760 function _fullsearch_sql_match_clause($word)
762 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
763 $word = $this->_dbh->escapeSimple($word);
764 //$page_tbl = $this->_table_names['page_tbl'];
765 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
766 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
769 function _fullsearch_sql_casematch_clause($word)
771 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
772 $word = $this->_dbh->escapeSimple($word);
773 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
777 * Find highest or lowest hit counts.
779 function most_popular($limit = 20, $sortby = '-hits')
782 extract($this->_table_names);
788 $order = "hits DESC";
789 $where = " AND hits > 0";
792 if ($sortby != '-hits') {
793 if ($order = $this->sortby($sortby, 'db'))
794 $orderby = " ORDER BY " . $order;
796 $orderby = " ORDER BY $order";
798 //$limitclause = $limit ? " LIMIT $limit" : '';
800 . $this->page_tbl_fields
801 . " FROM $nonempty_tbl, $page_tbl"
802 . " WHERE $nonempty_tbl.id=$page_tbl.id"
806 list($from, $count) = $this->limit($limit);
807 $result = $dbh->limitQuery($sql, $from, $count);
809 $result = $dbh->query($sql);
812 return new WikiDB_backend_PearDB_iter($this, $result);
816 * Find recent changes.
818 function most_recent($params)
822 $include_minor_revisions = false;
823 $exclude_major_revisions = false;
824 $include_all_revisions = false;
828 extract($this->_table_names);
832 $pick[] = "mtime >= $since";
834 if ($include_all_revisions) {
835 // Include all revisions of each page.
836 $table = "$page_tbl, $version_tbl";
837 $join_clause = "$page_tbl.id=$version_tbl.id";
839 if ($exclude_major_revisions) {
840 // Include only minor revisions
841 $pick[] = "minor_edit <> 0";
842 } elseif (!$include_minor_revisions) {
843 // Include only major revisions
844 $pick[] = "minor_edit = 0";
847 $table = "$page_tbl, $recent_tbl";
848 $join_clause = "$page_tbl.id=$recent_tbl.id";
849 $table .= ", $version_tbl";
850 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
852 if ($exclude_major_revisions) {
853 // Include only most recent minor revision
854 $pick[] = 'version=latestminor';
855 } elseif (!$include_minor_revisions) {
856 // Include only most recent major revision
857 $pick[] = 'version=latestmajor';
859 // Include only the latest revision (whether major or minor).
860 $pick[] = 'version=latestversion';
868 // $limitclause = $limit ? " LIMIT $limit" : '';
869 $where_clause = $join_clause;
871 $where_clause .= " AND " . join(" AND ", $pick);
873 // FIXME: use SQL_BUFFER_RESULT for mysql?
875 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
877 . " WHERE $where_clause"
878 . " ORDER BY mtime $order";
880 list($from, $count) = $this->limit($limit);
881 $result = $dbh->limitQuery($sql, $from, $count);
883 $result = $dbh->query($sql);
885 return new WikiDB_backend_PearDB_iter($this, $result);
889 * Find referenced empty pages.
891 function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
894 extract($this->_table_names);
895 if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom')))
896 $orderby = 'ORDER BY ' . $orderby;
898 if ($exclude_from) // array of pagenames
899 $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from);
900 if ($exclude) // array of pagenames
901 $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude);
902 $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
903 . " FROM $page_tbl p, $link_tbl linked"
904 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
905 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
906 . " WHERE ne.id IS NULL"
907 . " AND p.id = linked.linkfrom"
912 // oci8 error: WHERE NULL = NULL appended
913 list($from, $count) = $this->limit($limit);
914 $result = $dbh->limitQuery($sql, $from, $count * 3);
916 $result = $dbh->query($sql);
918 return new WikiDB_backend_PearDB_generic_iter($this, $result);
921 function _sql_set(&$pagenames)
924 foreach ($pagenames as $p) {
925 $s .= ("'" . $this->_dbh->escapeSimple($p) . "',");
927 return substr($s, 0, -1) . ")";
931 * Rename page in the database.
933 function rename_page($pagename, $to)
936 extract($this->_table_names);
939 if (($id = $this->_get_pageid($pagename, false))) {
940 if ($new = $this->_get_pageid($to, false)) {
942 // This page does not exist (already verified before), but exists in the page table.
943 // So we delete this page.
944 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
945 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
946 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
947 // We have to fix all referring tables to the old id
948 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
949 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
950 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
952 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
953 $dbh->escapeSimple($to)));
959 function _update_recent_table($pageid = false)
962 extract($this->_table_names);
963 extract($this->_expressions);
965 $pageid = (int)$pageid;
968 $dbh->query("DELETE FROM $recent_tbl"
969 . ($pageid ? " WHERE id=$pageid" : ""));
970 $dbh->query("INSERT INTO $recent_tbl"
971 . " (id, latestversion, latestmajor, latestminor)"
972 . " SELECT id, $maxversion, $maxmajor, $maxminor"
973 . " FROM $version_tbl"
974 . ($pageid ? " WHERE id=$pageid" : "")
979 function _update_nonempty_table($pageid = false)
982 extract($this->_table_names);
984 $pageid = (int)$pageid;
986 extract($this->_expressions);
988 $dbh->query("DELETE FROM $nonempty_tbl"
989 . ($pageid ? " WHERE id=$pageid" : ""));
990 $dbh->query("INSERT INTO $nonempty_tbl (id)"
991 . " SELECT $recent_tbl.id"
992 . " FROM $recent_tbl, $version_tbl"
993 . " WHERE $recent_tbl.id=$version_tbl.id"
994 . " AND version=latestversion"
995 // We have some specifics here (Oracle)
996 //. " AND content<>''"
997 . " AND content $notempty"
998 . ($pageid ? " AND $recent_tbl.id=$pageid" : ""));
1004 * Grab a write lock on the tables in the SQL database.
1006 * Calls can be nested. The tables won't be unlocked until
1007 * _unlock_database() is called as many times as _lock_database().
1011 function lock($tables = false, $write_lock = true)
1013 if ($this->_lock_count++ == 0)
1014 $this->_lock_tables($write_lock);
1018 * Actually lock the required tables.
1020 function _lock_tables($write_lock)
1022 trigger_error("virtual", E_USER_ERROR);
1026 * Release a write lock on the tables in the SQL database.
1030 * @param $force boolean Unlock even if not every call to lock() has been matched
1031 * by a call to unlock().
1033 * @see _lock_database
1035 function unlock($tables = false, $force = false)
1037 if ($this->_lock_count == 0)
1039 if (--$this->_lock_count <= 0 || $force) {
1040 $this->_unlock_tables();
1041 $this->_lock_count = 0;
1046 * Actually unlock the required tables.
1048 function _unlock_tables($write_lock)
1050 trigger_error("virtual", E_USER_ERROR);
1057 function _serialize($data)
1061 assert(is_array($data));
1062 return serialize($data);
1068 function _unserialize($data)
1070 return empty($data) ? array() : unserialize($data);
1074 * Callback for PEAR (DB) errors.
1078 * @param A PEAR_error object.
1080 function _pear_error_callback($error)
1082 if ($this->_is_false_error($error))
1085 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
1087 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1091 * Detect false errors messages from PEAR DB.
1093 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1094 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1095 * return any data. (So when a "LOCK" command doesn't return any data,
1096 * DB reports it as an error, when in fact, it's not.)
1099 * @return bool True iff error is not really an error.
1101 function _is_false_error($error)
1103 if ($error->getCode() != DB_ERROR)
1106 $query = $this->_dbh->last_query;
1108 if (!preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1109 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)
1111 // Last query was not of the sort which doesn't return any data.
1112 //" <--kludge for brain-dead syntax coloring
1116 if (!in_array('ismanip', get_class_methods('DB'))) {
1117 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1118 // does not have the DB::isManip method.
1122 if (DB::isManip($query)) {
1123 // If Pear thinks it's an isManip then it wouldn't have thrown
1124 // the error we're testing for....
1131 function _pear_error_message($error)
1133 $class = get_class($this);
1134 $message = "$class: fatal database error\n"
1135 . "\t" . $error->getMessage() . "\n"
1136 . "\t(" . $error->getDebugInfo() . ")\n";
1138 // Prevent password from being exposed during a connection error
1139 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1140 '\\1:XXXXXXXX', $this->_dsn);
1141 return str_replace($this->_dsn, $safe_dsn, $message);
1145 * Filter PHP errors notices from PEAR DB code.
1147 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1148 * errors and notices. This is an error callback (for use with
1149 * ErrorManager which will filter out those spurious messages.)
1150 * @see _is_false_error, ErrorManager
1153 function _pear_notice_filter($err)
1155 return ($err->isNotice()
1156 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1157 && $err->errline == 126
1158 && preg_match('/Undefined offset: +0\b/', $err->errstr));
1161 /* some variables and functions for DB backend abstraction (action=upgrade) */
1164 return $this->_dbh->dsn['database'];
1167 function backendType()
1169 return $this->_dbh->phptype;
1172 function connection()
1174 return $this->_dbh->connection;
1177 function getRow($query)
1179 return $this->_dbh->getRow($query);
1182 function listOfTables()
1184 return $this->_dbh->getListOf('tables');
1187 function listOfFields($database, $table)
1189 if ($this->backendType() == 'mysql') {
1191 assert(!empty($database));
1192 assert(!empty($table));
1193 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1194 trigger_error(__FILE__ . ':' . __LINE__ . ' ' . mysql_error(), E_USER_WARNING);
1195 if (!$result) return array();
1196 $columns = mysql_num_fields($result);
1197 for ($i = 0; $i < $columns; $i++) {
1198 $fields[] = mysql_field_name($result, $i);
1200 mysql_free_result($result);
1203 // TODO: try ADODB version?
1204 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1211 * This class is a generic iterator.
1213 * WikiDB_backend_PearDB_iter only iterates over things that have
1214 * 'pagename', 'pagedata', etc. etc.
1216 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1217 * (most of the code is cut-and-paste :-( ), but I am trying to make
1218 * changes that could be merged easily.
1220 * @author: Dan Frankowski
1222 class WikiDB_backend_PearDB_generic_iter
1223 extends WikiDB_backend_iterator
1225 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL)
1227 if (DB::isError($query_result)) {
1228 // This shouldn't happen, I thought.
1229 $backend->_pear_error_callback($query_result);
1232 $this->_backend = &$backend;
1233 $this->_result = $query_result;
1234 $this->_options = $field_list;
1239 if (!$this->_result)
1241 return $this->_result->numRows();
1246 if (!$this->_result)
1249 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1260 if ($this->_result) {
1261 $this->_result->MoveFirst();
1267 if ($this->_result) {
1268 $this->_result->free();
1269 $this->_result = false;
1276 while ($page = $this->next())
1282 class WikiDB_backend_PearDB_iter
1283 extends WikiDB_backend_PearDB_generic_iter
1288 $backend = &$this->_backend;
1289 if (!$this->_result) {
1293 if (!is_object($this->_result)) {
1297 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1303 $pagedata = $backend->_extract_page_data($record);
1304 $rec = array('pagename' => $record['pagename'],
1305 'pagedata' => $pagedata);
1307 if (!empty($record['version'])) {
1308 $rec['versiondata'] = $backend->_extract_version_data($record);
1309 $rec['version'] = $record['version'];
1316 class WikiDB_backend_PearDB_search extends WikiDB_backend_search_sql
1318 // no surrounding quotes because we know it's a string
1319 // function _quote($word) { return $this->_dbh->addq($word); }
1325 // c-basic-offset: 4
1326 // c-hanging-comment-ender-p: nil
1327 // indent-tabs-mode: nil