3 require_once 'lib/WikiDB/backend.php';
4 //require_once('lib/FileFinder.php');
5 //require_once('lib/ErrorManager.php');
7 class WikiDB_backend_PearDB
12 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)),
59 isset($dbparams['_tryroot_from_upgrade']) // hack!
60 ? E_USER_WARNING : E_USER_ERROR);
61 if (isset($dbparams['_tryroot_from_upgrade']))
64 $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
65 array($this, '_pear_error_callback'));
66 $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
68 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
70 = array('page_tbl' => $prefix . 'page',
71 'version_tbl' => $prefix . 'version',
72 'link_tbl' => $prefix . 'link',
73 'recent_tbl' => $prefix . 'recent',
74 'nonempty_tbl' => $prefix . 'nonempty');
75 $page_tbl = $this->_table_names['page_tbl'];
76 $version_tbl = $this->_table_names['version_tbl'];
77 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
78 $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, " .
79 "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
82 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
83 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
84 'maxversion' => "MAX(version)",
86 'iscontent' => "content<>''");
91 * Close database connection.
97 if ($this->_lock_count) {
98 trigger_error("WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
101 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
102 $this->unlock('force');
104 $this->_dbh->disconnect();
106 if (!empty($this->_pearerrhandler)) {
107 $GLOBALS['ErrorManager']->popErrorHandler();
112 * Test fast wikipage.
114 function is_wiki_page($pagename)
117 extract($this->_table_names);
118 return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
119 . " FROM $nonempty_tbl, $page_tbl"
120 . " WHERE $nonempty_tbl.id=$page_tbl.id"
121 . " AND pagename='%s'",
122 $dbh->escapeSimple($pagename)));
125 function get_all_pagenames()
128 extract($this->_table_names);
129 return $dbh->getCol("SELECT pagename"
130 . " FROM $nonempty_tbl, $page_tbl"
131 . " WHERE $nonempty_tbl.id=$page_tbl.id");
134 function numPages($filter = false, $exclude = '')
137 extract($this->_table_names);
138 return $dbh->getOne("SELECT count(*)"
139 . " FROM $nonempty_tbl, $page_tbl"
140 . " WHERE $nonempty_tbl.id=$page_tbl.id");
143 function increaseHitCount($pagename)
146 // Hits is the only thing we can update in a fast manner.
147 // Note that this will fail silently if the page does not
148 // have a record in the page table. Since it's just the
149 // hit count, who cares?
150 $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
151 $this->_table_names['page_tbl'],
152 $dbh->escapeSimple($pagename)));
157 * Read page information from database.
159 function get_pagedata($pagename)
162 //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
163 $result = $dbh->getRow(sprintf("SELECT hits,pagedata FROM %s WHERE pagename='%s'",
164 $this->_table_names['page_tbl'],
165 $dbh->escapeSimple($pagename)),
167 return $result ? $this->_extract_page_data($result) : false;
170 function _extract_page_data($data)
172 if (empty($data)) return array();
173 elseif (empty($data['pagedata'])) return $data; else {
174 $data = array_merge($data, $this->_unserialize($data['pagedata']));
175 unset($data['pagedata']);
180 function update_pagedata($pagename, $newdata)
183 $page_tbl = $this->_table_names['page_tbl'];
185 // Hits is the only thing we can update in a fast manner.
186 if (count($newdata) == 1 && isset($newdata['hits'])) {
187 // Note that this will fail silently if the page does not
188 // have a record in the page table. Since it's just the
189 // hit count, who cares?
190 $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
191 $newdata['hits'], $dbh->escapeSimple($pagename)));
195 $this->lock(array($page_tbl), true);
196 $data = $this->get_pagedata($pagename);
199 $this->_get_pageid($pagename, true); // Creates page record
202 $hits = !empty($data['hits']) ? (int)$data['hits'] : 0;
203 unset($data['hits']);
205 foreach ($newdata as $key => $val) {
208 else if (empty($val))
214 /* Portability issue -- not all DBMS supports huge strings
215 * so we need to 'bind' instead of building a simple SQL statment.
216 * Note that we do not need to escapeSimple when we bind
217 $dbh->query(sprintf("UPDATE $page_tbl"
218 . " SET hits=%d, pagedata='%s'"
219 . " WHERE pagename='%s'",
221 $dbh->escapeSimple($this->_serialize($data)),
222 $dbh->escapeSimple($pagename)));
224 $dbh->query("UPDATE $page_tbl"
225 . " SET hits=?, pagedata=?"
226 . " WHERE pagename=?",
227 array($hits, $this->_serialize($data), $pagename));
228 $this->unlock(array($page_tbl));
231 function get_cached_html($pagename)
234 $page_tbl = $this->_table_names['page_tbl'];
235 return $dbh->GetOne(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename='%s'",
236 $dbh->escapeSimple($pagename)));
239 function set_cached_html($pagename, $data)
242 $page_tbl = $this->_table_names['page_tbl'];
243 $dbh->query("UPDATE $page_tbl"
244 . " SET cached_html=?"
245 . " WHERE pagename=?",
246 array($data, $pagename));
249 function _get_pageid($pagename, $create_if_missing = false)
254 $cache =& $request->_dbi->_cache->_id_cache;
255 if (isset($cache[$pagename])) {
256 if ($cache[$pagename] or !$create_if_missing) {
257 return $cache[$pagename];
261 // attributes play this game.
262 if ($pagename === '') return 0;
265 $page_tbl = $this->_table_names['page_tbl'];
267 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
268 $dbh->escapeSimple($pagename));
270 if (!$create_if_missing)
271 return $dbh->getOne($query);
273 $id = $dbh->getOne($query);
275 $this->lock(array($page_tbl), true); // write lock
276 $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
278 // requires createSequence and on mysql lock the interim table ->getSequenceName
279 //$id = $dbh->nextId($page_tbl . "_id");
280 $dbh->query(sprintf("INSERT INTO $page_tbl"
281 . " (id,pagename,hits)"
282 . " VALUES (%d,'%s',0)",
283 $id, $dbh->escapeSimple($pagename)));
284 $this->unlock(array($page_tbl));
289 function get_latest_version($pagename)
292 extract($this->_table_names);
294 (int)$dbh->getOne(sprintf("SELECT latestversion"
295 . " FROM $page_tbl, $recent_tbl"
296 . " WHERE $page_tbl.id=$recent_tbl.id"
297 . " AND pagename='%s'",
298 $dbh->escapeSimple($pagename)));
301 function get_previous_version($pagename, $version)
304 extract($this->_table_names);
307 (int)$dbh->getOne(sprintf("SELECT version"
308 . " FROM $version_tbl, $page_tbl"
309 . " WHERE $version_tbl.id=$page_tbl.id"
310 . " AND pagename='%s'"
311 . " AND version < %d"
312 . " ORDER BY version DESC",
313 /* Non portable and useless anyway with getOne
316 $dbh->escapeSimple($pagename),
323 * @param $version int Which version to get.
325 * @return hash The version data, or false if specified version does not
328 function get_versiondata($pagename, $version, $want_content = false)
331 extract($this->_table_names);
332 extract($this->_expressions);
334 assert(is_string($pagename) and $pagename != "");
335 assert($version > 0);
337 //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
338 // FIXME: optimization: sometimes don't get page data?
340 $fields = $this->page_tbl_fields
341 . ",$page_tbl.pagedata as pagedata,"
342 . $this->version_tbl_fields;
344 $fields = $this->page_tbl_fields . ","
345 . "mtime, minor_edit, versiondata,"
346 . "$iscontent AS have_content";
349 $result = $dbh->getRow(sprintf("SELECT $fields"
350 . " FROM $page_tbl, $version_tbl"
351 . " WHERE $page_tbl.id=$version_tbl.id"
352 . " AND pagename='%s'"
354 $dbh->escapeSimple($pagename), $version),
357 return $this->_extract_version_data($result);
360 function _extract_version_data($query_result)
365 /* Earlier versions (<= 1.3.7) stored the version data in base64.
366 This could be done here or in upgrade.
368 if (!strstr($query_result['versiondata'], ":")) {
369 $query_result['versiondata'] =
370 base64_decode($query_result['versiondata']);
372 $data = $this->_unserialize($query_result['versiondata']);
374 $data['mtime'] = $query_result['mtime'];
375 $data['is_minor_edit'] = !empty($query_result['minor_edit']);
377 if (isset($query_result['content']))
378 $data['%content'] = $query_result['content'];
379 elseif ($query_result['have_content'])
380 $data['%content'] = true; else
381 $data['%content'] = '';
383 // FIXME: this is ugly.
384 if (isset($query_result['pagedata'])) {
385 // Query also includes page data.
386 // We might as well send that back too...
387 unset($query_result['versiondata']);
388 $data['%pagedata'] = $this->_extract_page_data($query_result);
396 * Create a new revision of a page.
398 function set_versiondata($pagename, $version, $data)
401 $version_tbl = $this->_table_names['version_tbl'];
403 $minor_edit = (int)!empty($data['is_minor_edit']);
404 unset($data['is_minor_edit']);
406 $mtime = (int)$data['mtime'];
407 unset($data['mtime']);
408 assert(!empty($mtime));
410 $content = isset($data['%content']) ? (string)$data['%content'] : '';
411 unset($data['%content']);
413 unset($data['%pagedata']);
416 $id = $this->_get_pageid($pagename, true);
418 $dbh->query(sprintf("DELETE FROM $version_tbl"
419 . " WHERE id=%d AND version=%d",
421 // generic slow PearDB bind eh quoting.
422 $dbh->query("INSERT INTO $version_tbl"
423 . " (id,version,mtime,minor_edit,content,versiondata)"
424 . " VALUES(?, ?, ?, ?, ?, ?)",
425 array($id, $version, $mtime, $minor_edit, $content,
426 $this->_serialize($data)));
428 $this->_update_recent_table($id);
429 $this->_update_nonempty_table($id);
435 * Delete an old revision of a page.
437 function delete_versiondata($pagename, $version)
440 extract($this->_table_names);
443 if (($id = $this->_get_pageid($pagename))) {
444 $dbh->query("DELETE FROM $version_tbl"
445 . " WHERE id=$id AND version=$version");
447 $this->_update_recent_table($id);
448 // This shouldn't be needed (as long as the latestversion
449 // never gets deleted.) But, let's be safe.
450 $this->_update_nonempty_table($id);
456 * Delete page from the database with backup possibility.
457 * i.e save_page('') and DELETE nonempty id
458 * Can be undone and is seen in RecentChanges.
460 /* // see parent backend.php
461 function delete_page($pagename) {
463 $user =& $GLOBALS['request']->_user;
464 $vdata = array('author' => $user->getId(),
465 'author_id' => $user->getAuthenticatedId(),
469 $version = $this->get_latest_version($pagename);
470 $this->set_versiondata($pagename, $version+1, $vdata);
471 $this->set_links($pagename, false);
472 $pagedata = get_pagedata($pagename);
473 $this->update_pagedata($pagename, array('hits' => $pagedata['hits']));
479 * Delete page completely from the database.
480 * I'm not sure if this is what we want. Maybe just delete the revisions
482 function purge_page($pagename)
485 extract($this->_table_names);
488 if (($id = $this->_get_pageid($pagename, false))) {
489 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
490 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
491 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
492 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$id");
493 $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
495 // We're still in the link table (dangling link) so we can't delete this
497 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
500 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
503 $this->_update_recent_table();
504 $this->_update_nonempty_table();
506 $result = -1; // already purged or not existing
512 // The only thing we might be interested in updating which we can
513 // do fast in the flags (minor_edit). I think the default
514 // update_versiondata will work fine...
515 //function update_versiondata($pagename, $version, $data) {
518 function set_links($pagename, $links)
520 // Update link table.
521 // FIXME: optimize: mysql can do this all in one big INSERT.
524 extract($this->_table_names);
527 $pageid = $this->_get_pageid($pagename, true);
529 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
532 foreach ($links as $link) {
533 $linkto = $link['linkto'];
534 if ($linkto === "") { // ignore attributes
537 if (isset($link['relation']))
538 $relation = $this->_get_pageid($link['relation'], true);
542 if (isset($linkseen[$linkto]) and !$relation)
545 $linkseen[$linkto] = true;
546 $linkid = $this->_get_pageid($linkto, true);
548 echo("No link for $linkto on page $pagename");
549 //printSimpleTrace(debug_backtrace());
550 trigger_error("No link for $linkto on page $pagename");
553 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
554 . " VALUES ($pageid, $linkid, $relation)");
562 * Find pages which link to or are linked from a page.
564 * TESTME relations: get_links is responsible to add the relation to the pagehash
565 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
566 * if (isset($next['linkrelation']))
568 function get_links($pagename, $reversed = true, $include_empty = false,
569 $sortby = '', $limit = '', $exclude = '',
570 $want_relations = false)
573 extract($this->_table_names);
576 list($have, $want) = array('linkee', 'linker');
578 list($have, $want) = array('linker', 'linkee');
579 $orderby = $this->sortby($sortby, 'db', array('pagename'));
580 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
581 if ($exclude) // array of pagenames
582 $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude);
586 $qpagename = $dbh->escapeSimple($pagename);
587 $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
588 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
590 . (!$include_empty ? "$nonempty_tbl, " : '')
591 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
592 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
593 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
594 . " AND $have.pagename='$qpagename'"
595 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
596 //. " GROUP BY $want.id"
600 // extract from,count from limit
601 list($from, $count) = $this->limit($limit);
602 $result = $dbh->limitQuery($sql, $from, $count);
604 $result = $dbh->query($sql);
607 return new WikiDB_backend_PearDB_iter($this, $result);
611 * Find if a page links to another page
613 function exists_link($pagename, $link, $reversed = false)
616 extract($this->_table_names);
619 list($have, $want) = array('linkee', 'linker');
621 list($have, $want) = array('linker', 'linkee');
622 $qpagename = $dbh->escapeSimple($pagename);
623 $qlink = $dbh->escapeSimple($link);
624 $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename='$qlink' THEN 1 ELSE 0 END as result"
625 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
626 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
627 . " AND $have.pagename='$qpagename'"
628 . " AND $want.pagename='$qlink'");
629 return $row['result'];
632 function get_all_pages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
635 extract($this->_table_names);
636 $orderby = $this->sortby($sortby, 'db');
637 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
638 if ($exclude) // array of pagenames
639 $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
643 if (strstr($orderby, 'mtime ')) { // multiple columns possible
644 if ($include_empty) {
646 . $this->page_tbl_fields
647 . " FROM $page_tbl, $recent_tbl, $version_tbl"
648 . " WHERE $page_tbl.id=$recent_tbl.id"
649 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
654 . $this->page_tbl_fields
655 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
656 . " WHERE $nonempty_tbl.id=$page_tbl.id"
657 . " AND $page_tbl.id=$recent_tbl.id"
658 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
663 if ($include_empty) {
665 . $this->page_tbl_fields
667 . ($exclude ? " WHERE $exclude" : '')
671 . $this->page_tbl_fields
672 . " FROM $nonempty_tbl, $page_tbl"
673 . " WHERE $nonempty_tbl.id=$page_tbl.id"
678 if ($limit && $orderby) {
679 // extract from,count from limit
680 list($from, $count) = $this->limit($limit);
681 $result = $dbh->limitQuery($sql, $from, $count);
682 $options = array('limit_by_db' => 1);
684 $result = $dbh->query($sql);
685 $options = array('limit_by_db' => 0);
687 return new WikiDB_backend_PearDB_iter($this, $result, $options);
694 function text_search($search, $fulltext = false, $sortby = '', $limit = '',
698 extract($this->_table_names);
699 $orderby = $this->sortby($sortby, 'db');
700 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
701 //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
703 $searchclass = get_class($this) . "_search";
704 // no need to define it everywhere and then fallback. memory!
705 if (!class_exists($searchclass))
706 $searchclass = "WikiDB_backend_PearDB_search";
707 $searchobj = new $searchclass($search, $dbh);
709 $table = "$nonempty_tbl, $page_tbl";
710 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
711 $fields = $this->page_tbl_fields;
714 $table .= ", $recent_tbl";
715 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
717 $table .= ", $version_tbl";
718 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
720 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
721 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
723 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
725 $search_clause = $search->makeSqlClauseObj($callback);
727 $sql = "SELECT $fields FROM $table"
728 . " WHERE $join_clause"
729 . " AND ($search_clause)"
732 list($from, $count) = $this->limit($limit);
733 $result = $dbh->limitQuery($sql, $from, $count);
735 $result = $dbh->query($sql);
738 $iter = new WikiDB_backend_PearDB_iter($this, $result);
739 $iter->stoplisted = @$searchobj->stoplisted;
743 //Todo: check if the better Mysql MATCH operator is supported,
744 // (ranked search) and also google like expressions.
745 function _sql_match_clause($word)
747 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
748 $word = $this->_dbh->escapeSimple($word);
749 //$page_tbl = $this->_table_names['page_tbl'];
750 //Note: Mysql 4.1.0 has a bug which fails with binary fields.
751 // e.g. if word is lowercased.
752 // http://bugs.mysql.com/bug.php?id=1491
753 return "LOWER(pagename) LIKE '%$word%'";
756 function _sql_casematch_clause($word)
758 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
759 $word = $this->_dbh->escapeSimple($word);
760 return "pagename LIKE '%$word%'";
763 function _fullsearch_sql_match_clause($word)
765 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
766 $word = $this->_dbh->escapeSimple($word);
767 //$page_tbl = $this->_table_names['page_tbl'];
768 //Mysql 4.1.1 has a bug which fails here if word is lowercased.
769 return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
772 function _fullsearch_sql_casematch_clause($word)
774 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
775 $word = $this->_dbh->escapeSimple($word);
776 return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
780 * Find highest or lowest hit counts.
782 function most_popular($limit = 20, $sortby = '-hits')
785 extract($this->_table_names);
791 $order = "hits DESC";
792 $where = " AND hits > 0";
795 if ($sortby != '-hits') {
796 if ($order = $this->sortby($sortby, 'db'))
797 $orderby = " ORDER BY " . $order;
799 $orderby = " ORDER BY $order";
801 //$limitclause = $limit ? " LIMIT $limit" : '';
803 . $this->page_tbl_fields
804 . " FROM $nonempty_tbl, $page_tbl"
805 . " WHERE $nonempty_tbl.id=$page_tbl.id"
809 list($from, $count) = $this->limit($limit);
810 $result = $dbh->limitQuery($sql, $from, $count);
812 $result = $dbh->query($sql);
815 return new WikiDB_backend_PearDB_iter($this, $result);
819 * Find recent changes.
821 function most_recent($params)
825 $include_minor_revisions = false;
826 $exclude_major_revisions = false;
827 $include_all_revisions = false;
831 extract($this->_table_names);
835 $pick[] = "mtime >= $since";
837 if ($include_all_revisions) {
838 // Include all revisions of each page.
839 $table = "$page_tbl, $version_tbl";
840 $join_clause = "$page_tbl.id=$version_tbl.id";
842 if ($exclude_major_revisions) {
843 // Include only minor revisions
844 $pick[] = "minor_edit <> 0";
845 } elseif (!$include_minor_revisions) {
846 // Include only major revisions
847 $pick[] = "minor_edit = 0";
850 $table = "$page_tbl, $recent_tbl";
851 $join_clause = "$page_tbl.id=$recent_tbl.id";
852 $table .= ", $version_tbl";
853 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
855 if ($exclude_major_revisions) {
856 // Include only most recent minor revision
857 $pick[] = 'version=latestminor';
858 } elseif (!$include_minor_revisions) {
859 // Include only most recent major revision
860 $pick[] = 'version=latestmajor';
862 // Include only the latest revision (whether major or minor).
863 $pick[] = 'version=latestversion';
871 // $limitclause = $limit ? " LIMIT $limit" : '';
872 $where_clause = $join_clause;
874 $where_clause .= " AND " . join(" AND ", $pick);
876 // FIXME: use SQL_BUFFER_RESULT for mysql?
878 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
880 . " WHERE $where_clause"
881 . " ORDER BY mtime $order";
883 list($from, $count) = $this->limit($limit);
884 $result = $dbh->limitQuery($sql, $from, $count);
886 $result = $dbh->query($sql);
888 return new WikiDB_backend_PearDB_iter($this, $result);
892 * Find referenced empty pages.
894 function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
897 extract($this->_table_names);
898 if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom')))
899 $orderby = 'ORDER BY ' . $orderby;
901 if ($exclude_from) // array of pagenames
902 $exclude_from = " AND pp.pagename NOT IN " . $this->_sql_set($exclude_from);
903 if ($exclude) // array of pagenames
904 $exclude = " AND p.pagename NOT IN " . $this->_sql_set($exclude);
905 $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
906 . " FROM $page_tbl p, $link_tbl linked"
907 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
908 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
909 . " WHERE ne.id IS NULL"
910 . " AND p.id = linked.linkfrom"
915 // oci8 error: WHERE NULL = NULL appended
916 list($from, $count) = $this->limit($limit);
917 $result = $dbh->limitQuery($sql, $from, $count * 3);
919 $result = $dbh->query($sql);
921 return new WikiDB_backend_PearDB_generic_iter($this, $result);
924 function _sql_set(&$pagenames)
927 foreach ($pagenames as $p) {
928 $s .= ("'" . $this->_dbh->escapeSimple($p) . "',");
930 return substr($s, 0, -1) . ")";
934 * Rename page in the database.
936 function rename_page($pagename, $to)
939 extract($this->_table_names);
942 if (($id = $this->_get_pageid($pagename, false))) {
943 if ($new = $this->_get_pageid($to, false)) {
945 // This page does not exist (already verified before), but exists in the page table.
946 // So we delete this page.
947 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
948 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
949 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
950 // We have to fix all referring tables to the old id
951 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
952 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
953 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
955 $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
956 $dbh->escapeSimple($to)));
962 function _update_recent_table($pageid = false)
965 extract($this->_table_names);
966 extract($this->_expressions);
968 $pageid = (int)$pageid;
971 $dbh->query("DELETE FROM $recent_tbl"
972 . ($pageid ? " WHERE id=$pageid" : ""));
973 $dbh->query("INSERT INTO $recent_tbl"
974 . " (id, latestversion, latestmajor, latestminor)"
975 . " SELECT id, $maxversion, $maxmajor, $maxminor"
976 . " FROM $version_tbl"
977 . ($pageid ? " WHERE id=$pageid" : "")
982 function _update_nonempty_table($pageid = false)
985 extract($this->_table_names);
987 $pageid = (int)$pageid;
989 extract($this->_expressions);
991 $dbh->query("DELETE FROM $nonempty_tbl"
992 . ($pageid ? " WHERE id=$pageid" : ""));
993 $dbh->query("INSERT INTO $nonempty_tbl (id)"
994 . " SELECT $recent_tbl.id"
995 . " FROM $recent_tbl, $version_tbl"
996 . " WHERE $recent_tbl.id=$version_tbl.id"
997 . " AND version=latestversion"
998 // We have some specifics here (Oracle)
999 //. " AND content<>''"
1000 . " AND content $notempty"
1001 . ($pageid ? " AND $recent_tbl.id=$pageid" : ""));
1007 * Grab a write lock on the tables in the SQL database.
1009 * Calls can be nested. The tables won't be unlocked until
1010 * _unlock_database() is called as many times as _lock_database().
1014 function lock($tables = false, $write_lock = true)
1016 if ($this->_lock_count++ == 0)
1017 $this->_lock_tables($write_lock);
1021 * Actually lock the required tables.
1023 function _lock_tables($write_lock)
1025 trigger_error("virtual", E_USER_ERROR);
1029 * Release a write lock on the tables in the SQL database.
1033 * @param $force boolean Unlock even if not every call to lock() has been matched
1034 * by a call to unlock().
1036 * @see _lock_database
1038 function unlock($tables = false, $force = false)
1040 if ($this->_lock_count == 0)
1042 if (--$this->_lock_count <= 0 || $force) {
1043 $this->_unlock_tables();
1044 $this->_lock_count = 0;
1049 * Actually unlock the required tables.
1051 function _unlock_tables($write_lock)
1053 trigger_error("virtual", E_USER_ERROR);
1060 function _serialize($data)
1064 assert(is_array($data));
1065 return serialize($data);
1071 function _unserialize($data)
1073 return empty($data) ? array() : unserialize($data);
1077 * Callback for PEAR (DB) errors.
1081 * @param A PEAR_error object.
1083 function _pear_error_callback($error)
1085 if ($this->_is_false_error($error))
1088 $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
1090 trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1094 * Detect false errors messages from PEAR DB.
1096 * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1097 * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1098 * return any data. (So when a "LOCK" command doesn't return any data,
1099 * DB reports it as an error, when in fact, it's not.)
1102 * @return bool True iff error is not really an error.
1104 function _is_false_error($error)
1106 if ($error->getCode() != DB_ERROR)
1109 $query = $this->_dbh->last_query;
1111 if (!preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1112 . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)
1114 // Last query was not of the sort which doesn't return any data.
1115 //" <--kludge for brain-dead syntax coloring
1119 if (!in_array('ismanip', get_class_methods('DB'))) {
1120 // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1121 // does not have the DB::isManip method.
1125 if (DB::isManip($query)) {
1126 // If Pear thinks it's an isManip then it wouldn't have thrown
1127 // the error we're testing for....
1134 function _pear_error_message($error)
1136 $class = get_class($this);
1137 $message = "$class: fatal database error\n"
1138 . "\t" . $error->getMessage() . "\n"
1139 . "\t(" . $error->getDebugInfo() . ")\n";
1141 // Prevent password from being exposed during a connection error
1142 $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1143 '\\1:XXXXXXXX', $this->_dsn);
1144 return str_replace($this->_dsn, $safe_dsn, $message);
1148 * Filter PHP errors notices from PEAR DB code.
1150 * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1151 * errors and notices. This is an error callback (for use with
1152 * ErrorManager which will filter out those spurious messages.)
1153 * @see _is_false_error, ErrorManager
1156 function _pear_notice_filter($err)
1158 return ($err->isNotice()
1159 && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1160 && $err->errline == 126
1161 && preg_match('/Undefined offset: +0\b/', $err->errstr));
1164 /* some variables and functions for DB backend abstraction (action=upgrade) */
1167 return $this->_dbh->dsn['database'];
1170 function backendType()
1172 return $this->_dbh->phptype;
1175 function connection()
1177 return $this->_dbh->connection;
1180 function getRow($query)
1182 return $this->_dbh->getRow($query);
1185 function listOfTables()
1187 return $this->_dbh->getListOf('tables');
1190 function listOfFields($database, $table)
1192 if ($this->backendType() == 'mysql') {
1194 assert(!empty($database));
1195 assert(!empty($table));
1196 $result = mysql_list_fields($database, $table, $this->_dbh->connection) or
1197 trigger_error(__FILE__ . ':' . __LINE__ . ' ' . mysql_error(), E_USER_WARNING);
1198 if (!$result) return array();
1199 $columns = mysql_num_fields($result);
1200 for ($i = 0; $i < $columns; $i++) {
1201 $fields[] = mysql_field_name($result, $i);
1203 mysql_free_result($result);
1206 // TODO: try ADODB version?
1207 trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1216 * This class is a generic iterator.
1218 * WikiDB_backend_PearDB_iter only iterates over things that have
1219 * 'pagename', 'pagedata', etc. etc.
1221 * Probably WikiDB_backend_PearDB_iter and this class should be merged
1222 * (most of the code is cut-and-paste :-( ), but I am trying to make
1223 * changes that could be merged easily.
1225 * @author: Dan Frankowski
1227 class WikiDB_backend_PearDB_generic_iter
1228 extends WikiDB_backend_iterator
1230 function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL)
1232 if (DB::isError($query_result)) {
1233 // This shouldn't happen, I thought.
1234 $backend->_pear_error_callback($query_result);
1237 $this->_backend = &$backend;
1238 $this->_result = $query_result;
1239 $this->_options = $field_list;
1244 if (!$this->_result)
1246 return $this->_result->numRows();
1251 if (!$this->_result)
1254 $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1265 if ($this->_result) {
1266 $this->_result->MoveFirst();
1272 if ($this->_result) {
1273 $this->_result->free();
1274 $this->_result = false;
1281 while ($page = $this->next())
1287 class WikiDB_backend_PearDB_iter
1288 extends WikiDB_backend_PearDB_generic_iter
1293 $backend = &$this->_backend;
1294 if (!$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