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 array $dbparams Database configuration parameters (hash).
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 static 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 (defined('ENABLE_MAILNOTIFY') and 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.
249 public function purgePage($pagename)
251 if (!empty($this->readonly)) {
252 trigger_error("readonly database", E_USER_WARNING);
255 $result = $this->_cache->purge_page($pagename);
256 $this->deletePage($pagename); // just for the notification
261 * Retrieve all pages.
263 * Gets the set of all pages with non-default contents.
265 * @param bool $include_empty Optional. Normally pages whose most
266 * recent revision has empty content are considered to be
267 * non-existant. Unless $include_defaulted is set to true, those
268 * pages will not be returned.
269 * @param string $sortby Optional. "+-column,+-column2".
270 * If false the result is faster in natural order.
271 * @param string $limit Optional. Encoded as "$offset,$count".
272 * $offset defaults to 0.
273 * @param string $exclude Optional comma-separated list of pagenames.
275 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
276 * in the WikiDB which have non-default contents.
278 public function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
280 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
282 return new WikiDB_PageIterator($this, $result,
283 array('include_empty' => $include_empty,
284 'exclude' => $exclude,
285 'limit_by_db' => $result->_options['limit_by_db'],
286 'limit' => $result->limit()));
290 * @param boolean $include_empty If true include also empty pages
291 * @param string $exclude: comma-separated list of pagenames.
292 * TBD: array of pagenames
296 public function numPages($include_empty = false, $exclude = '')
298 if (method_exists($this->_backend, 'numPages'))
299 // FIXME: currently are all args ignored.
300 $count = $this->_backend->numPages($include_empty, $exclude);
302 // FIXME: exclude ignored.
303 $iter = $this->getAllPages($include_empty, false, false, $exclude);
304 $count = $iter->count();
313 * Search for pages containing (or not containing) certain words
316 * Pages are returned in alphabetical order whenever it is
317 * practical to do so.
318 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
320 * @param TextSearchQuery $search A TextSearchQuery object
321 * @param string $sortby Optional. "+-column,+-column2".
322 * If false the result is faster in natural order.
323 * @param string $limit Optional. Encoded as "$offset,$count".
324 * $offset defaults to 0.
325 * @param string $exclude Optional comma-separated list of pagenames.
326 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
327 * @see TextSearchQuery
329 public function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
331 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
332 $options = array('exclude' => $exclude,
334 //if (isset($result->_count)) $options['count'] = $result->_count;
335 return new WikiDB_PageIterator($this, $result, $options);
341 * Search for pages containing (or not containing) certain words
342 * in their entire text (this includes the page content and the
345 * Pages are returned in alphabetical order whenever it is
346 * practical to do so.
347 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
349 * @param TextSearchQuery $search A TextSearchQuery object.
350 * @param string $sortby Optional. "+-column,+-column2".
351 * If false the result is faster in natural order.
352 * @param string $limit Optional. Encoded as "$offset,$count".
353 * $offset defaults to 0.
354 * @param string $exclude Optional comma-separated list of pagenames.
355 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
356 * @see TextSearchQuery
358 public function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
360 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
361 return new WikiDB_PageIterator($this, $result,
362 array('exclude' => $exclude,
364 'stoplisted' => $result->stoplisted
369 * Find the pages with the greatest hit counts.
371 * Pages are returned in reverse order by hit count.
373 * @param int $limit The maximum number of pages to return.
374 * Set $limit to zero to return all pages. If $limit < 0, pages will
375 * be sorted in decreasing order of popularity.
376 * @param string $sortby Optional. "+-column,+-column2".
377 * If false the result is faster in natural order.
379 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
382 public function mostPopular($limit = 20, $sortby = '-hits')
384 $result = $this->_backend->most_popular($limit, $sortby);
385 return new WikiDB_PageIterator($this, $result);
389 * Find recent page revisions.
391 * Revisions are returned in reverse order by creation time.
393 * @param array $params This hash is used to specify various optional
397 * <dd> (integer) At most this many revisions will be returned.
399 * <dd> (integer) Only revisions since this time (unix-timestamp)
401 * <dt> include_minor_revisions
402 * <dd> (boolean) Also include minor revisions. (Default is not to.)
403 * <dt> exclude_major_revisions
404 * <dd> (boolean) Don't include non-minor revisions.
405 * (Exclude_major_revisions implies include_minor_revisions.)
406 * <dt> include_all_revisions
407 * <dd> (boolean) Return all matching revisions for each page.
408 * Normally only the most recent matching revision is returned
412 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
413 * containing the matching revisions.
415 public function mostRecent($params = array())
417 $result = $this->_backend->most_recent($params);
418 return new WikiDB_PageRevisionIterator($this, $result);
422 * @param string $exclude_from
423 * @param string $exclude
424 * @param string $sortby Optional. "+-column,+-column2".
425 * If false the result is faster in natural order.
426 * @param string $limit Optional. Encoded as "$offset,$count".
427 * $offset defaults to 0.
428 * @return Iterator A generic iterator containing rows of
429 * (duplicate) pagename, wantedfrom.
431 public function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
433 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
437 * Generic interface to the link table. Esp. useful to search for rdf triples as in
438 * SemanticSearch and ListRelations.
440 * @param object $pages A TextSearchQuery object.
441 * @param object $search A TextSearchQuery object.
442 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
443 * linktype parameter:
446 * <dd> search for simple out-links
448 * <dd> in-links, i.e BackLinks
450 * <dd> the first part in a <>::<> link
452 * <dd> the first part in a <>:=<> link
454 * @param mixed $relation An optional TextSearchQuery to match the
455 * relation name. Ignored on simple in-out links.
457 * @return Iterator A generic iterator containing links to pages or values.
458 * hash of "pagename", "linkname", "linkvalue.
460 public function linkSearch($pages, $search, $linktype, $relation = false)
462 return $this->_backend->link_search($pages, $search, $linktype, $relation);
466 * Return a simple list of all defined relations (and attributes), mainly
467 * for the SemanticSearch autocompletion.
469 * @param bool $also_attributes
470 * @param bool $only_attributes
471 * @param bool $sorted
472 * @return array of strings
474 public function listRelations($also_attributes = false, $only_attributes = false, $sorted = true)
476 if (method_exists($this->_backend, "list_relations"))
477 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
478 // dumb, slow fallback. no iter, so simply define it here.
479 $relations = array();
480 $iter = $this->getAllPages();
481 while ($page = $iter->next()) {
482 $reliter = $page->getRelations();
484 while ($rel = $reliter->next()) {
485 // if there's no pagename it's an attribute
486 $names[] = $rel->getName();
488 $relations = array_merge($relations, $names);
500 * Call the appropriate backend method.
502 * @param string $from Page to rename
503 * @param string $to New name
504 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
505 * @return boolean true or false
507 public function renamePage($from, $to, $updateWikiLinks = false)
509 if (!empty($this->readonly)) {
510 trigger_error("readonly database", E_USER_WARNING);
513 assert(is_string($from) && $from != '');
514 assert(is_string($to) && $to != '');
516 if (method_exists($this->_backend, 'rename_page')) {
517 $oldpage = $this->getPage($from);
518 $newpage = $this->getPage($to);
519 //update all WikiLinks in existing pages
520 //non-atomic! i.e. if rename fails the links are not undone
521 if ($updateWikiLinks) {
522 $lookbehind = "/(?<=[\W:])\Q";
523 $lookahead = "\E(?=[\W:])/";
524 require_once 'lib/plugin/WikiAdminSearchReplace.php';
525 $links = $oldpage->getBackLinks();
526 while ($linked_page = $links->next()) {
527 WikiPlugin_WikiAdminSearchReplace::replaceHelper
529 $linked_page->getName(),
530 $lookbehind . $from . $lookahead, $to,
533 // FIXME: Disabled to avoid recursive modification when renaming
534 // a page like 'PageFoo to 'PageFooTwo'
536 $links = $newpage->getBackLinks();
537 while ($linked_page = $links->next()) {
538 WikiPlugin_WikiAdminSearchReplace::replaceHelper
540 $linked_page->getName(),
541 $lookbehind . $from . $lookahead, $to,
546 if ($oldpage->exists() and !$newpage->exists()) {
547 if ($result = $this->_backend->rename_page($from, $to)) {
548 // create a RecentChanges entry with explaining summary
549 $page = $this->getPage($to);
550 $current = $page->getCurrentRevision();
551 $meta = $current->_data;
552 $version = $current->getVersion();
553 $meta['summary'] = sprintf(_("renamed from %s"), $from);
554 unset($meta['mtime']); // force new date
555 $page->save($current->getPackedContent(), $version + 1, $meta);
557 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
558 // if a version 0 exists try it also.
559 $result = $this->_backend->rename_page($from, $to);
562 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
565 /* Generate notification emails? */
566 if ($result and ENABLE_MAILNOTIFY and !is_a($GLOBALS['request'], 'MockRequest')) {
567 $notify = $this->get('notify');
568 if (!empty($notify) and is_array($notify)) {
569 include_once 'lib/MailNotify.php';
570 $MailNotify = new MailNotify($from);
571 $MailNotify->onRenamePage($this, $from, $to);
577 /** Get timestamp when database was last modified.
579 * @return string A string consisting of two integers,
580 * separated by a space. The first is the time in
581 * unix timestamp format, the second is a modification
582 * count for the database.
584 * The idea is that you can cast the return value to an
585 * int to get a timestamp, or you can use the string value
586 * as a good hash for the entire database.
588 function getTimestamp()
590 $ts = $this->get('_timestamp');
591 return sprintf("%d %d", $ts[0], $ts[1]);
595 * Update the database timestamp.
600 $ts = $this->get('_timestamp');
601 $this->set('_timestamp', array(time(), $ts[1] + 1));
605 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
607 function get_db_version()
609 return (float)$this->get('_db_version');
612 function set_db_version($ver)
614 $this->set('_db_version', (float)$ver);
618 * Access WikiDB global meta-data.
620 * NOTE: this is currently implemented in a hackish and
621 * not very efficient manner.
623 * @param string $key Which meta data to get.
624 * Some reserved meta-data keys are:
626 * <dt>'_timestamp' <dd> Data used by getTimestamp().
629 * @return mixed The requested value, or false if the requested data
632 public function get($key)
634 if (!$key || $key[0] == '%')
637 * Hack Alert: We can use any page (existing or not) to store
638 * this data (as long as we always use the same one.)
640 $gd = $this->getPage('global_data');
641 $data = $gd->get('__global');
643 if ($data && isset($data[$key]))
650 * Set global meta-data.
652 * NOTE: this is currently implemented in a hackish and
653 * not very efficient manner.
657 * @param string $key Meta-data key to set.
658 * @param string $newval New value.
660 public function set($key, $newval)
662 if (!empty($this->readonly)) {
663 trigger_error("readonly database", E_USER_WARNING);
666 if (!$key || $key[0] == '%')
669 $gd = $this->getPage('global_data');
670 $data = $gd->get('__global');
677 $data[$key] = $newval;
679 $gd->set('__global', $data);
682 /* TODO: these are really backend methods */
684 // SQL result: for simple select or create/update queries
685 // returns the database specific resource type
686 function genericSqlQuery($sql, $args = false)
689 printSimpleTrace(debug_backtrace());
691 trigger_error("no SQL database", E_USER_ERROR);
695 // SQL iter: for simple select or create/update queries
696 // returns the generic iterator object (count,next)
697 function genericSqlIter($sql, $field_list = NULL)
700 printSimpleTrace(debug_backtrace());
702 trigger_error("no SQL database", E_USER_ERROR);
706 // see backend upstream methods
707 // ADODB adds surrounding quotes, SQL not yet!
716 if (!$request->_dbi) return false;
717 else return false; /* so far only needed for sql so false it.
718 later we have to check dba also */
721 function getParam($param)
724 if (isset($DBParams[$param])) return $DBParams[$param];
725 elseif ($param == 'prefix') return ''; else return false;
728 function getAuthParam($param)
730 global $DBAuthParams;
731 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
732 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false;
737 * A base class which representing a wiki-page within a
740 * A WikiDB_Page contains a number (at least one) of
741 * WikiDB_PageRevisions.
745 function WikiDB_Page(&$wikidb, $pagename)
747 $this->_wikidb = &$wikidb;
748 $this->_pagename = $pagename;
750 if (!(is_string($pagename) and $pagename != '')) {
751 if (function_exists("xdebug_get_function_stack")) {
752 echo "xdebug_get_function_stack(): ";
753 var_dump(xdebug_get_function_stack());
755 printSimpleTrace(debug_backtrace());
757 trigger_error("empty pagename", E_USER_WARNING);
761 assert(is_string($pagename) and $pagename != '');
766 * Get the name of the wiki page.
768 * @return string The page name.
770 public function getName()
772 return $this->_pagename;
775 // To reduce the memory footprint for larger sets of pagelists,
776 // we don't cache the content (only true or false) and
777 // we purge the pagedata (_cached_html) also
780 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
781 $current = $this->getCurrentRevision(false);
782 if (!$current) return false;
783 return !$current->hasDefaultContents();
787 * Delete an old revision of a WikiDB_Page.
789 * Deletes the specified revision of the page.
790 * It is a fatal error to attempt to delete the current revision.
792 * @param integer $version Which revision to delete. (You can also
793 * use a WikiDB_PageRevision object here.)
795 public function deleteRevision($version)
797 if ($this->_wikidb->readonly) {
798 trigger_error("readonly database", E_USER_WARNING);
801 $backend = &$this->_wikidb->_backend;
802 $cache = &$this->_wikidb->_cache;
803 $pagename = &$this->_pagename;
805 $version = $this->_coerce_to_version($version);
809 $backend->lock(array('page', 'version'));
810 $latestversion = $cache->get_latest_version($pagename);
811 if ($latestversion && ($version == $latestversion)) {
812 $backend->unlock(array('page', 'version'));
813 trigger_error(sprintf("Attempt to delete most recent revision of “%s”",
814 $pagename), E_USER_ERROR);
818 $cache->delete_versiondata($pagename, $version);
819 $backend->unlock(array('page', 'version'));
823 * Delete a revision, or possibly merge it with a previous
827 * Suppose an author make a (major) edit to a page. Shortly
828 * after that the same author makes a minor edit (e.g. to fix
829 * spelling mistakes he just made.)
831 * Now some time later, where cleaning out old saved revisions,
832 * and would like to delete his minor revision (since there's
833 * really no point in keeping minor revisions around for a long
836 * Note that the text after the minor revision probably represents
837 * what the author intended to write better than the text after
838 * the preceding major edit.
840 * So what we really want to do is merge the minor edit with the
843 * We will only do this when:
845 * <li>The revision being deleted is a minor one, and
846 * <li>It has the same author as the immediately preceding revision.
849 function mergeRevision($version)
851 if ($this->_wikidb->readonly) {
852 trigger_error("readonly database", E_USER_WARNING);
855 $backend = &$this->_wikidb->_backend;
856 $cache = &$this->_wikidb->_cache;
857 $pagename = &$this->_pagename;
859 $version = $this->_coerce_to_version($version);
863 $backend->lock(array('version'));
864 $latestversion = $cache->get_latest_version($pagename);
865 if ($latestversion && $version == $latestversion) {
866 $backend->unlock(array('version'));
867 trigger_error(sprintf("Attempt to merge most recent revision of “%s”",
868 $pagename), E_USER_ERROR);
872 $versiondata = $cache->get_versiondata($pagename, $version, true);
874 // Not there? ... we're done!
875 $backend->unlock(array('version'));
879 if ($versiondata['is_minor_edit']) {
880 $previous = $backend->get_previous_version($pagename, $version);
882 $prevdata = $cache->get_versiondata($pagename, $previous);
883 if ($prevdata['author_id'] == $versiondata['author_id']) {
884 // This is a minor revision, previous version is
885 // by the same author. We will merge the
887 $cache->update_versiondata($pagename, $previous,
888 array('%content' => $versiondata['%content'],
889 '_supplanted' => $versiondata['_supplanted']));
894 $cache->delete_versiondata($pagename, $version);
895 $backend->unlock(array('version'));
899 * Create a new revision of a {@link WikiDB_Page}.
901 * @param int $version Version number for new revision.
902 * To ensure proper serialization of edits, $version must be
903 * exactly one higher than the current latest version.
904 * (You can defeat this check by setting $version to
905 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
907 * @param string $content Contents of new revision.
909 * @param array $metadata Metadata for new revision (hash).
910 * All values in the hash should be scalars (strings or integers).
912 * @param array $links List of linkto=>pagename, relation=>pagename which this page links to (hash).
914 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
915 * $version was incorrect, returns false
917 public function createRevision($version, &$content, $metadata, $links)
919 if ($this->_wikidb->readonly) {
920 trigger_error("readonly database", E_USER_WARNING);
923 $backend = &$this->_wikidb->_backend;
924 $cache = &$this->_wikidb->_cache;
925 $pagename = &$this->_pagename;
926 $cache->invalidate_cache($pagename);
928 $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
930 $latestversion = $backend->get_latest_version($pagename);
931 $newversion = ($latestversion ? $latestversion : 0) + 1;
932 assert($newversion >= 1);
934 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
935 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
941 foreach ($data as $key => $val) {
942 if (empty($val) || $key[0] == '_' || $key[0] == '%')
946 assert(!empty($data['author']));
947 if (empty($data['author_id']))
948 @$data['author_id'] = $data['author'];
950 if (empty($data['mtime']))
951 $data['mtime'] = time();
953 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
954 // Ensure mtimes are monotonic.
955 $pdata = $cache->get_versiondata($pagename, $latestversion);
956 if ($data['mtime'] < $pdata['mtime']) {
957 trigger_error(sprintf(_("%s: Date of new revision is %s"),
958 $pagename, "'non-monotonic'"),
960 $data['orig_mtime'] = $data['mtime'];
961 $data['mtime'] = $pdata['mtime'];
964 // FIXME: use (possibly user specified) 'mtime' time or
966 $cache->update_versiondata($pagename, $latestversion,
967 array('_supplanted' => $data['mtime']));
970 $data['%content'] = &$content;
972 $cache->set_versiondata($pagename, $newversion, $data);
974 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
975 //':deleted' => empty($content)));
977 $backend->set_links($pagename, $links);
979 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
981 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
985 /** A higher-level interface to createRevision.
987 * This takes care of computing the links, and storing
988 * a cached version of the transformed wiki-text.
990 * @param string $wikitext The page content.
992 * @param int $version Version number for new revision.
993 * To ensure proper serialization of edits, $version must be
994 * exactly one higher than the current latest version.
995 * (You can defeat this check by setting $version to
996 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
998 * @param array $meta Meta-data for new revision.
1000 * @param mixed $formatted
1004 function save($wikitext, $version, $meta, $formatted = null)
1006 if ($this->_wikidb->readonly) {
1007 trigger_error("readonly database", E_USER_WARNING);
1010 if (is_null($formatted))
1011 $formatted = new TransformedText($this, $wikitext, $meta);
1012 $type = $formatted->getType();
1013 $meta['pagetype'] = $type->getName();
1014 $links = $formatted->getWikiPageLinks(); // linkto => relation
1015 $attributes = array();
1016 foreach ($links as $link) {
1017 if ($link['linkto'] === "" and !empty($link['relation'])) {
1018 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1021 $meta['attribute'] = $attributes;
1023 $backend = &$this->_wikidb->_backend;
1024 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1025 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1026 $this->set('_cached_html', $formatted->pack());
1028 // FIXME: probably should have some global state information
1029 // in the backend to control when to optimize.
1031 // We're doing this here rather than in createRevision because
1032 // postgresql can't optimize while locked.
1033 if (((int)DEBUG & _DEBUG_SQL)
1034 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1035 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1037 if ($backend->optimize()) {
1039 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1044 /* Generate notification emails? */
1045 if (ENABLE_MAILNOTIFY and is_a($newrevision, 'WikiDB_PageRevision')) {
1046 // Save didn't fail because of concurrent updates.
1047 $notify = $this->_wikidb->get('notify');
1049 and is_array($notify)
1050 and !is_a($GLOBALS['request'], 'MockRequest')
1052 include_once 'lib/MailNotify.php';
1053 $MailNotify = new MailNotify($newrevision->getName());
1054 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1056 $newrevision->_transformedContent = $formatted;
1058 // more pagechange callbacks: (in a hackish manner for now)
1059 if (ENABLE_RECENTCHANGESBOX
1060 and empty($meta['is_minor_edit'])
1061 and !in_array($GLOBALS['request']->getArg('action'),
1062 array('loadfile', 'upgrade'))
1064 require_once 'lib/WikiPlugin.php';
1065 $w = new WikiPluginLoader();
1066 $p = $w->getPlugin("RecentChangesCached", false);
1067 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1069 return $newrevision;
1073 * Get the most recent revision of a page.
1075 * @param bool $need_content
1076 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1078 public function getCurrentRevision($need_content = true)
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 = '')
1213 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1217 * Forward Links: All Links from this page to other pages.
1219 function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1221 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1225 * Relations: All links from this page to other pages with relation <> 0.
1226 * is_a:=page or population:=number
1228 function getRelations($sortby = '', $limit = '', $exclude = '')
1230 $backend = &$this->_wikidb->_backend;
1231 $result = $backend->get_links($this->_pagename, false, true,
1232 $sortby, $limit, $exclude,
1234 // we do not care for the linked page versiondata, just the pagename and linkrelation
1235 return new WikiDB_PageIterator($this->_wikidb, $result,
1236 array('include_empty' => true,
1237 'sortby' => $sortby,
1239 'exclude' => $exclude,
1240 'want_relations' => true));
1244 * possibly faster link existance check. not yet accelerated.
1246 function existLink($link, $reversed = false)
1248 $backend = &$this->_wikidb->_backend;
1249 if (method_exists($backend, 'exists_link'))
1250 return $backend->exists_link($this->_pagename, $link, $reversed);
1251 //$cache = &$this->_wikidb->_cache;
1252 // TODO: check cache if it is possible
1253 $iter = $this->getLinks($reversed, false);
1254 while ($page = $iter->next()) {
1255 if ($page->getName() == $link)
1262 /* Semantic relations are links with the relation pointing to another page,
1263 the so-called "RDF Triple".
1264 [San Diego] is%20a::city
1265 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1268 /* Semantic attributes for a page.
1269 [San Diego] population:=1,305,736
1270 Attributes are links with the relation pointing to another page.
1274 * Access WikiDB_Page non version-specific meta-data.
1276 * @param string $key Which meta data to get.
1277 * Some reserved meta-data keys are:
1279 * <dt>'date' <dd> Created as unixtime
1280 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1281 * <dt>'hits' <dd> Page hit counter.
1282 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1283 * In SQL stored now in an extra column.
1285 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1286 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1287 * E.g. "owner.users"
1288 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1289 * page-headers and content.
1290 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1291 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1294 * @return mixed The requested value, or false if the requested data
1297 public function get($key)
1299 $cache = &$this->_wikidb->_cache;
1300 $backend = &$this->_wikidb->_backend;
1301 if (!$key || $key[0] == '%')
1303 // several new SQL backends optimize this.
1304 if (!WIKIDB_NOCACHE_MARKUP
1305 and $key == '_cached_html'
1306 and method_exists($backend, 'get_cached_html')
1308 return $backend->get_cached_html($this->_pagename);
1310 $data = $cache->get_pagedata($this->_pagename);
1311 return isset($data[$key]) ? $data[$key] : false;
1315 * Get all the page meta-data as a hash.
1317 * @return array The page meta-data (hash).
1319 function getMetaData()
1321 $cache = &$this->_wikidb->_cache;
1322 $data = $cache->get_pagedata($this->_pagename);
1324 foreach ($data as $key => $val) {
1325 if ( /*!empty($val) &&*/
1334 * Set page meta-data.
1338 * @param string $key Meta-data key to set.
1339 * @param string $newval New value.
1341 public function set($key, $newval)
1343 $cache = &$this->_wikidb->_cache;
1344 $backend = &$this->_wikidb->_backend;
1345 $pagename = &$this->_pagename;
1347 assert($key && $key[0] != '%');
1349 // several new SQL backends optimize this.
1350 if (!WIKIDB_NOCACHE_MARKUP
1351 and $key == '_cached_html'
1352 and method_exists($backend, 'set_cached_html')
1354 if ($this->_wikidb->readonly) {
1355 trigger_error("readonly database", E_USER_WARNING);
1358 $backend->set_cached_html($pagename, $newval);
1362 $data = $cache->get_pagedata($pagename);
1364 if (!empty($newval)) {
1365 if (!empty($data[$key]) && $data[$key] == $newval)
1366 return; // values identical, skip update.
1368 if (empty($data[$key]))
1369 return; // values identical, skip update.
1372 if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1373 trigger_error("readonly database", E_USER_WARNING);
1376 $cache->update_pagedata($pagename, array($key => $newval));
1380 * Increase page hit count.
1382 * FIXME: IS this needed? Probably not.
1384 * This is a convenience function.
1385 * <pre> $page->increaseHitCount(); </pre>
1386 * is functionally identical to
1387 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1388 * but less expensive (ignores the pagadata string)
1390 * Note that this method may be implemented in more efficient ways
1391 * in certain backends.
1393 public function increaseHitCount()
1395 if ($this->_wikidb->readonly) {
1396 trigger_error("readonly database", E_USER_NOTICE);
1399 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1400 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1402 @$newhits = $this->get('hits') + 1;
1403 $this->set('hits', $newhits);
1408 * Return a string representation of the WikiDB_Page
1410 * This is really only for debugging.
1412 * @return string Printable representation of the WikiDB_Page.
1414 public function asString()
1417 printf("[%s:%s\n", get_class($this), $this->getName());
1418 print_r($this->getMetaData());
1420 $strval = ob_get_contents();
1426 * @param int|object $version_or_pagerevision
1427 * Takes either the version number (and int) or a WikiDB_PageRevision
1429 * @return integer The version number.
1431 private function _coerce_to_version($version_or_pagerevision)
1433 if (method_exists($version_or_pagerevision, "getContent"))
1434 $version = $version_or_pagerevision->getVersion();
1436 $version = (int)$version_or_pagerevision;
1438 assert($version >= 0);
1442 function isUserPage($include_empty = true)
1444 if (!$include_empty and !$this->exists()) return false;
1445 return $this->get('pref') ? true : false;
1448 // May be empty. Either the stored owner (/Chown), or the first authorized author
1451 if ($owner = $this->get('owner'))
1453 // check all revisions forwards for the first author_id
1454 $backend = &$this->_wikidb->_backend;
1455 $pagename = &$this->_pagename;
1456 $latestversion = $backend->get_latest_version($pagename);
1457 for ($v = 1; $v <= $latestversion; $v++) {
1458 $rev = $this->getRevision($v, false);
1459 if ($rev and $owner = $rev->get('author_id')) {
1466 // The authenticated author of the first revision or empty if not authenticated then.
1467 function getCreator()
1469 if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1473 // The authenticated author of the current revision.
1474 function getAuthor()
1476 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1480 /* Semantic Web value, not stored in the links.
1481 * todo: unify with some unit knowledge
1483 function setAttribute($relation, $value)
1485 $attr = $this->get('attributes');
1487 $attr = array($relation => $value);
1489 $attr[$relation] = $value;
1490 $this->set('attributes', $attr);
1493 function getAttribute($relation)
1495 $meta = $this->get('attributes');
1499 return $meta[$relation];
1505 * This class represents a specific revision of a WikiDB_Page within
1508 * A WikiDB_PageRevision has read-only semantics. You may only create
1509 * new revisions (and delete old ones) --- you cannot modify existing
1512 class WikiDB_PageRevision
1514 public $_transformedContent = false; // set by WikiDB_Page::save()
1516 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1517 $versiondata = false)
1519 $this->_wikidb = &$wikidb;
1520 $this->_pagename = $pagename;
1521 $this->_version = $version;
1522 $this->_data = $versiondata ? $versiondata : array();
1523 $this->_transformedContent = false; // set by WikiDB_Page::save()
1527 * Get the WikiDB_Page which this revision belongs to.
1529 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1531 public function getPage()
1533 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1537 * Get the version number of this revision.
1539 * @return integer The version number of this revision.
1541 public function getVersion()
1543 return $this->_version;
1547 * Determine whether this revision has defaulted content.
1549 * The default revision (version 0) of each page, as well as any
1550 * pages which are created with empty content have their content
1551 * defaulted to something like:
1553 * Describe [ThisPage] here.
1556 * @return boolean Returns true if the page has default content.
1558 public function hasDefaultContents()
1560 $data = &$this->_data;
1561 if (!isset($data['%content'])) return true;
1562 if ($data['%content'] === true) return false;
1563 return $data['%content'] === false or $data['%content'] === "";
1567 * Get the content as an array of lines.
1569 * @return array An array of lines.
1570 * The lines should contain no trailing white space.
1572 public function getContent()
1574 return explode("\n", $this->getPackedContent());
1578 * Get the pagename of the revision.
1580 * @return string pagename.
1582 public function getPageName()
1584 return $this->_pagename;
1589 return $this->_pagename;
1593 * Determine whether revision is the latest.
1595 * @return boolean True iff the revision is the latest (most recent) one.
1597 public function isCurrent()
1599 if (!isset($this->_iscurrent)) {
1600 $page = $this->getPage();
1601 $current = $page->getCurrentRevision(false);
1602 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1604 return $this->_iscurrent;
1608 * Get the transformed content of a page.
1610 * @param bool $pagetype_override
1611 * @return object An XmlContent-like object containing the page transformed
1614 function getTransformedContent($pagetype_override = false)
1616 if ($pagetype_override) {
1617 // Figure out the normal page-type for this page.
1618 $type = PageType::GetPageType($this->get('pagetype'));
1619 if ($type->getName() == $pagetype_override)
1620 $pagetype_override = false; // Not really an override...
1623 if ($pagetype_override) {
1624 // Overriden page type, don't cache (or check cache).
1625 return new TransformedText($this->getPage(),
1626 $this->getPackedContent(),
1627 $this->getMetaData(),
1628 $pagetype_override);
1631 $possibly_cache_results = true;
1633 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1634 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1635 // flush cache for this page.
1636 $page = $this->getPage();
1637 $page->set('_cached_html', ''); // ignored with !USECACHE
1639 $possibly_cache_results = false;
1640 } elseif (USECACHE and !$this->_transformedContent) {
1642 if ($this->isCurrent()) {
1643 $page = $this->getPage();
1644 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1646 $possibly_cache_results = false;
1648 //$backend->unlock();
1651 if (!$this->_transformedContent) {
1652 $this->_transformedContent
1653 = new TransformedText($this->getPage(),
1654 $this->getPackedContent(),
1655 $this->getMetaData());
1657 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1658 // If we're still the current version, cache the transfomed page.
1660 if ($this->isCurrent()) {
1661 $page->set('_cached_html', $this->_transformedContent->pack());
1663 //$backend->unlock();
1667 return $this->_transformedContent;
1671 * Get the content as a string.
1673 * @return string The page content.
1674 * Lines are separated by new-lines.
1676 public function getPackedContent()
1678 $data = &$this->_data;
1680 if (empty($data['%content'])
1681 || (!$this->_wikidb->isWikiPage($this->_pagename)
1682 && $this->isCurrent())
1684 include_once 'lib/InlineParser.php';
1686 // A feature similar to taglines at http://www.wlug.org.nz/
1687 // Lib from http://www.aasted.org/quote/
1688 if (defined('FORTUNE_DIR')
1689 and is_dir(FORTUNE_DIR)
1690 and in_array($GLOBALS['request']->getArg('action'),
1691 array('create', 'edit'))
1693 include_once 'lib/fortune.php';
1694 $fortune = new Fortune();
1695 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1697 $quote = "<verbatim>\n"
1698 . str_replace("\n<br>", "\n", $quote)
1699 . "</verbatim>\n\n";
1703 . sprintf(_("Describe %s here."),
1704 "[" . WikiEscape($this->_pagename) . "]");
1706 // Replace empty content with default value.
1707 return sprintf(_("Describe %s here."),
1708 "[" . WikiEscape($this->_pagename) . "]");
1711 // There is (non-default) content.
1712 assert($this->_version > 0);
1714 if (!is_string($data['%content'])) {
1715 // Content was not provided to us at init time.
1716 // (This is allowed because for some backends, fetching
1717 // the content may be expensive, and often is not wanted
1720 // In any case, now we need to get it.
1721 $data['%content'] = $this->_get_content();
1722 assert(is_string($data['%content']));
1725 return $data['%content'];
1728 function _get_content()
1730 $cache = &$this->_wikidb->_cache;
1731 $pagename = $this->_pagename;
1732 $version = $this->_version;
1734 assert($version > 0);
1736 $newdata = $cache->get_versiondata($pagename, $version, true);
1738 assert(is_string($newdata['%content']));
1739 return $newdata['%content'];
1741 // else revision has been deleted... What to do?
1742 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1743 $version, $pagename);
1748 * Get meta-data for this revision.
1750 * @param string $key Which meta-data to access.
1752 * Some reserved revision meta-data keys are:
1754 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1755 * The 'mtime' meta-value is normally set automatically by the database
1756 * backend, but it may be specified explicitly when creating a new revision.
1758 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1759 * of a page must be monotonically increasing. If an attempt is
1760 * made to create a new revision with an mtime less than that of
1761 * the preceeding revision, the new revisions timestamp is force
1762 * to be equal to that of the preceeding revision. In that case,
1763 * the originally requested mtime is preserved in 'orig_mtime'.
1764 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1765 * This meta-value is <em>always</em> automatically maintained by the database
1766 * backend. (It is set from the 'mtime' meta-value of the superceding
1767 * revision.) '_supplanted' has a value of 'false' for the current revision.
1769 * FIXME: this could be refactored:
1771 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1773 * <dd> Authenticated author of a page. This is used to identify
1774 * the distinctness of authors when cleaning old revisions from
1776 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1777 * <dt> 'summary' <dd> Short change summary entered by page author.
1780 * Meta-data keys must be valid C identifers (they have to start with a letter
1781 * or underscore, and can contain only alphanumerics and underscores.)
1783 * @return string The requested value, or false if the requested value
1786 public function get($key)
1788 if (!$key || $key[0] == '%')
1790 $data = &$this->_data;
1791 return isset($data[$key]) ? $data[$key] : false;
1795 * Get all the revision page meta-data as a hash.
1797 * @return array The revision meta-data.
1799 function getMetaData()
1802 foreach ($this->_data as $key => $val) {
1803 if (!empty($val) && $key[0] != '%')
1810 * Return a string representation of the revision.
1812 * This is really only for debugging.
1814 * @return string Printable representation of the WikiDB_Page.
1816 public function asString()
1819 printf("[%s:%d\n", get_class($this), $this->get('version'));
1820 print_r($this->_data);
1821 echo $this->getPackedContent() . "\n]\n";
1822 $strval = ob_get_contents();
1829 * Class representing a sequence of WikiDB_Pages.
1830 * TODO: Enhance to php5 iterators
1832 * apply filters for options like 'sortby', 'limit', 'exclude'
1833 * for simple queries like titleSearch, where the backend is not ready yet.
1835 class WikiDB_PageIterator
1837 function WikiDB_PageIterator(&$wikidb, &$iter, $options = false)
1839 $this->_iter = $iter; // a WikiDB_backend_iterator
1840 $this->_wikidb = &$wikidb;
1841 $this->_options = $options;
1846 return $this->_iter->count();
1851 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1855 * Get next WikiDB_Page in sequence.
1857 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1859 public function next()
1861 if (!($next = $this->_iter->next())) {
1865 $pagename = &$next['pagename'];
1866 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1867 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1871 if (isset($next['linkrelation'])
1872 or isset($next['pagedata']['linkrelation'])
1878 // There's always hits, but we cache only if more
1879 // (well not with file, cvs and dba)
1880 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1881 $this->_wikidb->_cache->cache_data($next);
1882 // cache existing page id's since we iterate over all links in GleanDescription
1883 // and need them later for LinkExistingWord
1884 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1885 and !$this->_options['include_empty'] and isset($next['id'])
1887 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1889 $page = new WikiDB_Page($this->_wikidb, $pagename);
1890 if (isset($next['linkrelation']))
1891 $page->set('linkrelation', $next['linkrelation']);
1892 if (isset($next['score']))
1893 $page->score = $next['score'];
1898 * Release resources held by this iterator.
1900 * The iterator may not be used after free() is called.
1902 * There is no need to call free(), if next() has returned false.
1903 * (I.e. if you iterate through all the pages in the sequence,
1904 * you do not need to call free() --- you only need to call it
1905 * if you stop before the end of the iterator is reached.)
1907 public function free()
1909 // $this->_iter->free();
1914 $this->_iter->reset();
1920 while ($page = $this->next())
1927 * Apply filters for options like 'sortby', 'limit', 'exclude'
1928 * for simple queries like titleSearch, where the backend is not ready yet.
1929 * Since iteration is usually destructive for SQL results,
1930 * we have to generate a copy.
1932 function applyFilters($options = false)
1934 if (!$options) $options = $this->_options;
1935 if (isset($options['sortby'])) {
1937 /* this is destructive */
1938 while ($page = $this->next())
1939 $result[] = $page->getName();
1940 $this->_doSort($array, $options['sortby']);
1942 /* the rest is not destructive.
1943 * reconstruct a new iterator
1945 $pagenames = array();
1947 if (isset($options['limit']))
1948 $limit = $options['limit'];
1951 if (isset($options['exclude']))
1952 $exclude = $options['exclude'];
1953 if (is_string($exclude) and !is_array($exclude))
1954 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1955 foreach ($array as $pagename) {
1956 if ($limit and $i++ > $limit)
1957 return new WikiDB_Array_PageIterator($pagenames);
1958 if (!empty($exclude) and !in_array($pagename, $exclude))
1959 $pagenames[] = $pagename;
1960 elseif (empty($exclude))
1961 $pagenames[] = $pagename;
1963 return new WikiDB_Array_PageIterator($pagenames);
1967 function _doSort(&$array, $sortby)
1969 $sortby = PageList::sortby($sortby, 'init');
1970 if ($sortby == '+pagename')
1971 sort($array, SORT_STRING);
1972 elseif ($sortby == '-pagename')
1973 rsort($array, SORT_STRING);
1980 * A class which represents a sequence of WikiDB_PageRevisions.
1981 * TODO: Enhance to php5 iterators
1983 class WikiDB_PageRevisionIterator
1985 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
1987 $this->_revisions = $revisions;
1988 $this->_wikidb = &$wikidb;
1989 $this->_options = $options;
1994 return $this->_revisions->count();
1998 * Get next WikiDB_PageRevision in sequence.
2000 * @return WikiDB_PageRevision
2001 * The next WikiDB_PageRevision in the sequence.
2003 public function next()
2005 if (!($next = $this->_revisions->next()))
2008 //$this->_wikidb->_cache->cache_data($next);
2010 $pagename = $next['pagename'];
2011 $version = $next['version'];
2012 $versiondata = $next['versiondata'];
2014 if (!(is_string($pagename) and $pagename != '')) {
2015 trigger_error("empty pagename", E_USER_WARNING);
2018 } else assert(is_string($pagename) and $pagename != '');
2020 if (!is_array($versiondata)) {
2021 trigger_error("empty versiondata", E_USER_WARNING);
2024 } else assert(is_array($versiondata));
2026 if (!($version > 0)) {
2027 trigger_error("invalid version", E_USER_WARNING);
2030 } else assert($version > 0);
2032 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2037 * Release resources held by this iterator.
2039 * The iterator may not be used after free() is called.
2041 * There is no need to call free(), if next() has returned false.
2042 * (I.e. if you iterate through all the revisions in the sequence,
2043 * you do not need to call free() --- you only need to call it
2044 * if you stop before the end of the iterator is reached.)
2046 public function free()
2048 $this->_revisions->free();
2054 while ($rev = $this->next())
2063 class WikiDB_Array_PageIterator
2065 function WikiDB_Array_PageIterator($pagenames)
2068 $this->_dbi = $request->getDbh();
2069 $this->_pages = $pagenames;
2070 reset($this->_pages);
2075 $c = current($this->_pages);
2076 next($this->_pages);
2077 return $c !== false ? $this->_dbi->getPage($c) : false;
2082 return count($this->_pages);
2087 reset($this->_pages);
2096 reset($this->_pages);
2097 return $this->_pages;
2101 class WikiDB_Array_generic_iter
2103 function WikiDB_Array_generic_iter($result)
2105 // $result may be either an array or a query result
2106 if (is_array($result)) {
2107 $this->_array = $result;
2108 } elseif (is_object($result)) {
2109 $this->_array = $result->asArray();
2111 $this->_array = array();
2113 if (!empty($this->_array))
2114 reset($this->_array);
2119 $c = current($this->_array);
2120 next($this->_array);
2121 return $c !== false ? $c : false;
2126 return count($this->_array);
2131 reset($this->_array);
2140 if (!empty($this->_array))
2141 reset($this->_array);
2142 return $this->_array;
2147 * Data cache used by WikiDB.
2149 * FIXME: Maybe rename this to caching_backend (or some such).
2155 // FIXME: beautify versiondata cache. Cache only limited data?
2157 function WikiDB_cache(&$backend)
2159 $this->_backend = &$backend;
2161 $this->_pagedata_cache = array();
2162 $this->_versiondata_cache = array();
2163 array_push($this->_versiondata_cache, array());
2164 $this->_glv_cache = array();
2165 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2167 if (isset($GLOBALS['request']->_dbi))
2168 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2173 $this->_pagedata_cache = array();
2174 $this->_versiondata_cache = array();
2175 $this->_glv_cache = array();
2176 $this->_id_cache = array();
2179 function get_pagedata($pagename)
2181 assert(is_string($pagename) && $pagename != '');
2183 $cache = &$this->_pagedata_cache;
2184 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2185 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2186 if (empty($cache[$pagename]))
2187 $cache[$pagename] = array();
2189 return $cache[$pagename];
2191 return $this->_backend->get_pagedata($pagename);
2195 function update_pagedata($pagename, $newdata)
2197 assert(is_string($pagename) && $pagename != '');
2198 if (!empty($this->readonly)) {
2199 trigger_error("readonly database", E_USER_WARNING);
2203 $this->_backend->update_pagedata($pagename, $newdata);
2206 if (!empty($this->_pagedata_cache[$pagename])
2207 and is_array($this->_pagedata_cache[$pagename])
2209 $cachedata = &$this->_pagedata_cache[$pagename];
2210 foreach ($newdata as $key => $val)
2211 $cachedata[$key] = $val;
2213 $this->_pagedata_cache[$pagename] = $newdata;
2217 function invalidate_cache($pagename)
2219 unset ($this->_pagedata_cache[$pagename]);
2220 unset ($this->_versiondata_cache[$pagename]);
2221 unset ($this->_glv_cache[$pagename]);
2222 unset ($this->_id_cache[$pagename]);
2223 //unset ($this->_backend->_page_data);
2226 function delete_page($pagename)
2228 if (!empty($this->readonly)) {
2229 trigger_error("readonly database", E_USER_WARNING);
2232 $result = $this->_backend->delete_page($pagename);
2233 $this->invalidate_cache($pagename);
2237 function purge_page($pagename)
2239 if (!empty($this->readonly)) {
2240 trigger_error("readonly database", E_USER_WARNING);
2243 $result = $this->_backend->purge_page($pagename);
2244 $this->invalidate_cache($pagename);
2248 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2249 function cache_data($data)
2252 //if (isset($data['pagedata']))
2253 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2256 function get_versiondata($pagename, $version, $need_content = false)
2258 // FIXME: Seriously ugly hackage
2260 if (USECACHE) { //temporary - for debugging
2261 assert(is_string($pagename) && $pagename != '');
2262 // There is a bug here somewhere which results in an assertion failure at line 105
2263 // of ArchiveCleaner.php It goes away if we use the next line.
2264 //$need_content = true;
2265 $nc = $need_content ? '1' : '0';
2266 $cache = &$this->_versiondata_cache;
2267 if (!isset($cache[$pagename][$version][$nc])
2268 || !(is_array($cache[$pagename]))
2269 || !(is_array($cache[$pagename][$version]))
2271 $cache[$pagename][$version][$nc] =
2272 $this->_backend->get_versiondata($pagename, $version, $need_content);
2274 // If we have retrieved all data, we may as well set the cache for
2275 // $need_content = false
2276 if ($need_content) {
2277 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2280 $vdata = $cache[$pagename][$version][$nc];
2282 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2285 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2286 if (empty($this->_pagedata_cache))
2287 $this->_pagedata_cache = array();
2288 /* 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 */
2289 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2294 function set_versiondata($pagename, $version, $data)
2296 //unset($this->_versiondata_cache[$pagename][$version]);
2298 if (!empty($this->readonly)) {
2299 trigger_error("readonly database", E_USER_WARNING);
2302 $this->_backend->set_versiondata($pagename, $version, $data);
2304 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2305 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2306 // Is this necessary?
2307 unset($this->_glv_cache[$pagename]);
2310 function update_versiondata($pagename, $version, $data)
2312 if (!empty($this->readonly)) {
2313 trigger_error("readonly database", E_USER_WARNING);
2316 $this->_backend->update_versiondata($pagename, $version, $data);
2318 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2320 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2321 // Is this necessary?
2322 unset($this->_glv_cache[$pagename]);
2325 function delete_versiondata($pagename, $version)
2327 if (!empty($this->readonly)) {
2328 trigger_error("readonly database", E_USER_WARNING);
2331 $this->_backend->delete_versiondata($pagename, $version);
2332 if (isset($this->_versiondata_cache[$pagename][$version]))
2333 unset ($this->_versiondata_cache[$pagename][$version]);
2334 // dirty latest version cache only if latest version gets deleted
2335 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2336 unset ($this->_glv_cache[$pagename]);
2339 function get_latest_version($pagename)
2342 assert(is_string($pagename) && $pagename != '');
2343 $cache = &$this->_glv_cache;
2344 if (!isset($cache[$pagename])) {
2345 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2346 if (empty($cache[$pagename]))
2347 $cache[$pagename] = 0;
2349 return $cache[$pagename];
2351 return $this->_backend->get_latest_version($pagename);
2356 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2361 $stamp = strftime("%y%m%d-%H%M%S");
2362 $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2363 register_shutdown_function("_sql_debuglog_shutdown_function");
2364 } elseif ($shutdown) {
2368 if ($newline) fputs($fp, "[$i++] $msg");
2369 else fwrite($fp, $msg);
2372 function _sql_debuglog_shutdown_function()
2374 _sql_debuglog('', false, true);
2380 // c-basic-offset: 4
2381 // c-hanging-comment-ender-p: nil
2382 // indent-tabs-mode: nil