1 <?php //rcs_id('$Id$');
2 require_once('lib/PageType.php');
5 * The classes in the file define the interface to the
9 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
10 * Minor enhancements by Reini Urban
14 * Force the creation of a new revision.
15 * @see WikiDB_Page::createRevision()
17 if (!defined('WIKIDB_FORCE_CREATE'))
18 define('WIKIDB_FORCE_CREATE', -1);
21 * Abstract base class for the database used by PhpWiki.
23 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
24 * turn contain <tt>WikiDB_PageRevision</tt>s.
26 * Conceptually a <tt>WikiDB</tt> contains all possible
27 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
28 * Since all possible pages are already contained in a WikiDB, a call
29 * to WikiDB::getPage() will never fail (barring bugs and
30 * e.g. filesystem or SQL database problems.)
32 * Also each <tt>WikiDB_Page</tt> always contains at least one
33 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
34 * [PageName] here."). This default content has a version number of
37 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
38 * only create new revisions or delete old ones --- one can not modify
39 * an existing revision.
43 * Open a WikiDB database.
45 * This is a static member function. This function inspects its
46 * arguments to determine the proper subclass of WikiDB to
47 * instantiate, and then it instantiates it.
51 * @param hash $dbparams Database configuration parameters.
52 * Some pertinent parameters are:
55 * <dd> The back-end type. Current supported types are:
58 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
59 * library. (More stable and conservative)
61 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
63 * <dd> Dba based backend. The default and by far the fastest.
71 * <dd> (Used by the SQL and ADODB backends.)
72 * The DSN specifying which database to connect to.
75 * <dd> Prefix to be prepended to database tables (and file names).
78 * <dd> (Used by the dba backend.)
79 * Which directory db files reside in.
82 * <dd> Used only by the dba backend so far.
83 * And: When optimizing mysql it closes timed out mysql processes.
84 * otherwise only used for dba: Timeout in seconds for opening (and
85 * obtaining lock) on the dbm file.
88 * <dd> (Used by the dba backend.)
90 * Which dba handler to use. Good choices are probably either
94 * <dd> Either set by config.ini: READONLY = true or detected automatically
95 * when a database can be read but cannot be updated.
98 * @return WikiDB A WikiDB object.
100 function open ($dbparams) {
101 $dbtype = $dbparams{'dbtype'};
102 include_once("lib/WikiDB/$dbtype.php");
104 $class = 'WikiDB_' . $dbtype;
105 return new $class ($dbparams);
115 function WikiDB (&$backend, $dbparams) {
116 $this->_backend =& $backend;
117 // don't do the following with the auth_dsn!
118 if (isset($dbparams['auth_dsn'])) return;
120 $this->_cache = new WikiDB_cache($backend);
121 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
123 // If the database doesn't yet have a timestamp, initialize it now.
124 if ($this->get('_timestamp') === false)
128 if ((int)DEBUG & _DEBUG_SQL) {
129 $this->_backend->check();
131 // might be changed when opening the database fails
132 $this->readonly = defined("READONLY") ? READONLY : false;
136 * Close database connection.
138 * The database may no longer be used after it is closed.
140 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
141 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
142 * which have been obtained from it.
147 $this->_backend->close();
148 $this->_cache->close();
152 * Get a WikiDB_Page from a WikiDB.
154 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
155 * therefore this method never fails.
158 * @param string $pagename Which page to get.
159 * @return WikiDB_Page The requested WikiDB_Page.
161 function getPage($pagename) {
162 static $error_displayed = false;
163 $pagename = (string) $pagename;
165 if ($pagename === '') {
166 if ($error_displayed) return false;
167 $error_displayed = true;
168 if (function_exists("xdebug_get_function_stack"))
169 var_dump(xdebug_get_function_stack());
170 trigger_error("empty pagename", E_USER_WARNING);
174 assert($pagename != '');
176 return new WikiDB_Page($this, $pagename);
180 * Determine whether page exists (in non-default form).
183 * $is_page = $dbi->isWikiPage($pagename);
187 * $page = $dbi->getPage($pagename);
188 * $current = $page->getCurrentRevision();
189 * $is_page = ! $current->hasDefaultContents();
191 * however isWikiPage may be implemented in a more efficient
192 * manner in certain back-ends.
195 * @param string $pagename string Which page to check.
196 * @return boolean True if the page actually exists with
197 * non-default contents in the WikiDataBase.
199 function isWikiPage ($pagename) {
200 $page = $this->getPage($pagename);
201 return ($page and $page->exists());
205 * Delete page from the WikiDB.
207 * Deletes the page from the WikiDB with the possibility to revert and diff.
208 * //Also resets all page meta-data to the default values.
210 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
213 * @param string $pagename Name of page to delete.
216 function deletePage($pagename) {
217 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
218 // don't create empty revisions of already purged pages.
219 if ($this->_backend->get_latest_version($pagename))
220 $result = $this->_cache->delete_page($pagename);
224 /* Generate notification emails */
225 if (ENABLE_MAILNOTIFY) {
226 include_once("lib/MailNotify.php");
227 $MailNotify = new MailNotify($pagename);
228 $MailNotify->onDeletePage ($this, $pagename);
231 //How to create a RecentChanges entry with explaining summary? Dynamically
233 $page = $this->getPage($pagename);
234 $current = $page->getCurrentRevision();
235 $meta = $current->_data;
236 $version = $current->getVersion();
237 $meta['summary'] = _("removed");
238 $page->save($current->getPackedContent(), $version + 1, $meta);
244 * Completely remove the page from the WikiDB, without undo possibility.
246 * @param string $pagename Name of page to delete.
249 function purgePage($pagename) {
250 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
251 $result = $this->_cache->purge_page($pagename);
252 $this->deletePage($pagename); // just for the notification
257 * Retrieve all pages.
259 * Gets the set of all pages with non-default contents.
263 * @param boolean $include_empty Optional. Normally pages whose most
264 * recent revision has empty content are considered to be
265 * non-existant. Unless $include_defaulted is set to true, those
266 * pages will not be returned.
267 * @param string or false $sortby Optional. "+-column,+-column2".
268 * If false the result is faster in natural order.
269 * @param string or false $limit Optional. Encoded as "$offset,$count".
270 * $offset defaults to 0.
271 * @param string $exclude: Optional comma-seperated list of pagenames.
273 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
274 * in the WikiDB which have non-default contents.
276 function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
278 // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
280 $mem = ini_get("memory_limit");
281 if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
283 $GLOBALS['request']->setArg('limit', $limit);
284 $GLOBALS['request']->setArg('paging', 'auto');
287 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
289 if (isa($this->_backend, "WikiDB_backend_dba"))
291 return new WikiDB_PageIterator($this, $result,
292 array('include_empty' => $include_empty,
293 'exclude' => $exclude,
300 * @param boolean $include_empty If true include also empty pages
301 * @param string $exclude: comma-seperated list of pagenames.
302 * TBD: array of pagenames
306 function numPages($include_empty=false, $exclude='') {
307 if (method_exists($this->_backend, 'numPages'))
308 // FIXME: currently are all args ignored.
309 $count = $this->_backend->numPages($include_empty, $exclude);
311 // FIXME: exclude ignored.
312 $iter = $this->getAllPages($include_empty, false, false, $exclude);
313 $count = $iter->count();
322 * Search for pages containing (or not containing) certain words
325 * Pages are returned in alphabetical order whenever it is
326 * practical to do so.
327 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
330 * @param TextSearchQuery $search A TextSearchQuery object
331 * @param string or false $sortby Optional. "+-column,+-column2".
332 * If false the result is faster in natural order.
333 * @param string or false $limit Optional. Encoded as "$offset,$count".
334 * $offset defaults to 0.
335 * @param string $exclude: Optional comma-seperated list of pagenames.
336 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
337 * @see TextSearchQuery
339 function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
340 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
341 $options = array('exclude' => $exclude,
343 //if (isset($result->_count)) $options['count'] = $result->_count;
344 return new WikiDB_PageIterator($this, $result, $options);
350 * Search for pages containing (or not containing) certain words
351 * in their entire text (this includes the page content and the
354 * Pages are returned in alphabetical order whenever it is
355 * practical to do so.
356 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
360 * @param TextSearchQuery $search A TextSearchQuery object.
361 * @param string or false $sortby Optional. "+-column,+-column2".
362 * If false the result is faster in natural order.
363 * @param string or false $limit Optional. Encoded as "$offset,$count".
364 * $offset defaults to 0.
365 * @param string $exclude: Optional comma-seperated list of pagenames.
366 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
367 * @see TextSearchQuery
369 function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
370 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
371 return new WikiDB_PageIterator($this, $result,
372 array('exclude' => $exclude,
374 'stoplisted' => $result->stoplisted
379 * Find the pages with the greatest hit counts.
381 * Pages are returned in reverse order by hit count.
385 * @param integer $limit The maximum number of pages to return.
386 * Set $limit to zero to return all pages. If $limit < 0, pages will
387 * be sorted in decreasing order of popularity.
388 * @param string or false $sortby Optional. "+-column,+-column2".
389 * If false the result is faster in natural order.
391 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
394 function mostPopular($limit = 20, $sortby = '-hits') {
395 $result = $this->_backend->most_popular($limit, $sortby);
396 return new WikiDB_PageIterator($this, $result);
400 * Find recent page revisions.
402 * Revisions are returned in reverse order by creation time.
406 * @param hash $params This hash is used to specify various optional
410 * <dd> (integer) At most this many revisions will be returned.
412 * <dd> (integer) Only revisions since this time (unix-timestamp)
414 * <dt> include_minor_revisions
415 * <dd> (boolean) Also include minor revisions. (Default is not to.)
416 * <dt> exclude_major_revisions
417 * <dd> (boolean) Don't include non-minor revisions.
418 * (Exclude_major_revisions implies include_minor_revisions.)
419 * <dt> include_all_revisions
420 * <dd> (boolean) Return all matching revisions for each page.
421 * Normally only the most recent matching revision is returned
425 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
426 * containing the matching revisions.
428 function mostRecent($params = false) {
429 $result = $this->_backend->most_recent($params);
430 return new WikiDB_PageRevisionIterator($this, $result);
436 * @param string or false $sortby Optional. "+-column,+-column2".
437 * If false the result is faster in natural order.
438 * @param string or false $limit Optional. Encoded as "$offset,$count".
439 * $offset defaults to 0.
440 * @return Iterator A generic iterator containing rows of
441 * (duplicate) pagename, wantedfrom.
443 function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
444 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
445 //return new WikiDB_PageIterator($this, $result);
449 * Generic interface to the link table. Esp. useful to search for rdf triples as in
450 * SemanticSearch and ListRelations.
454 * @param $pages object A TextSearchQuery object.
455 * @param $search object A TextSearchQuery object.
456 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
457 * linktype parameter:
460 * <dd> search for simple out-links
462 * <dd> in-links, i.e BackLinks
464 * <dd> the first part in a <>::<> link
466 * <dd> the first part in a <>:=<> link
468 * @param $relation object An optional TextSearchQuery to match the
469 * relation name. Ignored on simple in-out links.
471 * @return Iterator A generic iterator containing links to pages or values.
472 * hash of "pagename", "linkname", "linkvalue.
474 function linkSearch($pages, $search, $linktype, $relation=false) {
475 return $this->_backend->link_search($pages, $search, $linktype, $relation);
479 * Return a simple list of all defined relations (and attributes), mainly
480 * for the SemanticSearch autocompletion.
484 * @return array of strings
486 function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
487 if (method_exists($this->_backend, "list_relations"))
488 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
489 // dumb, slow fallback. no iter, so simply define it here.
490 $relations = array();
491 $iter = $this->getAllPages();
492 while ($page = $iter->next()) {
493 $reliter = $page->getRelations();
495 while ($rel = $reliter->next()) {
496 // if there's no pagename it's an attribute
497 $names[] = $rel->getName();
499 $relations = array_merge($relations, $names);
511 * Call the appropriate backend method.
514 * @param string $from Page to rename
515 * @param string $to New name
516 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
517 * @return boolean true or false
519 function renamePage($from, $to, $updateWikiLinks = false) {
520 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
521 assert(is_string($from) && $from != '');
522 assert(is_string($to) && $to != '');
524 if (method_exists($this->_backend, 'rename_page')) {
525 $oldpage = $this->getPage($from);
526 $newpage = $this->getPage($to);
527 //update all WikiLinks in existing pages
528 //non-atomic! i.e. if rename fails the links are not undone
529 if ($updateWikiLinks) {
530 $lookbehind = "/(?<=[\W:])\Q";
531 $lookahead = "\E(?=[\W:])/";
532 if (!check_php_version(4,3,3)) {
533 $lookbehind = "/(?<=[\W:])";
534 $lookahead = "(?=[\W:])/";
535 $from = preg_quote($from, "/");
536 $to = preg_quote($to, "/");
538 require_once('lib/plugin/WikiAdminSearchReplace.php');
539 $links = $oldpage->getBackLinks();
540 while ($linked_page = $links->next()) {
541 WikiPlugin_WikiAdminSearchReplace::replaceHelper
543 $linked_page->getName(),
544 $lookbehind.$from.$lookahead, $to,
547 // FIXME: Disabled to avoid recursive modification when renaming
548 // a page like 'PageFoo to 'PageFooTwo'
550 $links = $newpage->getBackLinks();
551 while ($linked_page = $links->next()) {
552 WikiPlugin_WikiAdminSearchReplace::replaceHelper
554 $linked_page->getName(),
555 $lookbehind.$from.$lookahead, $to,
560 if ($oldpage->exists() and ! $newpage->exists()) {
561 if ($result = $this->_backend->rename_page($from, $to)) {
562 // create a RecentChanges entry with explaining summary
563 $page = $this->getPage($to);
564 $current = $page->getCurrentRevision();
565 $meta = $current->_data;
566 $version = $current->getVersion();
567 $meta['summary'] = sprintf(_("renamed from %s"), $from);
568 unset($meta['mtime']); // force new date
569 $page->save($current->getPackedContent(), $version + 1, $meta);
571 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
572 // if a version 0 exists try it also.
573 $result = $this->_backend->rename_page($from, $to);
576 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
579 /* Generate notification emails? */
580 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
581 $notify = $this->get('notify');
582 if (!empty($notify) and is_array($notify)) {
583 include_once("lib/MailNotify.php");
584 $MailNotify = new MailNotify($from);
585 $MailNotify->onRenamePage ($this, $from, $to);
591 /** Get timestamp when database was last modified.
593 * @return string A string consisting of two integers,
594 * separated by a space. The first is the time in
595 * unix timestamp format, the second is a modification
596 * count for the database.
598 * The idea is that you can cast the return value to an
599 * int to get a timestamp, or you can use the string value
600 * as a good hash for the entire database.
602 function getTimestamp() {
603 $ts = $this->get('_timestamp');
604 return sprintf("%d %d", $ts[0], $ts[1]);
608 * Update the database timestamp.
612 $ts = $this->get('_timestamp');
613 $this->set('_timestamp', array(time(), $ts[1] + 1));
617 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
619 function get_db_version() {
620 return (float) $this->get('_db_version');
622 function set_db_version($ver) {
623 return $this->set('_db_version', (float)$ver);
627 * Access WikiDB global meta-data.
629 * NOTE: this is currently implemented in a hackish and
630 * not very efficient manner.
634 * @param string $key Which meta data to get.
635 * Some reserved meta-data keys are:
637 * <dt>'_timestamp' <dd> Data used by getTimestamp().
640 * @return scalar The requested value, or false if the requested data
644 if (!$key || $key[0] == '%')
647 * Hack Alert: We can use any page (existing or not) to store
648 * this data (as long as we always use the same one.)
650 $gd = $this->getPage('global_data');
651 $data = $gd->get('__global');
653 if ($data && isset($data[$key]))
660 * Set global meta-data.
662 * NOTE: this is currently implemented in a hackish and
663 * not very efficient manner.
668 * @param string $key Meta-data key to set.
669 * @param string $newval New value.
671 function set($key, $newval) {
672 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
673 if (!$key || $key[0] == '%')
676 $gd = $this->getPage('global_data');
677 $data = $gd->get('__global');
684 $data[$key] = $newval;
686 $gd->set('__global', $data);
689 /* TODO: these are really backend methods */
691 // SQL result: for simple select or create/update queries
692 // returns the database specific resource type
693 function genericSqlQuery($sql, $args=false) {
694 if (function_exists('debug_backtrace')) { // >= 4.3.0
695 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
697 trigger_error("no SQL database", E_USER_ERROR);
701 // SQL iter: for simple select or create/update queries
702 // returns the generic iterator object (count,next)
703 function genericSqlIter($sql, $field_list = NULL) {
704 if (function_exists('debug_backtrace')) { // >= 4.3.0
705 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
707 trigger_error("no SQL database", E_USER_ERROR);
711 // see backend upstream methods
712 // ADODB adds surrounding quotes, SQL not yet!
713 function quote ($s) {
719 if (!$request->_dbi) return false;
720 else return false; /* so far only needed for sql so false it.
721 later we have to check dba also */
724 function getParam($param) {
726 if (isset($DBParams[$param])) return $DBParams[$param];
727 elseif ($param == 'prefix') return '';
731 function getAuthParam($param) {
732 global $DBAuthParams;
733 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
734 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
735 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
742 * A base class which representing a wiki-page within a
745 * A WikiDB_Page contains a number (at least one) of
746 * WikiDB_PageRevisions.
750 function WikiDB_Page(&$wikidb, $pagename) {
751 $this->_wikidb = &$wikidb;
752 $this->_pagename = $pagename;
754 if (!(is_string($pagename) and $pagename != '')) {
755 if (function_exists("xdebug_get_function_stack")) {
756 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
757 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
758 printSimpleTrace(debug_backtrace());
760 trigger_error("empty pagename", E_USER_WARNING);
764 assert(is_string($pagename) and $pagename != '');
769 * Get the name of the wiki page.
773 * @return string The page name.
776 return $this->_pagename;
779 // To reduce the memory footprint for larger sets of pagelists,
780 // we don't cache the content (only true or false) and
781 // we purge the pagedata (_cached_html) also
783 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
784 $current = $this->getCurrentRevision(false);
785 if (!$current) return false;
786 return ! $current->hasDefaultContents();
790 * Delete an old revision of a WikiDB_Page.
792 * Deletes the specified revision of the page.
793 * It is a fatal error to attempt to delete the current revision.
797 * @param integer $version Which revision to delete. (You can also
798 * use a WikiDB_PageRevision object here.)
800 function deleteRevision($version) {
801 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
802 $backend = &$this->_wikidb->_backend;
803 $cache = &$this->_wikidb->_cache;
804 $pagename = &$this->_pagename;
806 $version = $this->_coerce_to_version($version);
810 $backend->lock(array('page','version'));
811 $latestversion = $cache->get_latest_version($pagename);
812 if ($latestversion && ($version == $latestversion)) {
813 $backend->unlock(array('page','version'));
814 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
815 $pagename), E_USER_ERROR);
819 $cache->delete_versiondata($pagename, $version);
820 $backend->unlock(array('page','version'));
824 * Delete a revision, or possibly merge it with a previous
828 * Suppose an author make a (major) edit to a page. Shortly
829 * after that the same author makes a minor edit (e.g. to fix
830 * spelling mistakes he just made.)
832 * Now some time later, where cleaning out old saved revisions,
833 * and would like to delete his minor revision (since there's
834 * really no point in keeping minor revisions around for a long
837 * Note that the text after the minor revision probably represents
838 * what the author intended to write better than the text after
839 * the preceding major edit.
841 * So what we really want to do is merge the minor edit with the
844 * We will only do this when:
846 * <li>The revision being deleted is a minor one, and
847 * <li>It has the same author as the immediately preceding revision.
850 function mergeRevision($version) {
851 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
852 $backend = &$this->_wikidb->_backend;
853 $cache = &$this->_wikidb->_cache;
854 $pagename = &$this->_pagename;
856 $version = $this->_coerce_to_version($version);
860 $backend->lock(array('version'));
861 $latestversion = $cache->get_latest_version($pagename);
862 if ($latestversion && $version == $latestversion) {
863 $backend->unlock(array('version'));
864 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
865 $pagename), E_USER_ERROR);
869 $versiondata = $cache->get_versiondata($pagename, $version, true);
871 // Not there? ... we're done!
872 $backend->unlock(array('version'));
876 if ($versiondata['is_minor_edit']) {
877 $previous = $backend->get_previous_version($pagename, $version);
879 $prevdata = $cache->get_versiondata($pagename, $previous);
880 if ($prevdata['author_id'] == $versiondata['author_id']) {
881 // This is a minor revision, previous version is
882 // by the same author. We will merge the
884 $cache->update_versiondata($pagename, $previous,
885 array('%content' => $versiondata['%content'],
886 '_supplanted' => $versiondata['_supplanted']));
891 $cache->delete_versiondata($pagename, $version);
892 $backend->unlock(array('version'));
897 * 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 hash $metadata Metadata for new revision.
910 * All values in the hash should be scalars (strings or integers).
912 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
914 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
915 * $version was incorrect, returns false
917 function createRevision($version, &$content, $metadata, $links) {
918 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
919 $backend = &$this->_wikidb->_backend;
920 $cache = &$this->_wikidb->_cache;
921 $pagename = &$this->_pagename;
922 $cache->invalidate_cache($pagename);
924 $backend->lock(array('version','page','recent','link','nonempty'));
926 $latestversion = $backend->get_latest_version($pagename);
927 $newversion = ($latestversion ? $latestversion : 0) + 1;
928 assert($newversion >= 1);
930 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
931 $backend->unlock(array('version','page','recent','link','nonempty'));
937 foreach ($data as $key => $val) {
938 if (empty($val) || $key[0] == '_' || $key[0] == '%')
942 assert(!empty($data['author']));
943 if (empty($data['author_id']))
944 @$data['author_id'] = $data['author'];
946 if (empty($data['mtime']))
947 $data['mtime'] = time();
949 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
950 // Ensure mtimes are monotonic.
951 $pdata = $cache->get_versiondata($pagename, $latestversion);
952 if ($data['mtime'] < $pdata['mtime']) {
953 trigger_error(sprintf(_("%s: Date of new revision is %s"),
954 $pagename,"'non-monotonic'"),
956 $data['orig_mtime'] = $data['mtime'];
957 $data['mtime'] = $pdata['mtime'];
960 // FIXME: use (possibly user specified) 'mtime' time or
962 $cache->update_versiondata($pagename, $latestversion,
963 array('_supplanted' => $data['mtime']));
966 $data['%content'] = &$content;
968 $cache->set_versiondata($pagename, $newversion, $data);
970 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
971 //':deleted' => empty($content)));
973 $backend->set_links($pagename, $links);
975 $backend->unlock(array('version','page','recent','link','nonempty'));
977 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
981 /** A higher-level interface to createRevision.
983 * This takes care of computing the links, and storing
984 * a cached version of the transformed wiki-text.
986 * @param string $wikitext The page content.
988 * @param int $version Version number for new revision.
989 * To ensure proper serialization of edits, $version must be
990 * exactly one higher than the current latest version.
991 * (You can defeat this check by setting $version to
992 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
994 * @param hash $meta Meta-data for new revision.
996 function save($wikitext, $version, $meta, $formatted = null) {
997 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
998 if (is_null($formatted))
999 $formatted = new TransformedText($this, $wikitext, $meta);
1000 $type = $formatted->getType();
1001 $meta['pagetype'] = $type->getName();
1002 $links = $formatted->getWikiPageLinks(); // linkto => relation
1003 $attributes = array();
1004 foreach ($links as $link) {
1005 if ($link['linkto'] === "" and !empty($link['relation'])) {
1006 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1009 $meta['attribute'] = $attributes;
1011 $backend = &$this->_wikidb->_backend;
1012 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1013 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1014 $this->set('_cached_html', $formatted->pack());
1016 // FIXME: probably should have some global state information
1017 // in the backend to control when to optimize.
1019 // We're doing this here rather than in createRevision because
1020 // postgresql can't optimize while locked.
1021 if (((int)DEBUG & _DEBUG_SQL)
1022 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1023 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1024 if ($backend->optimize()) {
1026 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1030 /* Generate notification emails? */
1031 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1032 // Save didn't fail because of concurrent updates.
1033 $notify = $this->_wikidb->get('notify');
1035 and is_array($notify)
1036 and !isa($GLOBALS['request'],'MockRequest'))
1038 include_once("lib/MailNotify.php");
1039 $MailNotify = new MailNotify($newrevision->getName());
1040 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1042 $newrevision->_transformedContent = $formatted;
1044 // more pagechange callbacks: (in a hackish manner for now)
1045 if (ENABLE_RECENTCHANGESBOX
1046 and empty($meta['is_minor_edit'])
1047 and !in_array($GLOBALS['request']->getArg('action'),
1048 array('loadfile','upgrade')))
1050 require_once("lib/WikiPlugin.php");
1051 $w = new WikiPluginLoader;
1052 $p = $w->getPlugin("RecentChangesCached", false);
1053 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1055 return $newrevision;
1059 * Get the most recent revision of a page.
1063 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1065 function getCurrentRevision ($need_content=true) {
1066 $backend = &$this->_wikidb->_backend;
1067 $cache = &$this->_wikidb->_cache;
1068 $pagename = &$this->_pagename;
1070 // Prevent deadlock in case of memory exhausted errors
1071 // Pure selection doesn't really need locking here.
1072 // sf.net bug#927395
1073 // I know it would be better to lock, but with lots of pages this deadlock is more
1074 // severe than occasionally get not the latest revision.
1075 // In spirit to wikiwiki: read fast, edit slower.
1077 $version = $cache->get_latest_version($pagename);
1078 // getRevision gets the content also!
1079 $revision = $this->getRevision($version, $need_content);
1080 //$backend->unlock();
1086 * Get a specific revision of a WikiDB_Page.
1090 * @param integer $version Which revision to get.
1092 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1093 * false if the requested revision does not exist in the {@link WikiDB}.
1094 * Note that version zero of any page always exists.
1096 function getRevision ($version, $need_content=true) {
1097 $cache = &$this->_wikidb->_cache;
1098 $pagename = &$this->_pagename;
1100 if (! $version or $version == -1) // 0 or false
1101 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1103 assert($version > 0);
1104 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1106 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1108 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1113 * Get previous page revision.
1115 * This method find the most recent revision before a specified
1120 * @param integer $version Find most recent revision before this version.
1121 * You can also use a WikiDB_PageRevision object to specify the $version.
1123 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1124 * requested revision does not exist in the {@link WikiDB}. Note that
1125 * unless $version is greater than zero, a revision (perhaps version zero,
1126 * the default revision) will always be found.
1128 function getRevisionBefore ($version=false, $need_content=true) {
1129 $backend = &$this->_wikidb->_backend;
1130 $pagename = &$this->_pagename;
1131 if ($version === false)
1132 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1134 $version = $this->_coerce_to_version($version);
1139 $previous = $backend->get_previous_version($pagename, $version);
1140 $revision = $this->getRevision($previous, $need_content);
1141 //$backend->unlock();
1147 * Get all revisions of the WikiDB_Page.
1149 * This does not include the version zero (default) revision in the
1150 * returned revision set.
1152 * @return WikiDB_PageRevisionIterator A
1153 * WikiDB_PageRevisionIterator containing all revisions of this
1154 * WikiDB_Page in reverse order by version number.
1156 function getAllRevisions() {
1157 $backend = &$this->_wikidb->_backend;
1158 $revs = $backend->get_all_revisions($this->_pagename);
1159 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1163 * Find pages which link to or are linked from a page.
1164 * relations: $backend->get_links is responsible to add the relation to the pagehash
1165 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1166 * if (isset($next['linkrelation']))
1170 * @param boolean $reversed Which links to find: true for backlinks (default).
1172 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1173 * all matching pages.
1175 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1176 $limit='', $exclude='', $want_relations=false)
1178 $backend = &$this->_wikidb->_backend;
1179 $result = $backend->get_links($this->_pagename, $reversed,
1180 $include_empty, $sortby, $limit, $exclude,
1182 return new WikiDB_PageIterator($this->_wikidb, $result,
1183 array('include_empty' => $include_empty,
1184 'sortby' => $sortby,
1186 'exclude' => $exclude,
1187 'want_relations'=> $want_relations));
1191 * All Links from other pages to this page.
1193 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1194 $want_relations=false)
1196 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1199 * Forward Links: All Links from this page to other pages.
1201 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1202 $want_relations=false)
1204 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1207 * Relations: All links from this page to other pages with relation <> 0.
1208 * is_a:=page or population:=number
1210 function getRelations($sortby='', $limit='', $exclude='') {
1211 $backend = &$this->_wikidb->_backend;
1212 $result = $backend->get_links($this->_pagename, false, true,
1213 $sortby, $limit, $exclude,
1215 // we do not care for the linked page versiondata, just the pagename and linkrelation
1216 return new WikiDB_PageIterator($this->_wikidb, $result,
1217 array('include_empty' => true,
1218 'sortby' => $sortby,
1220 'exclude' => $exclude,
1221 'want_relations'=> true));
1225 * possibly faster link existance check. not yet accelerated.
1227 function existLink($link, $reversed=false) {
1228 $backend = &$this->_wikidb->_backend;
1229 if (method_exists($backend,'exists_link'))
1230 return $backend->exists_link($this->_pagename, $link, $reversed);
1231 //$cache = &$this->_wikidb->_cache;
1232 // TODO: check cache if it is possible
1233 $iter = $this->getLinks($reversed, false);
1234 while ($page = $iter->next()) {
1235 if ($page->getName() == $link)
1242 /* Semantic relations are links with the relation pointing to another page,
1243 the so-called "RDF Triple".
1244 [San Diego] is%20a::city
1245 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1248 /* Semantic attributes for a page.
1249 [San Diego] population:=1,305,736
1250 Attributes are links with the relation pointing to another page.
1254 * Access WikiDB_Page non version-specific meta-data.
1258 * @param string $key Which meta data to get.
1259 * Some reserved meta-data keys are:
1261 * <dt>'date' <dd> Created as unixtime
1262 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1263 * <dt>'hits' <dd> Page hit counter.
1264 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1265 * In SQL stored now in an extra column.
1267 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1268 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1269 * E.g. "owner.users"
1270 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1271 * page-headers and content.
1272 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1273 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1276 * @return scalar The requested value, or false if the requested data
1279 function get($key) {
1280 $cache = &$this->_wikidb->_cache;
1281 $backend = &$this->_wikidb->_backend;
1282 if (!$key || $key[0] == '%')
1284 // several new SQL backends optimize this.
1285 if (!WIKIDB_NOCACHE_MARKUP
1286 and $key == '_cached_html'
1287 and method_exists($backend, 'get_cached_html'))
1289 return $backend->get_cached_html($this->_pagename);
1291 $data = $cache->get_pagedata($this->_pagename);
1292 return isset($data[$key]) ? $data[$key] : false;
1296 * Get all the page meta-data as a hash.
1298 * @return hash The page meta-data.
1300 function getMetaData() {
1301 $cache = &$this->_wikidb->_cache;
1302 $data = $cache->get_pagedata($this->_pagename);
1304 foreach ($data as $key => $val) {
1305 if (/*!empty($val) &&*/ $key[0] != '%')
1312 * Set page meta-data.
1317 * @param string $key Meta-data key to set.
1318 * @param string $newval New value.
1320 function set($key, $newval) {
1321 $cache = &$this->_wikidb->_cache;
1322 $backend = &$this->_wikidb->_backend;
1323 $pagename = &$this->_pagename;
1325 assert($key && $key[0] != '%');
1327 // several new SQL backends optimize this.
1328 if (!WIKIDB_NOCACHE_MARKUP
1329 and $key == '_cached_html'
1330 and method_exists($backend, 'set_cached_html'))
1332 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1333 return $backend->set_cached_html($pagename, $newval);
1336 $data = $cache->get_pagedata($pagename);
1338 if (!empty($newval)) {
1339 if (!empty($data[$key]) && $data[$key] == $newval)
1340 return; // values identical, skip update.
1343 if (empty($data[$key]))
1344 return; // values identical, skip update.
1347 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1348 $cache->update_pagedata($pagename, array($key => $newval));
1352 * Increase page hit count.
1354 * FIXME: IS this needed? Probably not.
1356 * This is a convenience function.
1357 * <pre> $page->increaseHitCount(); </pre>
1358 * is functionally identical to
1359 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1360 * but less expensive (ignores the pagadata string)
1362 * Note that this method may be implemented in more efficient ways
1363 * in certain backends.
1367 function increaseHitCount() {
1368 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; }
1369 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1370 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1372 @$newhits = $this->get('hits') + 1;
1373 $this->set('hits', $newhits);
1378 * Return a string representation of the WikiDB_Page
1380 * This is really only for debugging.
1384 * @return string Printable representation of the WikiDB_Page.
1386 function asString () {
1388 printf("[%s:%s\n", get_class($this), $this->getName());
1389 print_r($this->getMetaData());
1391 $strval = ob_get_contents();
1399 * @param integer_or_object $version_or_pagerevision
1400 * Takes either the version number (and int) or a WikiDB_PageRevision
1402 * @return integer The version number.
1404 function _coerce_to_version($version_or_pagerevision) {
1405 if (method_exists($version_or_pagerevision, "getContent"))
1406 $version = $version_or_pagerevision->getVersion();
1408 $version = (int) $version_or_pagerevision;
1410 assert($version >= 0);
1414 function isUserPage ($include_empty = true) {
1415 if (!$include_empty and !$this->exists()) return false;
1416 return $this->get('pref') ? true : false;
1419 // May be empty. Either the stored owner (/Chown), or the first authorized author
1420 function getOwner() {
1421 if ($owner = $this->get('owner'))
1423 // check all revisions forwards for the first author_id
1424 $backend = &$this->_wikidb->_backend;
1425 $pagename = &$this->_pagename;
1426 $latestversion = $backend->get_latest_version($pagename);
1427 for ($v=1; $v <= $latestversion; $v++) {
1428 $rev = $this->getRevision($v,false);
1429 if ($rev and $owner = $rev->get('author_id')) {
1436 // The authenticated author of the first revision or empty if not authenticated then.
1437 function getCreator() {
1438 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1442 // The authenticated author of the current revision.
1443 function getAuthor() {
1444 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1448 /* Semantic Web value, not stored in the links.
1449 * todo: unify with some unit knowledge
1451 function setAttribute($relation, $value) {
1452 $attr = $this->get('attributes');
1454 $attr = array($relation => $value);
1456 $attr[$relation] = $value;
1457 $this->set('attributes', $attr);
1460 function getAttribute($relation) {
1461 $meta = $this->get('attributes');
1465 return $meta[$relation];
1471 * This class represents a specific revision of a WikiDB_Page within
1474 * A WikiDB_PageRevision has read-only semantics. You may only create
1475 * new revisions (and delete old ones) --- you cannot modify existing
1478 class WikiDB_PageRevision
1480 //var $_transformedContent = false; // set by WikiDB_Page::save()
1482 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1483 $versiondata = false)
1485 $this->_wikidb = &$wikidb;
1486 $this->_pagename = $pagename;
1487 $this->_version = $version;
1488 $this->_data = $versiondata ? $versiondata : array();
1489 $this->_transformedContent = false; // set by WikiDB_Page::save()
1493 * Get the WikiDB_Page which this revision belongs to.
1497 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1499 function getPage() {
1500 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1504 * Get the version number of this revision.
1508 * @return integer The version number of this revision.
1510 function getVersion() {
1511 return $this->_version;
1515 * Determine whether this revision has defaulted content.
1517 * The default revision (version 0) of each page, as well as any
1518 * pages which are created with empty content have their content
1519 * defaulted to something like:
1521 * Describe [ThisPage] here.
1526 * @return boolean Returns true if the page has default content.
1528 function hasDefaultContents() {
1529 $data = &$this->_data;
1530 if (!isset($data['%content'])) return true;
1531 if ($data['%content'] === true) return false;
1532 return $data['%content'] === false or $data['%content'] === "";
1536 * Get the content as an array of lines.
1540 * @return array An array of lines.
1541 * The lines should contain no trailing white space.
1543 function getContent() {
1544 return explode("\n", $this->getPackedContent());
1548 * Get the pagename of the revision.
1552 * @return string pagename.
1554 function getPageName() {
1555 return $this->_pagename;
1557 function getName() {
1558 return $this->_pagename;
1562 * Determine whether revision is the latest.
1566 * @return boolean True iff the revision is the latest (most recent) one.
1568 function isCurrent() {
1569 if (!isset($this->_iscurrent)) {
1570 $page = $this->getPage();
1571 $current = $page->getCurrentRevision(false);
1572 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1574 return $this->_iscurrent;
1578 * Get the transformed content of a page.
1580 * @param string $pagetype Override the page-type of the revision.
1582 * @return object An XmlContent-like object containing the page transformed
1585 function getTransformedContent($pagetype_override=false) {
1586 $backend = &$this->_wikidb->_backend;
1588 if ($pagetype_override) {
1589 // Figure out the normal page-type for this page.
1590 $type = PageType::GetPageType($this->get('pagetype'));
1591 if ($type->getName() == $pagetype_override)
1592 $pagetype_override = false; // Not really an override...
1595 if ($pagetype_override) {
1596 // Overriden page type, don't cache (or check cache).
1597 return new TransformedText($this->getPage(),
1598 $this->getPackedContent(),
1599 $this->getMetaData(),
1600 $pagetype_override);
1603 $possibly_cache_results = true;
1605 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1606 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1607 // flush cache for this page.
1608 $page = $this->getPage();
1609 $page->set('_cached_html', ''); // ignored with !USECACHE
1611 $possibly_cache_results = false;
1613 elseif (USECACHE and !$this->_transformedContent) {
1615 if ($this->isCurrent()) {
1616 $page = $this->getPage();
1617 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1620 $possibly_cache_results = false;
1622 //$backend->unlock();
1625 if (!$this->_transformedContent) {
1626 $this->_transformedContent
1627 = new TransformedText($this->getPage(),
1628 $this->getPackedContent(),
1629 $this->getMetaData());
1631 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1632 // If we're still the current version, cache the transfomed page.
1634 if ($this->isCurrent()) {
1635 $page->set('_cached_html', $this->_transformedContent->pack());
1637 //$backend->unlock();
1641 return $this->_transformedContent;
1645 * Get the content as a string.
1649 * @return string The page content.
1650 * Lines are separated by new-lines.
1652 function getPackedContent() {
1653 $data = &$this->_data;
1655 if (empty($data['%content'])
1656 || (!$this->_wikidb->isWikiPage($this->_pagename)
1657 && $this->isCurrent())) {
1658 include_once('lib/InlineParser.php');
1660 // A feature similar to taglines at http://www.wlug.org.nz/
1661 // Lib from http://www.aasted.org/quote/
1662 if (defined('FORTUNE_DIR')
1663 and is_dir(FORTUNE_DIR)
1664 and in_array($GLOBALS['request']->getArg('action'),
1665 array('create','edit')))
1667 include_once("lib/fortune.php");
1668 $fortune = new Fortune();
1669 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1671 $quote = "<verbatim>\n"
1672 . str_replace("\n<br>","\n", $quote)
1673 . "</verbatim>\n\n";
1677 . sprintf(_("Describe %s here."),
1678 "[" . WikiEscape($this->_pagename) . "]");
1680 // Replace empty content with default value.
1681 return sprintf(_("Describe %s here."),
1682 "[" . WikiEscape($this->_pagename) . "]");
1685 // There is (non-default) content.
1686 assert($this->_version > 0);
1688 if (!is_string($data['%content'])) {
1689 // Content was not provided to us at init time.
1690 // (This is allowed because for some backends, fetching
1691 // the content may be expensive, and often is not wanted
1694 // In any case, now we need to get it.
1695 $data['%content'] = $this->_get_content();
1696 assert(is_string($data['%content']));
1699 return $data['%content'];
1702 function _get_content() {
1703 $cache = &$this->_wikidb->_cache;
1704 $pagename = $this->_pagename;
1705 $version = $this->_version;
1707 assert($version > 0);
1709 $newdata = $cache->get_versiondata($pagename, $version, true);
1711 assert(is_string($newdata['%content']));
1712 return $newdata['%content'];
1715 // else revision has been deleted... What to do?
1716 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1717 $version, $pagename);
1722 * Get meta-data for this revision.
1727 * @param string $key Which meta-data to access.
1729 * Some reserved revision meta-data keys are:
1731 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1732 * The 'mtime' meta-value is normally set automatically by the database
1733 * backend, but it may be specified explicitly when creating a new revision.
1735 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1736 * of a page must be monotonically increasing. If an attempt is
1737 * made to create a new revision with an mtime less than that of
1738 * the preceeding revision, the new revisions timestamp is force
1739 * to be equal to that of the preceeding revision. In that case,
1740 * the originally requested mtime is preserved in 'orig_mtime'.
1741 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1742 * This meta-value is <em>always</em> automatically maintained by the database
1743 * backend. (It is set from the 'mtime' meta-value of the superceding
1744 * revision.) '_supplanted' has a value of 'false' for the current revision.
1746 * FIXME: this could be refactored:
1748 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1750 * <dd> Authenticated author of a page. This is used to identify
1751 * the distinctness of authors when cleaning old revisions from
1753 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1754 * <dt> 'summary' <dd> Short change summary entered by page author.
1757 * Meta-data keys must be valid C identifers (they have to start with a letter
1758 * or underscore, and can contain only alphanumerics and underscores.)
1760 * @return string The requested value, or false if the requested value
1763 function get($key) {
1764 if (!$key || $key[0] == '%')
1766 $data = &$this->_data;
1767 return isset($data[$key]) ? $data[$key] : false;
1771 * Get all the revision page meta-data as a hash.
1773 * @return hash The revision meta-data.
1775 function getMetaData() {
1777 foreach ($this->_data as $key => $val) {
1778 if (!empty($val) && $key[0] != '%')
1786 * Return a string representation of the revision.
1788 * This is really only for debugging.
1792 * @return string Printable representation of the WikiDB_Page.
1794 function asString () {
1796 printf("[%s:%d\n", get_class($this), $this->get('version'));
1797 print_r($this->_data);
1798 echo $this->getPackedContent() . "\n]\n";
1799 $strval = ob_get_contents();
1807 * Class representing a sequence of WikiDB_Pages.
1808 * TODO: Enhance to php5 iterators
1810 * apply filters for options like 'sortby', 'limit', 'exclude'
1811 * for simple queries like titleSearch, where the backend is not ready yet.
1813 class WikiDB_PageIterator
1815 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1816 $this->_iter = $iter; // a WikiDB_backend_iterator
1817 $this->_wikidb = &$wikidb;
1818 $this->_options = $options;
1822 return $this->_iter->count();
1826 * Get next WikiDB_Page in sequence.
1830 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1833 if ( ! ($next = $this->_iter->next()) )
1836 $pagename = &$next['pagename'];
1837 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1838 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1839 $pagename = $pagename['linkto'];
1841 $pagename = strval($pagename);*/
1842 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1845 if (isset($next['linkrelation'])
1846 or isset($next['pagedata']['linkrelation'])) return false;
1847 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1851 // There's always hits, but we cache only if more
1852 // (well not with file, cvs and dba)
1853 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1854 $this->_wikidb->_cache->cache_data($next);
1855 // cache existing page id's since we iterate over all links in GleanDescription
1856 // and need them later for LinkExistingWord
1857 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1858 and !$this->_options['include_empty'] and isset($next['id'])) {
1859 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1861 $page = new WikiDB_Page($this->_wikidb, $pagename);
1862 if (isset($next['linkrelation']))
1863 $page->set('linkrelation', $next['linkrelation']);
1864 if (isset($next['score']))
1865 $page->score = $next['score'];
1870 * Release resources held by this iterator.
1872 * The iterator may not be used after free() is called.
1874 * There is no need to call free(), if next() has returned false.
1875 * (I.e. if you iterate through all the pages in the sequence,
1876 * you do not need to call free() --- you only need to call it
1877 * if you stop before the end of the iterator is reached.)
1882 $this->_iter->free();
1885 $this->_iter->reset();
1887 function asArray() {
1889 while ($page = $this->next())
1896 * Apply filters for options like 'sortby', 'limit', 'exclude'
1897 * for simple queries like titleSearch, where the backend is not ready yet.
1898 * Since iteration is usually destructive for SQL results,
1899 * we have to generate a copy.
1901 function applyFilters($options = false) {
1902 if (!$options) $options = $this->_options;
1903 if (isset($options['sortby'])) {
1905 /* this is destructive */
1906 while ($page = $this->next())
1907 $result[] = $page->getName();
1908 $this->_doSort($array, $options['sortby']);
1910 /* the rest is not destructive.
1911 * reconstruct a new iterator
1913 $pagenames = array(); $i = 0;
1914 if (isset($options['limit']))
1915 $limit = $options['limit'];
1918 if (isset($options['exclude']))
1919 $exclude = $options['exclude'];
1920 if (is_string($exclude) and !is_array($exclude))
1921 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1922 foreach($array as $pagename) {
1923 if ($limit and $i++ > $limit)
1924 return new WikiDB_Array_PageIterator($pagenames);
1925 if (!empty($exclude) and !in_array($pagename, $exclude))
1926 $pagenames[] = $pagename;
1927 elseif (empty($exclude))
1928 $pagenames[] = $pagename;
1930 return new WikiDB_Array_PageIterator($pagenames);
1934 function _doSort(&$array, $sortby) {
1935 $sortby = PageList::sortby($sortby, 'init');
1936 if ($sortby == '+pagename')
1937 sort($array, SORT_STRING);
1938 elseif ($sortby == '-pagename')
1939 rsort($array, SORT_STRING);
1946 * A class which represents a sequence of WikiDB_PageRevisions.
1947 * TODO: Enhance to php5 iterators
1949 class WikiDB_PageRevisionIterator
1951 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1952 $this->_revisions = $revisions;
1953 $this->_wikidb = &$wikidb;
1954 $this->_options = $options;
1958 return $this->_revisions->count();
1962 * Get next WikiDB_PageRevision in sequence.
1966 * @return WikiDB_PageRevision
1967 * The next WikiDB_PageRevision in the sequence.
1970 if ( ! ($next = $this->_revisions->next()) )
1973 //$this->_wikidb->_cache->cache_data($next);
1975 $pagename = $next['pagename'];
1976 $version = $next['version'];
1977 $versiondata = $next['versiondata'];
1979 if (!(is_string($pagename) and $pagename != '')) {
1980 trigger_error("empty pagename",E_USER_WARNING);
1983 } else assert(is_string($pagename) and $pagename != '');
1985 if (!is_array($versiondata)) {
1986 trigger_error("empty versiondata",E_USER_WARNING);
1989 } else assert(is_array($versiondata));
1991 if (!($version > 0)) {
1992 trigger_error("invalid version",E_USER_WARNING);
1995 } else assert($version > 0);
1997 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2002 * Release resources held by this iterator.
2004 * The iterator may not be used after free() is called.
2006 * There is no need to call free(), if next() has returned false.
2007 * (I.e. if you iterate through all the revisions in the sequence,
2008 * you do not need to call free() --- you only need to call it
2009 * if you stop before the end of the iterator is reached.)
2014 $this->_revisions->free();
2017 function asArray() {
2019 while ($rev = $this->next())
2028 class WikiDB_Array_PageIterator
2030 function WikiDB_Array_PageIterator($pagenames) {
2032 $this->_dbi = $request->getDbh();
2033 $this->_pages = $pagenames;
2034 reset($this->_pages);
2037 $c = current($this->_pages);
2038 next($this->_pages);
2039 return $c !== false ? $this->_dbi->getPage($c) : false;
2042 return count($this->_pages);
2045 reset($this->_pages);
2048 function asArray() {
2049 reset($this->_pages);
2050 return $this->_pages;
2054 class WikiDB_Array_generic_iter
2056 function WikiDB_Array_generic_iter($result) {
2057 // $result may be either an array or a query result
2058 if (is_array($result)) {
2059 $this->_array = $result;
2060 } elseif (is_object($result)) {
2061 $this->_array = $result->asArray();
2063 $this->_array = array();
2065 if (!empty($this->_array))
2066 reset($this->_array);
2069 $c = current($this->_array);
2070 next($this->_array);
2071 return $c !== false ? $c : false;
2074 return count($this->_array);
2077 reset($this->_array);
2080 function asArray() {
2081 if (!empty($this->_array))
2082 reset($this->_array);
2083 return $this->_array;
2088 * Data cache used by WikiDB.
2090 * FIXME: Maybe rename this to caching_backend (or some such).
2096 // FIXME: beautify versiondata cache. Cache only limited data?
2098 function WikiDB_cache (&$backend) {
2099 $this->_backend = &$backend;
2101 $this->_pagedata_cache = array();
2102 $this->_versiondata_cache = array();
2103 array_push ($this->_versiondata_cache, array());
2104 $this->_glv_cache = array();
2105 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2107 if (isset($GLOBALS['request']->_dbi))
2108 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2112 $this->_pagedata_cache = array();
2113 $this->_versiondata_cache = array();
2114 $this->_glv_cache = array();
2115 $this->_id_cache = array();
2118 function get_pagedata($pagename) {
2119 assert(is_string($pagename) && $pagename != '');
2121 $cache = &$this->_pagedata_cache;
2122 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2123 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2124 if (empty($cache[$pagename]))
2125 $cache[$pagename] = array();
2127 return $cache[$pagename];
2129 return $this->_backend->get_pagedata($pagename);
2133 function update_pagedata($pagename, $newdata) {
2134 assert(is_string($pagename) && $pagename != '');
2135 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2137 $this->_backend->update_pagedata($pagename, $newdata);
2140 if (!empty($this->_pagedata_cache[$pagename])
2141 and is_array($this->_pagedata_cache[$pagename]))
2143 $cachedata = &$this->_pagedata_cache[$pagename];
2144 foreach($newdata as $key => $val)
2145 $cachedata[$key] = $val;
2147 $this->_pagedata_cache[$pagename] = $newdata;
2151 function invalidate_cache($pagename) {
2152 unset ($this->_pagedata_cache[$pagename]);
2153 unset ($this->_versiondata_cache[$pagename]);
2154 unset ($this->_glv_cache[$pagename]);
2155 unset ($this->_id_cache[$pagename]);
2156 //unset ($this->_backend->_page_data);
2159 function delete_page($pagename) {
2160 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2161 $result = $this->_backend->delete_page($pagename);
2162 $this->invalidate_cache($pagename);
2166 function purge_page($pagename) {
2167 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2168 $result = $this->_backend->purge_page($pagename);
2169 $this->invalidate_cache($pagename);
2173 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2174 function cache_data($data) {
2176 //if (isset($data['pagedata']))
2177 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2180 function get_versiondata($pagename, $version, $need_content = false) {
2181 // FIXME: Seriously ugly hackage
2183 if (USECACHE) { //temporary - for debugging
2184 assert(is_string($pagename) && $pagename != '');
2185 // There is a bug here somewhere which results in an assertion failure at line 105
2186 // of ArchiveCleaner.php It goes away if we use the next line.
2187 //$need_content = true;
2188 $nc = $need_content ? '1':'0';
2189 $cache = &$this->_versiondata_cache;
2190 if (!isset($cache[$pagename][$version][$nc])
2191 || !(is_array ($cache[$pagename]))
2192 || !(is_array ($cache[$pagename][$version])))
2194 $cache[$pagename][$version][$nc] =
2195 $this->_backend->get_versiondata($pagename, $version, $need_content);
2197 // If we have retrieved all data, we may as well set the cache for
2198 // $need_content = false
2200 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2203 $vdata = $cache[$pagename][$version][$nc];
2205 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2208 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2209 if (empty($this->_pagedata_cache))
2210 $this->_pagedata_cache = array();
2211 /* 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 */
2212 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2217 function set_versiondata($pagename, $version, $data) {
2218 //unset($this->_versiondata_cache[$pagename][$version]);
2220 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2221 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2223 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2224 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2225 // Is this necessary?
2226 unset($this->_glv_cache[$pagename]);
2229 function update_versiondata($pagename, $version, $data) {
2230 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2231 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2233 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2235 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2236 // Is this necessary?
2237 unset($this->_glv_cache[$pagename]);
2240 function delete_versiondata($pagename, $version) {
2241 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2242 $new = $this->_backend->delete_versiondata($pagename, $version);
2243 if (isset($this->_versiondata_cache[$pagename][$version]))
2244 unset ($this->_versiondata_cache[$pagename][$version]);
2245 // dirty latest version cache only if latest version gets deleted
2246 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2247 unset ($this->_glv_cache[$pagename]);
2250 function get_latest_version($pagename) {
2252 assert (is_string($pagename) && $pagename != '');
2253 $cache = &$this->_glv_cache;
2254 if (!isset($cache[$pagename])) {
2255 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2256 if (empty($cache[$pagename]))
2257 $cache[$pagename] = 0;
2259 return $cache[$pagename];
2261 return $this->_backend->get_latest_version($pagename);
2266 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2270 $stamp = strftime("%y%m%d-%H%M%S");
2271 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2272 register_shutdown_function("_sql_debuglog_shutdown_function");
2273 } elseif ($shutdown) {
2277 if ($newline) fputs($fp, "[$i++] $msg");
2278 else fwrite($fp, $msg);
2281 function _sql_debuglog_shutdown_function() {
2282 _sql_debuglog('',false,true);
2288 // c-basic-offset: 4
2289 // c-hanging-comment-ender-p: nil
2290 // indent-tabs-mode: nil