1 <?php //rcs_id('$Id$');
2 require_once('lib/PageType.php');
5 * The classes in the file define the interface to the
9 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
10 * Minor enhancements by Reini Urban
14 * Force the creation of a new revision.
15 * @see WikiDB_Page::createRevision()
17 if (!defined('WIKIDB_FORCE_CREATE'))
18 define('WIKIDB_FORCE_CREATE', -1);
21 * Abstract base class for the database used by PhpWiki.
23 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
24 * turn contain <tt>WikiDB_PageRevision</tt>s.
26 * Conceptually a <tt>WikiDB</tt> contains all possible
27 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
28 * Since all possible pages are already contained in a WikiDB, a call
29 * to WikiDB::getPage() will never fail (barring bugs and
30 * e.g. filesystem or SQL database problems.)
32 * Also each <tt>WikiDB_Page</tt> always contains at least one
33 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
34 * [PageName] here."). This default content has a version number of
37 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
38 * only create new revisions or delete old ones --- one can not modify
39 * an existing revision.
43 * Open a WikiDB database.
45 * This is a static member function. This function inspects its
46 * arguments to determine the proper subclass of WikiDB to
47 * instantiate, and then it instantiates it.
51 * @param hash $dbparams Database configuration parameters.
52 * Some pertinent parameters are:
55 * <dd> The back-end type. Current supported types are:
58 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
59 * library. (More stable and conservative)
61 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
63 * <dd> Dba based backend. The default and by far the fastest.
71 * <dd> (Used by the SQL and ADODB backends.)
72 * The DSN specifying which database to connect to.
75 * <dd> Prefix to be prepended to database tables (and file names).
78 * <dd> (Used by the dba backend.)
79 * Which directory db files reside in.
82 * <dd> Used only by the dba backend so far.
83 * And: When optimizing mysql it closes timed out mysql processes.
84 * otherwise only used for dba: Timeout in seconds for opening (and
85 * obtaining lock) on the dbm file.
88 * <dd> (Used by the dba backend.)
90 * Which dba handler to use. Good choices are probably either
94 * <dd> Either set by config.ini: READONLY = true or detected automatically
95 * when a database can be read but cannot be updated.
98 * @return WikiDB A WikiDB object.
100 function open ($dbparams) {
101 $dbtype = $dbparams{'dbtype'};
102 include_once("lib/WikiDB/$dbtype.php");
104 $class = 'WikiDB_' . $dbtype;
105 return new $class ($dbparams);
115 function WikiDB (&$backend, $dbparams) {
116 $this->_backend =& $backend;
117 // don't do the following with the auth_dsn!
118 if (isset($dbparams['auth_dsn'])) return;
120 $this->_cache = new WikiDB_cache($backend);
121 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
123 // If the database doesn't yet have a timestamp, initialize it now.
124 if ($this->get('_timestamp') === false)
128 if ((int)DEBUG & _DEBUG_SQL) {
129 $this->_backend->check();
131 // might be changed when opening the database fails
132 $this->readonly = defined("READONLY") ? READONLY : false;
136 * Close database connection.
138 * The database may no longer be used after it is closed.
140 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
141 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
142 * which have been obtained from it.
147 $this->_backend->close();
148 $this->_cache->close();
152 * Get a WikiDB_Page from a WikiDB.
154 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
155 * therefore this method never fails.
158 * @param string $pagename Which page to get.
159 * @return WikiDB_Page The requested WikiDB_Page.
161 function getPage($pagename) {
162 static $error_displayed = false;
163 $pagename = (string) $pagename;
165 if ($pagename === '') {
166 if ($error_displayed) return false;
167 $error_displayed = true;
168 if (function_exists("xdebug_get_function_stack"))
169 var_dump(xdebug_get_function_stack());
170 trigger_error("empty pagename", E_USER_WARNING);
174 assert($pagename != '');
176 return new WikiDB_Page($this, $pagename);
180 * Determine whether page exists (in non-default form).
183 * $is_page = $dbi->isWikiPage($pagename);
187 * $page = $dbi->getPage($pagename);
188 * $current = $page->getCurrentRevision();
189 * $is_page = ! $current->hasDefaultContents();
191 * however isWikiPage may be implemented in a more efficient
192 * manner in certain back-ends.
195 * @param string $pagename string Which page to check.
196 * @return boolean True if the page actually exists with
197 * non-default contents in the WikiDataBase.
199 function isWikiPage ($pagename) {
200 $page = $this->getPage($pagename);
201 return ($page and $page->exists());
205 * Delete page from the WikiDB.
207 * Deletes the page from the WikiDB with the possibility to revert and diff.
208 * //Also resets all page meta-data to the default values.
210 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
213 * @param string $pagename Name of page to delete.
216 function deletePage($pagename) {
217 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
218 // don't create empty revisions of already purged pages.
219 if ($this->_backend->get_latest_version($pagename))
220 $result = $this->_cache->delete_page($pagename);
224 /* Generate notification emails */
225 if (ENABLE_MAILNOTIFY) {
226 include_once("lib/MailNotify.php");
227 $MailNotify = new MailNotify($pagename);
228 $MailNotify->onDeletePage ($this, $pagename);
231 //How to create a RecentChanges entry with explaining summary? Dynamically
233 $page = $this->getPage($pagename);
234 $current = $page->getCurrentRevision();
235 $meta = $current->_data;
236 $version = $current->getVersion();
237 $meta['summary'] = _("removed");
238 $page->save($current->getPackedContent(), $version + 1, $meta);
244 * Completely remove the page from the WikiDB, without undo possibility.
246 * @param string $pagename Name of page to delete.
249 function purgePage($pagename) {
250 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
251 $result = $this->_cache->purge_page($pagename);
252 $this->deletePage($pagename); // just for the notification
257 * Retrieve all pages.
259 * Gets the set of all pages with non-default contents.
263 * @param boolean $include_empty Optional. Normally pages whose most
264 * recent revision has empty content are considered to be
265 * non-existant. Unless $include_defaulted is set to true, those
266 * pages will not be returned.
267 * @param string or false $sortby Optional. "+-column,+-column2".
268 * If false the result is faster in natural order.
269 * @param string or false $limit Optional. Encoded as "$offset,$count".
270 * $offset defaults to 0.
271 * @param string $exclude: Optional comma-seperated list of pagenames.
273 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
274 * in the WikiDB which have non-default contents.
276 function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
278 // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
280 $mem = ini_get("memory_limit");
281 if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
283 $GLOBALS['request']->setArg('limit', $limit);
284 $GLOBALS['request']->setArg('paging', 'auto');
287 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
289 return new WikiDB_PageIterator($this, $result,
290 array('include_empty' => $include_empty,
291 'exclude' => $exclude,
292 'limit' => $result->limit()));
298 * @param boolean $include_empty If true include also empty pages
299 * @param string $exclude: comma-seperated list of pagenames.
300 * TBD: array of pagenames
304 function numPages($include_empty=false, $exclude='') {
305 if (method_exists($this->_backend, 'numPages'))
306 // FIXME: currently are all args ignored.
307 $count = $this->_backend->numPages($include_empty, $exclude);
309 // FIXME: exclude ignored.
310 $iter = $this->getAllPages($include_empty, false, false, $exclude);
311 $count = $iter->count();
320 * Search for pages containing (or not containing) certain words
323 * Pages are returned in alphabetical order whenever it is
324 * practical to do so.
325 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
328 * @param TextSearchQuery $search A TextSearchQuery object
329 * @param string or false $sortby Optional. "+-column,+-column2".
330 * If false the result is faster in natural order.
331 * @param string or false $limit Optional. Encoded as "$offset,$count".
332 * $offset defaults to 0.
333 * @param string $exclude: Optional comma-seperated list of pagenames.
334 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
335 * @see TextSearchQuery
337 function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
338 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
339 $options = array('exclude' => $exclude,
341 //if (isset($result->_count)) $options['count'] = $result->_count;
342 return new WikiDB_PageIterator($this, $result, $options);
348 * Search for pages containing (or not containing) certain words
349 * in their entire text (this includes the page content and the
352 * Pages are returned in alphabetical order whenever it is
353 * practical to do so.
354 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
358 * @param TextSearchQuery $search A TextSearchQuery object.
359 * @param string or false $sortby Optional. "+-column,+-column2".
360 * If false the result is faster in natural order.
361 * @param string or false $limit Optional. Encoded as "$offset,$count".
362 * $offset defaults to 0.
363 * @param string $exclude: Optional comma-seperated list of pagenames.
364 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
365 * @see TextSearchQuery
367 function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
368 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
369 return new WikiDB_PageIterator($this, $result,
370 array('exclude' => $exclude,
372 'stoplisted' => $result->stoplisted
377 * Find the pages with the greatest hit counts.
379 * Pages are returned in reverse order by hit count.
383 * @param integer $limit The maximum number of pages to return.
384 * Set $limit to zero to return all pages. If $limit < 0, pages will
385 * be sorted in decreasing order of popularity.
386 * @param string or false $sortby Optional. "+-column,+-column2".
387 * If false the result is faster in natural order.
389 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
392 function mostPopular($limit = 20, $sortby = '-hits') {
393 $result = $this->_backend->most_popular($limit, $sortby);
394 return new WikiDB_PageIterator($this, $result);
398 * Find recent page revisions.
400 * Revisions are returned in reverse order by creation time.
404 * @param hash $params This hash is used to specify various optional
408 * <dd> (integer) At most this many revisions will be returned.
410 * <dd> (integer) Only revisions since this time (unix-timestamp)
412 * <dt> include_minor_revisions
413 * <dd> (boolean) Also include minor revisions. (Default is not to.)
414 * <dt> exclude_major_revisions
415 * <dd> (boolean) Don't include non-minor revisions.
416 * (Exclude_major_revisions implies include_minor_revisions.)
417 * <dt> include_all_revisions
418 * <dd> (boolean) Return all matching revisions for each page.
419 * Normally only the most recent matching revision is returned
423 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
424 * containing the matching revisions.
426 function mostRecent($params = false) {
427 $result = $this->_backend->most_recent($params);
428 return new WikiDB_PageRevisionIterator($this, $result);
434 * @param string or false $sortby Optional. "+-column,+-column2".
435 * If false the result is faster in natural order.
436 * @param string or false $limit Optional. Encoded as "$offset,$count".
437 * $offset defaults to 0.
438 * @return Iterator A generic iterator containing rows of
439 * (duplicate) pagename, wantedfrom.
441 function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
442 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
443 //return new WikiDB_PageIterator($this, $result);
447 * Generic interface to the link table. Esp. useful to search for rdf triples as in
448 * SemanticSearch and ListRelations.
452 * @param $pages object A TextSearchQuery object.
453 * @param $search object A TextSearchQuery object.
454 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
455 * linktype parameter:
458 * <dd> search for simple out-links
460 * <dd> in-links, i.e BackLinks
462 * <dd> the first part in a <>::<> link
464 * <dd> the first part in a <>:=<> link
466 * @param $relation object An optional TextSearchQuery to match the
467 * relation name. Ignored on simple in-out links.
469 * @return Iterator A generic iterator containing links to pages or values.
470 * hash of "pagename", "linkname", "linkvalue.
472 function linkSearch($pages, $search, $linktype, $relation=false) {
473 return $this->_backend->link_search($pages, $search, $linktype, $relation);
477 * Return a simple list of all defined relations (and attributes), mainly
478 * for the SemanticSearch autocompletion.
482 * @return array of strings
484 function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
485 if (method_exists($this->_backend, "list_relations"))
486 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
487 // dumb, slow fallback. no iter, so simply define it here.
488 $relations = array();
489 $iter = $this->getAllPages();
490 while ($page = $iter->next()) {
491 $reliter = $page->getRelations();
493 while ($rel = $reliter->next()) {
494 // if there's no pagename it's an attribute
495 $names[] = $rel->getName();
497 $relations = array_merge($relations, $names);
509 * Call the appropriate backend method.
512 * @param string $from Page to rename
513 * @param string $to New name
514 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
515 * @return boolean true or false
517 function renamePage($from, $to, $updateWikiLinks = false) {
518 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
519 assert(is_string($from) && $from != '');
520 assert(is_string($to) && $to != '');
522 if (method_exists($this->_backend, 'rename_page')) {
523 $oldpage = $this->getPage($from);
524 $newpage = $this->getPage($to);
525 //update all WikiLinks in existing pages
526 //non-atomic! i.e. if rename fails the links are not undone
527 if ($updateWikiLinks) {
528 $lookbehind = "/(?<=[\W:])\Q";
529 $lookahead = "\E(?=[\W:])/";
530 if (!check_php_version(4,3,3)) {
531 $lookbehind = "/(?<=[\W:])";
532 $lookahead = "(?=[\W:])/";
533 $from = preg_quote($from, "/");
534 $to = preg_quote($to, "/");
536 require_once('lib/plugin/WikiAdminSearchReplace.php');
537 $links = $oldpage->getBackLinks();
538 while ($linked_page = $links->next()) {
539 WikiPlugin_WikiAdminSearchReplace::replaceHelper
541 $linked_page->getName(),
542 $lookbehind.$from.$lookahead, $to,
545 // FIXME: Disabled to avoid recursive modification when renaming
546 // a page like 'PageFoo to 'PageFooTwo'
548 $links = $newpage->getBackLinks();
549 while ($linked_page = $links->next()) {
550 WikiPlugin_WikiAdminSearchReplace::replaceHelper
552 $linked_page->getName(),
553 $lookbehind.$from.$lookahead, $to,
558 if ($oldpage->exists() and ! $newpage->exists()) {
559 if ($result = $this->_backend->rename_page($from, $to)) {
560 // create a RecentChanges entry with explaining summary
561 $page = $this->getPage($to);
562 $current = $page->getCurrentRevision();
563 $meta = $current->_data;
564 $version = $current->getVersion();
565 $meta['summary'] = sprintf(_("renamed from %s"), $from);
566 unset($meta['mtime']); // force new date
567 $page->save($current->getPackedContent(), $version + 1, $meta);
569 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
570 // if a version 0 exists try it also.
571 $result = $this->_backend->rename_page($from, $to);
574 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
577 /* Generate notification emails? */
578 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
579 $notify = $this->get('notify');
580 if (!empty($notify) and is_array($notify)) {
581 include_once("lib/MailNotify.php");
582 $MailNotify = new MailNotify($from);
583 $MailNotify->onRenamePage ($this, $from, $to);
589 /** Get timestamp when database was last modified.
591 * @return string A string consisting of two integers,
592 * separated by a space. The first is the time in
593 * unix timestamp format, the second is a modification
594 * count for the database.
596 * The idea is that you can cast the return value to an
597 * int to get a timestamp, or you can use the string value
598 * as a good hash for the entire database.
600 function getTimestamp() {
601 $ts = $this->get('_timestamp');
602 return sprintf("%d %d", $ts[0], $ts[1]);
606 * Update the database timestamp.
610 $ts = $this->get('_timestamp');
611 $this->set('_timestamp', array(time(), $ts[1] + 1));
615 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
617 function get_db_version() {
618 return (float) $this->get('_db_version');
620 function set_db_version($ver) {
621 return $this->set('_db_version', (float)$ver);
625 * Access WikiDB global meta-data.
627 * NOTE: this is currently implemented in a hackish and
628 * not very efficient manner.
632 * @param string $key Which meta data to get.
633 * Some reserved meta-data keys are:
635 * <dt>'_timestamp' <dd> Data used by getTimestamp().
638 * @return scalar The requested value, or false if the requested data
642 if (!$key || $key[0] == '%')
645 * Hack Alert: We can use any page (existing or not) to store
646 * this data (as long as we always use the same one.)
648 $gd = $this->getPage('global_data');
649 $data = $gd->get('__global');
651 if ($data && isset($data[$key]))
658 * Set global meta-data.
660 * NOTE: this is currently implemented in a hackish and
661 * not very efficient manner.
666 * @param string $key Meta-data key to set.
667 * @param string $newval New value.
669 function set($key, $newval) {
670 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
671 if (!$key || $key[0] == '%')
674 $gd = $this->getPage('global_data');
675 $data = $gd->get('__global');
682 $data[$key] = $newval;
684 $gd->set('__global', $data);
687 /* TODO: these are really backend methods */
689 // SQL result: for simple select or create/update queries
690 // returns the database specific resource type
691 function genericSqlQuery($sql, $args=false) {
692 if (function_exists('debug_backtrace')) { // >= 4.3.0
693 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
695 trigger_error("no SQL database", E_USER_ERROR);
699 // SQL iter: for simple select or create/update queries
700 // returns the generic iterator object (count,next)
701 function genericSqlIter($sql, $field_list = NULL) {
702 if (function_exists('debug_backtrace')) { // >= 4.3.0
703 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
705 trigger_error("no SQL database", E_USER_ERROR);
709 // see backend upstream methods
710 // ADODB adds surrounding quotes, SQL not yet!
711 function quote ($s) {
717 if (!$request->_dbi) return false;
718 else return false; /* so far only needed for sql so false it.
719 later we have to check dba also */
722 function getParam($param) {
724 if (isset($DBParams[$param])) return $DBParams[$param];
725 elseif ($param == 'prefix') return '';
729 function getAuthParam($param) {
730 global $DBAuthParams;
731 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
732 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
733 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
740 * A base class which representing a wiki-page within a
743 * A WikiDB_Page contains a number (at least one) of
744 * WikiDB_PageRevisions.
748 function WikiDB_Page(&$wikidb, $pagename) {
749 $this->_wikidb = &$wikidb;
750 $this->_pagename = $pagename;
752 if (!(is_string($pagename) and $pagename != '')) {
753 if (function_exists("xdebug_get_function_stack")) {
754 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
755 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
756 printSimpleTrace(debug_backtrace());
758 trigger_error("empty pagename", E_USER_WARNING);
762 assert(is_string($pagename) and $pagename != '');
767 * Get the name of the wiki page.
771 * @return string The page name.
774 return $this->_pagename;
777 // To reduce the memory footprint for larger sets of pagelists,
778 // we don't cache the content (only true or false) and
779 // we purge the pagedata (_cached_html) also
781 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
782 $current = $this->getCurrentRevision(false);
783 if (!$current) return false;
784 return ! $current->hasDefaultContents();
788 * Delete an old revision of a WikiDB_Page.
790 * Deletes the specified revision of the page.
791 * It is a fatal error to attempt to delete the current revision.
795 * @param integer $version Which revision to delete. (You can also
796 * use a WikiDB_PageRevision object here.)
798 function deleteRevision($version) {
799 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
800 $backend = &$this->_wikidb->_backend;
801 $cache = &$this->_wikidb->_cache;
802 $pagename = &$this->_pagename;
804 $version = $this->_coerce_to_version($version);
808 $backend->lock(array('page','version'));
809 $latestversion = $cache->get_latest_version($pagename);
810 if ($latestversion && ($version == $latestversion)) {
811 $backend->unlock(array('page','version'));
812 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
813 $pagename), E_USER_ERROR);
817 $cache->delete_versiondata($pagename, $version);
818 $backend->unlock(array('page','version'));
822 * Delete a revision, or possibly merge it with a previous
826 * Suppose an author make a (major) edit to a page. Shortly
827 * after that the same author makes a minor edit (e.g. to fix
828 * spelling mistakes he just made.)
830 * Now some time later, where cleaning out old saved revisions,
831 * and would like to delete his minor revision (since there's
832 * really no point in keeping minor revisions around for a long
835 * Note that the text after the minor revision probably represents
836 * what the author intended to write better than the text after
837 * the preceding major edit.
839 * So what we really want to do is merge the minor edit with the
842 * We will only do this when:
844 * <li>The revision being deleted is a minor one, and
845 * <li>It has the same author as the immediately preceding revision.
848 function mergeRevision($version) {
849 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
850 $backend = &$this->_wikidb->_backend;
851 $cache = &$this->_wikidb->_cache;
852 $pagename = &$this->_pagename;
854 $version = $this->_coerce_to_version($version);
858 $backend->lock(array('version'));
859 $latestversion = $cache->get_latest_version($pagename);
860 if ($latestversion && $version == $latestversion) {
861 $backend->unlock(array('version'));
862 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
863 $pagename), E_USER_ERROR);
867 $versiondata = $cache->get_versiondata($pagename, $version, true);
869 // Not there? ... we're done!
870 $backend->unlock(array('version'));
874 if ($versiondata['is_minor_edit']) {
875 $previous = $backend->get_previous_version($pagename, $version);
877 $prevdata = $cache->get_versiondata($pagename, $previous);
878 if ($prevdata['author_id'] == $versiondata['author_id']) {
879 // This is a minor revision, previous version is
880 // by the same author. We will merge the
882 $cache->update_versiondata($pagename, $previous,
883 array('%content' => $versiondata['%content'],
884 '_supplanted' => $versiondata['_supplanted']));
889 $cache->delete_versiondata($pagename, $version);
890 $backend->unlock(array('version'));
895 * Create a new revision of a {@link WikiDB_Page}.
899 * @param int $version Version number for new revision.
900 * To ensure proper serialization of edits, $version must be
901 * exactly one higher than the current latest version.
902 * (You can defeat this check by setting $version to
903 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
905 * @param string $content Contents of new revision.
907 * @param hash $metadata Metadata for new revision.
908 * All values in the hash should be scalars (strings or integers).
910 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
912 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
913 * $version was incorrect, returns false
915 function createRevision($version, &$content, $metadata, $links) {
916 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
917 $backend = &$this->_wikidb->_backend;
918 $cache = &$this->_wikidb->_cache;
919 $pagename = &$this->_pagename;
920 $cache->invalidate_cache($pagename);
922 $backend->lock(array('version','page','recent','link','nonempty'));
924 $latestversion = $backend->get_latest_version($pagename);
925 $newversion = ($latestversion ? $latestversion : 0) + 1;
926 assert($newversion >= 1);
928 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
929 $backend->unlock(array('version','page','recent','link','nonempty'));
935 foreach ($data as $key => $val) {
936 if (empty($val) || $key[0] == '_' || $key[0] == '%')
940 assert(!empty($data['author']));
941 if (empty($data['author_id']))
942 @$data['author_id'] = $data['author'];
944 if (empty($data['mtime']))
945 $data['mtime'] = time();
947 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
948 // Ensure mtimes are monotonic.
949 $pdata = $cache->get_versiondata($pagename, $latestversion);
950 if ($data['mtime'] < $pdata['mtime']) {
951 trigger_error(sprintf(_("%s: Date of new revision is %s"),
952 $pagename,"'non-monotonic'"),
954 $data['orig_mtime'] = $data['mtime'];
955 $data['mtime'] = $pdata['mtime'];
958 // FIXME: use (possibly user specified) 'mtime' time or
960 $cache->update_versiondata($pagename, $latestversion,
961 array('_supplanted' => $data['mtime']));
964 $data['%content'] = &$content;
966 $cache->set_versiondata($pagename, $newversion, $data);
968 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
969 //':deleted' => empty($content)));
971 $backend->set_links($pagename, $links);
973 $backend->unlock(array('version','page','recent','link','nonempty'));
975 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
979 /** A higher-level interface to createRevision.
981 * This takes care of computing the links, and storing
982 * a cached version of the transformed wiki-text.
984 * @param string $wikitext The page content.
986 * @param int $version Version number for new revision.
987 * To ensure proper serialization of edits, $version must be
988 * exactly one higher than the current latest version.
989 * (You can defeat this check by setting $version to
990 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
992 * @param hash $meta Meta-data for new revision.
994 function save($wikitext, $version, $meta, $formatted = null) {
995 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
996 if (is_null($formatted))
997 $formatted = new TransformedText($this, $wikitext, $meta);
998 $type = $formatted->getType();
999 $meta['pagetype'] = $type->getName();
1000 $links = $formatted->getWikiPageLinks(); // linkto => relation
1001 $attributes = array();
1002 foreach ($links as $link) {
1003 if ($link['linkto'] === "" and !empty($link['relation'])) {
1004 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1007 $meta['attribute'] = $attributes;
1009 $backend = &$this->_wikidb->_backend;
1010 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1011 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1012 $this->set('_cached_html', $formatted->pack());
1014 // FIXME: probably should have some global state information
1015 // in the backend to control when to optimize.
1017 // We're doing this here rather than in createRevision because
1018 // postgresql can't optimize while locked.
1019 if (((int)DEBUG & _DEBUG_SQL)
1020 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1021 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1022 if ($backend->optimize()) {
1024 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1028 /* Generate notification emails? */
1029 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1030 // Save didn't fail because of concurrent updates.
1031 $notify = $this->_wikidb->get('notify');
1033 and is_array($notify)
1034 and !isa($GLOBALS['request'],'MockRequest'))
1036 include_once("lib/MailNotify.php");
1037 $MailNotify = new MailNotify($newrevision->getName());
1038 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1040 $newrevision->_transformedContent = $formatted;
1042 // more pagechange callbacks: (in a hackish manner for now)
1043 if (ENABLE_RECENTCHANGESBOX
1044 and empty($meta['is_minor_edit'])
1045 and !in_array($GLOBALS['request']->getArg('action'),
1046 array('loadfile','upgrade')))
1048 require_once("lib/WikiPlugin.php");
1049 $w = new WikiPluginLoader;
1050 $p = $w->getPlugin("RecentChangesCached", false);
1051 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1053 return $newrevision;
1057 * Get the most recent revision of a page.
1061 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1063 function getCurrentRevision ($need_content=true) {
1064 $backend = &$this->_wikidb->_backend;
1065 $cache = &$this->_wikidb->_cache;
1066 $pagename = &$this->_pagename;
1068 // Prevent deadlock in case of memory exhausted errors
1069 // Pure selection doesn't really need locking here.
1070 // sf.net bug#927395
1071 // I know it would be better to lock, but with lots of pages this deadlock is more
1072 // severe than occasionally get not the latest revision.
1073 // In spirit to wikiwiki: read fast, edit slower.
1075 $version = $cache->get_latest_version($pagename);
1076 // getRevision gets the content also!
1077 $revision = $this->getRevision($version, $need_content);
1078 //$backend->unlock();
1084 * Get a specific revision of a WikiDB_Page.
1088 * @param integer $version Which revision to get.
1090 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1091 * false if the requested revision does not exist in the {@link WikiDB}.
1092 * Note that version zero of any page always exists.
1094 function getRevision ($version, $need_content=true) {
1095 $cache = &$this->_wikidb->_cache;
1096 $pagename = &$this->_pagename;
1098 if (! $version or $version == -1) // 0 or false
1099 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1101 assert($version > 0);
1102 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1104 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1106 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1111 * Get previous page revision.
1113 * This method find the most recent revision before a specified
1118 * @param integer $version Find most recent revision before this version.
1119 * You can also use a WikiDB_PageRevision object to specify the $version.
1121 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1122 * requested revision does not exist in the {@link WikiDB}. Note that
1123 * unless $version is greater than zero, a revision (perhaps version zero,
1124 * the default revision) will always be found.
1126 function getRevisionBefore ($version=false, $need_content=true) {
1127 $backend = &$this->_wikidb->_backend;
1128 $pagename = &$this->_pagename;
1129 if ($version === false)
1130 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1132 $version = $this->_coerce_to_version($version);
1137 $previous = $backend->get_previous_version($pagename, $version);
1138 $revision = $this->getRevision($previous, $need_content);
1139 //$backend->unlock();
1145 * Get all revisions of the WikiDB_Page.
1147 * This does not include the version zero (default) revision in the
1148 * returned revision set.
1150 * @return WikiDB_PageRevisionIterator A
1151 * WikiDB_PageRevisionIterator containing all revisions of this
1152 * WikiDB_Page in reverse order by version number.
1154 function getAllRevisions() {
1155 $backend = &$this->_wikidb->_backend;
1156 $revs = $backend->get_all_revisions($this->_pagename);
1157 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1161 * Find pages which link to or are linked from a page.
1162 * relations: $backend->get_links is responsible to add the relation to the pagehash
1163 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1164 * if (isset($next['linkrelation']))
1168 * @param boolean $reversed Which links to find: true for backlinks (default).
1170 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1171 * all matching pages.
1173 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1174 $limit='', $exclude='', $want_relations=false)
1176 $backend = &$this->_wikidb->_backend;
1177 $result = $backend->get_links($this->_pagename, $reversed,
1178 $include_empty, $sortby, $limit, $exclude,
1180 return new WikiDB_PageIterator($this->_wikidb, $result,
1181 array('include_empty' => $include_empty,
1182 'sortby' => $sortby,
1184 'exclude' => $exclude,
1185 'want_relations'=> $want_relations));
1189 * All Links from other pages to this page.
1191 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1192 $want_relations=false)
1194 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1197 * Forward Links: All Links from this page to other pages.
1199 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1200 $want_relations=false)
1202 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1205 * Relations: All links from this page to other pages with relation <> 0.
1206 * is_a:=page or population:=number
1208 function getRelations($sortby='', $limit='', $exclude='') {
1209 $backend = &$this->_wikidb->_backend;
1210 $result = $backend->get_links($this->_pagename, false, true,
1211 $sortby, $limit, $exclude,
1213 // we do not care for the linked page versiondata, just the pagename and linkrelation
1214 return new WikiDB_PageIterator($this->_wikidb, $result,
1215 array('include_empty' => true,
1216 'sortby' => $sortby,
1218 'exclude' => $exclude,
1219 'want_relations'=> true));
1223 * possibly faster link existance check. not yet accelerated.
1225 function existLink($link, $reversed=false) {
1226 $backend = &$this->_wikidb->_backend;
1227 if (method_exists($backend,'exists_link'))
1228 return $backend->exists_link($this->_pagename, $link, $reversed);
1229 //$cache = &$this->_wikidb->_cache;
1230 // TODO: check cache if it is possible
1231 $iter = $this->getLinks($reversed, false);
1232 while ($page = $iter->next()) {
1233 if ($page->getName() == $link)
1240 /* Semantic relations are links with the relation pointing to another page,
1241 the so-called "RDF Triple".
1242 [San Diego] is%20a::city
1243 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1246 /* Semantic attributes for a page.
1247 [San Diego] population:=1,305,736
1248 Attributes are links with the relation pointing to another page.
1252 * Access WikiDB_Page non version-specific meta-data.
1256 * @param string $key Which meta data to get.
1257 * Some reserved meta-data keys are:
1259 * <dt>'date' <dd> Created as unixtime
1260 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1261 * <dt>'hits' <dd> Page hit counter.
1262 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1263 * In SQL stored now in an extra column.
1265 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1266 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1267 * E.g. "owner.users"
1268 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1269 * page-headers and content.
1270 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1271 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1274 * @return scalar The requested value, or false if the requested data
1277 function get($key) {
1278 $cache = &$this->_wikidb->_cache;
1279 $backend = &$this->_wikidb->_backend;
1280 if (!$key || $key[0] == '%')
1282 // several new SQL backends optimize this.
1283 if (!WIKIDB_NOCACHE_MARKUP
1284 and $key == '_cached_html'
1285 and method_exists($backend, 'get_cached_html'))
1287 return $backend->get_cached_html($this->_pagename);
1289 $data = $cache->get_pagedata($this->_pagename);
1290 return isset($data[$key]) ? $data[$key] : false;
1294 * Get all the page meta-data as a hash.
1296 * @return hash The page meta-data.
1298 function getMetaData() {
1299 $cache = &$this->_wikidb->_cache;
1300 $data = $cache->get_pagedata($this->_pagename);
1302 foreach ($data as $key => $val) {
1303 if (/*!empty($val) &&*/ $key[0] != '%')
1310 * Set page meta-data.
1315 * @param string $key Meta-data key to set.
1316 * @param string $newval New value.
1318 function set($key, $newval) {
1319 $cache = &$this->_wikidb->_cache;
1320 $backend = &$this->_wikidb->_backend;
1321 $pagename = &$this->_pagename;
1323 assert($key && $key[0] != '%');
1325 // several new SQL backends optimize this.
1326 if (!WIKIDB_NOCACHE_MARKUP
1327 and $key == '_cached_html'
1328 and method_exists($backend, 'set_cached_html'))
1330 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1331 return $backend->set_cached_html($pagename, $newval);
1334 $data = $cache->get_pagedata($pagename);
1336 if (!empty($newval)) {
1337 if (!empty($data[$key]) && $data[$key] == $newval)
1338 return; // values identical, skip update.
1341 if (empty($data[$key]))
1342 return; // values identical, skip update.
1345 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1346 $cache->update_pagedata($pagename, array($key => $newval));
1350 * Increase page hit count.
1352 * FIXME: IS this needed? Probably not.
1354 * This is a convenience function.
1355 * <pre> $page->increaseHitCount(); </pre>
1356 * is functionally identical to
1357 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1358 * but less expensive (ignores the pagadata string)
1360 * Note that this method may be implemented in more efficient ways
1361 * in certain backends.
1365 function increaseHitCount() {
1366 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; }
1367 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1368 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1370 @$newhits = $this->get('hits') + 1;
1371 $this->set('hits', $newhits);
1376 * Return a string representation of the WikiDB_Page
1378 * This is really only for debugging.
1382 * @return string Printable representation of the WikiDB_Page.
1384 function asString () {
1386 printf("[%s:%s\n", get_class($this), $this->getName());
1387 print_r($this->getMetaData());
1389 $strval = ob_get_contents();
1397 * @param integer_or_object $version_or_pagerevision
1398 * Takes either the version number (and int) or a WikiDB_PageRevision
1400 * @return integer The version number.
1402 function _coerce_to_version($version_or_pagerevision) {
1403 if (method_exists($version_or_pagerevision, "getContent"))
1404 $version = $version_or_pagerevision->getVersion();
1406 $version = (int) $version_or_pagerevision;
1408 assert($version >= 0);
1412 function isUserPage ($include_empty = true) {
1413 if (!$include_empty and !$this->exists()) return false;
1414 return $this->get('pref') ? true : false;
1417 // May be empty. Either the stored owner (/Chown), or the first authorized author
1418 function getOwner() {
1419 if ($owner = $this->get('owner'))
1421 // check all revisions forwards for the first author_id
1422 $backend = &$this->_wikidb->_backend;
1423 $pagename = &$this->_pagename;
1424 $latestversion = $backend->get_latest_version($pagename);
1425 for ($v=1; $v <= $latestversion; $v++) {
1426 $rev = $this->getRevision($v,false);
1427 if ($rev and $owner = $rev->get('author_id')) {
1434 // The authenticated author of the first revision or empty if not authenticated then.
1435 function getCreator() {
1436 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1440 // The authenticated author of the current revision.
1441 function getAuthor() {
1442 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1446 /* Semantic Web value, not stored in the links.
1447 * todo: unify with some unit knowledge
1449 function setAttribute($relation, $value) {
1450 $attr = $this->get('attributes');
1452 $attr = array($relation => $value);
1454 $attr[$relation] = $value;
1455 $this->set('attributes', $attr);
1458 function getAttribute($relation) {
1459 $meta = $this->get('attributes');
1463 return $meta[$relation];
1469 * This class represents a specific revision of a WikiDB_Page within
1472 * A WikiDB_PageRevision has read-only semantics. You may only create
1473 * new revisions (and delete old ones) --- you cannot modify existing
1476 class WikiDB_PageRevision
1478 //var $_transformedContent = false; // set by WikiDB_Page::save()
1480 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1481 $versiondata = false)
1483 $this->_wikidb = &$wikidb;
1484 $this->_pagename = $pagename;
1485 $this->_version = $version;
1486 $this->_data = $versiondata ? $versiondata : array();
1487 $this->_transformedContent = false; // set by WikiDB_Page::save()
1491 * Get the WikiDB_Page which this revision belongs to.
1495 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1497 function getPage() {
1498 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1502 * Get the version number of this revision.
1506 * @return integer The version number of this revision.
1508 function getVersion() {
1509 return $this->_version;
1513 * Determine whether this revision has defaulted content.
1515 * The default revision (version 0) of each page, as well as any
1516 * pages which are created with empty content have their content
1517 * defaulted to something like:
1519 * Describe [ThisPage] here.
1524 * @return boolean Returns true if the page has default content.
1526 function hasDefaultContents() {
1527 $data = &$this->_data;
1528 if (!isset($data['%content'])) return true;
1529 if ($data['%content'] === true) return false;
1530 return $data['%content'] === false or $data['%content'] === "";
1534 * Get the content as an array of lines.
1538 * @return array An array of lines.
1539 * The lines should contain no trailing white space.
1541 function getContent() {
1542 return explode("\n", $this->getPackedContent());
1546 * Get the pagename of the revision.
1550 * @return string pagename.
1552 function getPageName() {
1553 return $this->_pagename;
1555 function getName() {
1556 return $this->_pagename;
1560 * Determine whether revision is the latest.
1564 * @return boolean True iff the revision is the latest (most recent) one.
1566 function isCurrent() {
1567 if (!isset($this->_iscurrent)) {
1568 $page = $this->getPage();
1569 $current = $page->getCurrentRevision(false);
1570 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1572 return $this->_iscurrent;
1576 * Get the transformed content of a page.
1578 * @param string $pagetype Override the page-type of the revision.
1580 * @return object An XmlContent-like object containing the page transformed
1583 function getTransformedContent($pagetype_override=false) {
1584 $backend = &$this->_wikidb->_backend;
1586 if ($pagetype_override) {
1587 // Figure out the normal page-type for this page.
1588 $type = PageType::GetPageType($this->get('pagetype'));
1589 if ($type->getName() == $pagetype_override)
1590 $pagetype_override = false; // Not really an override...
1593 if ($pagetype_override) {
1594 // Overriden page type, don't cache (or check cache).
1595 return new TransformedText($this->getPage(),
1596 $this->getPackedContent(),
1597 $this->getMetaData(),
1598 $pagetype_override);
1601 $possibly_cache_results = true;
1603 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1604 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1605 // flush cache for this page.
1606 $page = $this->getPage();
1607 $page->set('_cached_html', ''); // ignored with !USECACHE
1609 $possibly_cache_results = false;
1611 elseif (USECACHE and !$this->_transformedContent) {
1613 if ($this->isCurrent()) {
1614 $page = $this->getPage();
1615 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1618 $possibly_cache_results = false;
1620 //$backend->unlock();
1623 if (!$this->_transformedContent) {
1624 $this->_transformedContent
1625 = new TransformedText($this->getPage(),
1626 $this->getPackedContent(),
1627 $this->getMetaData());
1629 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1630 // If we're still the current version, cache the transfomed page.
1632 if ($this->isCurrent()) {
1633 $page->set('_cached_html', $this->_transformedContent->pack());
1635 //$backend->unlock();
1639 return $this->_transformedContent;
1643 * Get the content as a string.
1647 * @return string The page content.
1648 * Lines are separated by new-lines.
1650 function getPackedContent() {
1651 $data = &$this->_data;
1653 if (empty($data['%content'])
1654 || (!$this->_wikidb->isWikiPage($this->_pagename)
1655 && $this->isCurrent())) {
1656 include_once('lib/InlineParser.php');
1658 // A feature similar to taglines at http://www.wlug.org.nz/
1659 // Lib from http://www.aasted.org/quote/
1660 if (defined('FORTUNE_DIR')
1661 and is_dir(FORTUNE_DIR)
1662 and in_array($GLOBALS['request']->getArg('action'),
1663 array('create','edit')))
1665 include_once("lib/fortune.php");
1666 $fortune = new Fortune();
1667 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1669 $quote = "<verbatim>\n"
1670 . str_replace("\n<br>","\n", $quote)
1671 . "</verbatim>\n\n";
1675 . sprintf(_("Describe %s here."),
1676 "[" . WikiEscape($this->_pagename) . "]");
1678 // Replace empty content with default value.
1679 return sprintf(_("Describe %s here."),
1680 "[" . WikiEscape($this->_pagename) . "]");
1683 // There is (non-default) content.
1684 assert($this->_version > 0);
1686 if (!is_string($data['%content'])) {
1687 // Content was not provided to us at init time.
1688 // (This is allowed because for some backends, fetching
1689 // the content may be expensive, and often is not wanted
1692 // In any case, now we need to get it.
1693 $data['%content'] = $this->_get_content();
1694 assert(is_string($data['%content']));
1697 return $data['%content'];
1700 function _get_content() {
1701 $cache = &$this->_wikidb->_cache;
1702 $pagename = $this->_pagename;
1703 $version = $this->_version;
1705 assert($version > 0);
1707 $newdata = $cache->get_versiondata($pagename, $version, true);
1709 assert(is_string($newdata['%content']));
1710 return $newdata['%content'];
1713 // else revision has been deleted... What to do?
1714 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1715 $version, $pagename);
1720 * Get meta-data for this revision.
1725 * @param string $key Which meta-data to access.
1727 * Some reserved revision meta-data keys are:
1729 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1730 * The 'mtime' meta-value is normally set automatically by the database
1731 * backend, but it may be specified explicitly when creating a new revision.
1733 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1734 * of a page must be monotonically increasing. If an attempt is
1735 * made to create a new revision with an mtime less than that of
1736 * the preceeding revision, the new revisions timestamp is force
1737 * to be equal to that of the preceeding revision. In that case,
1738 * the originally requested mtime is preserved in 'orig_mtime'.
1739 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1740 * This meta-value is <em>always</em> automatically maintained by the database
1741 * backend. (It is set from the 'mtime' meta-value of the superceding
1742 * revision.) '_supplanted' has a value of 'false' for the current revision.
1744 * FIXME: this could be refactored:
1746 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1748 * <dd> Authenticated author of a page. This is used to identify
1749 * the distinctness of authors when cleaning old revisions from
1751 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1752 * <dt> 'summary' <dd> Short change summary entered by page author.
1755 * Meta-data keys must be valid C identifers (they have to start with a letter
1756 * or underscore, and can contain only alphanumerics and underscores.)
1758 * @return string The requested value, or false if the requested value
1761 function get($key) {
1762 if (!$key || $key[0] == '%')
1764 $data = &$this->_data;
1765 return isset($data[$key]) ? $data[$key] : false;
1769 * Get all the revision page meta-data as a hash.
1771 * @return hash The revision meta-data.
1773 function getMetaData() {
1775 foreach ($this->_data as $key => $val) {
1776 if (!empty($val) && $key[0] != '%')
1784 * Return a string representation of the revision.
1786 * This is really only for debugging.
1790 * @return string Printable representation of the WikiDB_Page.
1792 function asString () {
1794 printf("[%s:%d\n", get_class($this), $this->get('version'));
1795 print_r($this->_data);
1796 echo $this->getPackedContent() . "\n]\n";
1797 $strval = ob_get_contents();
1805 * Class representing a sequence of WikiDB_Pages.
1806 * TODO: Enhance to php5 iterators
1808 * apply filters for options like 'sortby', 'limit', 'exclude'
1809 * for simple queries like titleSearch, where the backend is not ready yet.
1811 class WikiDB_PageIterator
1813 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1814 $this->_iter = $iter; // a WikiDB_backend_iterator
1815 $this->_wikidb = &$wikidb;
1816 $this->_options = $options;
1820 return $this->_iter->count();
1823 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1827 * Get next WikiDB_Page in sequence.
1831 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1834 if ( ! ($next = $this->_iter->next()) )
1837 $pagename = &$next['pagename'];
1838 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1839 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1840 $pagename = $pagename['linkto'];
1842 $pagename = strval($pagename);*/
1843 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1846 if (isset($next['linkrelation'])
1847 or isset($next['pagedata']['linkrelation'])) return false;
1848 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1852 // There's always hits, but we cache only if more
1853 // (well not with file, cvs and dba)
1854 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1855 $this->_wikidb->_cache->cache_data($next);
1856 // cache existing page id's since we iterate over all links in GleanDescription
1857 // and need them later for LinkExistingWord
1858 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1859 and !$this->_options['include_empty'] and isset($next['id'])) {
1860 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1862 $page = new WikiDB_Page($this->_wikidb, $pagename);
1863 if (isset($next['linkrelation']))
1864 $page->set('linkrelation', $next['linkrelation']);
1865 if (isset($next['score']))
1866 $page->score = $next['score'];
1871 * Release resources held by this iterator.
1873 * The iterator may not be used after free() is called.
1875 * There is no need to call free(), if next() has returned false.
1876 * (I.e. if you iterate through all the pages in the sequence,
1877 * you do not need to call free() --- you only need to call it
1878 * if you stop before the end of the iterator is reached.)
1883 $this->_iter->free();
1886 $this->_iter->reset();
1888 function asArray() {
1890 while ($page = $this->next())
1897 * Apply filters for options like 'sortby', 'limit', 'exclude'
1898 * for simple queries like titleSearch, where the backend is not ready yet.
1899 * Since iteration is usually destructive for SQL results,
1900 * we have to generate a copy.
1902 function applyFilters($options = false) {
1903 if (!$options) $options = $this->_options;
1904 if (isset($options['sortby'])) {
1906 /* this is destructive */
1907 while ($page = $this->next())
1908 $result[] = $page->getName();
1909 $this->_doSort($array, $options['sortby']);
1911 /* the rest is not destructive.
1912 * reconstruct a new iterator
1914 $pagenames = array(); $i = 0;
1915 if (isset($options['limit']))
1916 $limit = $options['limit'];
1919 if (isset($options['exclude']))
1920 $exclude = $options['exclude'];
1921 if (is_string($exclude) and !is_array($exclude))
1922 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1923 foreach($array as $pagename) {
1924 if ($limit and $i++ > $limit)
1925 return new WikiDB_Array_PageIterator($pagenames);
1926 if (!empty($exclude) and !in_array($pagename, $exclude))
1927 $pagenames[] = $pagename;
1928 elseif (empty($exclude))
1929 $pagenames[] = $pagename;
1931 return new WikiDB_Array_PageIterator($pagenames);
1935 function _doSort(&$array, $sortby) {
1936 $sortby = PageList::sortby($sortby, 'init');
1937 if ($sortby == '+pagename')
1938 sort($array, SORT_STRING);
1939 elseif ($sortby == '-pagename')
1940 rsort($array, SORT_STRING);
1947 * A class which represents a sequence of WikiDB_PageRevisions.
1948 * TODO: Enhance to php5 iterators
1950 class WikiDB_PageRevisionIterator
1952 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1953 $this->_revisions = $revisions;
1954 $this->_wikidb = &$wikidb;
1955 $this->_options = $options;
1959 return $this->_revisions->count();
1963 * Get next WikiDB_PageRevision in sequence.
1967 * @return WikiDB_PageRevision
1968 * The next WikiDB_PageRevision in the sequence.
1971 if ( ! ($next = $this->_revisions->next()) )
1974 //$this->_wikidb->_cache->cache_data($next);
1976 $pagename = $next['pagename'];
1977 $version = $next['version'];
1978 $versiondata = $next['versiondata'];
1980 if (!(is_string($pagename) and $pagename != '')) {
1981 trigger_error("empty pagename",E_USER_WARNING);
1984 } else assert(is_string($pagename) and $pagename != '');
1986 if (!is_array($versiondata)) {
1987 trigger_error("empty versiondata",E_USER_WARNING);
1990 } else assert(is_array($versiondata));
1992 if (!($version > 0)) {
1993 trigger_error("invalid version",E_USER_WARNING);
1996 } else assert($version > 0);
1998 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2003 * Release resources held by this iterator.
2005 * The iterator may not be used after free() is called.
2007 * There is no need to call free(), if next() has returned false.
2008 * (I.e. if you iterate through all the revisions in the sequence,
2009 * you do not need to call free() --- you only need to call it
2010 * if you stop before the end of the iterator is reached.)
2015 $this->_revisions->free();
2018 function asArray() {
2020 while ($rev = $this->next())
2029 class WikiDB_Array_PageIterator
2031 function WikiDB_Array_PageIterator($pagenames) {
2033 $this->_dbi = $request->getDbh();
2034 $this->_pages = $pagenames;
2035 reset($this->_pages);
2038 $c = current($this->_pages);
2039 next($this->_pages);
2040 return $c !== false ? $this->_dbi->getPage($c) : false;
2043 return count($this->_pages);
2046 reset($this->_pages);
2049 function asArray() {
2050 reset($this->_pages);
2051 return $this->_pages;
2055 class WikiDB_Array_generic_iter
2057 function WikiDB_Array_generic_iter($result) {
2058 // $result may be either an array or a query result
2059 if (is_array($result)) {
2060 $this->_array = $result;
2061 } elseif (is_object($result)) {
2062 $this->_array = $result->asArray();
2064 $this->_array = array();
2066 if (!empty($this->_array))
2067 reset($this->_array);
2070 $c = current($this->_array);
2071 next($this->_array);
2072 return $c !== false ? $c : false;
2075 return count($this->_array);
2078 reset($this->_array);
2081 function asArray() {
2082 if (!empty($this->_array))
2083 reset($this->_array);
2084 return $this->_array;
2089 * Data cache used by WikiDB.
2091 * FIXME: Maybe rename this to caching_backend (or some such).
2097 // FIXME: beautify versiondata cache. Cache only limited data?
2099 function WikiDB_cache (&$backend) {
2100 $this->_backend = &$backend;
2102 $this->_pagedata_cache = array();
2103 $this->_versiondata_cache = array();
2104 array_push ($this->_versiondata_cache, array());
2105 $this->_glv_cache = array();
2106 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2108 if (isset($GLOBALS['request']->_dbi))
2109 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2113 $this->_pagedata_cache = array();
2114 $this->_versiondata_cache = array();
2115 $this->_glv_cache = array();
2116 $this->_id_cache = array();
2119 function get_pagedata($pagename) {
2120 assert(is_string($pagename) && $pagename != '');
2122 $cache = &$this->_pagedata_cache;
2123 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2124 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2125 if (empty($cache[$pagename]))
2126 $cache[$pagename] = array();
2128 return $cache[$pagename];
2130 return $this->_backend->get_pagedata($pagename);
2134 function update_pagedata($pagename, $newdata) {
2135 assert(is_string($pagename) && $pagename != '');
2136 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2138 $this->_backend->update_pagedata($pagename, $newdata);
2141 if (!empty($this->_pagedata_cache[$pagename])
2142 and is_array($this->_pagedata_cache[$pagename]))
2144 $cachedata = &$this->_pagedata_cache[$pagename];
2145 foreach($newdata as $key => $val)
2146 $cachedata[$key] = $val;
2148 $this->_pagedata_cache[$pagename] = $newdata;
2152 function invalidate_cache($pagename) {
2153 unset ($this->_pagedata_cache[$pagename]);
2154 unset ($this->_versiondata_cache[$pagename]);
2155 unset ($this->_glv_cache[$pagename]);
2156 unset ($this->_id_cache[$pagename]);
2157 //unset ($this->_backend->_page_data);
2160 function delete_page($pagename) {
2161 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2162 $result = $this->_backend->delete_page($pagename);
2163 $this->invalidate_cache($pagename);
2167 function purge_page($pagename) {
2168 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2169 $result = $this->_backend->purge_page($pagename);
2170 $this->invalidate_cache($pagename);
2174 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2175 function cache_data($data) {
2177 //if (isset($data['pagedata']))
2178 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2181 function get_versiondata($pagename, $version, $need_content = false) {
2182 // FIXME: Seriously ugly hackage
2184 if (USECACHE) { //temporary - for debugging
2185 assert(is_string($pagename) && $pagename != '');
2186 // There is a bug here somewhere which results in an assertion failure at line 105
2187 // of ArchiveCleaner.php It goes away if we use the next line.
2188 //$need_content = true;
2189 $nc = $need_content ? '1':'0';
2190 $cache = &$this->_versiondata_cache;
2191 if (!isset($cache[$pagename][$version][$nc])
2192 || !(is_array ($cache[$pagename]))
2193 || !(is_array ($cache[$pagename][$version])))
2195 $cache[$pagename][$version][$nc] =
2196 $this->_backend->get_versiondata($pagename, $version, $need_content);
2198 // If we have retrieved all data, we may as well set the cache for
2199 // $need_content = false
2201 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2204 $vdata = $cache[$pagename][$version][$nc];
2206 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2209 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2210 if (empty($this->_pagedata_cache))
2211 $this->_pagedata_cache = array();
2212 /* PHP Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/html/phpwiki/lib/WikiDB.php on line 2180, referer: wiki/TitleSearch?s=and&auto_redirect=1 */
2213 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2218 function set_versiondata($pagename, $version, $data) {
2219 //unset($this->_versiondata_cache[$pagename][$version]);
2221 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2222 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2224 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2225 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2226 // Is this necessary?
2227 unset($this->_glv_cache[$pagename]);
2230 function update_versiondata($pagename, $version, $data) {
2231 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2232 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2234 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2236 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2237 // Is this necessary?
2238 unset($this->_glv_cache[$pagename]);
2241 function delete_versiondata($pagename, $version) {
2242 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2243 $new = $this->_backend->delete_versiondata($pagename, $version);
2244 if (isset($this->_versiondata_cache[$pagename][$version]))
2245 unset ($this->_versiondata_cache[$pagename][$version]);
2246 // dirty latest version cache only if latest version gets deleted
2247 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2248 unset ($this->_glv_cache[$pagename]);
2251 function get_latest_version($pagename) {
2253 assert (is_string($pagename) && $pagename != '');
2254 $cache = &$this->_glv_cache;
2255 if (!isset($cache[$pagename])) {
2256 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2257 if (empty($cache[$pagename]))
2258 $cache[$pagename] = 0;
2260 return $cache[$pagename];
2262 return $this->_backend->get_latest_version($pagename);
2267 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2271 $stamp = strftime("%y%m%d-%H%M%S");
2272 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2273 register_shutdown_function("_sql_debuglog_shutdown_function");
2274 } elseif ($shutdown) {
2278 if ($newline) fputs($fp, "[$i++] $msg");
2279 else fwrite($fp, $msg);
2282 function _sql_debuglog_shutdown_function() {
2283 _sql_debuglog('',false,true);
2289 // c-basic-offset: 4
2290 // c-hanging-comment-ender-p: nil
2291 // indent-tabs-mode: nil