4 require_once('lib/PageType.php');
7 * The classes in the file define the interface to the
11 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
12 * Minor enhancements by Reini Urban
16 * Force the creation of a new revision.
17 * @see WikiDB_Page::createRevision()
19 if (!defined('WIKIDB_FORCE_CREATE'))
20 define('WIKIDB_FORCE_CREATE', -1);
23 * Abstract base class for the database used by PhpWiki.
25 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
26 * turn contain <tt>WikiDB_PageRevision</tt>s.
28 * Conceptually a <tt>WikiDB</tt> contains all possible
29 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
30 * Since all possible pages are already contained in a WikiDB, a call
31 * to WikiDB::getPage() will never fail (barring bugs and
32 * e.g. filesystem or SQL database problems.)
34 * Also each <tt>WikiDB_Page</tt> always contains at least one
35 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
36 * [PageName] here."). This default content has a version number of
39 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
40 * only create new revisions or delete old ones --- one can not modify
41 * an existing revision.
45 * Open a WikiDB database.
47 * This is a static member function. This function inspects its
48 * arguments to determine the proper subclass of WikiDB to
49 * instantiate, and then it instantiates it.
53 * @param hash $dbparams Database configuration parameters.
54 * Some pertinent parameters are:
57 * <dd> The back-end type. Current supported types are:
60 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
61 * library. (More stable and conservative)
63 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
65 * <dd> Dba based backend. The default and by far the fastest.
73 * <dd> (Used by the SQL and ADODB backends.)
74 * The DSN specifying which database to connect to.
77 * <dd> Prefix to be prepended to database tables (and file names).
80 * <dd> (Used by the dba backend.)
81 * Which directory db files reside in.
84 * <dd> Used only by the dba backend so far.
85 * And: When optimizing mysql it closes timed out mysql processes.
86 * otherwise only used for dba: Timeout in seconds for opening (and
87 * obtaining lock) on the dbm file.
90 * <dd> (Used by the dba backend.)
92 * Which dba handler to use. Good choices are probably either
96 * <dd> Either set by config.ini: READONLY = true or detected automatically
97 * when a database can be read but cannot be updated.
100 * @return WikiDB A WikiDB object.
102 function open ($dbparams) {
103 $dbtype = $dbparams{'dbtype'};
104 include_once("lib/WikiDB/$dbtype.php");
106 $class = 'WikiDB_' . $dbtype;
107 return new $class ($dbparams);
117 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.
149 $this->_backend->close();
150 $this->_cache->close();
154 * Get a WikiDB_Page from a WikiDB.
156 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
157 * therefore this method never fails.
160 * @param string $pagename Which page to get.
161 * @return WikiDB_Page The requested WikiDB_Page.
163 function getPage($pagename) {
164 static $error_displayed = false;
165 $pagename = (string) $pagename;
167 if ($pagename === '') {
168 if ($error_displayed) return false;
169 $error_displayed = true;
170 if (function_exists("xdebug_get_function_stack"))
171 var_dump(xdebug_get_function_stack());
172 trigger_error("empty pagename", E_USER_WARNING);
176 assert($pagename != '');
178 return new WikiDB_Page($this, $pagename);
182 * Determine whether page exists (in non-default form).
185 * $is_page = $dbi->isWikiPage($pagename);
189 * $page = $dbi->getPage($pagename);
190 * $current = $page->getCurrentRevision();
191 * $is_page = ! $current->hasDefaultContents();
193 * however isWikiPage may be implemented in a more efficient
194 * manner in certain back-ends.
197 * @param string $pagename string Which page to check.
198 * @return boolean True if the page actually exists with
199 * non-default contents in the WikiDataBase.
201 function isWikiPage ($pagename) {
202 $page = $this->getPage($pagename);
203 return ($page and $page->exists());
207 * Delete page from the WikiDB.
209 * Deletes the page from the WikiDB with the possibility to revert and diff.
210 * //Also resets all page meta-data to the default values.
212 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
215 * @param string $pagename Name of page to delete.
218 function deletePage($pagename) {
219 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
220 // don't create empty revisions of already purged pages.
221 if ($this->_backend->get_latest_version($pagename))
222 $result = $this->_cache->delete_page($pagename);
226 /* Generate notification emails */
227 if (ENABLE_MAILNOTIFY) {
228 include_once("lib/MailNotify.php");
229 $MailNotify = new MailNotify($pagename);
230 $MailNotify->onDeletePage ($this, $pagename);
233 //How to create a RecentChanges entry with explaining summary? Dynamically
235 $page = $this->getPage($pagename);
236 $current = $page->getCurrentRevision();
237 $meta = $current->_data;
238 $version = $current->getVersion();
239 $meta['summary'] = _("removed");
240 $page->save($current->getPackedContent(), $version + 1, $meta);
246 * Completely remove the page from the WikiDB, without undo possibility.
248 * @param string $pagename Name of page to delete.
251 function purgePage($pagename) {
252 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
253 $result = $this->_cache->purge_page($pagename);
254 $this->deletePage($pagename); // just for the notification
259 * Retrieve all pages.
261 * Gets the set of all pages with non-default contents.
265 * @param boolean $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 or false $sortby Optional. "+-column,+-column2".
270 * If false the result is faster in natural order.
271 * @param string or false $limit Optional. Encoded as "$offset,$count".
272 * $offset defaults to 0.
273 * @param string $exclude: Optional comma-seperated list of pagenames.
275 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
276 * in the WikiDB which have non-default contents.
278 function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
280 // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
282 $mem = ini_get("memory_limit");
283 if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
285 $GLOBALS['request']->setArg('limit', $limit);
286 $GLOBALS['request']->setArg('paging', 'auto');
289 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
291 if (isa($this->_backend, "WikiDB_backend_dba"))
293 return new WikiDB_PageIterator($this, $result,
294 array('include_empty' => $include_empty,
295 'exclude' => $exclude,
302 * @param boolean $include_empty If true include also empty pages
303 * @param string $exclude: comma-seperated list of pagenames.
304 * TBD: array of pagenames
308 function numPages($include_empty=false, $exclude='') {
309 if (method_exists($this->_backend, 'numPages'))
310 // FIXME: currently are all args ignored.
311 $count = $this->_backend->numPages($include_empty, $exclude);
313 // FIXME: exclude ignored.
314 $iter = $this->getAllPages($include_empty, false, false, $exclude);
315 $count = $iter->count();
324 * Search for pages containing (or not containing) certain words
327 * Pages are returned in alphabetical order whenever it is
328 * practical to do so.
329 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
332 * @param TextSearchQuery $search A TextSearchQuery object
333 * @param string or false $sortby Optional. "+-column,+-column2".
334 * If false the result is faster in natural order.
335 * @param string or false $limit Optional. Encoded as "$offset,$count".
336 * $offset defaults to 0.
337 * @param string $exclude: Optional comma-seperated list of pagenames.
338 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
339 * @see TextSearchQuery
341 function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
342 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
343 $options = array('exclude' => $exclude,
345 //if (isset($result->_count)) $options['count'] = $result->_count;
346 return new WikiDB_PageIterator($this, $result, $options);
352 * Search for pages containing (or not containing) certain words
353 * in their entire text (this includes the page content and the
356 * Pages are returned in alphabetical order whenever it is
357 * practical to do so.
358 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
362 * @param TextSearchQuery $search A TextSearchQuery object.
363 * @param string or false $sortby Optional. "+-column,+-column2".
364 * If false the result is faster in natural order.
365 * @param string or false $limit Optional. Encoded as "$offset,$count".
366 * $offset defaults to 0.
367 * @param string $exclude: Optional comma-seperated list of pagenames.
368 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
369 * @see TextSearchQuery
371 function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
372 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
373 return new WikiDB_PageIterator($this, $result,
374 array('exclude' => $exclude,
376 'stoplisted' => $result->stoplisted
381 * Find the pages with the greatest hit counts.
383 * Pages are returned in reverse order by hit count.
387 * @param integer $limit The maximum number of pages to return.
388 * Set $limit to zero to return all pages. If $limit < 0, pages will
389 * be sorted in decreasing order of popularity.
390 * @param string or false $sortby Optional. "+-column,+-column2".
391 * If false the result is faster in natural order.
393 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
396 function mostPopular($limit = 20, $sortby = '-hits') {
397 $result = $this->_backend->most_popular($limit, $sortby);
398 return new WikiDB_PageIterator($this, $result);
402 * Find recent page revisions.
404 * Revisions are returned in reverse order by creation time.
408 * @param hash $params This hash is used to specify various optional
412 * <dd> (integer) At most this many revisions will be returned.
414 * <dd> (integer) Only revisions since this time (unix-timestamp)
416 * <dt> include_minor_revisions
417 * <dd> (boolean) Also include minor revisions. (Default is not to.)
418 * <dt> exclude_major_revisions
419 * <dd> (boolean) Don't include non-minor revisions.
420 * (Exclude_major_revisions implies include_minor_revisions.)
421 * <dt> include_all_revisions
422 * <dd> (boolean) Return all matching revisions for each page.
423 * Normally only the most recent matching revision is returned
427 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
428 * containing the matching revisions.
430 function mostRecent($params = false) {
431 $result = $this->_backend->most_recent($params);
432 return new WikiDB_PageRevisionIterator($this, $result);
438 * @param string or false $sortby Optional. "+-column,+-column2".
439 * If false the result is faster in natural order.
440 * @param string or false $limit Optional. Encoded as "$offset,$count".
441 * $offset defaults to 0.
442 * @return Iterator A generic iterator containing rows of
443 * (duplicate) pagename, wantedfrom.
445 function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
446 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
447 //return new WikiDB_PageIterator($this, $result);
451 * Generic interface to the link table. Esp. useful to search for rdf triples as in
452 * SemanticSearch and ListRelations.
456 * @param $pages object A TextSearchQuery object.
457 * @param $search object A TextSearchQuery object.
458 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
459 * linktype parameter:
462 * <dd> search for simple out-links
464 * <dd> in-links, i.e BackLinks
466 * <dd> the first part in a <>::<> link
468 * <dd> the first part in a <>:=<> link
470 * @param $relation object An optional TextSearchQuery to match the
471 * relation name. Ignored on simple in-out links.
473 * @return Iterator A generic iterator containing links to pages or values.
474 * hash of "pagename", "linkname", "linkvalue.
476 function linkSearch($pages, $search, $linktype, $relation=false) {
477 return $this->_backend->link_search($pages, $search, $linktype, $relation);
481 * Return a simple list of all defined relations (and attributes), mainly
482 * for the SemanticSearch autocompletion.
486 * @return array of strings
488 function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
489 if (method_exists($this->_backend, "list_relations"))
490 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
491 // dumb, slow fallback. no iter, so simply define it here.
492 $relations = array();
493 $iter = $this->getAllPages();
494 while ($page = $iter->next()) {
495 $reliter = $page->getRelations();
497 while ($rel = $reliter->next()) {
498 // if there's no pagename it's an attribute
499 $names[] = $rel->getName();
501 $relations = array_merge($relations, $names);
513 * Call the appropriate backend method.
516 * @param string $from Page to rename
517 * @param string $to New name
518 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
519 * @return boolean true or false
521 function renamePage($from, $to, $updateWikiLinks = false) {
522 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
523 assert(is_string($from) && $from != '');
524 assert(is_string($to) && $to != '');
526 if (method_exists($this->_backend, 'rename_page')) {
527 $oldpage = $this->getPage($from);
528 $newpage = $this->getPage($to);
529 //update all WikiLinks in existing pages
530 //non-atomic! i.e. if rename fails the links are not undone
531 if ($updateWikiLinks) {
532 $lookbehind = "/(?<=[\W:])\Q";
533 $lookahead = "\E(?=[\W:])/";
534 if (!check_php_version(4,3,3)) {
535 $lookbehind = "/(?<=[\W:])";
536 $lookahead = "(?=[\W:])/";
537 $from = preg_quote($from, "/");
538 $to = preg_quote($to, "/");
540 require_once('lib/plugin/WikiAdminSearchReplace.php');
541 $links = $oldpage->getBackLinks();
542 while ($linked_page = $links->next()) {
543 WikiPlugin_WikiAdminSearchReplace::replaceHelper
545 $linked_page->getName(),
546 $lookbehind.$from.$lookahead, $to,
549 // FIXME: Disabled to avoid recursive modification when renaming
550 // a page like 'PageFoo to 'PageFooTwo'
552 $links = $newpage->getBackLinks();
553 while ($linked_page = $links->next()) {
554 WikiPlugin_WikiAdminSearchReplace::replaceHelper
556 $linked_page->getName(),
557 $lookbehind.$from.$lookahead, $to,
562 if ($oldpage->exists() and ! $newpage->exists()) {
563 if ($result = $this->_backend->rename_page($from, $to)) {
564 // create a RecentChanges entry with explaining summary
565 $page = $this->getPage($to);
566 $current = $page->getCurrentRevision();
567 $meta = $current->_data;
568 $version = $current->getVersion();
569 $meta['summary'] = sprintf(_("renamed from %s"), $from);
570 unset($meta['mtime']); // force new date
571 $page->save($current->getPackedContent(), $version + 1, $meta);
573 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
574 // if a version 0 exists try it also.
575 $result = $this->_backend->rename_page($from, $to);
578 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
581 /* Generate notification emails? */
582 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
583 $notify = $this->get('notify');
584 if (!empty($notify) and is_array($notify)) {
585 include_once("lib/MailNotify.php");
586 $MailNotify = new MailNotify($from);
587 $MailNotify->onRenamePage ($this, $from, $to);
593 /** Get timestamp when database was last modified.
595 * @return string A string consisting of two integers,
596 * separated by a space. The first is the time in
597 * unix timestamp format, the second is a modification
598 * count for the database.
600 * The idea is that you can cast the return value to an
601 * int to get a timestamp, or you can use the string value
602 * as a good hash for the entire database.
604 function getTimestamp() {
605 $ts = $this->get('_timestamp');
606 return sprintf("%d %d", $ts[0], $ts[1]);
610 * Update the database timestamp.
614 $ts = $this->get('_timestamp');
615 $this->set('_timestamp', array(time(), $ts[1] + 1));
619 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
621 function get_db_version() {
622 return (float) $this->get('_db_version');
624 function set_db_version($ver) {
625 return $this->set('_db_version', (float)$ver);
629 * Access WikiDB global meta-data.
631 * NOTE: this is currently implemented in a hackish and
632 * not very efficient manner.
636 * @param string $key Which meta data to get.
637 * Some reserved meta-data keys are:
639 * <dt>'_timestamp' <dd> Data used by getTimestamp().
642 * @return scalar The requested value, or false if the requested data
646 if (!$key || $key[0] == '%')
649 * Hack Alert: We can use any page (existing or not) to store
650 * this data (as long as we always use the same one.)
652 $gd = $this->getPage('global_data');
653 $data = $gd->get('__global');
655 if ($data && isset($data[$key]))
662 * Set global meta-data.
664 * NOTE: this is currently implemented in a hackish and
665 * not very efficient manner.
670 * @param string $key Meta-data key to set.
671 * @param string $newval New value.
673 function set($key, $newval) {
674 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
675 if (!$key || $key[0] == '%')
678 $gd = $this->getPage('global_data');
679 $data = $gd->get('__global');
686 $data[$key] = $newval;
688 $gd->set('__global', $data);
691 /* TODO: these are really backend methods */
693 // SQL result: for simple select or create/update queries
694 // returns the database specific resource type
695 function genericSqlQuery($sql, $args=false) {
696 if (function_exists('debug_backtrace')) { // >= 4.3.0
697 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
699 trigger_error("no SQL database", E_USER_ERROR);
703 // SQL iter: for simple select or create/update queries
704 // returns the generic iterator object (count,next)
705 function genericSqlIter($sql, $field_list = NULL) {
706 if (function_exists('debug_backtrace')) { // >= 4.3.0
707 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
709 trigger_error("no SQL database", E_USER_ERROR);
713 // see backend upstream methods
714 // ADODB adds surrounding quotes, SQL not yet!
715 function quote ($s) {
721 if (!$request->_dbi) return false;
722 else return false; /* so far only needed for sql so false it.
723 later we have to check dba also */
726 function getParam($param) {
728 if (isset($DBParams[$param])) return $DBParams[$param];
729 elseif ($param == 'prefix') return '';
733 function getAuthParam($param) {
734 global $DBAuthParams;
735 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
736 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
737 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
744 * A base class which representing a wiki-page within a
747 * A WikiDB_Page contains a number (at least one) of
748 * WikiDB_PageRevisions.
752 function WikiDB_Page(&$wikidb, $pagename) {
753 $this->_wikidb = &$wikidb;
754 $this->_pagename = $pagename;
756 if (!(is_string($pagename) and $pagename != '')) {
757 if (function_exists("xdebug_get_function_stack")) {
758 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
759 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
760 printSimpleTrace(debug_backtrace());
762 trigger_error("empty pagename", E_USER_WARNING);
766 assert(is_string($pagename) and $pagename != '');
771 * Get the name of the wiki page.
775 * @return string The page name.
778 return $this->_pagename;
781 // To reduce the memory footprint for larger sets of pagelists,
782 // we don't cache the content (only true or false) and
783 // we purge the pagedata (_cached_html) also
785 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
786 $current = $this->getCurrentRevision(false);
787 if (!$current) return false;
788 return ! $current->hasDefaultContents();
792 * Delete an old revision of a WikiDB_Page.
794 * Deletes the specified revision of the page.
795 * It is a fatal error to attempt to delete the current revision.
799 * @param integer $version Which revision to delete. (You can also
800 * use a WikiDB_PageRevision object here.)
802 function deleteRevision($version) {
803 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
804 $backend = &$this->_wikidb->_backend;
805 $cache = &$this->_wikidb->_cache;
806 $pagename = &$this->_pagename;
808 $version = $this->_coerce_to_version($version);
812 $backend->lock(array('page','version'));
813 $latestversion = $cache->get_latest_version($pagename);
814 if ($latestversion && ($version == $latestversion)) {
815 $backend->unlock(array('page','version'));
816 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
817 $pagename), E_USER_ERROR);
821 $cache->delete_versiondata($pagename, $version);
822 $backend->unlock(array('page','version'));
826 * Delete a revision, or possibly merge it with a previous
830 * Suppose an author make a (major) edit to a page. Shortly
831 * after that the same author makes a minor edit (e.g. to fix
832 * spelling mistakes he just made.)
834 * Now some time later, where cleaning out old saved revisions,
835 * and would like to delete his minor revision (since there's
836 * really no point in keeping minor revisions around for a long
839 * Note that the text after the minor revision probably represents
840 * what the author intended to write better than the text after
841 * the preceding major edit.
843 * So what we really want to do is merge the minor edit with the
846 * We will only do this when:
848 * <li>The revision being deleted is a minor one, and
849 * <li>It has the same author as the immediately preceding revision.
852 function mergeRevision($version) {
853 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
854 $backend = &$this->_wikidb->_backend;
855 $cache = &$this->_wikidb->_cache;
856 $pagename = &$this->_pagename;
858 $version = $this->_coerce_to_version($version);
862 $backend->lock(array('version'));
863 $latestversion = $cache->get_latest_version($pagename);
864 if ($latestversion && $version == $latestversion) {
865 $backend->unlock(array('version'));
866 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
867 $pagename), E_USER_ERROR);
871 $versiondata = $cache->get_versiondata($pagename, $version, true);
873 // Not there? ... we're done!
874 $backend->unlock(array('version'));
878 if ($versiondata['is_minor_edit']) {
879 $previous = $backend->get_previous_version($pagename, $version);
881 $prevdata = $cache->get_versiondata($pagename, $previous);
882 if ($prevdata['author_id'] == $versiondata['author_id']) {
883 // This is a minor revision, previous version is
884 // by the same author. We will merge the
886 $cache->update_versiondata($pagename, $previous,
887 array('%content' => $versiondata['%content'],
888 '_supplanted' => $versiondata['_supplanted']));
893 $cache->delete_versiondata($pagename, $version);
894 $backend->unlock(array('version'));
899 * Create a new revision of a {@link WikiDB_Page}.
903 * @param int $version Version number for new revision.
904 * To ensure proper serialization of edits, $version must be
905 * exactly one higher than the current latest version.
906 * (You can defeat this check by setting $version to
907 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
909 * @param string $content Contents of new revision.
911 * @param hash $metadata Metadata for new revision.
912 * All values in the hash should be scalars (strings or integers).
914 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
916 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
917 * $version was incorrect, returns false
919 function createRevision($version, &$content, $metadata, $links) {
920 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
921 $backend = &$this->_wikidb->_backend;
922 $cache = &$this->_wikidb->_cache;
923 $pagename = &$this->_pagename;
924 $cache->invalidate_cache($pagename);
926 $backend->lock(array('version','page','recent','link','nonempty'));
928 $latestversion = $backend->get_latest_version($pagename);
929 $newversion = ($latestversion ? $latestversion : 0) + 1;
930 assert($newversion >= 1);
932 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
933 $backend->unlock(array('version','page','recent','link','nonempty'));
939 foreach ($data as $key => $val) {
940 if (empty($val) || $key[0] == '_' || $key[0] == '%')
944 assert(!empty($data['author']));
945 if (empty($data['author_id']))
946 @$data['author_id'] = $data['author'];
948 if (empty($data['mtime']))
949 $data['mtime'] = time();
951 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
952 // Ensure mtimes are monotonic.
953 $pdata = $cache->get_versiondata($pagename, $latestversion);
954 if ($data['mtime'] < $pdata['mtime']) {
955 trigger_error(sprintf(_("%s: Date of new revision is %s"),
956 $pagename,"'non-monotonic'"),
958 $data['orig_mtime'] = $data['mtime'];
959 $data['mtime'] = $pdata['mtime'];
962 // FIXME: use (possibly user specified) 'mtime' time or
964 $cache->update_versiondata($pagename, $latestversion,
965 array('_supplanted' => $data['mtime']));
968 $data['%content'] = &$content;
970 $cache->set_versiondata($pagename, $newversion, $data);
972 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
973 //':deleted' => empty($content)));
975 $backend->set_links($pagename, $links);
977 $backend->unlock(array('version','page','recent','link','nonempty'));
979 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
983 /** A higher-level interface to createRevision.
985 * This takes care of computing the links, and storing
986 * a cached version of the transformed wiki-text.
988 * @param string $wikitext The page content.
990 * @param int $version Version number for new revision.
991 * To ensure proper serialization of edits, $version must be
992 * exactly one higher than the current latest version.
993 * (You can defeat this check by setting $version to
994 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
996 * @param hash $meta Meta-data for new revision.
998 function save($wikitext, $version, $meta, $formatted = null) {
999 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1000 if (is_null($formatted))
1001 $formatted = new TransformedText($this, $wikitext, $meta);
1002 $type = $formatted->getType();
1003 $meta['pagetype'] = $type->getName();
1004 $links = $formatted->getWikiPageLinks(); // linkto => relation
1005 $attributes = array();
1006 foreach ($links as $link) {
1007 if ($link['linkto'] === "" and $link['relation']) {
1008 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1011 $meta['attribute'] = $attributes;
1013 $backend = &$this->_wikidb->_backend;
1014 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1015 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1016 $this->set('_cached_html', $formatted->pack());
1018 // FIXME: probably should have some global state information
1019 // in the backend to control when to optimize.
1021 // We're doing this here rather than in createRevision because
1022 // postgresql can't optimize while locked.
1023 if (((int)DEBUG & _DEBUG_SQL)
1024 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1025 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1026 if ($backend->optimize()) {
1028 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1032 /* Generate notification emails? */
1033 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1034 // Save didn't fail because of concurrent updates.
1035 $notify = $this->_wikidb->get('notify');
1037 and is_array($notify)
1038 and !isa($GLOBALS['request'],'MockRequest'))
1040 include_once("lib/MailNotify.php");
1041 $MailNotify = new MailNotify($newrevision->getName());
1042 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1044 $newrevision->_transformedContent = $formatted;
1046 // more pagechange callbacks: (in a hackish manner for now)
1047 if (ENABLE_RECENTCHANGESBOX
1048 and empty($meta['is_minor_edit'])
1049 and !in_array($GLOBALS['request']->getArg('action'),
1050 array('loadfile','upgrade')))
1052 require_once("lib/WikiPlugin.php");
1053 $w = new WikiPluginLoader;
1054 $p = $w->getPlugin("RecentChangesCached", false);
1055 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1057 return $newrevision;
1061 * Get the most recent revision of a page.
1065 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1067 function getCurrentRevision ($need_content=true) {
1068 $backend = &$this->_wikidb->_backend;
1069 $cache = &$this->_wikidb->_cache;
1070 $pagename = &$this->_pagename;
1072 // Prevent deadlock in case of memory exhausted errors
1073 // Pure selection doesn't really need locking here.
1074 // sf.net bug#927395
1075 // I know it would be better to lock, but with lots of pages this deadlock is more
1076 // severe than occasionally get not the latest revision.
1077 // In spirit to wikiwiki: read fast, edit slower.
1079 $version = $cache->get_latest_version($pagename);
1080 // getRevision gets the content also!
1081 $revision = $this->getRevision($version, $need_content);
1082 //$backend->unlock();
1088 * Get a specific revision of a WikiDB_Page.
1092 * @param integer $version Which revision to get.
1094 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1095 * false if the requested revision does not exist in the {@link WikiDB}.
1096 * Note that version zero of any page always exists.
1098 function getRevision ($version, $need_content=true) {
1099 $cache = &$this->_wikidb->_cache;
1100 $pagename = &$this->_pagename;
1102 if (! $version or $version == -1) // 0 or false
1103 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1105 assert($version > 0);
1106 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1108 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1110 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1115 * Get previous page revision.
1117 * This method find the most recent revision before a specified
1122 * @param integer $version Find most recent revision before this version.
1123 * You can also use a WikiDB_PageRevision object to specify the $version.
1125 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1126 * requested revision does not exist in the {@link WikiDB}. Note that
1127 * unless $version is greater than zero, a revision (perhaps version zero,
1128 * the default revision) will always be found.
1130 function getRevisionBefore ($version=false, $need_content=true) {
1131 $backend = &$this->_wikidb->_backend;
1132 $pagename = &$this->_pagename;
1133 if ($version === false)
1134 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1136 $version = $this->_coerce_to_version($version);
1141 $previous = $backend->get_previous_version($pagename, $version);
1142 $revision = $this->getRevision($previous, $need_content);
1143 //$backend->unlock();
1149 * Get all revisions of the WikiDB_Page.
1151 * This does not include the version zero (default) revision in the
1152 * returned revision set.
1154 * @return WikiDB_PageRevisionIterator A
1155 * WikiDB_PageRevisionIterator containing all revisions of this
1156 * WikiDB_Page in reverse order by version number.
1158 function getAllRevisions() {
1159 $backend = &$this->_wikidb->_backend;
1160 $revs = $backend->get_all_revisions($this->_pagename);
1161 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1165 * Find pages which link to or are linked from a page.
1166 * relations: $backend->get_links is responsible to add the relation to the pagehash
1167 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1168 * if (isset($next['linkrelation']))
1172 * @param boolean $reversed Which links to find: true for backlinks (default).
1174 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1175 * all matching pages.
1177 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1178 $limit='', $exclude='', $want_relations=false)
1180 $backend = &$this->_wikidb->_backend;
1181 $result = $backend->get_links($this->_pagename, $reversed,
1182 $include_empty, $sortby, $limit, $exclude,
1184 return new WikiDB_PageIterator($this->_wikidb, $result,
1185 array('include_empty' => $include_empty,
1186 'sortby' => $sortby,
1188 'exclude' => $exclude,
1189 'want_relations'=> $want_relations));
1193 * All Links from other pages to this page.
1195 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1196 $want_relations=false)
1198 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1201 * Forward Links: All Links from this page to other pages.
1203 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1204 $want_relations=false)
1206 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1209 * Relations: All links from this page to other pages with relation <> 0.
1210 * is_a:=page or population:=number
1212 function getRelations($sortby='', $limit='', $exclude='') {
1213 $backend = &$this->_wikidb->_backend;
1214 $result = $backend->get_links($this->_pagename, false, true,
1215 $sortby, $limit, $exclude,
1217 // we do not care for the linked page versiondata, just the pagename and linkrelation
1218 return new WikiDB_PageIterator($this->_wikidb, $result,
1219 array('include_empty' => true,
1220 'sortby' => $sortby,
1222 'exclude' => $exclude,
1223 'want_relations'=> true));
1227 * possibly faster link existance check. not yet accelerated.
1229 function existLink($link, $reversed=false) {
1230 $backend = &$this->_wikidb->_backend;
1231 if (method_exists($backend,'exists_link'))
1232 return $backend->exists_link($this->_pagename, $link, $reversed);
1233 //$cache = &$this->_wikidb->_cache;
1234 // TODO: check cache if it is possible
1235 $iter = $this->getLinks($reversed, false);
1236 while ($page = $iter->next()) {
1237 if ($page->getName() == $link)
1244 /* Semantic relations are links with the relation pointing to another page,
1245 the so-called "RDF Triple".
1246 [San Diego] is%20a::city
1247 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1250 /* Semantic attributes for a page.
1251 [San Diego] population:=1,305,736
1252 Attributes are links with the relation pointing to another page.
1256 * Access WikiDB_Page non version-specific meta-data.
1260 * @param string $key Which meta data to get.
1261 * Some reserved meta-data keys are:
1263 * <dt>'date' <dd> Created as unixtime
1264 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1265 * <dt>'hits' <dd> Page hit counter.
1266 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1267 * In SQL stored now in an extra column.
1269 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1270 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1271 * E.g. "owner.users"
1272 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1273 * page-headers and content.
1274 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1275 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1278 * @return scalar The requested value, or false if the requested data
1281 function get($key) {
1282 $cache = &$this->_wikidb->_cache;
1283 $backend = &$this->_wikidb->_backend;
1284 if (!$key || $key[0] == '%')
1286 // several new SQL backends optimize this.
1287 if (!WIKIDB_NOCACHE_MARKUP
1288 and $key == '_cached_html'
1289 and method_exists($backend, 'get_cached_html'))
1291 return $backend->get_cached_html($this->_pagename);
1293 $data = $cache->get_pagedata($this->_pagename);
1294 return isset($data[$key]) ? $data[$key] : false;
1298 * Get all the page meta-data as a hash.
1300 * @return hash The page meta-data.
1302 function getMetaData() {
1303 $cache = &$this->_wikidb->_cache;
1304 $data = $cache->get_pagedata($this->_pagename);
1306 foreach ($data as $key => $val) {
1307 if (/*!empty($val) &&*/ $key[0] != '%')
1314 * Set page meta-data.
1319 * @param string $key Meta-data key to set.
1320 * @param string $newval New value.
1322 function set($key, $newval) {
1323 $cache = &$this->_wikidb->_cache;
1324 $backend = &$this->_wikidb->_backend;
1325 $pagename = &$this->_pagename;
1327 assert($key && $key[0] != '%');
1329 // several new SQL backends optimize this.
1330 if (!WIKIDB_NOCACHE_MARKUP
1331 and $key == '_cached_html'
1332 and method_exists($backend, 'set_cached_html'))
1334 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1335 return $backend->set_cached_html($pagename, $newval);
1338 $data = $cache->get_pagedata($pagename);
1340 if (!empty($newval)) {
1341 if (!empty($data[$key]) && $data[$key] == $newval)
1342 return; // values identical, skip update.
1345 if (empty($data[$key]))
1346 return; // values identical, skip update.
1349 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1350 $cache->update_pagedata($pagename, array($key => $newval));
1354 * Increase page hit count.
1356 * FIXME: IS this needed? Probably not.
1358 * This is a convenience function.
1359 * <pre> $page->increaseHitCount(); </pre>
1360 * is functionally identical to
1361 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1362 * but less expensive (ignores the pagadata string)
1364 * Note that this method may be implemented in more efficient ways
1365 * in certain backends.
1369 function increaseHitCount() {
1370 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; }
1371 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1372 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1374 @$newhits = $this->get('hits') + 1;
1375 $this->set('hits', $newhits);
1380 * Return a string representation of the WikiDB_Page
1382 * This is really only for debugging.
1386 * @return string Printable representation of the WikiDB_Page.
1388 function asString () {
1390 printf("[%s:%s\n", get_class($this), $this->getName());
1391 print_r($this->getMetaData());
1393 $strval = ob_get_contents();
1401 * @param integer_or_object $version_or_pagerevision
1402 * Takes either the version number (and int) or a WikiDB_PageRevision
1404 * @return integer The version number.
1406 function _coerce_to_version($version_or_pagerevision) {
1407 if (method_exists($version_or_pagerevision, "getContent"))
1408 $version = $version_or_pagerevision->getVersion();
1410 $version = (int) $version_or_pagerevision;
1412 assert($version >= 0);
1416 function isUserPage ($include_empty = true) {
1417 if (!$include_empty and !$this->exists()) return false;
1418 return $this->get('pref') ? true : false;
1421 // May be empty. Either the stored owner (/Chown), or the first authorized author
1422 function getOwner() {
1423 if ($owner = $this->get('owner'))
1425 // check all revisions forwards for the first author_id
1426 $backend = &$this->_wikidb->_backend;
1427 $pagename = &$this->_pagename;
1428 $latestversion = $backend->get_latest_version($pagename);
1429 for ($v=1; $v <= $latestversion; $v++) {
1430 $rev = $this->getRevision($v,false);
1431 if ($rev and $owner = $rev->get('author_id')) {
1438 // The authenticated author of the first revision or empty if not authenticated then.
1439 function getCreator() {
1440 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1444 // The authenticated author of the current revision.
1445 function getAuthor() {
1446 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1450 /* Semantic Web value, not stored in the links.
1451 * todo: unify with some unit knowledge
1453 function setAttribute($relation, $value) {
1454 $attr = $this->get('attributes');
1456 $attr = array($relation => $value);
1458 $attr[$relation] = $value;
1459 $this->set('attributes', $attr);
1462 function getAttribute($relation) {
1463 $meta = $this->get('attributes');
1467 return $meta[$relation];
1473 * This class represents a specific revision of a WikiDB_Page within
1476 * A WikiDB_PageRevision has read-only semantics. You may only create
1477 * new revisions (and delete old ones) --- you cannot modify existing
1480 class WikiDB_PageRevision
1482 //var $_transformedContent = false; // set by WikiDB_Page::save()
1484 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1485 $versiondata = false)
1487 $this->_wikidb = &$wikidb;
1488 $this->_pagename = $pagename;
1489 $this->_version = $version;
1490 $this->_data = $versiondata ? $versiondata : array();
1491 $this->_transformedContent = false; // set by WikiDB_Page::save()
1495 * Get the WikiDB_Page which this revision belongs to.
1499 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1501 function getPage() {
1502 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1506 * Get the version number of this revision.
1510 * @return integer The version number of this revision.
1512 function getVersion() {
1513 return $this->_version;
1517 * Determine whether this revision has defaulted content.
1519 * The default revision (version 0) of each page, as well as any
1520 * pages which are created with empty content have their content
1521 * defaulted to something like:
1523 * Describe [ThisPage] here.
1528 * @return boolean Returns true if the page has default content.
1530 function hasDefaultContents() {
1531 $data = &$this->_data;
1532 if (!isset($data['%content'])) return true;
1533 if ($data['%content'] === true) return false;
1534 return $data['%content'] === false or $data['%content'] === "";
1538 * Get the content as an array of lines.
1542 * @return array An array of lines.
1543 * The lines should contain no trailing white space.
1545 function getContent() {
1546 return explode("\n", $this->getPackedContent());
1550 * Get the pagename of the revision.
1554 * @return string pagename.
1556 function getPageName() {
1557 return $this->_pagename;
1559 function getName() {
1560 return $this->_pagename;
1564 * Determine whether revision is the latest.
1568 * @return boolean True iff the revision is the latest (most recent) one.
1570 function isCurrent() {
1571 if (!isset($this->_iscurrent)) {
1572 $page = $this->getPage();
1573 $current = $page->getCurrentRevision(false);
1574 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1576 return $this->_iscurrent;
1580 * Get the transformed content of a page.
1582 * @param string $pagetype Override the page-type of the revision.
1584 * @return object An XmlContent-like object containing the page transformed
1587 function getTransformedContent($pagetype_override=false) {
1588 $backend = &$this->_wikidb->_backend;
1590 if ($pagetype_override) {
1591 // Figure out the normal page-type for this page.
1592 $type = PageType::GetPageType($this->get('pagetype'));
1593 if ($type->getName() == $pagetype_override)
1594 $pagetype_override = false; // Not really an override...
1597 if ($pagetype_override) {
1598 // Overriden page type, don't cache (or check cache).
1599 return new TransformedText($this->getPage(),
1600 $this->getPackedContent(),
1601 $this->getMetaData(),
1602 $pagetype_override);
1605 $possibly_cache_results = true;
1607 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1608 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1609 // flush cache for this page.
1610 $page = $this->getPage();
1611 $page->set('_cached_html', ''); // ignored with !USECACHE
1613 $possibly_cache_results = false;
1615 elseif (USECACHE and !$this->_transformedContent) {
1617 if ($this->isCurrent()) {
1618 $page = $this->getPage();
1619 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1622 $possibly_cache_results = false;
1624 //$backend->unlock();
1627 if (!$this->_transformedContent) {
1628 $this->_transformedContent
1629 = new TransformedText($this->getPage(),
1630 $this->getPackedContent(),
1631 $this->getMetaData());
1633 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1634 // If we're still the current version, cache the transfomed page.
1636 if ($this->isCurrent()) {
1637 $page->set('_cached_html', $this->_transformedContent->pack());
1639 //$backend->unlock();
1643 return $this->_transformedContent;
1647 * Get the content as a string.
1651 * @return string The page content.
1652 * Lines are separated by new-lines.
1654 function getPackedContent() {
1655 $data = &$this->_data;
1657 if (empty($data['%content'])
1658 || (!$this->_wikidb->isWikiPage($this->_pagename)
1659 && $this->isCurrent())) {
1660 include_once('lib/InlineParser.php');
1662 // A feature similar to taglines at http://www.wlug.org.nz/
1663 // Lib from http://www.aasted.org/quote/
1664 if (defined('FORTUNE_DIR')
1665 and is_dir(FORTUNE_DIR)
1666 and in_array($GLOBALS['request']->getArg('action'),
1667 array('create','edit')))
1669 include_once("lib/fortune.php");
1670 $fortune = new Fortune();
1671 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1673 $quote = "<verbatim>\n"
1674 . str_replace("\n<br>","\n", $quote)
1675 . "</verbatim>\n\n";
1679 . sprintf(_("Describe %s here."),
1680 "[" . WikiEscape($this->_pagename) . "]");
1682 // Replace empty content with default value.
1683 return sprintf(_("Describe %s here."),
1684 "[" . WikiEscape($this->_pagename) . "]");
1687 // There is (non-default) content.
1688 assert($this->_version > 0);
1690 if (!is_string($data['%content'])) {
1691 // Content was not provided to us at init time.
1692 // (This is allowed because for some backends, fetching
1693 // the content may be expensive, and often is not wanted
1696 // In any case, now we need to get it.
1697 $data['%content'] = $this->_get_content();
1698 assert(is_string($data['%content']));
1701 return $data['%content'];
1704 function _get_content() {
1705 $cache = &$this->_wikidb->_cache;
1706 $pagename = $this->_pagename;
1707 $version = $this->_version;
1709 assert($version > 0);
1711 $newdata = $cache->get_versiondata($pagename, $version, true);
1713 assert(is_string($newdata['%content']));
1714 return $newdata['%content'];
1717 // else revision has been deleted... What to do?
1718 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1719 $version, $pagename);
1724 * Get meta-data for this revision.
1729 * @param string $key Which meta-data to access.
1731 * Some reserved revision meta-data keys are:
1733 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1734 * The 'mtime' meta-value is normally set automatically by the database
1735 * backend, but it may be specified explicitly when creating a new revision.
1737 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1738 * of a page must be monotonically increasing. If an attempt is
1739 * made to create a new revision with an mtime less than that of
1740 * the preceeding revision, the new revisions timestamp is force
1741 * to be equal to that of the preceeding revision. In that case,
1742 * the originally requested mtime is preserved in 'orig_mtime'.
1743 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1744 * This meta-value is <em>always</em> automatically maintained by the database
1745 * backend. (It is set from the 'mtime' meta-value of the superceding
1746 * revision.) '_supplanted' has a value of 'false' for the current revision.
1748 * FIXME: this could be refactored:
1750 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1752 * <dd> Authenticated author of a page. This is used to identify
1753 * the distinctness of authors when cleaning old revisions from
1755 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1756 * <dt> 'summary' <dd> Short change summary entered by page author.
1759 * Meta-data keys must be valid C identifers (they have to start with a letter
1760 * or underscore, and can contain only alphanumerics and underscores.)
1762 * @return string The requested value, or false if the requested value
1765 function get($key) {
1766 if (!$key || $key[0] == '%')
1768 $data = &$this->_data;
1769 return isset($data[$key]) ? $data[$key] : false;
1773 * Get all the revision page meta-data as a hash.
1775 * @return hash The revision meta-data.
1777 function getMetaData() {
1779 foreach ($this->_data as $key => $val) {
1780 if (!empty($val) && $key[0] != '%')
1788 * Return a string representation of the revision.
1790 * This is really only for debugging.
1794 * @return string Printable representation of the WikiDB_Page.
1796 function asString () {
1798 printf("[%s:%d\n", get_class($this), $this->get('version'));
1799 print_r($this->_data);
1800 echo $this->getPackedContent() . "\n]\n";
1801 $strval = ob_get_contents();
1809 * Class representing a sequence of WikiDB_Pages.
1810 * TODO: Enhance to php5 iterators
1812 * apply filters for options like 'sortby', 'limit', 'exclude'
1813 * for simple queries like titleSearch, where the backend is not ready yet.
1815 class WikiDB_PageIterator
1817 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1818 $this->_iter = $iter; // a WikiDB_backend_iterator
1819 $this->_wikidb = &$wikidb;
1820 $this->_options = $options;
1824 return $this->_iter->count();
1828 * Get next WikiDB_Page in sequence.
1832 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1835 if ( ! ($next = $this->_iter->next()) )
1838 $pagename = &$next['pagename'];
1839 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1840 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1841 $pagename = $pagename['linkto'];
1843 $pagename = strval($pagename);*/
1844 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1847 if (isset($next['linkrelation'])
1848 or isset($next['pagedata']['linkrelation'])) return false;
1849 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1853 // There's always hits, but we cache only if more
1854 // (well not with file, cvs and dba)
1855 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1856 $this->_wikidb->_cache->cache_data($next);
1857 // cache existing page id's since we iterate over all links in GleanDescription
1858 // and need them later for LinkExistingWord
1859 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1860 and !$this->_options['include_empty'] and isset($next['id'])) {
1861 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1863 $page = new WikiDB_Page($this->_wikidb, $pagename);
1864 if (isset($next['linkrelation']))
1865 $page->set('linkrelation', $next['linkrelation']);
1866 if (isset($next['score']))
1867 $page->score = $next['score'];
1872 * Release resources held by this iterator.
1874 * The iterator may not be used after free() is called.
1876 * There is no need to call free(), if next() has returned false.
1877 * (I.e. if you iterate through all the pages in the sequence,
1878 * you do not need to call free() --- you only need to call it
1879 * if you stop before the end of the iterator is reached.)
1884 $this->_iter->free();
1887 $this->_iter->reset();
1889 function asArray() {
1891 while ($page = $this->next())
1898 * Apply filters for options like 'sortby', 'limit', 'exclude'
1899 * for simple queries like titleSearch, where the backend is not ready yet.
1900 * Since iteration is usually destructive for SQL results,
1901 * we have to generate a copy.
1903 function applyFilters($options = false) {
1904 if (!$options) $options = $this->_options;
1905 if (isset($options['sortby'])) {
1907 /* this is destructive */
1908 while ($page = $this->next())
1909 $result[] = $page->getName();
1910 $this->_doSort($array, $options['sortby']);
1912 /* the rest is not destructive.
1913 * reconstruct a new iterator
1915 $pagenames = array(); $i = 0;
1916 if (isset($options['limit']))
1917 $limit = $options['limit'];
1920 if (isset($options['exclude']))
1921 $exclude = $options['exclude'];
1922 if (is_string($exclude) and !is_array($exclude))
1923 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1924 foreach($array as $pagename) {
1925 if ($limit and $i++ > $limit)
1926 return new WikiDB_Array_PageIterator($pagenames);
1927 if (!empty($exclude) and !in_array($pagename, $exclude))
1928 $pagenames[] = $pagename;
1929 elseif (empty($exclude))
1930 $pagenames[] = $pagename;
1932 return new WikiDB_Array_PageIterator($pagenames);
1936 function _doSort(&$array, $sortby) {
1937 $sortby = PageList::sortby($sortby, 'init');
1938 if ($sortby == '+pagename')
1939 sort($array, SORT_STRING);
1940 elseif ($sortby == '-pagename')
1941 rsort($array, SORT_STRING);
1948 * A class which represents a sequence of WikiDB_PageRevisions.
1949 * TODO: Enhance to php5 iterators
1951 class WikiDB_PageRevisionIterator
1953 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1954 $this->_revisions = $revisions;
1955 $this->_wikidb = &$wikidb;
1956 $this->_options = $options;
1960 return $this->_revisions->count();
1964 * Get next WikiDB_PageRevision in sequence.
1968 * @return WikiDB_PageRevision
1969 * The next WikiDB_PageRevision in the sequence.
1972 if ( ! ($next = $this->_revisions->next()) )
1975 //$this->_wikidb->_cache->cache_data($next);
1977 $pagename = $next['pagename'];
1978 $version = $next['version'];
1979 $versiondata = $next['versiondata'];
1981 if (!(is_string($pagename) and $pagename != '')) {
1982 trigger_error("empty pagename",E_USER_WARNING);
1985 } else assert(is_string($pagename) and $pagename != '');
1987 if (!is_array($versiondata)) {
1988 trigger_error("empty versiondata",E_USER_WARNING);
1991 } else assert(is_array($versiondata));
1993 if (!($version > 0)) {
1994 trigger_error("invalid version",E_USER_WARNING);
1997 } else assert($version > 0);
1999 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2004 * Release resources held by this iterator.
2006 * The iterator may not be used after free() is called.
2008 * There is no need to call free(), if next() has returned false.
2009 * (I.e. if you iterate through all the revisions in the sequence,
2010 * you do not need to call free() --- you only need to call it
2011 * if you stop before the end of the iterator is reached.)
2016 $this->_revisions->free();
2019 function asArray() {
2021 while ($rev = $this->next())
2030 class WikiDB_Array_PageIterator
2032 function WikiDB_Array_PageIterator($pagenames) {
2034 $this->_dbi = $request->getDbh();
2035 $this->_pages = $pagenames;
2036 reset($this->_pages);
2039 $c = current($this->_pages);
2040 next($this->_pages);
2041 return $c !== false ? $this->_dbi->getPage($c) : false;
2044 return count($this->_pages);
2047 reset($this->_pages);
2050 function asArray() {
2051 reset($this->_pages);
2052 return $this->_pages;
2056 class WikiDB_Array_generic_iter
2058 function WikiDB_Array_generic_iter($result) {
2059 // $result may be either an array or a query result
2060 if (is_array($result)) {
2061 $this->_array = $result;
2062 } elseif (is_object($result)) {
2063 $this->_array = $result->asArray();
2065 $this->_array = array();
2067 if (!empty($this->_array))
2068 reset($this->_array);
2071 $c = current($this->_array);
2072 next($this->_array);
2073 return $c !== false ? $c : false;
2076 return count($this->_array);
2079 reset($this->_array);
2082 function asArray() {
2083 if (!empty($this->_array))
2084 reset($this->_array);
2085 return $this->_array;
2090 * Data cache used by WikiDB.
2092 * FIXME: Maybe rename this to caching_backend (or some such).
2098 // FIXME: beautify versiondata cache. Cache only limited data?
2100 function WikiDB_cache (&$backend) {
2101 $this->_backend = &$backend;
2103 $this->_pagedata_cache = array();
2104 $this->_versiondata_cache = array();
2105 array_push ($this->_versiondata_cache, array());
2106 $this->_glv_cache = array();
2107 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2109 if (isset($GLOBALS['request']->_dbi))
2110 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2114 $this->_pagedata_cache = array();
2115 $this->_versiondata_cache = array();
2116 $this->_glv_cache = array();
2117 $this->_id_cache = array();
2120 function get_pagedata($pagename) {
2121 assert(is_string($pagename) && $pagename != '');
2123 $cache = &$this->_pagedata_cache;
2124 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2125 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2126 if (empty($cache[$pagename]))
2127 $cache[$pagename] = array();
2129 return $cache[$pagename];
2131 return $this->_backend->get_pagedata($pagename);
2135 function update_pagedata($pagename, $newdata) {
2136 assert(is_string($pagename) && $pagename != '');
2137 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2139 $this->_backend->update_pagedata($pagename, $newdata);
2142 if (!empty($this->_pagedata_cache[$pagename])
2143 and is_array($this->_pagedata_cache[$pagename]))
2145 $cachedata = &$this->_pagedata_cache[$pagename];
2146 foreach($newdata as $key => $val)
2147 $cachedata[$key] = $val;
2149 $this->_pagedata_cache[$pagename] = $newdata;
2153 function invalidate_cache($pagename) {
2154 unset ($this->_pagedata_cache[$pagename]);
2155 unset ($this->_versiondata_cache[$pagename]);
2156 unset ($this->_glv_cache[$pagename]);
2157 unset ($this->_id_cache[$pagename]);
2158 //unset ($this->_backend->_page_data);
2161 function delete_page($pagename) {
2162 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2163 $result = $this->_backend->delete_page($pagename);
2164 $this->invalidate_cache($pagename);
2168 function purge_page($pagename) {
2169 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2170 $result = $this->_backend->purge_page($pagename);
2171 $this->invalidate_cache($pagename);
2175 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2176 function cache_data($data) {
2178 //if (isset($data['pagedata']))
2179 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2182 function get_versiondata($pagename, $version, $need_content = false) {
2183 // FIXME: Seriously ugly hackage
2185 if (USECACHE) { //temporary - for debugging
2186 assert(is_string($pagename) && $pagename != '');
2187 // There is a bug here somewhere which results in an assertion failure at line 105
2188 // of ArchiveCleaner.php It goes away if we use the next line.
2189 //$need_content = true;
2190 $nc = $need_content ? '1':'0';
2191 $cache = &$this->_versiondata_cache;
2192 if (!isset($cache[$pagename][$version][$nc])
2193 || !(is_array ($cache[$pagename]))
2194 || !(is_array ($cache[$pagename][$version])))
2196 $cache[$pagename][$version][$nc] =
2197 $this->_backend->get_versiondata($pagename, $version, $need_content);
2199 // If we have retrieved all data, we may as well set the cache for
2200 // $need_content = false
2202 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2205 $vdata = $cache[$pagename][$version][$nc];
2207 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2210 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2211 if (empty($this->_pagedata_cache))
2212 $this->_pagedata_cache = array();
2213 /* 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 */
2214 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2219 function set_versiondata($pagename, $version, $data) {
2220 //unset($this->_versiondata_cache[$pagename][$version]);
2222 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2223 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2225 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2226 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2227 // Is this necessary?
2228 unset($this->_glv_cache[$pagename]);
2231 function update_versiondata($pagename, $version, $data) {
2232 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2233 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2235 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2237 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2238 // Is this necessary?
2239 unset($this->_glv_cache[$pagename]);
2242 function delete_versiondata($pagename, $version) {
2243 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2244 $new = $this->_backend->delete_versiondata($pagename, $version);
2245 if (isset($this->_versiondata_cache[$pagename][$version]))
2246 unset ($this->_versiondata_cache[$pagename][$version]);
2247 // dirty latest version cache only if latest version gets deleted
2248 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2249 unset ($this->_glv_cache[$pagename]);
2252 function get_latest_version($pagename) {
2254 assert (is_string($pagename) && $pagename != '');
2255 $cache = &$this->_glv_cache;
2256 if (!isset($cache[$pagename])) {
2257 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2258 if (empty($cache[$pagename]))
2259 $cache[$pagename] = 0;
2261 return $cache[$pagename];
2263 return $this->_backend->get_latest_version($pagename);
2268 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2272 $stamp = strftime("%y%m%d-%H%M%S");
2273 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2274 register_shutdown_function("_sql_debuglog_shutdown_function");
2275 } elseif ($shutdown) {
2279 if ($newline) fputs($fp, "[$i++] $msg");
2280 else fwrite($fp, $msg);
2283 function _sql_debuglog_shutdown_function() {
2284 _sql_debuglog('',false,true);
2290 // c-basic-offset: 4
2291 // c-hanging-comment-ender-p: nil
2292 // indent-tabs-mode: nil