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.
44 * Open a WikiDB database.
46 * This is a static member function. This function inspects its
47 * arguments to determine the proper subclass of WikiDB to
48 * instantiate, and then it instantiates it.
50 * @param hash $dbparams Database configuration parameters.
51 * Some pertinent parameters are:
54 * <dd> The back-end type. Current supported types are:
57 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
58 * library. (More stable and conservative)
60 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
62 * <dd> Dba based backend. The default and by far the fastest.
70 * <dd> (Used by the SQL and ADODB backends.)
71 * The DSN specifying which database to connect to.
74 * <dd> Prefix to be prepended to database tables (and file names).
77 * <dd> (Used by the dba backend.)
78 * Which directory db files reside in.
81 * <dd> Used only by the dba backend so far.
82 * And: When optimizing mysql it closes timed out mysql processes.
83 * otherwise only used for dba: Timeout in seconds for opening (and
84 * obtaining lock) on the dbm file.
87 * <dd> (Used by the dba backend.)
89 * Which dba handler to use. Good choices are probably either
93 * <dd> Either set by config.ini: READONLY = true or detected automatically
94 * when a database can be read but cannot be updated.
97 * @return WikiDB A WikiDB object.
99 public function open($dbparams)
101 $dbtype = $dbparams{'dbtype'};
102 include_once("lib/WikiDB/$dbtype.php");
104 $class = 'WikiDB_' . $dbtype;
105 return new $class ($dbparams);
111 function __construct(&$backend, $dbparams)
113 $this->_backend =& $backend;
114 // don't do the following with the auth_dsn!
115 if (isset($dbparams['auth_dsn'])) return;
117 $this->_cache = new WikiDB_cache($backend);
118 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
120 // If the database doesn't yet have a timestamp, initialize it now.
121 if ($this->get('_timestamp') === false)
125 if ((int)DEBUG & _DEBUG_SQL) {
126 $this->_backend->check();
128 // might be changed when opening the database fails
129 $this->readonly = defined("READONLY") ? READONLY : false;
133 * Close database connection.
135 * The database may no longer be used after it is closed.
137 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
138 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
139 * which have been obtained from it.
141 public function close()
143 $this->_backend->close();
144 $this->_cache->close();
148 * Get a WikiDB_Page from a WikiDB.
150 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
151 * therefore this method never fails.
153 * @param string $pagename Which page to get.
154 * @return WikiDB_Page The requested WikiDB_Page.
156 public function getPage($pagename)
158 static $error_displayed = false;
159 $pagename = (string)$pagename;
161 if ($pagename === '') {
162 if ($error_displayed) return false;
163 $error_displayed = true;
164 if (function_exists("xdebug_get_function_stack"))
165 var_dump(xdebug_get_function_stack());
166 trigger_error("empty pagename", E_USER_WARNING);
170 assert($pagename != '');
172 return new WikiDB_Page($this, $pagename);
176 * Determine whether page exists (in non-default form).
179 * $is_page = $dbi->isWikiPage($pagename);
183 * $page = $dbi->getPage($pagename);
184 * $current = $page->getCurrentRevision();
185 * $is_page = ! $current->hasDefaultContents();
187 * however isWikiPage may be implemented in a more efficient
188 * manner in certain back-ends.
190 * @param string $pagename string Which page to check.
191 * @return boolean True if the page actually exists with
192 * non-default contents in the WikiDataBase.
194 public function isWikiPage($pagename)
196 $page = $this->getPage($pagename);
197 return ($page and $page->exists());
201 * Delete page from the WikiDB.
203 * Deletes the page from the WikiDB with the possibility to revert and diff.
204 * //Also resets all page meta-data to the default values.
206 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
208 * @param string $pagename Name of page to delete.
212 public function deletePage($pagename)
214 if (!empty($this->readonly)) {
215 trigger_error("readonly database", E_USER_WARNING);
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.
245 * @param string $pagename Name of page to delete.
248 public function purgePage($pagename)
250 if (!empty($this->readonly)) {
251 trigger_error("readonly database", E_USER_WARNING);
254 $result = $this->_cache->purge_page($pagename);
255 $this->deletePage($pagename); // just for the notification
260 * Retrieve all pages.
262 * Gets the set of all pages with non-default contents.
264 * @param bool $include_empty Optional. Normally pages whose most
265 * recent revision has empty content are considered to be
266 * non-existant. Unless $include_defaulted is set to true, those
267 * pages will not be returned.
268 * @param string $sortby Optional. "+-column,+-column2".
269 * If false the result is faster in natural order.
270 * @param string $limit Optional. Encoded as "$offset,$count".
271 * $offset defaults to 0.
272 * @param string $exclude Optional comma-separated list of pagenames.
274 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
275 * in the WikiDB which have non-default contents.
277 public function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
279 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
281 return new WikiDB_PageIterator($this, $result,
282 array('include_empty' => $include_empty,
283 'exclude' => $exclude,
284 'limit_by_db' => $result->_options['limit_by_db'],
285 'limit' => $result->limit()));
289 * @param boolean $include_empty If true include also empty pages
290 * @param string $exclude: comma-separated list of pagenames.
291 * TBD: array of pagenames
295 public function numPages($include_empty = false, $exclude = '')
297 if (method_exists($this->_backend, 'numPages'))
298 // FIXME: currently are all args ignored.
299 $count = $this->_backend->numPages($include_empty, $exclude);
301 // FIXME: exclude ignored.
302 $iter = $this->getAllPages($include_empty, false, false, $exclude);
303 $count = $iter->count();
312 * Search for pages containing (or not containing) certain words
315 * Pages are returned in alphabetical order whenever it is
316 * practical to do so.
317 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
319 * @param TextSearchQuery $search A TextSearchQuery object
320 * @param string $sortby Optional. "+-column,+-column2".
321 * If false the result is faster in natural order.
322 * @param string $limit Optional. Encoded as "$offset,$count".
323 * $offset defaults to 0.
324 * @param string $exclude Optional comma-separated list of pagenames.
325 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
326 * @see TextSearchQuery
328 public function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
330 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
331 $options = array('exclude' => $exclude,
333 //if (isset($result->_count)) $options['count'] = $result->_count;
334 return new WikiDB_PageIterator($this, $result, $options);
340 * Search for pages containing (or not containing) certain words
341 * in their entire text (this includes the page content and the
344 * Pages are returned in alphabetical order whenever it is
345 * practical to do so.
346 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
348 * @param TextSearchQuery $search A TextSearchQuery object.
349 * @param string $sortby Optional. "+-column,+-column2".
350 * If false the result is faster in natural order.
351 * @param string $limit Optional. Encoded as "$offset,$count".
352 * $offset defaults to 0.
353 * @param string $exclude Optional comma-separated list of pagenames.
354 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
355 * @see TextSearchQuery
357 public function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
359 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
360 return new WikiDB_PageIterator($this, $result,
361 array('exclude' => $exclude,
363 'stoplisted' => $result->stoplisted
368 * Find the pages with the greatest hit counts.
370 * Pages are returned in reverse order by hit count.
372 * @param int $limit The maximum number of pages to return.
373 * Set $limit to zero to return all pages. If $limit < 0, pages will
374 * be sorted in decreasing order of popularity.
375 * @param string $sortby Optional. "+-column,+-column2".
376 * If false the result is faster in natural order.
378 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
381 public function mostPopular($limit = 20, $sortby = '-hits')
383 $result = $this->_backend->most_popular($limit, $sortby);
384 return new WikiDB_PageIterator($this, $result);
388 * Find recent page revisions.
390 * Revisions are returned in reverse order by creation time.
392 * @param array $params This hash is used to specify various optional
396 * <dd> (integer) At most this many revisions will be returned.
398 * <dd> (integer) Only revisions since this time (unix-timestamp)
400 * <dt> include_minor_revisions
401 * <dd> (boolean) Also include minor revisions. (Default is not to.)
402 * <dt> exclude_major_revisions
403 * <dd> (boolean) Don't include non-minor revisions.
404 * (Exclude_major_revisions implies include_minor_revisions.)
405 * <dt> include_all_revisions
406 * <dd> (boolean) Return all matching revisions for each page.
407 * Normally only the most recent matching revision is returned
411 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
412 * containing the matching revisions.
414 public function mostRecent($params = array())
416 $result = $this->_backend->most_recent($params);
417 return new WikiDB_PageRevisionIterator($this, $result);
421 * @param string $exclude_from
422 * @param string $exclude
423 * @param string $sortby Optional. "+-column,+-column2".
424 * If false the result is faster in natural order.
425 * @param string $limit Optional. Encoded as "$offset,$count".
426 * $offset defaults to 0.
427 * @return Iterator A generic iterator containing rows of
428 * (duplicate) pagename, wantedfrom.
430 public function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
432 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
436 * Generic interface to the link table. Esp. useful to search for rdf triples as in
437 * SemanticSearch and ListRelations.
439 * @param object $pages A TextSearchQuery object.
440 * @param object $search A TextSearchQuery object.
441 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
442 * linktype parameter:
445 * <dd> search for simple out-links
447 * <dd> in-links, i.e BackLinks
449 * <dd> the first part in a <>::<> link
451 * <dd> the first part in a <>:=<> link
453 * @param mixed $relation An optional TextSearchQuery to match the
454 * relation name. Ignored on simple in-out links.
456 * @return Iterator A generic iterator containing links to pages or values.
457 * hash of "pagename", "linkname", "linkvalue.
459 public function linkSearch($pages, $search, $linktype, $relation = false)
461 return $this->_backend->link_search($pages, $search, $linktype, $relation);
465 * Return a simple list of all defined relations (and attributes), mainly
466 * for the SemanticSearch autocompletion.
468 * @param bool $also_attributes
469 * @param bool $only_attributes
470 * @param bool $sorted
471 * @return array of strings
473 public function listRelations($also_attributes = false, $only_attributes = false, $sorted = true)
475 if (method_exists($this->_backend, "list_relations"))
476 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
477 // dumb, slow fallback. no iter, so simply define it here.
478 $relations = array();
479 $iter = $this->getAllPages();
480 while ($page = $iter->next()) {
481 $reliter = $page->getRelations();
483 while ($rel = $reliter->next()) {
484 // if there's no pagename it's an attribute
485 $names[] = $rel->getName();
487 $relations = array_merge($relations, $names);
499 * Call the appropriate backend method.
501 * @param string $from Page to rename
502 * @param string $to New name
503 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
504 * @return boolean true or false
506 public function renamePage($from, $to, $updateWikiLinks = false)
508 if (!empty($this->readonly)) {
509 trigger_error("readonly database", E_USER_WARNING);
512 assert(is_string($from) && $from != '');
513 assert(is_string($to) && $to != '');
515 if (method_exists($this->_backend, 'rename_page')) {
516 $oldpage = $this->getPage($from);
517 $newpage = $this->getPage($to);
518 //update all WikiLinks in existing pages
519 //non-atomic! i.e. if rename fails the links are not undone
520 if ($updateWikiLinks) {
521 $lookbehind = "/(?<=[\W:])\Q";
522 $lookahead = "\E(?=[\W:])/";
523 require_once 'lib/plugin/WikiAdminSearchReplace.php';
524 $links = $oldpage->getBackLinks();
525 while ($linked_page = $links->next()) {
526 WikiPlugin_WikiAdminSearchReplace::replaceHelper
528 $linked_page->getName(),
529 $lookbehind . $from . $lookahead, $to,
532 // FIXME: Disabled to avoid recursive modification when renaming
533 // a page like 'PageFoo to 'PageFooTwo'
535 $links = $newpage->getBackLinks();
536 while ($linked_page = $links->next()) {
537 WikiPlugin_WikiAdminSearchReplace::replaceHelper
539 $linked_page->getName(),
540 $lookbehind . $from . $lookahead, $to,
545 if ($oldpage->exists() and !$newpage->exists()) {
546 if ($result = $this->_backend->rename_page($from, $to)) {
547 // create a RecentChanges entry with explaining summary
548 $page = $this->getPage($to);
549 $current = $page->getCurrentRevision();
550 $meta = $current->_data;
551 $version = $current->getVersion();
552 $meta['summary'] = sprintf(_("renamed from %s"), $from);
553 unset($meta['mtime']); // force new date
554 $page->save($current->getPackedContent(), $version + 1, $meta);
556 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
557 // if a version 0 exists try it also.
558 $result = $this->_backend->rename_page($from, $to);
561 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
564 /* Generate notification emails? */
565 if ($result and ENABLE_MAILNOTIFY and !is_a($GLOBALS['request'], 'MockRequest')) {
566 $notify = $this->get('notify');
567 if (!empty($notify) and is_array($notify)) {
568 include_once 'lib/MailNotify.php';
569 $MailNotify = new MailNotify($from);
570 $MailNotify->onRenamePage($this, $from, $to);
576 /** Get timestamp when database was last modified.
578 * @return string A string consisting of two integers,
579 * separated by a space. The first is the time in
580 * unix timestamp format, the second is a modification
581 * count for the database.
583 * The idea is that you can cast the return value to an
584 * int to get a timestamp, or you can use the string value
585 * as a good hash for the entire database.
587 function getTimestamp()
589 $ts = $this->get('_timestamp');
590 return sprintf("%d %d", $ts[0], $ts[1]);
594 * Update the database timestamp.
599 $ts = $this->get('_timestamp');
600 $this->set('_timestamp', array(time(), $ts[1] + 1));
604 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
606 function get_db_version()
608 return (float)$this->get('_db_version');
611 function set_db_version($ver)
613 return $this->set('_db_version', (float)$ver);
617 * Access WikiDB global meta-data.
619 * NOTE: this is currently implemented in a hackish and
620 * not very efficient manner.
622 * @param string $key Which meta data to get.
623 * Some reserved meta-data keys are:
625 * <dt>'_timestamp' <dd> Data used by getTimestamp().
628 * @return scalar The requested value, or false if the requested data
631 public function get($key)
633 if (!$key || $key[0] == '%')
636 * Hack Alert: We can use any page (existing or not) to store
637 * this data (as long as we always use the same one.)
639 $gd = $this->getPage('global_data');
640 $data = $gd->get('__global');
642 if ($data && isset($data[$key]))
649 * Set global meta-data.
651 * NOTE: this is currently implemented in a hackish and
652 * not very efficient manner.
656 * @param string $key Meta-data key to set.
657 * @param string $newval New value.
659 public function set($key, $newval)
661 if (!empty($this->readonly)) {
662 trigger_error("readonly database", E_USER_WARNING);
665 if (!$key || $key[0] == '%')
668 $gd = $this->getPage('global_data');
669 $data = $gd->get('__global');
676 $data[$key] = $newval;
678 $gd->set('__global', $data);
681 /* TODO: these are really backend methods */
683 // SQL result: for simple select or create/update queries
684 // returns the database specific resource type
685 function genericSqlQuery($sql, $args = false)
688 printSimpleTrace(debug_backtrace());
690 trigger_error("no SQL database", E_USER_ERROR);
694 // SQL iter: for simple select or create/update queries
695 // returns the generic iterator object (count,next)
696 function genericSqlIter($sql, $field_list = NULL)
699 printSimpleTrace(debug_backtrace());
701 trigger_error("no SQL database", E_USER_ERROR);
705 // see backend upstream methods
706 // ADODB adds surrounding quotes, SQL not yet!
715 if (!$request->_dbi) return false;
716 else return false; /* so far only needed for sql so false it.
717 later we have to check dba also */
720 function getParam($param)
723 if (isset($DBParams[$param])) return $DBParams[$param];
724 elseif ($param == 'prefix') return ''; else return false;
727 function getAuthParam($param)
729 global $DBAuthParams;
730 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
731 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false;
736 * A base class which representing a wiki-page within a
739 * A WikiDB_Page contains a number (at least one) of
740 * WikiDB_PageRevisions.
744 function WikiDB_Page(&$wikidb, $pagename)
746 $this->_wikidb = &$wikidb;
747 $this->_pagename = $pagename;
749 if (!(is_string($pagename) and $pagename != '')) {
750 if (function_exists("xdebug_get_function_stack")) {
751 echo "xdebug_get_function_stack(): ";
752 var_dump(xdebug_get_function_stack());
754 printSimpleTrace(debug_backtrace());
756 trigger_error("empty pagename", E_USER_WARNING);
760 assert(is_string($pagename) and $pagename != '');
765 * Get the name of the wiki page.
767 * @return string The page name.
769 public function getName()
771 return $this->_pagename;
774 // To reduce the memory footprint for larger sets of pagelists,
775 // we don't cache the content (only true or false) and
776 // we purge the pagedata (_cached_html) also
779 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
780 $current = $this->getCurrentRevision(false);
781 if (!$current) return false;
782 return !$current->hasDefaultContents();
786 * Delete an old revision of a WikiDB_Page.
788 * Deletes the specified revision of the page.
789 * It is a fatal error to attempt to delete the current revision.
791 * @param integer $version Which revision to delete. (You can also
792 * use a WikiDB_PageRevision object here.)
794 public function deleteRevision($version)
796 if ($this->_wikidb->readonly) {
797 trigger_error("readonly database", E_USER_WARNING);
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)
850 if ($this->_wikidb->readonly) {
851 trigger_error("readonly database", E_USER_WARNING);
854 $backend = &$this->_wikidb->_backend;
855 $cache = &$this->_wikidb->_cache;
856 $pagename = &$this->_pagename;
858 $version = $this->_coerce_to_version($version);
862 $backend->lock(array('version'));
863 $latestversion = $cache->get_latest_version($pagename);
864 if ($latestversion && $version == $latestversion) {
865 $backend->unlock(array('version'));
866 trigger_error(sprintf("Attempt to merge most recent revision of “%s”",
867 $pagename), E_USER_ERROR);
871 $versiondata = $cache->get_versiondata($pagename, $version, true);
873 // Not there? ... we're done!
874 $backend->unlock(array('version'));
878 if ($versiondata['is_minor_edit']) {
879 $previous = $backend->get_previous_version($pagename, $version);
881 $prevdata = $cache->get_versiondata($pagename, $previous);
882 if ($prevdata['author_id'] == $versiondata['author_id']) {
883 // This is a minor revision, previous version is
884 // by the same author. We will merge the
886 $cache->update_versiondata($pagename, $previous,
887 array('%content' => $versiondata['%content'],
888 '_supplanted' => $versiondata['_supplanted']));
893 $cache->delete_versiondata($pagename, $version);
894 $backend->unlock(array('version'));
898 * Create a new revision of a {@link WikiDB_Page}.
900 * @param int $version Version number for new revision.
901 * To ensure proper serialization of edits, $version must be
902 * exactly one higher than the current latest version.
903 * (You can defeat this check by setting $version to
904 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
906 * @param string $content Contents of new revision.
908 * @param hash $metadata Metadata for new revision.
909 * All values in the hash should be scalars (strings or integers).
911 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
913 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
914 * $version was incorrect, returns false
916 public function createRevision($version, &$content, $metadata, $links)
918 if ($this->_wikidb->readonly) {
919 trigger_error("readonly database", E_USER_WARNING);
922 $backend = &$this->_wikidb->_backend;
923 $cache = &$this->_wikidb->_cache;
924 $pagename = &$this->_pagename;
925 $cache->invalidate_cache($pagename);
927 $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
929 $latestversion = $backend->get_latest_version($pagename);
930 $newversion = ($latestversion ? $latestversion : 0) + 1;
931 assert($newversion >= 1);
933 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
934 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
940 foreach ($data as $key => $val) {
941 if (empty($val) || $key[0] == '_' || $key[0] == '%')
945 assert(!empty($data['author']));
946 if (empty($data['author_id']))
947 @$data['author_id'] = $data['author'];
949 if (empty($data['mtime']))
950 $data['mtime'] = time();
952 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
953 // Ensure mtimes are monotonic.
954 $pdata = $cache->get_versiondata($pagename, $latestversion);
955 if ($data['mtime'] < $pdata['mtime']) {
956 trigger_error(sprintf(_("%s: Date of new revision is %s"),
957 $pagename, "'non-monotonic'"),
959 $data['orig_mtime'] = $data['mtime'];
960 $data['mtime'] = $pdata['mtime'];
963 // FIXME: use (possibly user specified) 'mtime' time or
965 $cache->update_versiondata($pagename, $latestversion,
966 array('_supplanted' => $data['mtime']));
969 $data['%content'] = &$content;
971 $cache->set_versiondata($pagename, $newversion, $data);
973 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
974 //':deleted' => empty($content)));
976 $backend->set_links($pagename, $links);
978 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
980 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
984 /** A higher-level interface to createRevision.
986 * This takes care of computing the links, and storing
987 * a cached version of the transformed wiki-text.
989 * @param string $wikitext The page content.
991 * @param int $version Version number for new revision.
992 * To ensure proper serialization of edits, $version must be
993 * exactly one higher than the current latest version.
994 * (You can defeat this check by setting $version to
995 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
997 * @param array $meta Meta-data for new revision.
999 * @param mixed $formatted
1003 function save($wikitext, $version, $meta, $formatted = null)
1005 if ($this->_wikidb->readonly) {
1006 trigger_error("readonly database", E_USER_WARNING);
1009 if (is_null($formatted))
1010 $formatted = new TransformedText($this, $wikitext, $meta);
1011 $type = $formatted->getType();
1012 $meta['pagetype'] = $type->getName();
1013 $links = $formatted->getWikiPageLinks(); // linkto => relation
1014 $attributes = array();
1015 foreach ($links as $link) {
1016 if ($link['linkto'] === "" and !empty($link['relation'])) {
1017 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1020 $meta['attribute'] = $attributes;
1022 $backend = &$this->_wikidb->_backend;
1023 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1024 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1025 $this->set('_cached_html', $formatted->pack());
1027 // FIXME: probably should have some global state information
1028 // in the backend to control when to optimize.
1030 // We're doing this here rather than in createRevision because
1031 // postgresql can't optimize while locked.
1032 if (((int)DEBUG & _DEBUG_SQL)
1033 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1034 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1036 if ($backend->optimize()) {
1038 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1043 /* Generate notification emails? */
1044 if (ENABLE_MAILNOTIFY and is_a($newrevision, 'WikiDB_PageRevision')) {
1045 // Save didn't fail because of concurrent updates.
1046 $notify = $this->_wikidb->get('notify');
1048 and is_array($notify)
1049 and !is_a($GLOBALS['request'], 'MockRequest')
1051 include_once 'lib/MailNotify.php';
1052 $MailNotify = new MailNotify($newrevision->getName());
1053 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1055 $newrevision->_transformedContent = $formatted;
1057 // more pagechange callbacks: (in a hackish manner for now)
1058 if (ENABLE_RECENTCHANGESBOX
1059 and empty($meta['is_minor_edit'])
1060 and !in_array($GLOBALS['request']->getArg('action'),
1061 array('loadfile', 'upgrade'))
1063 require_once 'lib/WikiPlugin.php';
1064 $w = new WikiPluginLoader();
1065 $p = $w->getPlugin("RecentChangesCached", false);
1066 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1068 return $newrevision;
1072 * Get the most recent revision of a page.
1074 * @param bool $need_content
1075 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1077 public function getCurrentRevision($need_content = true)
1079 $backend = &$this->_wikidb->_backend;
1080 $cache = &$this->_wikidb->_cache;
1081 $pagename = &$this->_pagename;
1083 // Prevent deadlock in case of memory exhausted errors
1084 // Pure selection doesn't really need locking here.
1085 // sf.net bug#927395
1086 // I know it would be better to lock, but with lots of pages this deadlock is more
1087 // severe than occasionally get not the latest revision.
1088 // In spirit to wikiwiki: read fast, edit slower.
1090 $version = $cache->get_latest_version($pagename);
1091 // getRevision gets the content also!
1092 $revision = $this->getRevision($version, $need_content);
1093 //$backend->unlock();
1099 * Get a specific revision of a WikiDB_Page.
1101 * @param int $version Which revision to get.
1102 * @param bool $need_content
1103 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1104 * false if the requested revision does not exist in the {@link WikiDB}.
1105 * Note that version zero of any page always exists.
1107 public function getRevision($version, $need_content = true)
1109 $cache = &$this->_wikidb->_cache;
1110 $pagename = &$this->_pagename;
1112 if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1113 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1116 assert($version > 0);
1117 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1119 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1121 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1126 * Get previous page revision.
1128 * This method find the most recent revision before a specified
1131 * @param bool|int $version Find most recent revision before this version.
1132 * You can also use a WikiDB_PageRevision object to specify the $version.
1134 * @param bool $need_content
1136 * @return WikiDB_PageRevision|bool The requested WikiDB_PageRevision object, or false if the
1137 * requested revision does not exist in the {@link WikiDB}. Note that
1138 * unless $version is greater than zero, a revision (perhaps version zero,
1139 * the default revision) will always be found.
1141 public function getRevisionBefore($version = false, $need_content = true)
1143 $backend = &$this->_wikidb->_backend;
1144 $pagename = &$this->_pagename;
1145 if ($version === false)
1146 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1148 $version = $this->_coerce_to_version($version);
1153 $previous = $backend->get_previous_version($pagename, $version);
1154 $revision = $this->getRevision($previous, $need_content);
1155 //$backend->unlock();
1161 * Get all revisions of the WikiDB_Page.
1163 * This does not include the version zero (default) revision in the
1164 * returned revision set.
1166 * @return WikiDB_PageRevisionIterator A
1167 * WikiDB_PageRevisionIterator containing all revisions of this
1168 * WikiDB_Page in reverse order by version number.
1170 function getAllRevisions()
1172 $backend = &$this->_wikidb->_backend;
1173 $revs = $backend->get_all_revisions($this->_pagename);
1174 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1178 * Find pages which link to or are linked from a page.
1179 * relations: $backend->get_links is responsible to add the relation to the pagehash
1180 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1181 * if (isset($next['linkrelation']))
1183 * @param bool $reversed Which links to find: true for backlinks (default).
1184 * @param bool $include_empty
1185 * @param string $sortby
1186 * @param string $limit
1187 * @param string $sortby
1188 * @param string $exclude
1189 * @param bool $want_relations
1190 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1191 * all matching pages.
1193 public function getLinks($reversed = true, $include_empty = false, $sortby = '',
1194 $limit = '', $exclude = '', $want_relations = false)
1196 $backend = &$this->_wikidb->_backend;
1197 $result = $backend->get_links($this->_pagename, $reversed,
1198 $include_empty, $sortby, $limit, $exclude,
1200 return new WikiDB_PageIterator($this->_wikidb, $result,
1201 array('include_empty' => $include_empty,
1202 'sortby' => $sortby,
1204 'exclude' => $exclude,
1205 'want_relations' => $want_relations));
1209 * All Links from other pages to this page.
1211 function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1212 $want_relations = false)
1214 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1218 * Forward Links: All Links from this page to other pages.
1220 function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1221 $want_relations = false)
1223 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1227 * Relations: All links from this page to other pages with relation <> 0.
1228 * is_a:=page or population:=number
1230 function getRelations($sortby = '', $limit = '', $exclude = '')
1232 $backend = &$this->_wikidb->_backend;
1233 $result = $backend->get_links($this->_pagename, false, true,
1234 $sortby, $limit, $exclude,
1236 // we do not care for the linked page versiondata, just the pagename and linkrelation
1237 return new WikiDB_PageIterator($this->_wikidb, $result,
1238 array('include_empty' => true,
1239 'sortby' => $sortby,
1241 'exclude' => $exclude,
1242 'want_relations' => true));
1246 * possibly faster link existance check. not yet accelerated.
1248 function existLink($link, $reversed = false)
1250 $backend = &$this->_wikidb->_backend;
1251 if (method_exists($backend, 'exists_link'))
1252 return $backend->exists_link($this->_pagename, $link, $reversed);
1253 //$cache = &$this->_wikidb->_cache;
1254 // TODO: check cache if it is possible
1255 $iter = $this->getLinks($reversed, false);
1256 while ($page = $iter->next()) {
1257 if ($page->getName() == $link)
1264 /* Semantic relations are links with the relation pointing to another page,
1265 the so-called "RDF Triple".
1266 [San Diego] is%20a::city
1267 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1270 /* Semantic attributes for a page.
1271 [San Diego] population:=1,305,736
1272 Attributes are links with the relation pointing to another page.
1276 * Access WikiDB_Page non version-specific meta-data.
1278 * @param string $key Which meta data to get.
1279 * Some reserved meta-data keys are:
1281 * <dt>'date' <dd> Created as unixtime
1282 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1283 * <dt>'hits' <dd> Page hit counter.
1284 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1285 * In SQL stored now in an extra column.
1287 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1288 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1289 * E.g. "owner.users"
1290 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1291 * page-headers and content.
1292 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1293 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1296 * @return scalar The requested value, or false if the requested data
1299 public function get($key)
1301 $cache = &$this->_wikidb->_cache;
1302 $backend = &$this->_wikidb->_backend;
1303 if (!$key || $key[0] == '%')
1305 // several new SQL backends optimize this.
1306 if (!WIKIDB_NOCACHE_MARKUP
1307 and $key == '_cached_html'
1308 and method_exists($backend, 'get_cached_html')
1310 return $backend->get_cached_html($this->_pagename);
1312 $data = $cache->get_pagedata($this->_pagename);
1313 return isset($data[$key]) ? $data[$key] : false;
1317 * Get all the page meta-data as a hash.
1319 * @return hash The page meta-data.
1321 function getMetaData()
1323 $cache = &$this->_wikidb->_cache;
1324 $data = $cache->get_pagedata($this->_pagename);
1326 foreach ($data as $key => $val) {
1327 if ( /*!empty($val) &&*/
1336 * Set page meta-data.
1340 * @param string $key Meta-data key to set.
1341 * @param string $newval New value.
1343 public function set($key, $newval)
1345 $cache = &$this->_wikidb->_cache;
1346 $backend = &$this->_wikidb->_backend;
1347 $pagename = &$this->_pagename;
1349 assert($key && $key[0] != '%');
1351 // several new SQL backends optimize this.
1352 if (!WIKIDB_NOCACHE_MARKUP
1353 and $key == '_cached_html'
1354 and method_exists($backend, 'set_cached_html')
1356 if ($this->_wikidb->readonly) {
1357 trigger_error("readonly database", E_USER_WARNING);
1360 return $backend->set_cached_html($pagename, $newval);
1363 $data = $cache->get_pagedata($pagename);
1365 if (!empty($newval)) {
1366 if (!empty($data[$key]) && $data[$key] == $newval)
1367 return; // values identical, skip update.
1369 if (empty($data[$key]))
1370 return; // values identical, skip update.
1373 if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1374 trigger_error("readonly database", E_USER_WARNING);
1377 $cache->update_pagedata($pagename, array($key => $newval));
1381 * Increase page hit count.
1383 * FIXME: IS this needed? Probably not.
1385 * This is a convenience function.
1386 * <pre> $page->increaseHitCount(); </pre>
1387 * is functionally identical to
1388 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1389 * but less expensive (ignores the pagadata string)
1391 * Note that this method may be implemented in more efficient ways
1392 * in certain backends.
1394 public function increaseHitCount()
1396 if ($this->_wikidb->readonly) {
1397 trigger_error("readonly database", E_USER_NOTICE);
1400 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1401 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1403 @$newhits = $this->get('hits') + 1;
1404 $this->set('hits', $newhits);
1409 * Return a string representation of the WikiDB_Page
1411 * This is really only for debugging.
1413 * @return string Printable representation of the WikiDB_Page.
1415 public function asString()
1418 printf("[%s:%s\n", get_class($this), $this->getName());
1419 print_r($this->getMetaData());
1421 $strval = ob_get_contents();
1427 * @param int|object $version_or_pagerevision
1428 * Takes either the version number (and int) or a WikiDB_PageRevision
1430 * @return integer The version number.
1432 private function _coerce_to_version($version_or_pagerevision)
1434 if (method_exists($version_or_pagerevision, "getContent"))
1435 $version = $version_or_pagerevision->getVersion();
1437 $version = (int)$version_or_pagerevision;
1439 assert($version >= 0);
1443 function isUserPage($include_empty = true)
1445 if (!$include_empty and !$this->exists()) return false;
1446 return $this->get('pref') ? true : false;
1449 // May be empty. Either the stored owner (/Chown), or the first authorized author
1452 if ($owner = $this->get('owner'))
1454 // check all revisions forwards for the first author_id
1455 $backend = &$this->_wikidb->_backend;
1456 $pagename = &$this->_pagename;
1457 $latestversion = $backend->get_latest_version($pagename);
1458 for ($v = 1; $v <= $latestversion; $v++) {
1459 $rev = $this->getRevision($v, false);
1460 if ($rev and $owner = $rev->get('author_id')) {
1467 // The authenticated author of the first revision or empty if not authenticated then.
1468 function getCreator()
1470 if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1474 // The authenticated author of the current revision.
1475 function getAuthor()
1477 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1481 /* Semantic Web value, not stored in the links.
1482 * todo: unify with some unit knowledge
1484 function setAttribute($relation, $value)
1486 $attr = $this->get('attributes');
1488 $attr = array($relation => $value);
1490 $attr[$relation] = $value;
1491 $this->set('attributes', $attr);
1494 function getAttribute($relation)
1496 $meta = $this->get('attributes');
1500 return $meta[$relation];
1506 * This class represents a specific revision of a WikiDB_Page within
1509 * A WikiDB_PageRevision has read-only semantics. You may only create
1510 * new revisions (and delete old ones) --- you cannot modify existing
1513 class WikiDB_PageRevision
1515 public $_transformedContent = false; // set by WikiDB_Page::save()
1517 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1518 $versiondata = false)
1520 $this->_wikidb = &$wikidb;
1521 $this->_pagename = $pagename;
1522 $this->_version = $version;
1523 $this->_data = $versiondata ? $versiondata : array();
1524 $this->_transformedContent = false; // set by WikiDB_Page::save()
1528 * Get the WikiDB_Page which this revision belongs to.
1530 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1532 public function getPage()
1534 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1538 * Get the version number of this revision.
1540 * @return integer The version number of this revision.
1542 public function getVersion()
1544 return $this->_version;
1548 * Determine whether this revision has defaulted content.
1550 * The default revision (version 0) of each page, as well as any
1551 * pages which are created with empty content have their content
1552 * defaulted to something like:
1554 * Describe [ThisPage] here.
1557 * @return boolean Returns true if the page has default content.
1559 public function hasDefaultContents()
1561 $data = &$this->_data;
1562 if (!isset($data['%content'])) return true;
1563 if ($data['%content'] === true) return false;
1564 return $data['%content'] === false or $data['%content'] === "";
1568 * Get the content as an array of lines.
1570 * @return array An array of lines.
1571 * The lines should contain no trailing white space.
1573 public function getContent()
1575 return explode("\n", $this->getPackedContent());
1579 * Get the pagename of the revision.
1581 * @return string pagename.
1583 public function getPageName()
1585 return $this->_pagename;
1590 return $this->_pagename;
1594 * Determine whether revision is the latest.
1596 * @return boolean True iff the revision is the latest (most recent) one.
1598 public function isCurrent()
1600 if (!isset($this->_iscurrent)) {
1601 $page = $this->getPage();
1602 $current = $page->getCurrentRevision(false);
1603 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1605 return $this->_iscurrent;
1609 * Get the transformed content of a page.
1611 * @param bool $pagetype_override
1612 * @return object An XmlContent-like object containing the page transformed
1615 function getTransformedContent($pagetype_override = false)
1617 $backend = &$this->_wikidb->_backend;
1619 if ($pagetype_override) {
1620 // Figure out the normal page-type for this page.
1621 $type = PageType::GetPageType($this->get('pagetype'));
1622 if ($type->getName() == $pagetype_override)
1623 $pagetype_override = false; // Not really an override...
1626 if ($pagetype_override) {
1627 // Overriden page type, don't cache (or check cache).
1628 return new TransformedText($this->getPage(),
1629 $this->getPackedContent(),
1630 $this->getMetaData(),
1631 $pagetype_override);
1634 $possibly_cache_results = true;
1636 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1637 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1638 // flush cache for this page.
1639 $page = $this->getPage();
1640 $page->set('_cached_html', ''); // ignored with !USECACHE
1642 $possibly_cache_results = false;
1643 } elseif (USECACHE and !$this->_transformedContent) {
1645 if ($this->isCurrent()) {
1646 $page = $this->getPage();
1647 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1649 $possibly_cache_results = false;
1651 //$backend->unlock();
1654 if (!$this->_transformedContent) {
1655 $this->_transformedContent
1656 = new TransformedText($this->getPage(),
1657 $this->getPackedContent(),
1658 $this->getMetaData());
1660 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1661 // If we're still the current version, cache the transfomed page.
1663 if ($this->isCurrent()) {
1664 $page->set('_cached_html', $this->_transformedContent->pack());
1666 //$backend->unlock();
1670 return $this->_transformedContent;
1674 * Get the content as a string.
1676 * @return string The page content.
1677 * Lines are separated by new-lines.
1679 public function getPackedContent()
1681 $data = &$this->_data;
1683 if (empty($data['%content'])
1684 || (!$this->_wikidb->isWikiPage($this->_pagename)
1685 && $this->isCurrent())
1687 include_once 'lib/InlineParser.php';
1689 // A feature similar to taglines at http://www.wlug.org.nz/
1690 // Lib from http://www.aasted.org/quote/
1691 if (defined('FORTUNE_DIR')
1692 and is_dir(FORTUNE_DIR)
1693 and in_array($GLOBALS['request']->getArg('action'),
1694 array('create', 'edit'))
1696 include_once 'lib/fortune.php';
1697 $fortune = new Fortune();
1698 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1700 $quote = "<verbatim>\n"
1701 . str_replace("\n<br>", "\n", $quote)
1702 . "</verbatim>\n\n";
1706 . sprintf(_("Describe %s here."),
1707 "[" . WikiEscape($this->_pagename) . "]");
1709 // Replace empty content with default value.
1710 return sprintf(_("Describe %s here."),
1711 "[" . WikiEscape($this->_pagename) . "]");
1714 // There is (non-default) content.
1715 assert($this->_version > 0);
1717 if (!is_string($data['%content'])) {
1718 // Content was not provided to us at init time.
1719 // (This is allowed because for some backends, fetching
1720 // the content may be expensive, and often is not wanted
1723 // In any case, now we need to get it.
1724 $data['%content'] = $this->_get_content();
1725 assert(is_string($data['%content']));
1728 return $data['%content'];
1731 function _get_content()
1733 $cache = &$this->_wikidb->_cache;
1734 $pagename = $this->_pagename;
1735 $version = $this->_version;
1737 assert($version > 0);
1739 $newdata = $cache->get_versiondata($pagename, $version, true);
1741 assert(is_string($newdata['%content']));
1742 return $newdata['%content'];
1744 // else revision has been deleted... What to do?
1745 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1746 $version, $pagename);
1751 * Get meta-data for this revision.
1753 * @param string $key Which meta-data to access.
1755 * Some reserved revision meta-data keys are:
1757 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1758 * The 'mtime' meta-value is normally set automatically by the database
1759 * backend, but it may be specified explicitly when creating a new revision.
1761 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1762 * of a page must be monotonically increasing. If an attempt is
1763 * made to create a new revision with an mtime less than that of
1764 * the preceeding revision, the new revisions timestamp is force
1765 * to be equal to that of the preceeding revision. In that case,
1766 * the originally requested mtime is preserved in 'orig_mtime'.
1767 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1768 * This meta-value is <em>always</em> automatically maintained by the database
1769 * backend. (It is set from the 'mtime' meta-value of the superceding
1770 * revision.) '_supplanted' has a value of 'false' for the current revision.
1772 * FIXME: this could be refactored:
1774 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1776 * <dd> Authenticated author of a page. This is used to identify
1777 * the distinctness of authors when cleaning old revisions from
1779 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1780 * <dt> 'summary' <dd> Short change summary entered by page author.
1783 * Meta-data keys must be valid C identifers (they have to start with a letter
1784 * or underscore, and can contain only alphanumerics and underscores.)
1786 * @return string The requested value, or false if the requested value
1789 public function get($key)
1791 if (!$key || $key[0] == '%')
1793 $data = &$this->_data;
1794 return isset($data[$key]) ? $data[$key] : false;
1798 * Get all the revision page meta-data as a hash.
1800 * @return array The revision meta-data.
1802 function getMetaData()
1805 foreach ($this->_data as $key => $val) {
1806 if (!empty($val) && $key[0] != '%')
1813 * Return a string representation of the revision.
1815 * This is really only for debugging.
1817 * @return string Printable representation of the WikiDB_Page.
1819 public function asString()
1822 printf("[%s:%d\n", get_class($this), $this->get('version'));
1823 print_r($this->_data);
1824 echo $this->getPackedContent() . "\n]\n";
1825 $strval = ob_get_contents();
1832 * Class representing a sequence of WikiDB_Pages.
1833 * TODO: Enhance to php5 iterators
1835 * apply filters for options like 'sortby', 'limit', 'exclude'
1836 * for simple queries like titleSearch, where the backend is not ready yet.
1838 class WikiDB_PageIterator
1840 function WikiDB_PageIterator(&$wikidb, &$iter, $options = false)
1842 $this->_iter = $iter; // a WikiDB_backend_iterator
1843 $this->_wikidb = &$wikidb;
1844 $this->_options = $options;
1849 return $this->_iter->count();
1854 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1858 * Get next WikiDB_Page in sequence.
1860 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1862 public function next()
1864 if (!($next = $this->_iter->next())) {
1868 $pagename = &$next['pagename'];
1869 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1870 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1874 if (isset($next['linkrelation'])
1875 or isset($next['pagedata']['linkrelation'])
1881 // There's always hits, but we cache only if more
1882 // (well not with file, cvs and dba)
1883 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1884 $this->_wikidb->_cache->cache_data($next);
1885 // cache existing page id's since we iterate over all links in GleanDescription
1886 // and need them later for LinkExistingWord
1887 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1888 and !$this->_options['include_empty'] and isset($next['id'])
1890 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1892 $page = new WikiDB_Page($this->_wikidb, $pagename);
1893 if (isset($next['linkrelation']))
1894 $page->set('linkrelation', $next['linkrelation']);
1895 if (isset($next['score']))
1896 $page->score = $next['score'];
1901 * Release resources held by this iterator.
1903 * The iterator may not be used after free() is called.
1905 * There is no need to call free(), if next() has returned false.
1906 * (I.e. if you iterate through all the pages in the sequence,
1907 * you do not need to call free() --- you only need to call it
1908 * if you stop before the end of the iterator is reached.)
1910 public function free()
1912 // $this->_iter->free();
1917 $this->_iter->reset();
1923 while ($page = $this->next())
1930 * Apply filters for options like 'sortby', 'limit', 'exclude'
1931 * for simple queries like titleSearch, where the backend is not ready yet.
1932 * Since iteration is usually destructive for SQL results,
1933 * we have to generate a copy.
1935 function applyFilters($options = false)
1937 if (!$options) $options = $this->_options;
1938 if (isset($options['sortby'])) {
1940 /* this is destructive */
1941 while ($page = $this->next())
1942 $result[] = $page->getName();
1943 $this->_doSort($array, $options['sortby']);
1945 /* the rest is not destructive.
1946 * reconstruct a new iterator
1948 $pagenames = array();
1950 if (isset($options['limit']))
1951 $limit = $options['limit'];
1954 if (isset($options['exclude']))
1955 $exclude = $options['exclude'];
1956 if (is_string($exclude) and !is_array($exclude))
1957 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1958 foreach ($array as $pagename) {
1959 if ($limit and $i++ > $limit)
1960 return new WikiDB_Array_PageIterator($pagenames);
1961 if (!empty($exclude) and !in_array($pagename, $exclude))
1962 $pagenames[] = $pagename;
1963 elseif (empty($exclude))
1964 $pagenames[] = $pagename;
1966 return new WikiDB_Array_PageIterator($pagenames);
1970 function _doSort(&$array, $sortby)
1972 $sortby = PageList::sortby($sortby, 'init');
1973 if ($sortby == '+pagename')
1974 sort($array, SORT_STRING);
1975 elseif ($sortby == '-pagename')
1976 rsort($array, SORT_STRING);
1983 * A class which represents a sequence of WikiDB_PageRevisions.
1984 * TODO: Enhance to php5 iterators
1986 class WikiDB_PageRevisionIterator
1988 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
1990 $this->_revisions = $revisions;
1991 $this->_wikidb = &$wikidb;
1992 $this->_options = $options;
1997 return $this->_revisions->count();
2001 * Get next WikiDB_PageRevision in sequence.
2003 * @return WikiDB_PageRevision
2004 * The next WikiDB_PageRevision in the sequence.
2006 public function next()
2008 if (!($next = $this->_revisions->next()))
2011 //$this->_wikidb->_cache->cache_data($next);
2013 $pagename = $next['pagename'];
2014 $version = $next['version'];
2015 $versiondata = $next['versiondata'];
2017 if (!(is_string($pagename) and $pagename != '')) {
2018 trigger_error("empty pagename", E_USER_WARNING);
2021 } else assert(is_string($pagename) and $pagename != '');
2023 if (!is_array($versiondata)) {
2024 trigger_error("empty versiondata", E_USER_WARNING);
2027 } else assert(is_array($versiondata));
2029 if (!($version > 0)) {
2030 trigger_error("invalid version", E_USER_WARNING);
2033 } else assert($version > 0);
2035 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2040 * Release resources held by this iterator.
2042 * The iterator may not be used after free() is called.
2044 * There is no need to call free(), if next() has returned false.
2045 * (I.e. if you iterate through all the revisions in the sequence,
2046 * you do not need to call free() --- you only need to call it
2047 * if you stop before the end of the iterator is reached.)
2049 public function free()
2051 $this->_revisions->free();
2057 while ($rev = $this->next())
2066 class WikiDB_Array_PageIterator
2068 function WikiDB_Array_PageIterator($pagenames)
2071 $this->_dbi = $request->getDbh();
2072 $this->_pages = $pagenames;
2073 reset($this->_pages);
2078 $c = current($this->_pages);
2079 next($this->_pages);
2080 return $c !== false ? $this->_dbi->getPage($c) : false;
2085 return count($this->_pages);
2090 reset($this->_pages);
2099 reset($this->_pages);
2100 return $this->_pages;
2104 class WikiDB_Array_generic_iter
2106 function WikiDB_Array_generic_iter($result)
2108 // $result may be either an array or a query result
2109 if (is_array($result)) {
2110 $this->_array = $result;
2111 } elseif (is_object($result)) {
2112 $this->_array = $result->asArray();
2114 $this->_array = array();
2116 if (!empty($this->_array))
2117 reset($this->_array);
2122 $c = current($this->_array);
2123 next($this->_array);
2124 return $c !== false ? $c : false;
2129 return count($this->_array);
2134 reset($this->_array);
2143 if (!empty($this->_array))
2144 reset($this->_array);
2145 return $this->_array;
2150 * Data cache used by WikiDB.
2152 * FIXME: Maybe rename this to caching_backend (or some such).
2158 // FIXME: beautify versiondata cache. Cache only limited data?
2160 function WikiDB_cache(&$backend)
2162 $this->_backend = &$backend;
2164 $this->_pagedata_cache = array();
2165 $this->_versiondata_cache = array();
2166 array_push($this->_versiondata_cache, array());
2167 $this->_glv_cache = array();
2168 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2170 if (isset($GLOBALS['request']->_dbi))
2171 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2176 $this->_pagedata_cache = array();
2177 $this->_versiondata_cache = array();
2178 $this->_glv_cache = array();
2179 $this->_id_cache = array();
2182 function get_pagedata($pagename)
2184 assert(is_string($pagename) && $pagename != '');
2186 $cache = &$this->_pagedata_cache;
2187 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2188 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2189 if (empty($cache[$pagename]))
2190 $cache[$pagename] = array();
2192 return $cache[$pagename];
2194 return $this->_backend->get_pagedata($pagename);
2198 function update_pagedata($pagename, $newdata)
2200 assert(is_string($pagename) && $pagename != '');
2201 if (!empty($this->readonly)) {
2202 trigger_error("readonly database", E_USER_WARNING);
2206 $this->_backend->update_pagedata($pagename, $newdata);
2209 if (!empty($this->_pagedata_cache[$pagename])
2210 and is_array($this->_pagedata_cache[$pagename])
2212 $cachedata = &$this->_pagedata_cache[$pagename];
2213 foreach ($newdata as $key => $val)
2214 $cachedata[$key] = $val;
2216 $this->_pagedata_cache[$pagename] = $newdata;
2220 function invalidate_cache($pagename)
2222 unset ($this->_pagedata_cache[$pagename]);
2223 unset ($this->_versiondata_cache[$pagename]);
2224 unset ($this->_glv_cache[$pagename]);
2225 unset ($this->_id_cache[$pagename]);
2226 //unset ($this->_backend->_page_data);
2229 function delete_page($pagename)
2231 if (!empty($this->readonly)) {
2232 trigger_error("readonly database", E_USER_WARNING);
2235 $result = $this->_backend->delete_page($pagename);
2236 $this->invalidate_cache($pagename);
2240 function purge_page($pagename)
2242 if (!empty($this->readonly)) {
2243 trigger_error("readonly database", E_USER_WARNING);
2246 $result = $this->_backend->purge_page($pagename);
2247 $this->invalidate_cache($pagename);
2251 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2252 function cache_data($data)
2255 //if (isset($data['pagedata']))
2256 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2259 function get_versiondata($pagename, $version, $need_content = false)
2261 // FIXME: Seriously ugly hackage
2263 if (USECACHE) { //temporary - for debugging
2264 assert(is_string($pagename) && $pagename != '');
2265 // There is a bug here somewhere which results in an assertion failure at line 105
2266 // of ArchiveCleaner.php It goes away if we use the next line.
2267 //$need_content = true;
2268 $nc = $need_content ? '1' : '0';
2269 $cache = &$this->_versiondata_cache;
2270 if (!isset($cache[$pagename][$version][$nc])
2271 || !(is_array($cache[$pagename]))
2272 || !(is_array($cache[$pagename][$version]))
2274 $cache[$pagename][$version][$nc] =
2275 $this->_backend->get_versiondata($pagename, $version, $need_content);
2277 // If we have retrieved all data, we may as well set the cache for
2278 // $need_content = false
2279 if ($need_content) {
2280 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2283 $vdata = $cache[$pagename][$version][$nc];
2285 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2288 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2289 if (empty($this->_pagedata_cache))
2290 $this->_pagedata_cache = array();
2291 /* 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 */
2292 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2297 function set_versiondata($pagename, $version, $data)
2299 //unset($this->_versiondata_cache[$pagename][$version]);
2301 if (!empty($this->readonly)) {
2302 trigger_error("readonly database", E_USER_WARNING);
2305 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2307 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2308 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2309 // Is this necessary?
2310 unset($this->_glv_cache[$pagename]);
2313 function update_versiondata($pagename, $version, $data)
2315 if (!empty($this->readonly)) {
2316 trigger_error("readonly database", E_USER_WARNING);
2319 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2321 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2323 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2324 // Is this necessary?
2325 unset($this->_glv_cache[$pagename]);
2328 function delete_versiondata($pagename, $version)
2330 if (!empty($this->readonly)) {
2331 trigger_error("readonly database", E_USER_WARNING);
2334 $new = $this->_backend->delete_versiondata($pagename, $version);
2335 if (isset($this->_versiondata_cache[$pagename][$version]))
2336 unset ($this->_versiondata_cache[$pagename][$version]);
2337 // dirty latest version cache only if latest version gets deleted
2338 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2339 unset ($this->_glv_cache[$pagename]);
2342 function get_latest_version($pagename)
2345 assert(is_string($pagename) && $pagename != '');
2346 $cache = &$this->_glv_cache;
2347 if (!isset($cache[$pagename])) {
2348 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2349 if (empty($cache[$pagename]))
2350 $cache[$pagename] = 0;
2352 return $cache[$pagename];
2354 return $this->_backend->get_latest_version($pagename);
2359 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2364 $stamp = strftime("%y%m%d-%H%M%S");
2365 $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2366 register_shutdown_function("_sql_debuglog_shutdown_function");
2367 } elseif ($shutdown) {
2371 if ($newline) fputs($fp, "[$i++] $msg");
2372 else fwrite($fp, $msg);
2375 function _sql_debuglog_shutdown_function()
2377 _sql_debuglog('', false, true);
2383 // c-basic-offset: 4
2384 // c-hanging-comment-ender-p: nil
2385 // indent-tabs-mode: nil