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.
52 * @param hash $dbparams Database configuration parameters.
53 * Some pertinent parameters are:
56 * <dd> The back-end type. Current supported types are:
59 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
60 * library. (More stable and conservative)
62 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
64 * <dd> Dba based backend. The default and by far the fastest.
72 * <dd> (Used by the SQL and ADODB backends.)
73 * The DSN specifying which database to connect to.
76 * <dd> Prefix to be prepended to database tables (and file names).
79 * <dd> (Used by the dba backend.)
80 * Which directory db files reside in.
83 * <dd> Used only by the dba backend so far.
84 * And: When optimizing mysql it closes timed out mysql processes.
85 * otherwise only used for dba: Timeout in seconds for opening (and
86 * obtaining lock) on the dbm file.
89 * <dd> (Used by the dba backend.)
91 * Which dba handler to use. Good choices are probably either
95 * <dd> Either set by config.ini: READONLY = true or detected automatically
96 * when a database can be read but cannot be updated.
99 * @return WikiDB A WikiDB object.
101 function open($dbparams)
103 $dbtype = $dbparams{'dbtype'};
104 include_once("lib/WikiDB/$dbtype.php");
106 $class = 'WikiDB_' . $dbtype;
107 return new $class ($dbparams);
116 function WikiDB(&$backend, $dbparams)
118 $this->_backend =& $backend;
119 // don't do the following with the auth_dsn!
120 if (isset($dbparams['auth_dsn'])) return;
122 $this->_cache = new WikiDB_cache($backend);
123 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
125 // If the database doesn't yet have a timestamp, initialize it now.
126 if ($this->get('_timestamp') === false)
130 if ((int)DEBUG & _DEBUG_SQL) {
131 $this->_backend->check();
133 // might be changed when opening the database fails
134 $this->readonly = defined("READONLY") ? READONLY : false;
138 * Close database connection.
140 * The database may no longer be used after it is closed.
142 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
143 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
144 * which have been obtained from it.
150 $this->_backend->close();
151 $this->_cache->close();
155 * Get a WikiDB_Page from a WikiDB.
157 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
158 * therefore this method never fails.
161 * @param string $pagename Which page to get.
162 * @return WikiDB_Page The requested WikiDB_Page.
164 function getPage($pagename)
166 static $error_displayed = false;
167 $pagename = (string)$pagename;
169 if ($pagename === '') {
170 if ($error_displayed) return false;
171 $error_displayed = true;
172 if (function_exists("xdebug_get_function_stack"))
173 var_dump(xdebug_get_function_stack());
174 trigger_error("empty pagename", E_USER_WARNING);
178 assert($pagename != '');
180 return new WikiDB_Page($this, $pagename);
184 * Determine whether page exists (in non-default form).
187 * $is_page = $dbi->isWikiPage($pagename);
191 * $page = $dbi->getPage($pagename);
192 * $current = $page->getCurrentRevision();
193 * $is_page = ! $current->hasDefaultContents();
195 * however isWikiPage may be implemented in a more efficient
196 * manner in certain back-ends.
199 * @param string $pagename string Which page to check.
200 * @return boolean True if the page actually exists with
201 * non-default contents in the WikiDataBase.
203 function isWikiPage($pagename)
205 $page = $this->getPage($pagename);
206 return ($page and $page->exists());
210 * Delete page from the WikiDB.
212 * Deletes the page from the WikiDB with the possibility to revert and diff.
213 * //Also resets all page meta-data to the default values.
215 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
218 * @param string $pagename Name of page to delete.
221 function deletePage($pagename)
223 if (!empty($this->readonly)) {
224 trigger_error("readonly database", E_USER_WARNING);
227 // don't create empty revisions of already purged pages.
228 if ($this->_backend->get_latest_version($pagename))
229 $result = $this->_cache->delete_page($pagename);
233 /* Generate notification emails */
234 if (ENABLE_MAILNOTIFY) {
235 include_once 'lib/MailNotify.php';
236 $MailNotify = new MailNotify($pagename);
237 $MailNotify->onDeletePage($this, $pagename);
240 //How to create a RecentChanges entry with explaining summary? Dynamically
242 $page = $this->getPage($pagename);
243 $current = $page->getCurrentRevision();
244 $meta = $current->_data;
245 $version = $current->getVersion();
246 $meta['summary'] = _("removed");
247 $page->save($current->getPackedContent(), $version + 1, $meta);
253 * Completely remove the page from the WikiDB, without undo possibility.
255 * @param string $pagename Name of page to delete.
258 function purgePage($pagename)
260 if (!empty($this->readonly)) {
261 trigger_error("readonly database", E_USER_WARNING);
264 $result = $this->_cache->purge_page($pagename);
265 $this->deletePage($pagename); // just for the notification
270 * Retrieve all pages.
272 * Gets the set of all pages with non-default contents.
276 * @param boolean $include_empty Optional. Normally pages whose most
277 * recent revision has empty content are considered to be
278 * non-existant. Unless $include_defaulted is set to true, those
279 * pages will not be returned.
280 * @param string or false $sortby Optional. "+-column,+-column2".
281 * If false the result is faster in natural order.
282 * @param string or false $limit Optional. Encoded as "$offset,$count".
283 * $offset defaults to 0.
284 * @param string $exclude: Optional comma-seperated list of pagenames.
286 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
287 * in the WikiDB which have non-default contents.
289 function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
291 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
293 return new WikiDB_PageIterator($this, $result,
294 array('include_empty' => $include_empty,
295 'exclude' => $exclude,
296 'limit_by_db' => $result->_options['limit_by_db'],
297 'limit' => $result->limit()));
303 * @param boolean $include_empty If true include also empty pages
304 * @param string $exclude: comma-seperated list of pagenames.
305 * TBD: array of pagenames
309 function numPages($include_empty = false, $exclude = '')
311 if (method_exists($this->_backend, 'numPages'))
312 // FIXME: currently are all args ignored.
313 $count = $this->_backend->numPages($include_empty, $exclude);
315 // FIXME: exclude ignored.
316 $iter = $this->getAllPages($include_empty, false, false, $exclude);
317 $count = $iter->count();
326 * Search for pages containing (or not containing) certain words
329 * Pages are returned in alphabetical order whenever it is
330 * practical to do so.
331 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
334 * @param TextSearchQuery $search A TextSearchQuery object
335 * @param string or false $sortby Optional. "+-column,+-column2".
336 * If false the result is faster in natural order.
337 * @param string or false $limit Optional. Encoded as "$offset,$count".
338 * $offset defaults to 0.
339 * @param string $exclude: Optional comma-seperated list of pagenames.
340 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
341 * @see TextSearchQuery
343 function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
345 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
346 $options = array('exclude' => $exclude,
348 //if (isset($result->_count)) $options['count'] = $result->_count;
349 return new WikiDB_PageIterator($this, $result, $options);
355 * Search for pages containing (or not containing) certain words
356 * in their entire text (this includes the page content and the
359 * Pages are returned in alphabetical order whenever it is
360 * practical to do so.
361 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
365 * @param TextSearchQuery $search A TextSearchQuery object.
366 * @param string or false $sortby Optional. "+-column,+-column2".
367 * If false the result is faster in natural order.
368 * @param string or false $limit Optional. Encoded as "$offset,$count".
369 * $offset defaults to 0.
370 * @param string $exclude: Optional comma-seperated list of pagenames.
371 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
372 * @see TextSearchQuery
374 function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
376 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
377 return new WikiDB_PageIterator($this, $result,
378 array('exclude' => $exclude,
380 'stoplisted' => $result->stoplisted
385 * Find the pages with the greatest hit counts.
387 * Pages are returned in reverse order by hit count.
391 * @param integer $limit The maximum number of pages to return.
392 * Set $limit to zero to return all pages. If $limit < 0, pages will
393 * be sorted in decreasing order of popularity.
394 * @param string or false $sortby Optional. "+-column,+-column2".
395 * If false the result is faster in natural order.
397 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
400 function mostPopular($limit = 20, $sortby = '-hits')
402 $result = $this->_backend->most_popular($limit, $sortby);
403 return new WikiDB_PageIterator($this, $result);
407 * Find recent page revisions.
409 * Revisions are returned in reverse order by creation time.
413 * @param hash $params This hash is used to specify various optional
417 * <dd> (integer) At most this many revisions will be returned.
419 * <dd> (integer) Only revisions since this time (unix-timestamp)
421 * <dt> include_minor_revisions
422 * <dd> (boolean) Also include minor revisions. (Default is not to.)
423 * <dt> exclude_major_revisions
424 * <dd> (boolean) Don't include non-minor revisions.
425 * (Exclude_major_revisions implies include_minor_revisions.)
426 * <dt> include_all_revisions
427 * <dd> (boolean) Return all matching revisions for each page.
428 * Normally only the most recent matching revision is returned
432 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
433 * containing the matching revisions.
435 function mostRecent($params = false)
437 $result = $this->_backend->most_recent($params);
438 return new WikiDB_PageRevisionIterator($this, $result);
444 * @param string or false $sortby Optional. "+-column,+-column2".
445 * If false the result is faster in natural order.
446 * @param string or false $limit Optional. Encoded as "$offset,$count".
447 * $offset defaults to 0.
448 * @return Iterator A generic iterator containing rows of
449 * (duplicate) pagename, wantedfrom.
451 function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
453 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
454 //return new WikiDB_PageIterator($this, $result);
458 * Generic interface to the link table. Esp. useful to search for rdf triples as in
459 * SemanticSearch and ListRelations.
463 * @param $pages object A TextSearchQuery object.
464 * @param $search object A TextSearchQuery object.
465 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
466 * linktype parameter:
469 * <dd> search for simple out-links
471 * <dd> in-links, i.e BackLinks
473 * <dd> the first part in a <>::<> link
475 * <dd> the first part in a <>:=<> link
477 * @param $relation object An optional TextSearchQuery to match the
478 * relation name. Ignored on simple in-out links.
480 * @return Iterator A generic iterator containing links to pages or values.
481 * hash of "pagename", "linkname", "linkvalue.
483 function linkSearch($pages, $search, $linktype, $relation = false)
485 return $this->_backend->link_search($pages, $search, $linktype, $relation);
489 * Return a simple list of all defined relations (and attributes), mainly
490 * for the SemanticSearch autocompletion.
494 * @return array of strings
496 function listRelations($also_attributes = false, $only_attributes = false, $sorted = true)
498 if (method_exists($this->_backend, "list_relations"))
499 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
500 // dumb, slow fallback. no iter, so simply define it here.
501 $relations = array();
502 $iter = $this->getAllPages();
503 while ($page = $iter->next()) {
504 $reliter = $page->getRelations();
506 while ($rel = $reliter->next()) {
507 // if there's no pagename it's an attribute
508 $names[] = $rel->getName();
510 $relations = array_merge($relations, $names);
522 * Call the appropriate backend method.
525 * @param string $from Page to rename
526 * @param string $to New name
527 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
528 * @return boolean true or false
530 function renamePage($from, $to, $updateWikiLinks = false)
532 if (!empty($this->readonly)) {
533 trigger_error("readonly database", E_USER_WARNING);
536 assert(is_string($from) && $from != '');
537 assert(is_string($to) && $to != '');
539 if (method_exists($this->_backend, 'rename_page')) {
540 $oldpage = $this->getPage($from);
541 $newpage = $this->getPage($to);
542 //update all WikiLinks in existing pages
543 //non-atomic! i.e. if rename fails the links are not undone
544 if ($updateWikiLinks) {
545 $lookbehind = "/(?<=[\W:])\Q";
546 $lookahead = "\E(?=[\W:])/";
547 require_once 'lib/plugin/WikiAdminSearchReplace.php';
548 $links = $oldpage->getBackLinks();
549 while ($linked_page = $links->next()) {
550 WikiPlugin_WikiAdminSearchReplace::replaceHelper
552 $linked_page->getName(),
553 $lookbehind . $from . $lookahead, $to,
556 // FIXME: Disabled to avoid recursive modification when renaming
557 // a page like 'PageFoo to 'PageFooTwo'
559 $links = $newpage->getBackLinks();
560 while ($linked_page = $links->next()) {
561 WikiPlugin_WikiAdminSearchReplace::replaceHelper
563 $linked_page->getName(),
564 $lookbehind . $from . $lookahead, $to,
569 if ($oldpage->exists() and !$newpage->exists()) {
570 if ($result = $this->_backend->rename_page($from, $to)) {
571 // create a RecentChanges entry with explaining summary
572 $page = $this->getPage($to);
573 $current = $page->getCurrentRevision();
574 $meta = $current->_data;
575 $version = $current->getVersion();
576 $meta['summary'] = sprintf(_("renamed from %s"), $from);
577 unset($meta['mtime']); // force new date
578 $page->save($current->getPackedContent(), $version + 1, $meta);
580 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
581 // if a version 0 exists try it also.
582 $result = $this->_backend->rename_page($from, $to);
585 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
588 /* Generate notification emails? */
589 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
590 $notify = $this->get('notify');
591 if (!empty($notify) and is_array($notify)) {
592 include_once 'lib/MailNotify.php';
593 $MailNotify = new MailNotify($from);
594 $MailNotify->onRenamePage($this, $from, $to);
600 /** Get timestamp when database was last modified.
602 * @return string A string consisting of two integers,
603 * separated by a space. The first is the time in
604 * unix timestamp format, the second is a modification
605 * count for the database.
607 * The idea is that you can cast the return value to an
608 * int to get a timestamp, or you can use the string value
609 * as a good hash for the entire database.
611 function getTimestamp()
613 $ts = $this->get('_timestamp');
614 return sprintf("%d %d", $ts[0], $ts[1]);
618 * Update the database timestamp.
623 $ts = $this->get('_timestamp');
624 $this->set('_timestamp', array(time(), $ts[1] + 1));
628 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
630 function get_db_version()
632 return (float)$this->get('_db_version');
635 function set_db_version($ver)
637 return $this->set('_db_version', (float)$ver);
641 * Access WikiDB global meta-data.
643 * NOTE: this is currently implemented in a hackish and
644 * not very efficient manner.
648 * @param string $key Which meta data to get.
649 * Some reserved meta-data keys are:
651 * <dt>'_timestamp' <dd> Data used by getTimestamp().
654 * @return scalar The requested value, or false if the requested data
659 if (!$key || $key[0] == '%')
662 * Hack Alert: We can use any page (existing or not) to store
663 * this data (as long as we always use the same one.)
665 $gd = $this->getPage('global_data');
666 $data = $gd->get('__global');
668 if ($data && isset($data[$key]))
675 * Set global meta-data.
677 * NOTE: this is currently implemented in a hackish and
678 * not very efficient manner.
683 * @param string $key Meta-data key to set.
684 * @param string $newval New value.
686 function set($key, $newval)
688 if (!empty($this->readonly)) {
689 trigger_error("readonly database", E_USER_WARNING);
692 if (!$key || $key[0] == '%')
695 $gd = $this->getPage('global_data');
696 $data = $gd->get('__global');
703 $data[$key] = $newval;
705 $gd->set('__global', $data);
708 /* TODO: these are really backend methods */
710 // SQL result: for simple select or create/update queries
711 // returns the database specific resource type
712 function genericSqlQuery($sql, $args = false)
714 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
715 trigger_error("no SQL database", E_USER_ERROR);
719 // SQL iter: for simple select or create/update queries
720 // returns the generic iterator object (count,next)
721 function genericSqlIter($sql, $field_list = NULL)
723 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
724 trigger_error("no SQL database", E_USER_ERROR);
728 // see backend upstream methods
729 // ADODB adds surrounding quotes, SQL not yet!
738 if (!$request->_dbi) return false;
739 else return false; /* so far only needed for sql so false it.
740 later we have to check dba also */
743 function getParam($param)
746 if (isset($DBParams[$param])) return $DBParams[$param];
747 elseif ($param == 'prefix') return ''; else return false;
750 function getAuthParam($param)
752 global $DBAuthParams;
753 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
754 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false;
759 * A base class which representing a wiki-page within a
762 * A WikiDB_Page contains a number (at least one) of
763 * WikiDB_PageRevisions.
767 function WikiDB_Page(&$wikidb, $pagename)
769 $this->_wikidb = &$wikidb;
770 $this->_pagename = $pagename;
772 if (!(is_string($pagename) and $pagename != '')) {
773 if (function_exists("xdebug_get_function_stack")) {
774 echo "xdebug_get_function_stack(): ";
775 var_dump(xdebug_get_function_stack());
777 printSimpleTrace(debug_backtrace());
779 trigger_error("empty pagename", E_USER_WARNING);
783 assert(is_string($pagename) and $pagename != '');
788 * Get the name of the wiki page.
792 * @return string The page name.
796 return $this->_pagename;
799 // To reduce the memory footprint for larger sets of pagelists,
800 // we don't cache the content (only true or false) and
801 // we purge the pagedata (_cached_html) also
804 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
805 $current = $this->getCurrentRevision(false);
806 if (!$current) return false;
807 return !$current->hasDefaultContents();
811 * Delete an old revision of a WikiDB_Page.
813 * Deletes the specified revision of the page.
814 * It is a fatal error to attempt to delete the current revision.
818 * @param integer $version Which revision to delete. (You can also
819 * use a WikiDB_PageRevision object here.)
821 function deleteRevision($version)
823 if ($this->_wikidb->readonly) {
824 trigger_error("readonly database", E_USER_WARNING);
827 $backend = &$this->_wikidb->_backend;
828 $cache = &$this->_wikidb->_cache;
829 $pagename = &$this->_pagename;
831 $version = $this->_coerce_to_version($version);
835 $backend->lock(array('page', 'version'));
836 $latestversion = $cache->get_latest_version($pagename);
837 if ($latestversion && ($version == $latestversion)) {
838 $backend->unlock(array('page', 'version'));
839 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
840 $pagename), E_USER_ERROR);
844 $cache->delete_versiondata($pagename, $version);
845 $backend->unlock(array('page', 'version'));
849 * Delete a revision, or possibly merge it with a previous
853 * Suppose an author make a (major) edit to a page. Shortly
854 * after that the same author makes a minor edit (e.g. to fix
855 * spelling mistakes he just made.)
857 * Now some time later, where cleaning out old saved revisions,
858 * and would like to delete his minor revision (since there's
859 * really no point in keeping minor revisions around for a long
862 * Note that the text after the minor revision probably represents
863 * what the author intended to write better than the text after
864 * the preceding major edit.
866 * So what we really want to do is merge the minor edit with the
869 * We will only do this when:
871 * <li>The revision being deleted is a minor one, and
872 * <li>It has the same author as the immediately preceding revision.
875 function mergeRevision($version)
877 if ($this->_wikidb->readonly) {
878 trigger_error("readonly database", E_USER_WARNING);
881 $backend = &$this->_wikidb->_backend;
882 $cache = &$this->_wikidb->_cache;
883 $pagename = &$this->_pagename;
885 $version = $this->_coerce_to_version($version);
889 $backend->lock(array('version'));
890 $latestversion = $cache->get_latest_version($pagename);
891 if ($latestversion && $version == $latestversion) {
892 $backend->unlock(array('version'));
893 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
894 $pagename), E_USER_ERROR);
898 $versiondata = $cache->get_versiondata($pagename, $version, true);
900 // Not there? ... we're done!
901 $backend->unlock(array('version'));
905 if ($versiondata['is_minor_edit']) {
906 $previous = $backend->get_previous_version($pagename, $version);
908 $prevdata = $cache->get_versiondata($pagename, $previous);
909 if ($prevdata['author_id'] == $versiondata['author_id']) {
910 // This is a minor revision, previous version is
911 // by the same author. We will merge the
913 $cache->update_versiondata($pagename, $previous,
914 array('%content' => $versiondata['%content'],
915 '_supplanted' => $versiondata['_supplanted']));
920 $cache->delete_versiondata($pagename, $version);
921 $backend->unlock(array('version'));
926 * Create a new revision of a {@link WikiDB_Page}.
930 * @param int $version Version number for new revision.
931 * To ensure proper serialization of edits, $version must be
932 * exactly one higher than the current latest version.
933 * (You can defeat this check by setting $version to
934 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
936 * @param string $content Contents of new revision.
938 * @param hash $metadata Metadata for new revision.
939 * All values in the hash should be scalars (strings or integers).
941 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
943 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
944 * $version was incorrect, returns false
946 function createRevision($version, &$content, $metadata, $links)
948 if ($this->_wikidb->readonly) {
949 trigger_error("readonly database", E_USER_WARNING);
952 $backend = &$this->_wikidb->_backend;
953 $cache = &$this->_wikidb->_cache;
954 $pagename = &$this->_pagename;
955 $cache->invalidate_cache($pagename);
957 $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
959 $latestversion = $backend->get_latest_version($pagename);
960 $newversion = ($latestversion ? $latestversion : 0) + 1;
961 assert($newversion >= 1);
963 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
964 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
970 foreach ($data as $key => $val) {
971 if (empty($val) || $key[0] == '_' || $key[0] == '%')
975 assert(!empty($data['author']));
976 if (empty($data['author_id']))
977 @$data['author_id'] = $data['author'];
979 if (empty($data['mtime']))
980 $data['mtime'] = time();
982 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
983 // Ensure mtimes are monotonic.
984 $pdata = $cache->get_versiondata($pagename, $latestversion);
985 if ($data['mtime'] < $pdata['mtime']) {
986 trigger_error(sprintf(_("%s: Date of new revision is %s"),
987 $pagename, "'non-monotonic'"),
989 $data['orig_mtime'] = $data['mtime'];
990 $data['mtime'] = $pdata['mtime'];
993 // FIXME: use (possibly user specified) 'mtime' time or
995 $cache->update_versiondata($pagename, $latestversion,
996 array('_supplanted' => $data['mtime']));
999 $data['%content'] = &$content;
1001 $cache->set_versiondata($pagename, $newversion, $data);
1003 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
1004 //':deleted' => empty($content)));
1006 $backend->set_links($pagename, $links);
1008 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
1010 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
1014 /** A higher-level interface to createRevision.
1016 * This takes care of computing the links, and storing
1017 * a cached version of the transformed wiki-text.
1019 * @param string $wikitext The page content.
1021 * @param int $version Version number for new revision.
1022 * To ensure proper serialization of edits, $version must be
1023 * exactly one higher than the current latest version.
1024 * (You can defeat this check by setting $version to
1025 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
1027 * @param hash $meta Meta-data for new revision.
1029 function save($wikitext, $version, $meta, $formatted = null)
1031 if ($this->_wikidb->readonly) {
1032 trigger_error("readonly database", E_USER_WARNING);
1035 if (is_null($formatted))
1036 $formatted = new TransformedText($this, $wikitext, $meta);
1037 $type = $formatted->getType();
1038 $meta['pagetype'] = $type->getName();
1039 $links = $formatted->getWikiPageLinks(); // linkto => relation
1040 $attributes = array();
1041 foreach ($links as $link) {
1042 if ($link['linkto'] === "" and !empty($link['relation'])) {
1043 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1046 $meta['attribute'] = $attributes;
1048 $backend = &$this->_wikidb->_backend;
1049 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1050 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1051 $this->set('_cached_html', $formatted->pack());
1053 // FIXME: probably should have some global state information
1054 // in the backend to control when to optimize.
1056 // We're doing this here rather than in createRevision because
1057 // postgresql can't optimize while locked.
1058 if (((int)DEBUG & _DEBUG_SQL)
1059 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1060 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1062 if ($backend->optimize()) {
1064 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1068 /* Generate notification emails? */
1069 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1070 // Save didn't fail because of concurrent updates.
1071 $notify = $this->_wikidb->get('notify');
1073 and is_array($notify)
1074 and !isa($GLOBALS['request'], 'MockRequest')
1076 include_once 'lib/MailNotify.php';
1077 $MailNotify = new MailNotify($newrevision->getName());
1078 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1080 $newrevision->_transformedContent = $formatted;
1082 // more pagechange callbacks: (in a hackish manner for now)
1083 if (ENABLE_RECENTCHANGESBOX
1084 and empty($meta['is_minor_edit'])
1085 and !in_array($GLOBALS['request']->getArg('action'),
1086 array('loadfile', 'upgrade'))
1088 require_once 'lib/WikiPlugin.php';
1089 $w = new WikiPluginLoader;
1090 $p = $w->getPlugin("RecentChangesCached", false);
1091 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1093 return $newrevision;
1097 * Get the most recent revision of a page.
1101 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1103 function getCurrentRevision($need_content = true)
1105 $backend = &$this->_wikidb->_backend;
1106 $cache = &$this->_wikidb->_cache;
1107 $pagename = &$this->_pagename;
1109 // Prevent deadlock in case of memory exhausted errors
1110 // Pure selection doesn't really need locking here.
1111 // sf.net bug#927395
1112 // I know it would be better to lock, but with lots of pages this deadlock is more
1113 // severe than occasionally get not the latest revision.
1114 // In spirit to wikiwiki: read fast, edit slower.
1116 $version = $cache->get_latest_version($pagename);
1117 // getRevision gets the content also!
1118 $revision = $this->getRevision($version, $need_content);
1119 //$backend->unlock();
1125 * Get a specific revision of a WikiDB_Page.
1129 * @param integer $version Which revision to get.
1131 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1132 * false if the requested revision does not exist in the {@link WikiDB}.
1133 * Note that version zero of any page always exists.
1135 function getRevision($version, $need_content = true)
1137 $cache = &$this->_wikidb->_cache;
1138 $pagename = &$this->_pagename;
1140 if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1141 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1144 assert($version > 0);
1145 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1147 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1149 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1154 * Get previous page revision.
1156 * This method find the most recent revision before a specified
1161 * @param integer $version Find most recent revision before this version.
1162 * You can also use a WikiDB_PageRevision object to specify the $version.
1164 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1165 * requested revision does not exist in the {@link WikiDB}. Note that
1166 * unless $version is greater than zero, a revision (perhaps version zero,
1167 * the default revision) will always be found.
1169 function getRevisionBefore($version = false, $need_content = true)
1171 $backend = &$this->_wikidb->_backend;
1172 $pagename = &$this->_pagename;
1173 if ($version === false)
1174 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1176 $version = $this->_coerce_to_version($version);
1181 $previous = $backend->get_previous_version($pagename, $version);
1182 $revision = $this->getRevision($previous, $need_content);
1183 //$backend->unlock();
1189 * Get all revisions of the WikiDB_Page.
1191 * This does not include the version zero (default) revision in the
1192 * returned revision set.
1194 * @return WikiDB_PageRevisionIterator A
1195 * WikiDB_PageRevisionIterator containing all revisions of this
1196 * WikiDB_Page in reverse order by version number.
1198 function getAllRevisions()
1200 $backend = &$this->_wikidb->_backend;
1201 $revs = $backend->get_all_revisions($this->_pagename);
1202 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1206 * Find pages which link to or are linked from a page.
1207 * relations: $backend->get_links is responsible to add the relation to the pagehash
1208 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1209 * if (isset($next['linkrelation']))
1213 * @param boolean $reversed Which links to find: true for backlinks (default).
1215 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1216 * all matching pages.
1218 function getLinks($reversed = true, $include_empty = false, $sortby = '',
1219 $limit = '', $exclude = '', $want_relations = false)
1221 $backend = &$this->_wikidb->_backend;
1222 $result = $backend->get_links($this->_pagename, $reversed,
1223 $include_empty, $sortby, $limit, $exclude,
1225 return new WikiDB_PageIterator($this->_wikidb, $result,
1226 array('include_empty' => $include_empty,
1227 'sortby' => $sortby,
1229 'exclude' => $exclude,
1230 'want_relations' => $want_relations));
1234 * All Links from other pages to this page.
1236 function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1237 $want_relations = false)
1239 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1243 * Forward Links: All Links from this page to other pages.
1245 function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1246 $want_relations = false)
1248 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1252 * Relations: All links from this page to other pages with relation <> 0.
1253 * is_a:=page or population:=number
1255 function getRelations($sortby = '', $limit = '', $exclude = '')
1257 $backend = &$this->_wikidb->_backend;
1258 $result = $backend->get_links($this->_pagename, false, true,
1259 $sortby, $limit, $exclude,
1261 // we do not care for the linked page versiondata, just the pagename and linkrelation
1262 return new WikiDB_PageIterator($this->_wikidb, $result,
1263 array('include_empty' => true,
1264 'sortby' => $sortby,
1266 'exclude' => $exclude,
1267 'want_relations' => true));
1271 * possibly faster link existance check. not yet accelerated.
1273 function existLink($link, $reversed = false)
1275 $backend = &$this->_wikidb->_backend;
1276 if (method_exists($backend, 'exists_link'))
1277 return $backend->exists_link($this->_pagename, $link, $reversed);
1278 //$cache = &$this->_wikidb->_cache;
1279 // TODO: check cache if it is possible
1280 $iter = $this->getLinks($reversed, false);
1281 while ($page = $iter->next()) {
1282 if ($page->getName() == $link)
1289 /* Semantic relations are links with the relation pointing to another page,
1290 the so-called "RDF Triple".
1291 [San Diego] is%20a::city
1292 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1295 /* Semantic attributes for a page.
1296 [San Diego] population:=1,305,736
1297 Attributes are links with the relation pointing to another page.
1301 * Access WikiDB_Page non version-specific meta-data.
1305 * @param string $key Which meta data to get.
1306 * Some reserved meta-data keys are:
1308 * <dt>'date' <dd> Created as unixtime
1309 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1310 * <dt>'hits' <dd> Page hit counter.
1311 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1312 * In SQL stored now in an extra column.
1314 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1315 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1316 * E.g. "owner.users"
1317 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1318 * page-headers and content.
1319 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1320 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1323 * @return scalar The requested value, or false if the requested data
1328 $cache = &$this->_wikidb->_cache;
1329 $backend = &$this->_wikidb->_backend;
1330 if (!$key || $key[0] == '%')
1332 // several new SQL backends optimize this.
1333 if (!WIKIDB_NOCACHE_MARKUP
1334 and $key == '_cached_html'
1335 and method_exists($backend, 'get_cached_html')
1337 return $backend->get_cached_html($this->_pagename);
1339 $data = $cache->get_pagedata($this->_pagename);
1340 return isset($data[$key]) ? $data[$key] : false;
1344 * Get all the page meta-data as a hash.
1346 * @return hash The page meta-data.
1348 function getMetaData()
1350 $cache = &$this->_wikidb->_cache;
1351 $data = $cache->get_pagedata($this->_pagename);
1353 foreach ($data as $key => $val) {
1354 if ( /*!empty($val) &&*/
1363 * Set page meta-data.
1368 * @param string $key Meta-data key to set.
1369 * @param string $newval New value.
1371 function set($key, $newval)
1373 $cache = &$this->_wikidb->_cache;
1374 $backend = &$this->_wikidb->_backend;
1375 $pagename = &$this->_pagename;
1377 assert($key && $key[0] != '%');
1379 // several new SQL backends optimize this.
1380 if (!WIKIDB_NOCACHE_MARKUP
1381 and $key == '_cached_html'
1382 and method_exists($backend, 'set_cached_html')
1384 if ($this->_wikidb->readonly) {
1385 trigger_error("readonly database", E_USER_WARNING);
1388 return $backend->set_cached_html($pagename, $newval);
1391 $data = $cache->get_pagedata($pagename);
1393 if (!empty($newval)) {
1394 if (!empty($data[$key]) && $data[$key] == $newval)
1395 return; // values identical, skip update.
1397 if (empty($data[$key]))
1398 return; // values identical, skip update.
1401 if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1402 trigger_error("readonly database", E_USER_WARNING);
1405 $cache->update_pagedata($pagename, array($key => $newval));
1409 * Increase page hit count.
1411 * FIXME: IS this needed? Probably not.
1413 * This is a convenience function.
1414 * <pre> $page->increaseHitCount(); </pre>
1415 * is functionally identical to
1416 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1417 * but less expensive (ignores the pagadata string)
1419 * Note that this method may be implemented in more efficient ways
1420 * in certain backends.
1424 function increaseHitCount()
1426 if ($this->_wikidb->readonly) {
1427 trigger_error("readonly database", E_USER_NOTICE);
1430 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1431 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1433 @$newhits = $this->get('hits') + 1;
1434 $this->set('hits', $newhits);
1439 * Return a string representation of the WikiDB_Page
1441 * This is really only for debugging.
1445 * @return string Printable representation of the WikiDB_Page.
1450 printf("[%s:%s\n", get_class($this), $this->getName());
1451 print_r($this->getMetaData());
1453 $strval = ob_get_contents();
1461 * @param integer_or_object $version_or_pagerevision
1462 * Takes either the version number (and int) or a WikiDB_PageRevision
1464 * @return integer The version number.
1466 function _coerce_to_version($version_or_pagerevision)
1468 if (method_exists($version_or_pagerevision, "getContent"))
1469 $version = $version_or_pagerevision->getVersion();
1471 $version = (int)$version_or_pagerevision;
1473 assert($version >= 0);
1477 function isUserPage($include_empty = true)
1479 if (!$include_empty and !$this->exists()) return false;
1480 return $this->get('pref') ? true : false;
1483 // May be empty. Either the stored owner (/Chown), or the first authorized author
1486 if ($owner = $this->get('owner'))
1488 // check all revisions forwards for the first author_id
1489 $backend = &$this->_wikidb->_backend;
1490 $pagename = &$this->_pagename;
1491 $latestversion = $backend->get_latest_version($pagename);
1492 for ($v = 1; $v <= $latestversion; $v++) {
1493 $rev = $this->getRevision($v, false);
1494 if ($rev and $owner = $rev->get('author_id')) {
1501 // The authenticated author of the first revision or empty if not authenticated then.
1502 function getCreator()
1504 if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1508 // The authenticated author of the current revision.
1509 function getAuthor()
1511 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1515 /* Semantic Web value, not stored in the links.
1516 * todo: unify with some unit knowledge
1518 function setAttribute($relation, $value)
1520 $attr = $this->get('attributes');
1522 $attr = array($relation => $value);
1524 $attr[$relation] = $value;
1525 $this->set('attributes', $attr);
1528 function getAttribute($relation)
1530 $meta = $this->get('attributes');
1534 return $meta[$relation];
1540 * This class represents a specific revision of a WikiDB_Page within
1543 * A WikiDB_PageRevision has read-only semantics. You may only create
1544 * new revisions (and delete old ones) --- you cannot modify existing
1547 class WikiDB_PageRevision
1549 //var $_transformedContent = false; // set by WikiDB_Page::save()
1551 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1552 $versiondata = false)
1554 $this->_wikidb = &$wikidb;
1555 $this->_pagename = $pagename;
1556 $this->_version = $version;
1557 $this->_data = $versiondata ? $versiondata : array();
1558 $this->_transformedContent = false; // set by WikiDB_Page::save()
1562 * Get the WikiDB_Page which this revision belongs to.
1566 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1570 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1574 * Get the version number of this revision.
1578 * @return integer The version number of this revision.
1580 function getVersion()
1582 return $this->_version;
1586 * Determine whether this revision has defaulted content.
1588 * The default revision (version 0) of each page, as well as any
1589 * pages which are created with empty content have their content
1590 * defaulted to something like:
1592 * Describe [ThisPage] here.
1597 * @return boolean Returns true if the page has default content.
1599 function hasDefaultContents()
1601 $data = &$this->_data;
1602 if (!isset($data['%content'])) return true;
1603 if ($data['%content'] === true) return false;
1604 return $data['%content'] === false or $data['%content'] === "";
1608 * Get the content as an array of lines.
1612 * @return array An array of lines.
1613 * The lines should contain no trailing white space.
1615 function getContent()
1617 return explode("\n", $this->getPackedContent());
1621 * Get the pagename of the revision.
1625 * @return string pagename.
1627 function getPageName()
1629 return $this->_pagename;
1634 return $this->_pagename;
1638 * Determine whether revision is the latest.
1642 * @return boolean True iff the revision is the latest (most recent) one.
1644 function isCurrent()
1646 if (!isset($this->_iscurrent)) {
1647 $page = $this->getPage();
1648 $current = $page->getCurrentRevision(false);
1649 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1651 return $this->_iscurrent;
1655 * Get the transformed content of a page.
1657 * @param string $pagetype Override the page-type of the revision.
1659 * @return object An XmlContent-like object containing the page transformed
1662 function getTransformedContent($pagetype_override = false)
1664 $backend = &$this->_wikidb->_backend;
1666 if ($pagetype_override) {
1667 // Figure out the normal page-type for this page.
1668 $type = PageType::GetPageType($this->get('pagetype'));
1669 if ($type->getName() == $pagetype_override)
1670 $pagetype_override = false; // Not really an override...
1673 if ($pagetype_override) {
1674 // Overriden page type, don't cache (or check cache).
1675 return new TransformedText($this->getPage(),
1676 $this->getPackedContent(),
1677 $this->getMetaData(),
1678 $pagetype_override);
1681 $possibly_cache_results = true;
1683 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1684 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1685 // flush cache for this page.
1686 $page = $this->getPage();
1687 $page->set('_cached_html', ''); // ignored with !USECACHE
1689 $possibly_cache_results = false;
1690 } elseif (USECACHE and !$this->_transformedContent) {
1692 if ($this->isCurrent()) {
1693 $page = $this->getPage();
1694 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1696 $possibly_cache_results = false;
1698 //$backend->unlock();
1701 if (!$this->_transformedContent) {
1702 $this->_transformedContent
1703 = new TransformedText($this->getPage(),
1704 $this->getPackedContent(),
1705 $this->getMetaData());
1707 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1708 // If we're still the current version, cache the transfomed page.
1710 if ($this->isCurrent()) {
1711 $page->set('_cached_html', $this->_transformedContent->pack());
1713 //$backend->unlock();
1717 return $this->_transformedContent;
1721 * Get the content as a string.
1725 * @return string The page content.
1726 * Lines are separated by new-lines.
1728 function getPackedContent()
1730 $data = &$this->_data;
1732 if (empty($data['%content'])
1733 || (!$this->_wikidb->isWikiPage($this->_pagename)
1734 && $this->isCurrent())
1736 include_once 'lib/InlineParser.php';
1738 // A feature similar to taglines at http://www.wlug.org.nz/
1739 // Lib from http://www.aasted.org/quote/
1740 if (defined('FORTUNE_DIR')
1741 and is_dir(FORTUNE_DIR)
1742 and in_array($GLOBALS['request']->getArg('action'),
1743 array('create', 'edit'))
1745 include_once 'lib/fortune.php';
1746 $fortune = new Fortune();
1747 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1749 $quote = "<verbatim>\n"
1750 . str_replace("\n<br>", "\n", $quote)
1751 . "</verbatim>\n\n";
1755 . sprintf(_("Describe %s here."),
1756 "[" . WikiEscape($this->_pagename) . "]");
1758 // Replace empty content with default value.
1759 return sprintf(_("Describe %s here."),
1760 "[" . WikiEscape($this->_pagename) . "]");
1763 // There is (non-default) content.
1764 assert($this->_version > 0);
1766 if (!is_string($data['%content'])) {
1767 // Content was not provided to us at init time.
1768 // (This is allowed because for some backends, fetching
1769 // the content may be expensive, and often is not wanted
1772 // In any case, now we need to get it.
1773 $data['%content'] = $this->_get_content();
1774 assert(is_string($data['%content']));
1777 return $data['%content'];
1780 function _get_content()
1782 $cache = &$this->_wikidb->_cache;
1783 $pagename = $this->_pagename;
1784 $version = $this->_version;
1786 assert($version > 0);
1788 $newdata = $cache->get_versiondata($pagename, $version, true);
1790 assert(is_string($newdata['%content']));
1791 return $newdata['%content'];
1793 // else revision has been deleted... What to do?
1794 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1795 $version, $pagename);
1800 * Get meta-data for this revision.
1805 * @param string $key Which meta-data to access.
1807 * Some reserved revision meta-data keys are:
1809 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1810 * The 'mtime' meta-value is normally set automatically by the database
1811 * backend, but it may be specified explicitly when creating a new revision.
1813 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1814 * of a page must be monotonically increasing. If an attempt is
1815 * made to create a new revision with an mtime less than that of
1816 * the preceeding revision, the new revisions timestamp is force
1817 * to be equal to that of the preceeding revision. In that case,
1818 * the originally requested mtime is preserved in 'orig_mtime'.
1819 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1820 * This meta-value is <em>always</em> automatically maintained by the database
1821 * backend. (It is set from the 'mtime' meta-value of the superceding
1822 * revision.) '_supplanted' has a value of 'false' for the current revision.
1824 * FIXME: this could be refactored:
1826 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1828 * <dd> Authenticated author of a page. This is used to identify
1829 * the distinctness of authors when cleaning old revisions from
1831 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1832 * <dt> 'summary' <dd> Short change summary entered by page author.
1835 * Meta-data keys must be valid C identifers (they have to start with a letter
1836 * or underscore, and can contain only alphanumerics and underscores.)
1838 * @return string The requested value, or false if the requested value
1843 if (!$key || $key[0] == '%')
1845 $data = &$this->_data;
1846 return isset($data[$key]) ? $data[$key] : false;
1850 * Get all the revision page meta-data as a hash.
1852 * @return hash The revision meta-data.
1854 function getMetaData()
1857 foreach ($this->_data as $key => $val) {
1858 if (!empty($val) && $key[0] != '%')
1866 * Return a string representation of the revision.
1868 * This is really only for debugging.
1872 * @return string Printable representation of the WikiDB_Page.
1877 printf("[%s:%d\n", get_class($this), $this->get('version'));
1878 print_r($this->_data);
1879 echo $this->getPackedContent() . "\n]\n";
1880 $strval = ob_get_contents();
1887 * Class representing a sequence of WikiDB_Pages.
1888 * TODO: Enhance to php5 iterators
1890 * apply filters for options like 'sortby', 'limit', 'exclude'
1891 * for simple queries like titleSearch, where the backend is not ready yet.
1893 class WikiDB_PageIterator
1895 function WikiDB_PageIterator(&$wikidb, &$iter, $options = false)
1897 $this->_iter = $iter; // a WikiDB_backend_iterator
1898 $this->_wikidb = &$wikidb;
1899 $this->_options = $options;
1904 return $this->_iter->count();
1909 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1913 * Get next WikiDB_Page in sequence.
1917 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1921 if (!($next = $this->_iter->next())) {
1925 $pagename = &$next['pagename'];
1926 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1927 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1931 if (isset($next['linkrelation'])
1932 or isset($next['pagedata']['linkrelation'])
1938 // There's always hits, but we cache only if more
1939 // (well not with file, cvs and dba)
1940 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1941 $this->_wikidb->_cache->cache_data($next);
1942 // cache existing page id's since we iterate over all links in GleanDescription
1943 // and need them later for LinkExistingWord
1944 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1945 and !$this->_options['include_empty'] and isset($next['id'])
1947 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1949 $page = new WikiDB_Page($this->_wikidb, $pagename);
1950 if (isset($next['linkrelation']))
1951 $page->set('linkrelation', $next['linkrelation']);
1952 if (isset($next['score']))
1953 $page->score = $next['score'];
1958 * Release resources held by this iterator.
1960 * The iterator may not be used after free() is called.
1962 * There is no need to call free(), if next() has returned false.
1963 * (I.e. if you iterate through all the pages in the sequence,
1964 * you do not need to call free() --- you only need to call it
1965 * if you stop before the end of the iterator is reached.)
1971 $this->_iter->free();
1976 $this->_iter->reset();
1982 while ($page = $this->next())
1989 * Apply filters for options like 'sortby', 'limit', 'exclude'
1990 * for simple queries like titleSearch, where the backend is not ready yet.
1991 * Since iteration is usually destructive for SQL results,
1992 * we have to generate a copy.
1994 function applyFilters($options = false)
1996 if (!$options) $options = $this->_options;
1997 if (isset($options['sortby'])) {
1999 /* this is destructive */
2000 while ($page = $this->next())
2001 $result[] = $page->getName();
2002 $this->_doSort($array, $options['sortby']);
2004 /* the rest is not destructive.
2005 * reconstruct a new iterator
2007 $pagenames = array();
2009 if (isset($options['limit']))
2010 $limit = $options['limit'];
2013 if (isset($options['exclude']))
2014 $exclude = $options['exclude'];
2015 if (is_string($exclude) and !is_array($exclude))
2016 $exclude = PageList::explodePageList($exclude, false, false, $limit);
2017 foreach ($array as $pagename) {
2018 if ($limit and $i++ > $limit)
2019 return new WikiDB_Array_PageIterator($pagenames);
2020 if (!empty($exclude) and !in_array($pagename, $exclude))
2021 $pagenames[] = $pagename;
2022 elseif (empty($exclude))
2023 $pagenames[] = $pagename;
2025 return new WikiDB_Array_PageIterator($pagenames);
2029 function _doSort(&$array, $sortby)
2031 $sortby = PageList::sortby($sortby, 'init');
2032 if ($sortby == '+pagename')
2033 sort($array, SORT_STRING);
2034 elseif ($sortby == '-pagename')
2035 rsort($array, SORT_STRING);
2042 * A class which represents a sequence of WikiDB_PageRevisions.
2043 * TODO: Enhance to php5 iterators
2045 class WikiDB_PageRevisionIterator
2047 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
2049 $this->_revisions = $revisions;
2050 $this->_wikidb = &$wikidb;
2051 $this->_options = $options;
2056 return $this->_revisions->count();
2060 * Get next WikiDB_PageRevision in sequence.
2064 * @return WikiDB_PageRevision
2065 * The next WikiDB_PageRevision in the sequence.
2069 if (!($next = $this->_revisions->next()))
2072 //$this->_wikidb->_cache->cache_data($next);
2074 $pagename = $next['pagename'];
2075 $version = $next['version'];
2076 $versiondata = $next['versiondata'];
2078 if (!(is_string($pagename) and $pagename != '')) {
2079 trigger_error("empty pagename", E_USER_WARNING);
2082 } else assert(is_string($pagename) and $pagename != '');
2084 if (!is_array($versiondata)) {
2085 trigger_error("empty versiondata", E_USER_WARNING);
2088 } else assert(is_array($versiondata));
2090 if (!($version > 0)) {
2091 trigger_error("invalid version", E_USER_WARNING);
2094 } else assert($version > 0);
2096 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2101 * Release resources held by this iterator.
2103 * The iterator may not be used after free() is called.
2105 * There is no need to call free(), if next() has returned false.
2106 * (I.e. if you iterate through all the revisions in the sequence,
2107 * you do not need to call free() --- you only need to call it
2108 * if you stop before the end of the iterator is reached.)
2114 $this->_revisions->free();
2120 while ($rev = $this->next())
2129 class WikiDB_Array_PageIterator
2131 function WikiDB_Array_PageIterator($pagenames)
2134 $this->_dbi = $request->getDbh();
2135 $this->_pages = $pagenames;
2136 reset($this->_pages);
2141 $c = current($this->_pages);
2142 next($this->_pages);
2143 return $c !== false ? $this->_dbi->getPage($c) : false;
2148 return count($this->_pages);
2153 reset($this->_pages);
2162 reset($this->_pages);
2163 return $this->_pages;
2167 class WikiDB_Array_generic_iter
2169 function WikiDB_Array_generic_iter($result)
2171 // $result may be either an array or a query result
2172 if (is_array($result)) {
2173 $this->_array = $result;
2174 } elseif (is_object($result)) {
2175 $this->_array = $result->asArray();
2177 $this->_array = array();
2179 if (!empty($this->_array))
2180 reset($this->_array);
2185 $c = current($this->_array);
2186 next($this->_array);
2187 return $c !== false ? $c : false;
2192 return count($this->_array);
2197 reset($this->_array);
2206 if (!empty($this->_array))
2207 reset($this->_array);
2208 return $this->_array;
2213 * Data cache used by WikiDB.
2215 * FIXME: Maybe rename this to caching_backend (or some such).
2221 // FIXME: beautify versiondata cache. Cache only limited data?
2223 function WikiDB_cache(&$backend)
2225 $this->_backend = &$backend;
2227 $this->_pagedata_cache = array();
2228 $this->_versiondata_cache = array();
2229 array_push($this->_versiondata_cache, array());
2230 $this->_glv_cache = array();
2231 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2233 if (isset($GLOBALS['request']->_dbi))
2234 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2239 $this->_pagedata_cache = array();
2240 $this->_versiondata_cache = array();
2241 $this->_glv_cache = array();
2242 $this->_id_cache = array();
2245 function get_pagedata($pagename)
2247 assert(is_string($pagename) && $pagename != '');
2249 $cache = &$this->_pagedata_cache;
2250 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2251 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2252 if (empty($cache[$pagename]))
2253 $cache[$pagename] = array();
2255 return $cache[$pagename];
2257 return $this->_backend->get_pagedata($pagename);
2261 function update_pagedata($pagename, $newdata)
2263 assert(is_string($pagename) && $pagename != '');
2264 if (!empty($this->readonly)) {
2265 trigger_error("readonly database", E_USER_WARNING);
2269 $this->_backend->update_pagedata($pagename, $newdata);
2272 if (!empty($this->_pagedata_cache[$pagename])
2273 and is_array($this->_pagedata_cache[$pagename])
2275 $cachedata = &$this->_pagedata_cache[$pagename];
2276 foreach ($newdata as $key => $val)
2277 $cachedata[$key] = $val;
2279 $this->_pagedata_cache[$pagename] = $newdata;
2283 function invalidate_cache($pagename)
2285 unset ($this->_pagedata_cache[$pagename]);
2286 unset ($this->_versiondata_cache[$pagename]);
2287 unset ($this->_glv_cache[$pagename]);
2288 unset ($this->_id_cache[$pagename]);
2289 //unset ($this->_backend->_page_data);
2292 function delete_page($pagename)
2294 if (!empty($this->readonly)) {
2295 trigger_error("readonly database", E_USER_WARNING);
2298 $result = $this->_backend->delete_page($pagename);
2299 $this->invalidate_cache($pagename);
2303 function purge_page($pagename)
2305 if (!empty($this->readonly)) {
2306 trigger_error("readonly database", E_USER_WARNING);
2309 $result = $this->_backend->purge_page($pagename);
2310 $this->invalidate_cache($pagename);
2314 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2315 function cache_data($data)
2318 //if (isset($data['pagedata']))
2319 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2322 function get_versiondata($pagename, $version, $need_content = false)
2324 // FIXME: Seriously ugly hackage
2326 if (USECACHE) { //temporary - for debugging
2327 assert(is_string($pagename) && $pagename != '');
2328 // There is a bug here somewhere which results in an assertion failure at line 105
2329 // of ArchiveCleaner.php It goes away if we use the next line.
2330 //$need_content = true;
2331 $nc = $need_content ? '1' : '0';
2332 $cache = &$this->_versiondata_cache;
2333 if (!isset($cache[$pagename][$version][$nc])
2334 || !(is_array($cache[$pagename]))
2335 || !(is_array($cache[$pagename][$version]))
2337 $cache[$pagename][$version][$nc] =
2338 $this->_backend->get_versiondata($pagename, $version, $need_content);
2340 // If we have retrieved all data, we may as well set the cache for
2341 // $need_content = false
2342 if ($need_content) {
2343 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2346 $vdata = $cache[$pagename][$version][$nc];
2348 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2351 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2352 if (empty($this->_pagedata_cache))
2353 $this->_pagedata_cache = array();
2354 /* 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 */
2355 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2360 function set_versiondata($pagename, $version, $data)
2362 //unset($this->_versiondata_cache[$pagename][$version]);
2364 if (!empty($this->readonly)) {
2365 trigger_error("readonly database", E_USER_WARNING);
2368 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2370 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2371 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2372 // Is this necessary?
2373 unset($this->_glv_cache[$pagename]);
2376 function update_versiondata($pagename, $version, $data)
2378 if (!empty($this->readonly)) {
2379 trigger_error("readonly database", E_USER_WARNING);
2382 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2384 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2386 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2387 // Is this necessary?
2388 unset($this->_glv_cache[$pagename]);
2391 function delete_versiondata($pagename, $version)
2393 if (!empty($this->readonly)) {
2394 trigger_error("readonly database", E_USER_WARNING);
2397 $new = $this->_backend->delete_versiondata($pagename, $version);
2398 if (isset($this->_versiondata_cache[$pagename][$version]))
2399 unset ($this->_versiondata_cache[$pagename][$version]);
2400 // dirty latest version cache only if latest version gets deleted
2401 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2402 unset ($this->_glv_cache[$pagename]);
2405 function get_latest_version($pagename)
2408 assert(is_string($pagename) && $pagename != '');
2409 $cache = &$this->_glv_cache;
2410 if (!isset($cache[$pagename])) {
2411 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2412 if (empty($cache[$pagename]))
2413 $cache[$pagename] = 0;
2415 return $cache[$pagename];
2417 return $this->_backend->get_latest_version($pagename);
2422 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2427 $stamp = strftime("%y%m%d-%H%M%S");
2428 $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2429 register_shutdown_function("_sql_debuglog_shutdown_function");
2430 } elseif ($shutdown) {
2434 if ($newline) fputs($fp, "[$i++] $msg");
2435 else fwrite($fp, $msg);
2438 function _sql_debuglog_shutdown_function()
2440 _sql_debuglog('', false, true);
2446 // c-basic-offset: 4
2447 // c-hanging-comment-ender-p: nil
2448 // indent-tabs-mode: nil