2 require_once 'lib/PageType.php';
5 * The classes in the file define the interface to the
9 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
10 * Minor enhancements by Reini Urban
14 * Force the creation of a new revision.
15 * @see WikiDB_Page::createRevision()
17 if (!defined('WIKIDB_FORCE_CREATE'))
18 define('WIKIDB_FORCE_CREATE', -1);
21 * Abstract base class for the database used by PhpWiki.
23 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
24 * turn contain <tt>WikiDB_PageRevision</tt>s.
26 * Conceptually a <tt>WikiDB</tt> contains all possible
27 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
28 * Since all possible pages are already contained in a WikiDB, a call
29 * to WikiDB::getPage() will never fail (barring bugs and
30 * e.g. filesystem or SQL database problems.)
32 * Also each <tt>WikiDB_Page</tt> always contains at least one
33 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
34 * [PageName] here."). This default content has a version number of
37 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
38 * only create new revisions or delete old ones --- one can not modify
39 * an existing revision.
44 * Open a WikiDB database.
46 * This is a static member function. This function inspects its
47 * arguments to determine the proper subclass of WikiDB to
48 * instantiate, and then it instantiates it.
50 * @param array $dbparams Database configuration parameters (hash).
51 * Some pertinent parameters are:
54 * <dd> The back-end type. Current supported types are:
57 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
58 * library. (More stable and conservative)
60 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
62 * <dd> Dba based backend. The default and by far the fastest.
70 * <dd> (Used by the SQL and ADODB backends.)
71 * The DSN specifying which database to connect to.
74 * <dd> Prefix to be prepended to database tables (and file names).
77 * <dd> (Used by the dba backend.)
78 * Which directory db files reside in.
81 * <dd> Used only by the dba backend so far.
82 * And: When optimizing mysql it closes timed out mysql processes.
83 * otherwise only used for dba: Timeout in seconds for opening (and
84 * obtaining lock) on the dbm file.
87 * <dd> (Used by the dba backend.)
89 * Which dba handler to use. Good choices are probably either
93 * <dd> Either set by config.ini: READONLY = true or detected automatically
94 * when a database can be read but cannot be updated.
97 * @return WikiDB A WikiDB object.
99 static public function open($dbparams)
101 $dbtype = $dbparams{'dbtype'};
102 include_once("lib/WikiDB/$dbtype.php");
104 $class = 'WikiDB_' . $dbtype;
105 return new $class($dbparams);
111 function __construct(&$backend, $dbparams)
113 $this->_backend =& $backend;
114 // don't do the following with the auth_dsn!
115 if (isset($dbparams['auth_dsn'])) return;
117 $this->_cache = new WikiDB_cache($backend);
118 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
120 // If the database doesn't yet have a timestamp, initialize it now.
121 if ($this->get('_timestamp') === false)
125 if ((int)DEBUG & _DEBUG_SQL) {
126 $this->_backend->check();
128 // might be changed when opening the database fails
129 $this->readonly = defined("READONLY") ? READONLY : false;
133 * Close database connection.
135 * The database may no longer be used after it is closed.
137 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
138 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
139 * which have been obtained from it.
141 public function close()
143 $this->_backend->close();
144 $this->_cache->close();
148 * Get a WikiDB_Page from a WikiDB.
150 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
151 * therefore this method never fails.
153 * @param string $pagename Which page to get.
154 * @return WikiDB_Page The requested WikiDB_Page.
156 public function getPage($pagename)
158 static $error_displayed = false;
159 $pagename = (string)$pagename;
161 if ($pagename === '') {
162 if ($error_displayed) return false;
163 $error_displayed = true;
164 if (function_exists("xdebug_get_function_stack"))
165 var_dump(xdebug_get_function_stack());
166 trigger_error("empty pagename", E_USER_WARNING);
170 assert($pagename != '');
172 return new WikiDB_Page($this, $pagename);
176 * Determine whether page exists (in non-default form).
179 * $is_page = $dbi->isWikiPage($pagename);
183 * $page = $dbi->getPage($pagename);
184 * $current = $page->getCurrentRevision();
185 * $is_page = ! $current->hasDefaultContents();
187 * however isWikiPage may be implemented in a more efficient
188 * manner in certain back-ends.
190 * @param string $pagename string Which page to check.
191 * @return boolean True if the page actually exists with
192 * non-default contents in the WikiDataBase.
194 public function isWikiPage($pagename)
196 $page = $this->getPage($pagename);
197 return ($page and $page->exists());
201 * Delete page from the WikiDB.
203 * Deletes the page from the WikiDB with the possibility to revert and diff.
204 * //Also resets all page meta-data to the default values.
206 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
208 * @param string $pagename Name of page to delete.
212 public function deletePage($pagename)
214 if (!empty($this->readonly)) {
215 trigger_error("readonly database", E_USER_WARNING);
218 // don't create empty revisions of already purged pages.
219 if ($this->_backend->get_latest_version($pagename))
220 $result = $this->_cache->delete_page($pagename);
224 /* Generate notification emails */
225 if (defined('ENABLE_MAILNOTIFY') and ENABLE_MAILNOTIFY) {
226 include_once 'lib/MailNotify.php';
227 $MailNotify = new MailNotify($pagename);
228 $MailNotify->onDeletePage($this, $pagename);
231 //How to create a RecentChanges entry with explaining summary? Dynamically
233 $page = $this->getPage($pagename);
234 $current = $page->getCurrentRevision();
235 $meta = $current->_data;
236 $version = $current->getVersion();
237 $meta['summary'] = _("removed");
238 $page->save($current->getPackedContent(), $version + 1, $meta);
244 * Completely remove the page from the WikiDB, without undo possibility.
245 * @param string $pagename Name of page to delete.
249 public function purgePage($pagename)
251 if (!empty($this->readonly)) {
252 trigger_error("readonly database", E_USER_WARNING);
255 $result = $this->_cache->purge_page($pagename);
256 $this->deletePage($pagename); // just for the notification
261 * Retrieve all pages.
263 * Gets the set of all pages with non-default contents.
265 * @param bool $include_empty Optional. Normally pages whose most
266 * recent revision has empty content are considered to be
267 * non-existant. Unless $include_defaulted is set to true, those
268 * pages will not be returned.
269 * @param string $sortby Optional. "+-column,+-column2".
270 * If false the result is faster in natural order.
271 * @param string $limit Optional. Encoded as "$offset,$count".
272 * $offset defaults to 0.
273 * @param string $exclude Optional comma-separated list of pagenames.
275 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
276 * in the WikiDB which have non-default contents.
278 public function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
280 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
282 return new WikiDB_PageIterator($this, $result,
283 array('include_empty' => $include_empty,
284 'exclude' => $exclude,
285 'limit_by_db' => $result->_options['limit_by_db'],
286 'limit' => $result->limit()));
290 * @param boolean $include_empty If true include also empty pages
291 * @param string $exclude: comma-separated list of pagenames.
292 * TBD: array of pagenames
296 public function numPages($include_empty = false, $exclude = '')
298 if (method_exists($this->_backend, 'numPages'))
299 // FIXME: currently are all args ignored.
300 $count = $this->_backend->numPages($include_empty, $exclude);
302 // FIXME: exclude ignored.
303 $iter = $this->getAllPages($include_empty, false, false, $exclude);
304 $count = $iter->count();
313 * Search for pages containing (or not containing) certain words
316 * Pages are returned in alphabetical order whenever it is
317 * practical to do so.
318 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
320 * @param TextSearchQuery $search A TextSearchQuery object
321 * @param string $sortby Optional. "+-column,+-column2".
322 * If false the result is faster in natural order.
323 * @param string $limit Optional. Encoded as "$offset,$count".
324 * $offset defaults to 0.
325 * @param string $exclude Optional comma-separated list of pagenames.
326 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
327 * @see TextSearchQuery
329 public function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
331 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
332 $options = array('exclude' => $exclude,
334 //if (isset($result->_count)) $options['count'] = $result->_count;
335 return new WikiDB_PageIterator($this, $result, $options);
341 * Search for pages containing (or not containing) certain words
342 * in their entire text (this includes the page content and the
345 * Pages are returned in alphabetical order whenever it is
346 * practical to do so.
347 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
349 * @param TextSearchQuery $search A TextSearchQuery object.
350 * @param string $sortby Optional. "+-column,+-column2".
351 * If false the result is faster in natural order.
352 * @param string $limit Optional. Encoded as "$offset,$count".
353 * $offset defaults to 0.
354 * @param string $exclude Optional comma-separated list of pagenames.
355 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
356 * @see TextSearchQuery
358 public function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
360 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
361 return new WikiDB_PageIterator($this, $result,
362 array('exclude' => $exclude,
364 'stoplisted' => $result->stoplisted
369 * Find the pages with the greatest hit counts.
371 * Pages are returned in reverse order by hit count.
373 * @param int $limit The maximum number of pages to return.
374 * Set $limit to zero to return all pages. If $limit < 0, pages will
375 * be sorted in decreasing order of popularity.
376 * @param string $sortby Optional. "+-column,+-column2".
377 * If false the result is faster in natural order.
379 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
382 public function mostPopular($limit = 20, $sortby = '-hits')
384 $result = $this->_backend->most_popular($limit, $sortby);
385 return new WikiDB_PageIterator($this, $result);
389 * Find recent page revisions.
391 * Revisions are returned in reverse order by creation time.
393 * @param array $params This hash is used to specify various optional
397 * <dd> (integer) At most this many revisions will be returned.
399 * <dd> (integer) Only revisions since this time (unix-timestamp)
401 * <dt> include_minor_revisions
402 * <dd> (boolean) Also include minor revisions. (Default is not to.)
403 * <dt> exclude_major_revisions
404 * <dd> (boolean) Don't include non-minor revisions.
405 * (Exclude_major_revisions implies include_minor_revisions.)
406 * <dt> include_all_revisions
407 * <dd> (boolean) Return all matching revisions for each page.
408 * Normally only the most recent matching revision is returned
412 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
413 * containing the matching revisions.
415 public function mostRecent($params = array())
417 $result = $this->_backend->most_recent($params);
418 return new WikiDB_PageRevisionIterator($this, $result);
422 * @param string $exclude_from
423 * @param string $exclude
424 * @param string $sortby Optional. "+-column,+-column2".
425 * If false the result is faster in natural order.
426 * @param string $limit Optional. Encoded as "$offset,$count".
427 * $offset defaults to 0.
428 * @return Iterator A generic iterator containing rows of
429 * (duplicate) pagename, wantedfrom.
431 public function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
433 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
437 * Generic interface to the link table. Esp. useful to search for rdf triples as in
438 * SemanticSearch and ListRelations.
440 * @param object $pages A TextSearchQuery object.
441 * @param object $search A TextSearchQuery object.
442 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
443 * linktype parameter:
446 * <dd> search for simple out-links
448 * <dd> in-links, i.e BackLinks
450 * <dd> the first part in a <>::<> link
452 * <dd> the first part in a <>:=<> link
454 * @param mixed $relation An optional TextSearchQuery to match the
455 * relation name. Ignored on simple in-out links.
457 * @return Iterator A generic iterator containing links to pages or values.
458 * hash of "pagename", "linkname", "linkvalue.
460 public function linkSearch($pages, $search, $linktype, $relation = false)
462 return $this->_backend->link_search($pages, $search, $linktype, $relation);
466 * Return a simple list of all defined relations (and attributes), mainly
467 * for the SemanticSearch autocompletion.
469 * @param bool $also_attributes
470 * @param bool $only_attributes
471 * @param bool $sorted
472 * @return array of strings
474 public function listRelations($also_attributes = false, $only_attributes = false, $sorted = true)
476 if (method_exists($this->_backend, "list_relations"))
477 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
478 // dumb, slow fallback. no iter, so simply define it here.
479 $relations = array();
480 $iter = $this->getAllPages();
481 while ($page = $iter->next()) {
482 $reliter = $page->getRelations();
484 while ($rel = $reliter->next()) {
485 // if there's no pagename it's an attribute
486 $names[] = $rel->getName();
488 $relations = array_merge($relations, $names);
500 * Call the appropriate backend method.
502 * @param string $from Page to rename
503 * @param string $to New name
504 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
505 * @return boolean true or false
507 public function renamePage($from, $to, $updateWikiLinks = false)
509 if (!empty($this->readonly)) {
510 trigger_error("readonly database", E_USER_WARNING);
513 assert(is_string($from) && $from != '');
514 assert(is_string($to) && $to != '');
516 if (method_exists($this->_backend, 'rename_page')) {
517 $oldpage = $this->getPage($from);
518 $newpage = $this->getPage($to);
519 //update all WikiLinks in existing pages
520 //non-atomic! i.e. if rename fails the links are not undone
521 if ($updateWikiLinks) {
522 $lookbehind = "/(?<=[\W:])\Q";
523 $lookahead = "\E(?=[\W:])/";
524 require_once 'lib/plugin/WikiAdminSearchReplace.php';
525 $links = $oldpage->getBackLinks();
526 while ($linked_page = $links->next()) {
527 WikiPlugin_WikiAdminSearchReplace::replaceHelper
529 $linked_page->getName(),
530 $lookbehind . $from . $lookahead, $to,
533 // FIXME: Disabled to avoid recursive modification when renaming
534 // a page like 'PageFoo to 'PageFooTwo'
536 $links = $newpage->getBackLinks();
537 while ($linked_page = $links->next()) {
538 WikiPlugin_WikiAdminSearchReplace::replaceHelper
540 $linked_page->getName(),
541 $lookbehind . $from . $lookahead, $to,
546 if ($oldpage->exists() and !$newpage->exists()) {
547 if ($result = $this->_backend->rename_page($from, $to)) {
548 // create a RecentChanges entry with explaining summary
549 $page = $this->getPage($to);
550 $current = $page->getCurrentRevision();
551 $meta = $current->_data;
552 $version = $current->getVersion();
553 $meta['summary'] = sprintf(_("renamed from %s"), $from);
554 unset($meta['mtime']); // force new date
555 $page->save($current->getPackedContent(), $version + 1, $meta);
557 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
558 // if a version 0 exists try it also.
559 $result = $this->_backend->rename_page($from, $to);
562 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
565 /* Generate notification emails? */
566 if ($result and ENABLE_MAILNOTIFY and !is_a($GLOBALS['request'], 'MockRequest')) {
567 $notify = $this->get('notify');
568 if (!empty($notify) and is_array($notify)) {
569 include_once 'lib/MailNotify.php';
570 $MailNotify = new MailNotify($from);
571 $MailNotify->onRenamePage($this, $from, $to);
577 /** Get timestamp when database was last modified.
579 * @return string A string consisting of two integers,
580 * separated by a space. The first is the time in
581 * unix timestamp format, the second is a modification
582 * count for the database.
584 * The idea is that you can cast the return value to an
585 * int to get a timestamp, or you can use the string value
586 * as a good hash for the entire database.
588 function getTimestamp()
590 $ts = $this->get('_timestamp');
591 return sprintf("%d %d", $ts[0], $ts[1]);
595 * Update the database timestamp.
600 $ts = $this->get('_timestamp');
601 $this->set('_timestamp', array(time(), $ts[1] + 1));
605 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
607 function get_db_version()
609 return (float)$this->get('_db_version');
612 function set_db_version($ver)
614 $this->set('_db_version', (float)$ver);
618 * Access WikiDB global meta-data.
620 * NOTE: this is currently implemented in a hackish and
621 * not very efficient manner.
623 * @param string $key Which meta data to get.
624 * Some reserved meta-data keys are:
626 * <dt>'_timestamp' <dd> Data used by getTimestamp().
629 * @return mixed The requested value, or false if the requested data
632 public function get($key)
634 if (!$key || $key[0] == '%')
637 * Hack Alert: We can use any page (existing or not) to store
638 * this data (as long as we always use the same one.)
640 $gd = $this->getPage('global_data');
641 $data = $gd->get('__global');
643 if ($data && isset($data[$key]))
650 * Set global meta-data.
652 * NOTE: this is currently implemented in a hackish and
653 * not very efficient manner.
657 * @param string $key Meta-data key to set.
658 * @param string $newval New value.
660 public function set($key, $newval)
662 if (!empty($this->readonly)) {
663 trigger_error("readonly database", E_USER_WARNING);
666 if (!$key || $key[0] == '%')
669 $gd = $this->getPage('global_data');
670 $data = $gd->get('__global');
677 $data[$key] = $newval;
679 $gd->set('__global', $data);
682 /* TODO: these are really backend methods */
684 // SQL result: for simple select or create/update queries
685 // returns the database specific resource type
686 function genericSqlQuery($sql, $args = false)
689 printSimpleTrace(debug_backtrace());
691 trigger_error("no SQL database", E_USER_ERROR);
695 // SQL iter: for simple select or create/update queries
696 // returns the generic iterator object (count,next)
697 function genericSqlIter($sql, $field_list = NULL)
700 printSimpleTrace(debug_backtrace());
702 trigger_error("no SQL database", E_USER_ERROR);
706 // see backend upstream methods
707 // ADODB adds surrounding quotes, SQL not yet!
716 if (!$request->_dbi) return false;
717 else return false; /* so far only needed for sql so false it.
718 later we have to check dba also */
721 function getParam($param)
724 if (isset($DBParams[$param])) return $DBParams[$param];
725 elseif ($param == 'prefix') return ''; else return false;
728 function getAuthParam($param)
730 global $DBAuthParams;
731 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
732 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false;
737 * A base class which representing a wiki-page within a
740 * A WikiDB_Page contains a number (at least one) of
741 * WikiDB_PageRevisions.
745 function WikiDB_Page(&$wikidb, $pagename)
747 $this->_wikidb = &$wikidb;
748 $this->_pagename = $pagename;
750 if (!(is_string($pagename) and $pagename != '')) {
751 if (function_exists("xdebug_get_function_stack")) {
752 echo "xdebug_get_function_stack(): ";
753 var_dump(xdebug_get_function_stack());
755 printSimpleTrace(debug_backtrace());
757 trigger_error("empty pagename", E_USER_WARNING);
761 assert(is_string($pagename) and $pagename != '');
766 * Get the name of the wiki page.
768 * @return string The page name.
770 public function getName()
772 return $this->_pagename;
775 // To reduce the memory footprint for larger sets of pagelists,
776 // we don't cache the content (only true or false) and
777 // we purge the pagedata (_cached_html) also
780 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
781 $current = $this->getCurrentRevision(false);
782 if (!$current) return false;
783 return !$current->hasDefaultContents();
787 * Delete an old revision of a WikiDB_Page.
789 * Deletes the specified revision of the page.
790 * It is a fatal error to attempt to delete the current revision.
792 * @param integer $version Which revision to delete. (You can also
793 * use a WikiDB_PageRevision object here.)
795 public function deleteRevision($version)
797 if ($this->_wikidb->readonly) {
798 trigger_error("readonly database", E_USER_WARNING);
801 $backend = &$this->_wikidb->_backend;
802 $cache = &$this->_wikidb->_cache;
803 $pagename = &$this->_pagename;
805 $version = $this->_coerce_to_version($version);
809 $backend->lock(array('page', 'version'));
810 $latestversion = $cache->get_latest_version($pagename);
811 if ($latestversion && ($version == $latestversion)) {
812 $backend->unlock(array('page', 'version'));
813 trigger_error(sprintf("Attempt to delete most recent revision of “%s”",
814 $pagename), E_USER_ERROR);
818 $cache->delete_versiondata($pagename, $version);
819 $backend->unlock(array('page', 'version'));
823 * Delete a revision, or possibly merge it with a previous
827 * Suppose an author make a (major) edit to a page. Shortly
828 * after that the same author makes a minor edit (e.g. to fix
829 * spelling mistakes he just made.)
831 * Now some time later, where cleaning out old saved revisions,
832 * and would like to delete his minor revision (since there's
833 * really no point in keeping minor revisions around for a long
836 * Note that the text after the minor revision probably represents
837 * what the author intended to write better than the text after
838 * the preceding major edit.
840 * So what we really want to do is merge the minor edit with the
843 * We will only do this when:
845 * <li>The revision being deleted is a minor one, and
846 * <li>It has the same author as the immediately preceding revision.
849 function mergeRevision($version)
851 if ($this->_wikidb->readonly) {
852 trigger_error("readonly database", E_USER_WARNING);
855 $backend = &$this->_wikidb->_backend;
856 $cache = &$this->_wikidb->_cache;
857 $pagename = &$this->_pagename;
859 $version = $this->_coerce_to_version($version);
863 $backend->lock(array('version'));
864 $latestversion = $cache->get_latest_version($pagename);
865 if ($latestversion && $version == $latestversion) {
866 $backend->unlock(array('version'));
867 trigger_error(sprintf("Attempt to merge most recent revision of “%s”",
868 $pagename), E_USER_ERROR);
872 $versiondata = $cache->get_versiondata($pagename, $version, true);
874 // Not there? ... we're done!
875 $backend->unlock(array('version'));
879 if ($versiondata['is_minor_edit']) {
880 $previous = $backend->get_previous_version($pagename, $version);
882 $prevdata = $cache->get_versiondata($pagename, $previous);
883 if ($prevdata['author_id'] == $versiondata['author_id']) {
884 // This is a minor revision, previous version is
885 // by the same author. We will merge the
887 $cache->update_versiondata($pagename, $previous,
888 array('%content' => $versiondata['%content'],
889 '_supplanted' => $versiondata['_supplanted']));
894 $cache->delete_versiondata($pagename, $version);
895 $backend->unlock(array('version'));
899 * Create a new revision of a {@link WikiDB_Page}.
901 * @param int $version Version number for new revision.
902 * To ensure proper serialization of edits, $version must be
903 * exactly one higher than the current latest version.
904 * (You can defeat this check by setting $version to
905 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
907 * @param string $content Contents of new revision.
909 * @param array $metadata Metadata for new revision (hash).
910 * All values in the hash should be scalars (strings or integers).
912 * @param array $links List of linkto=>pagename, relation=>pagename which this page links to (hash).
914 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
915 * $version was incorrect, returns false
917 public function createRevision($version, &$content, $metadata, $links)
919 if ($this->_wikidb->readonly) {
920 trigger_error("readonly database", E_USER_WARNING);
923 $backend = &$this->_wikidb->_backend;
924 $cache = &$this->_wikidb->_cache;
925 $pagename = &$this->_pagename;
926 $cache->invalidate_cache($pagename);
928 $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
930 $latestversion = $backend->get_latest_version($pagename);
931 $newversion = ($latestversion ? $latestversion : 0) + 1;
932 assert($newversion >= 1);
934 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
935 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
941 foreach ($data as $key => $val) {
942 if (empty($val) || $key[0] == '_' || $key[0] == '%')
946 assert(!empty($data['author']));
947 if (empty($data['author_id']))
948 @$data['author_id'] = $data['author'];
950 if (empty($data['mtime']))
951 $data['mtime'] = time();
953 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
954 // Ensure mtimes are monotonic.
955 $pdata = $cache->get_versiondata($pagename, $latestversion);
956 if ($data['mtime'] < $pdata['mtime']) {
957 trigger_error(sprintf(_("%s: Date of new revision is %s"),
958 $pagename, "'non-monotonic'"),
960 $data['orig_mtime'] = $data['mtime'];
961 $data['mtime'] = $pdata['mtime'];
964 // FIXME: use (possibly user specified) 'mtime' time or
966 $cache->update_versiondata($pagename, $latestversion,
967 array('_supplanted' => $data['mtime']));
970 $data['%content'] = &$content;
972 $cache->set_versiondata($pagename, $newversion, $data);
974 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
975 //':deleted' => empty($content)));
977 $backend->set_links($pagename, $links);
979 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
981 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
985 /** A higher-level interface to createRevision.
987 * This takes care of computing the links, and storing
988 * a cached version of the transformed wiki-text.
990 * @param string $wikitext The page content.
992 * @param int $version Version number for new revision.
993 * To ensure proper serialization of edits, $version must be
994 * exactly one higher than the current latest version.
995 * (You can defeat this check by setting $version to
996 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
998 * @param array $meta Meta-data for new revision.
1000 * @param mixed $formatted
1004 function save($wikitext, $version, $meta, $formatted = null)
1006 if ($this->_wikidb->readonly) {
1007 trigger_error("readonly database", E_USER_WARNING);
1010 if (is_null($formatted))
1011 $formatted = new TransformedText($this, $wikitext, $meta);
1012 $type = $formatted->getType();
1013 $meta['pagetype'] = $type->getName();
1014 $links = $formatted->getWikiPageLinks(); // linkto => relation
1015 $attributes = array();
1016 foreach ($links as $link) {
1017 if ($link['linkto'] === "" and !empty($link['relation'])) {
1018 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1021 $meta['attribute'] = $attributes;
1023 $backend = &$this->_wikidb->_backend;
1024 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1025 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1026 $this->set('_cached_html', $formatted->pack());
1028 // FIXME: probably should have some global state information
1029 // in the backend to control when to optimize.
1031 // We're doing this here rather than in createRevision because
1032 // postgresql can't optimize while locked.
1033 if (((int)DEBUG & _DEBUG_SQL)
1034 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1035 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1037 if ($backend->optimize()) {
1039 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1044 /* Generate notification emails? */
1045 if (ENABLE_MAILNOTIFY and is_a($newrevision, 'WikiDB_PageRevision')) {
1046 // Save didn't fail because of concurrent updates.
1047 $notify = $this->_wikidb->get('notify');
1049 and is_array($notify)
1050 and !is_a($GLOBALS['request'], 'MockRequest')
1052 include_once 'lib/MailNotify.php';
1053 $MailNotify = new MailNotify($newrevision->getName());
1054 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1056 $newrevision->_transformedContent = $formatted;
1058 // more pagechange callbacks: (in a hackish manner for now)
1059 if (ENABLE_RECENTCHANGESBOX
1060 and empty($meta['is_minor_edit'])
1061 and !in_array($GLOBALS['request']->getArg('action'),
1062 array('loadfile', 'upgrade'))
1064 require_once 'lib/WikiPlugin.php';
1065 $w = new WikiPluginLoader();
1066 $p = $w->getPlugin("RecentChangesCached", false);
1067 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1069 return $newrevision;
1073 * Get the most recent revision of a page.
1075 * @param bool $need_content
1076 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1078 public function getCurrentRevision($need_content = true)
1080 $cache = &$this->_wikidb->_cache;
1081 $pagename = &$this->_pagename;
1083 // Prevent deadlock in case of memory exhausted errors
1084 // Pure selection doesn't really need locking here.
1085 // sf.net bug#927395
1086 // I know it would be better to lock, but with lots of pages this deadlock is more
1087 // severe than occasionally get not the latest revision.
1088 // In spirit to wikiwiki: read fast, edit slower.
1090 $version = $cache->get_latest_version($pagename);
1091 // getRevision gets the content also!
1092 $revision = $this->getRevision($version, $need_content);
1093 //$backend->unlock();
1099 * Get a specific revision of a WikiDB_Page.
1101 * @param int $version Which revision to get.
1102 * @param bool $need_content
1103 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1104 * false if the requested revision does not exist in the {@link WikiDB}.
1105 * Note that version zero of any page always exists.
1107 public function getRevision($version, $need_content = true)
1109 $cache = &$this->_wikidb->_cache;
1110 $pagename = &$this->_pagename;
1112 if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1113 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1116 assert($version > 0);
1117 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1119 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1121 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1126 * Get previous page revision.
1128 * This method find the most recent revision before a specified
1131 * @param bool|int|WikiDB_PageRevision $version Find most recent revision before this version.
1133 * @param bool $need_content
1135 * @return WikiDB_PageRevision|bool The requested WikiDB_PageRevision object, or false if the
1136 * requested revision does not exist in the {@link WikiDB}. Note that
1137 * unless $version is greater than zero, a revision (perhaps version zero,
1138 * the default revision) will always be found.
1140 public function getRevisionBefore($version = false, $need_content = true)
1142 $backend = &$this->_wikidb->_backend;
1143 $pagename = &$this->_pagename;
1144 if ($version === false)
1145 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1147 $version = $this->_coerce_to_version($version);
1152 $previous = $backend->get_previous_version($pagename, $version);
1153 $revision = $this->getRevision($previous, $need_content);
1154 //$backend->unlock();
1160 * Get all revisions of the WikiDB_Page.
1162 * This does not include the version zero (default) revision in the
1163 * returned revision set.
1165 * @return WikiDB_PageRevisionIterator A
1166 * WikiDB_PageRevisionIterator containing all revisions of this
1167 * WikiDB_Page in reverse order by version number.
1169 function getAllRevisions()
1171 $backend = &$this->_wikidb->_backend;
1172 $revs = $backend->get_all_revisions($this->_pagename);
1173 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1177 * Find pages which link to or are linked from a page.
1178 * relations: $backend->get_links is responsible to add the relation to the pagehash
1179 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1180 * if (isset($next['linkrelation']))
1182 * @param bool $reversed Which links to find: true for backlinks (default).
1183 * @param bool $include_empty
1184 * @param string $sortby
1185 * @param string $limit
1186 * @param string $sortby
1187 * @param string $exclude
1188 * @param bool $want_relations
1189 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1190 * all matching pages.
1192 public function getLinks($reversed = true, $include_empty = false, $sortby = '',
1193 $limit = '', $exclude = '', $want_relations = false)
1195 $backend = &$this->_wikidb->_backend;
1196 $result = $backend->get_links($this->_pagename, $reversed,
1197 $include_empty, $sortby, $limit, $exclude,
1199 return new WikiDB_PageIterator($this->_wikidb, $result,
1200 array('include_empty' => $include_empty,
1201 'sortby' => $sortby,
1203 'exclude' => $exclude,
1204 'want_relations' => $want_relations));
1208 * All Links from other pages to this page.
1210 function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1212 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1216 * Forward Links: All Links from this page to other pages.
1218 function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1220 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1224 * Relations: All links from this page to other pages with relation <> 0.
1225 * is_a:=page or population:=number
1227 function getRelations($sortby = '', $limit = '', $exclude = '')
1229 $backend = &$this->_wikidb->_backend;
1230 $result = $backend->get_links($this->_pagename, false, true,
1231 $sortby, $limit, $exclude,
1233 // we do not care for the linked page versiondata, just the pagename and linkrelation
1234 return new WikiDB_PageIterator($this->_wikidb, $result,
1235 array('include_empty' => true,
1236 'sortby' => $sortby,
1238 'exclude' => $exclude,
1239 'want_relations' => true));
1243 * possibly faster link existance check. not yet accelerated.
1245 function existLink($link, $reversed = false)
1247 $backend = &$this->_wikidb->_backend;
1248 if (method_exists($backend, 'exists_link'))
1249 return $backend->exists_link($this->_pagename, $link, $reversed);
1250 //$cache = &$this->_wikidb->_cache;
1251 // TODO: check cache if it is possible
1252 $iter = $this->getLinks($reversed, false);
1253 while ($page = $iter->next()) {
1254 if ($page->getName() == $link)
1261 /* Semantic relations are links with the relation pointing to another page,
1262 the so-called "RDF Triple".
1263 [San Diego] is%20a::city
1264 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1267 /* Semantic attributes for a page.
1268 [San Diego] population:=1,305,736
1269 Attributes are links with the relation pointing to another page.
1273 * Access WikiDB_Page non version-specific meta-data.
1275 * @param string $key Which meta data to get.
1276 * Some reserved meta-data keys are:
1278 * <dt>'date' <dd> Created as unixtime
1279 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1280 * <dt>'hits' <dd> Page hit counter.
1281 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1282 * In SQL stored now in an extra column.
1284 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1285 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1286 * E.g. "owner.users"
1287 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1288 * page-headers and content.
1289 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1290 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1293 * @return mixed The requested value, or false if the requested data
1296 public function get($key)
1298 $cache = &$this->_wikidb->_cache;
1299 $backend = &$this->_wikidb->_backend;
1300 if (!$key || $key[0] == '%')
1302 // several new SQL backends optimize this.
1303 if (!WIKIDB_NOCACHE_MARKUP
1304 and $key == '_cached_html'
1305 and method_exists($backend, 'get_cached_html')
1307 return $backend->get_cached_html($this->_pagename);
1309 $data = $cache->get_pagedata($this->_pagename);
1310 return isset($data[$key]) ? $data[$key] : false;
1314 * Get all the page meta-data as a hash.
1316 * @return array The page meta-data (hash).
1318 function getMetaData()
1320 $cache = &$this->_wikidb->_cache;
1321 $data = $cache->get_pagedata($this->_pagename);
1323 foreach ($data as $key => $val) {
1324 if ( /*!empty($val) &&*/
1333 * Set page meta-data.
1337 * @param string $key Meta-data key to set.
1338 * @param string $newval New value.
1340 public function set($key, $newval)
1342 $cache = &$this->_wikidb->_cache;
1343 $backend = &$this->_wikidb->_backend;
1344 $pagename = &$this->_pagename;
1346 assert($key && $key[0] != '%');
1348 // several new SQL backends optimize this.
1349 if (!WIKIDB_NOCACHE_MARKUP
1350 and $key == '_cached_html'
1351 and method_exists($backend, 'set_cached_html')
1353 if ($this->_wikidb->readonly) {
1354 trigger_error("readonly database", E_USER_WARNING);
1357 $backend->set_cached_html($pagename, $newval);
1361 $data = $cache->get_pagedata($pagename);
1363 if (!empty($newval)) {
1364 if (!empty($data[$key]) && $data[$key] == $newval)
1365 return; // values identical, skip update.
1367 if (empty($data[$key]))
1368 return; // values identical, skip update.
1371 if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1372 trigger_error("readonly database", E_USER_WARNING);
1375 $cache->update_pagedata($pagename, array($key => $newval));
1379 * Increase page hit count.
1381 * FIXME: IS this needed? Probably not.
1383 * This is a convenience function.
1384 * <pre> $page->increaseHitCount(); </pre>
1385 * is functionally identical to
1386 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1387 * but less expensive (ignores the pagadata string)
1389 * Note that this method may be implemented in more efficient ways
1390 * in certain backends.
1392 public function increaseHitCount()
1394 if ($this->_wikidb->readonly) {
1395 trigger_error("readonly database", E_USER_NOTICE);
1398 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1399 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1401 @$newhits = $this->get('hits') + 1;
1402 $this->set('hits', $newhits);
1407 * Return a string representation of the WikiDB_Page
1409 * This is really only for debugging.
1411 * @return string Printable representation of the WikiDB_Page.
1413 public function asString()
1416 printf("[%s:%s\n", get_class($this), $this->getName());
1417 print_r($this->getMetaData());
1419 $strval = ob_get_contents();
1425 * @param int|object $version_or_pagerevision
1426 * Takes either the version number (and int) or a WikiDB_PageRevision
1428 * @return integer The version number.
1430 private function _coerce_to_version($version_or_pagerevision)
1432 if (method_exists($version_or_pagerevision, "getContent"))
1433 $version = $version_or_pagerevision->getVersion();
1435 $version = (int)$version_or_pagerevision;
1437 assert($version >= 0);
1441 function isUserPage($include_empty = true)
1443 if (!$include_empty and !$this->exists()) return false;
1444 return $this->get('pref') ? true : false;
1447 // May be empty. Either the stored owner (/Chown), or the first authorized author
1450 if ($owner = $this->get('owner'))
1452 // check all revisions forwards for the first author_id
1453 $backend = &$this->_wikidb->_backend;
1454 $pagename = &$this->_pagename;
1455 $latestversion = $backend->get_latest_version($pagename);
1456 for ($v = 1; $v <= $latestversion; $v++) {
1457 $rev = $this->getRevision($v, false);
1458 if ($rev and $owner = $rev->get('author_id')) {
1465 // The authenticated author of the first revision or empty if not authenticated then.
1466 function getCreator()
1468 if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1472 // The authenticated author of the current revision.
1473 function getAuthor()
1475 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1479 /* Semantic Web value, not stored in the links.
1480 * todo: unify with some unit knowledge
1482 function setAttribute($relation, $value)
1484 $attr = $this->get('attributes');
1486 $attr = array($relation => $value);
1488 $attr[$relation] = $value;
1489 $this->set('attributes', $attr);
1492 function getAttribute($relation)
1494 $meta = $this->get('attributes');
1498 return $meta[$relation];
1504 * This class represents a specific revision of a WikiDB_Page within
1507 * A WikiDB_PageRevision has read-only semantics. You may only create
1508 * new revisions (and delete old ones) --- you cannot modify existing
1511 class WikiDB_PageRevision
1513 public $_transformedContent = false; // set by WikiDB_Page::save()
1515 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1516 $versiondata = false)
1518 $this->_wikidb = &$wikidb;
1519 $this->_pagename = $pagename;
1520 $this->_version = $version;
1521 $this->_data = $versiondata ? $versiondata : array();
1522 $this->_transformedContent = false; // set by WikiDB_Page::save()
1526 * Get the WikiDB_Page which this revision belongs to.
1528 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1530 public function getPage()
1532 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1536 * Get the version number of this revision.
1538 * @return integer The version number of this revision.
1540 public function getVersion()
1542 return $this->_version;
1546 * Determine whether this revision has defaulted content.
1548 * The default revision (version 0) of each page, as well as any
1549 * pages which are created with empty content have their content
1550 * defaulted to something like:
1552 * Describe [ThisPage] here.
1555 * @return boolean Returns true if the page has default content.
1557 public function hasDefaultContents()
1559 $data = &$this->_data;
1560 if (!isset($data['%content'])) return true;
1561 if ($data['%content'] === true) return false;
1562 return $data['%content'] === false or $data['%content'] === "";
1566 * Get the content as an array of lines.
1568 * @return array An array of lines.
1569 * The lines should contain no trailing white space.
1571 public function getContent()
1573 return explode("\n", $this->getPackedContent());
1577 * Get the pagename of the revision.
1579 * @return string pagename.
1581 public function getPageName()
1583 return $this->_pagename;
1588 return $this->_pagename;
1592 * Determine whether revision is the latest.
1594 * @return boolean True iff the revision is the latest (most recent) one.
1596 public function isCurrent()
1598 if (!isset($this->_iscurrent)) {
1599 $page = $this->getPage();
1600 $current = $page->getCurrentRevision(false);
1601 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1603 return $this->_iscurrent;
1607 * Get the transformed content of a page.
1609 * @param bool $pagetype_override
1610 * @return object An XmlContent-like object containing the page transformed
1613 function getTransformedContent($pagetype_override = false)
1615 if ($pagetype_override) {
1616 // Figure out the normal page-type for this page.
1617 $type = PageType::GetPageType($this->get('pagetype'));
1618 if ($type->getName() == $pagetype_override)
1619 $pagetype_override = false; // Not really an override...
1622 if ($pagetype_override) {
1623 // Overriden page type, don't cache (or check cache).
1624 return new TransformedText($this->getPage(),
1625 $this->getPackedContent(),
1626 $this->getMetaData(),
1627 $pagetype_override);
1630 $possibly_cache_results = true;
1632 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1633 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1634 // flush cache for this page.
1635 $page = $this->getPage();
1636 $page->set('_cached_html', ''); // ignored with !USECACHE
1638 $possibly_cache_results = false;
1639 } elseif (USECACHE and !$this->_transformedContent) {
1641 if ($this->isCurrent()) {
1642 $page = $this->getPage();
1643 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1645 $possibly_cache_results = false;
1647 //$backend->unlock();
1650 if (!$this->_transformedContent) {
1651 $this->_transformedContent
1652 = new TransformedText($this->getPage(),
1653 $this->getPackedContent(),
1654 $this->getMetaData());
1656 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1657 // If we're still the current version, cache the transfomed page.
1659 if ($this->isCurrent()) {
1660 $page->set('_cached_html', $this->_transformedContent->pack());
1662 //$backend->unlock();
1666 return $this->_transformedContent;
1670 * Get the content as a string.
1672 * @return string The page content.
1673 * Lines are separated by new-lines.
1675 public function getPackedContent()
1677 $data = &$this->_data;
1679 if (empty($data['%content'])
1680 || (!$this->_wikidb->isWikiPage($this->_pagename)
1681 && $this->isCurrent())
1683 include_once 'lib/InlineParser.php';
1685 // A feature similar to taglines at http://www.wlug.org.nz/
1686 // Lib from http://www.aasted.org/quote/
1687 if (defined('FORTUNE_DIR')
1688 and is_dir(FORTUNE_DIR)
1689 and in_array($GLOBALS['request']->getArg('action'),
1690 array('create', 'edit'))
1692 include_once 'lib/fortune.php';
1693 $fortune = new Fortune();
1694 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1696 $quote = "<verbatim>\n"
1697 . str_replace("\n<br>", "\n", $quote)
1698 . "</verbatim>\n\n";
1702 . sprintf(_("Describe %s here."),
1703 "[" . WikiEscape($this->_pagename) . "]");
1705 // Replace empty content with default value.
1706 return sprintf(_("Describe %s here."),
1707 "[" . WikiEscape($this->_pagename) . "]");
1710 // There is (non-default) content.
1711 assert($this->_version > 0);
1713 if (!is_string($data['%content'])) {
1714 // Content was not provided to us at init time.
1715 // (This is allowed because for some backends, fetching
1716 // the content may be expensive, and often is not wanted
1719 // In any case, now we need to get it.
1720 $data['%content'] = $this->_get_content();
1721 assert(is_string($data['%content']));
1724 return $data['%content'];
1727 function _get_content()
1729 $cache = &$this->_wikidb->_cache;
1730 $pagename = $this->_pagename;
1731 $version = $this->_version;
1733 assert($version > 0);
1735 $newdata = $cache->get_versiondata($pagename, $version, true);
1737 assert(is_string($newdata['%content']));
1738 return $newdata['%content'];
1740 // else revision has been deleted... What to do?
1741 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1742 $version, $pagename);
1747 * Get meta-data for this revision.
1749 * @param string $key Which meta-data to access.
1751 * Some reserved revision meta-data keys are:
1753 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1754 * The 'mtime' meta-value is normally set automatically by the database
1755 * backend, but it may be specified explicitly when creating a new revision.
1757 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1758 * of a page must be monotonically increasing. If an attempt is
1759 * made to create a new revision with an mtime less than that of
1760 * the preceeding revision, the new revisions timestamp is force
1761 * to be equal to that of the preceeding revision. In that case,
1762 * the originally requested mtime is preserved in 'orig_mtime'.
1763 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1764 * This meta-value is <em>always</em> automatically maintained by the database
1765 * backend. (It is set from the 'mtime' meta-value of the superceding
1766 * revision.) '_supplanted' has a value of 'false' for the current revision.
1768 * FIXME: this could be refactored:
1770 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1772 * <dd> Authenticated author of a page. This is used to identify
1773 * the distinctness of authors when cleaning old revisions from
1775 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1776 * <dt> 'summary' <dd> Short change summary entered by page author.
1779 * Meta-data keys must be valid C identifers (they have to start with a letter
1780 * or underscore, and can contain only alphanumerics and underscores.)
1782 * @return string The requested value, or false if the requested value
1785 public function get($key)
1787 if (!$key || $key[0] == '%')
1789 $data = &$this->_data;
1790 return isset($data[$key]) ? $data[$key] : false;
1794 * Get all the revision page meta-data as a hash.
1796 * @return array The revision meta-data.
1798 function getMetaData()
1801 foreach ($this->_data as $key => $val) {
1802 if (!empty($val) && $key[0] != '%')
1809 * Return a string representation of the revision.
1811 * This is really only for debugging.
1813 * @return string Printable representation of the WikiDB_Page.
1815 public function asString()
1818 printf("[%s:%d\n", get_class($this), $this->get('version'));
1819 print_r($this->_data);
1820 echo $this->getPackedContent() . "\n]\n";
1821 $strval = ob_get_contents();
1828 * Class representing a sequence of WikiDB_Pages.
1829 * TODO: Enhance to php5 iterators
1831 * apply filters for options like 'sortby', 'limit', 'exclude'
1832 * for simple queries like titleSearch, where the backend is not ready yet.
1834 class WikiDB_PageIterator
1836 function WikiDB_PageIterator(&$wikidb, &$iter, $options = array())
1838 $this->_iter = $iter; // a WikiDB_backend_iterator
1839 $this->_wikidb = &$wikidb;
1840 $this->_options = $options;
1845 return $this->_iter->count();
1850 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1854 * Get next WikiDB_Page in sequence.
1856 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1858 public function next()
1860 if (!($next = $this->_iter->next())) {
1864 $pagename = &$next['pagename'];
1865 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1866 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1870 if (isset($next['linkrelation'])
1871 or isset($next['pagedata']['linkrelation'])
1877 // There's always hits, but we cache only if more
1878 // (well not with file, cvs and dba)
1879 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1880 $this->_wikidb->_cache->cache_data($next);
1881 // cache existing page id's since we iterate over all links in GleanDescription
1882 // and need them later for LinkExistingWord
1883 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1884 and !$this->_options['include_empty'] and isset($next['id'])
1886 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1888 $page = new WikiDB_Page($this->_wikidb, $pagename);
1889 if (isset($next['linkrelation']))
1890 $page->set('linkrelation', $next['linkrelation']);
1891 if (isset($next['score']))
1892 $page->score = $next['score'];
1897 * Release resources held by this iterator.
1899 * The iterator may not be used after free() is called.
1901 * There is no need to call free(), if next() has returned false.
1902 * (I.e. if you iterate through all the pages in the sequence,
1903 * you do not need to call free() --- you only need to call it
1904 * if you stop before the end of the iterator is reached.)
1906 public function free()
1908 // $this->_iter->free();
1913 $this->_iter->reset();
1919 while ($page = $this->next())
1926 * Apply filters for options like 'sortby', 'limit', 'exclude'
1927 * for simple queries like titleSearch, where the backend is not ready yet.
1928 * Since iteration is usually destructive for SQL results,
1929 * we have to generate a copy.
1931 function applyFilters($options = false)
1933 if (!$options) $options = $this->_options;
1934 if (isset($options['sortby'])) {
1936 /* this is destructive */
1937 while ($page = $this->next())
1938 $result[] = $page->getName();
1939 $this->_doSort($array, $options['sortby']);
1941 /* the rest is not destructive.
1942 * reconstruct a new iterator
1944 $pagenames = array();
1946 if (isset($options['limit']))
1947 $limit = $options['limit'];
1950 if (isset($options['exclude']))
1951 $exclude = $options['exclude'];
1952 if (is_string($exclude) and !is_array($exclude))
1953 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1954 foreach ($array as $pagename) {
1955 if ($limit and $i++ > $limit)
1956 return new WikiDB_Array_PageIterator($pagenames);
1957 if (!empty($exclude) and !in_array($pagename, $exclude))
1958 $pagenames[] = $pagename;
1959 elseif (empty($exclude))
1960 $pagenames[] = $pagename;
1962 return new WikiDB_Array_PageIterator($pagenames);
1966 function _doSort(&$array, $sortby)
1968 $sortby = PageList::sortby($sortby, 'init');
1969 if ($sortby == '+pagename')
1970 sort($array, SORT_STRING);
1971 elseif ($sortby == '-pagename')
1972 rsort($array, SORT_STRING);
1979 * A class which represents a sequence of WikiDB_PageRevisions.
1980 * TODO: Enhance to php5 iterators
1982 class WikiDB_PageRevisionIterator
1984 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
1986 $this->_revisions = $revisions;
1987 $this->_wikidb = &$wikidb;
1988 $this->_options = $options;
1993 return $this->_revisions->count();
1997 * Get next WikiDB_PageRevision in sequence.
1999 * @return WikiDB_PageRevision
2000 * The next WikiDB_PageRevision in the sequence.
2002 public function next()
2004 if (!($next = $this->_revisions->next()))
2007 //$this->_wikidb->_cache->cache_data($next);
2009 $pagename = $next['pagename'];
2010 $version = $next['version'];
2011 $versiondata = $next['versiondata'];
2013 if (!(is_string($pagename) and $pagename != '')) {
2014 trigger_error("empty pagename", E_USER_WARNING);
2017 } else assert(is_string($pagename) and $pagename != '');
2019 if (!is_array($versiondata)) {
2020 trigger_error("empty versiondata", E_USER_WARNING);
2023 } else assert(is_array($versiondata));
2025 if (!($version > 0)) {
2026 trigger_error("invalid version", E_USER_WARNING);
2029 } else assert($version > 0);
2031 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2036 * Release resources held by this iterator.
2038 * The iterator may not be used after free() is called.
2040 * There is no need to call free(), if next() has returned false.
2041 * (I.e. if you iterate through all the revisions in the sequence,
2042 * you do not need to call free() --- you only need to call it
2043 * if you stop before the end of the iterator is reached.)
2045 public function free()
2047 $this->_revisions->free();
2053 while ($rev = $this->next())
2062 class WikiDB_Array_PageIterator
2064 function WikiDB_Array_PageIterator($pagenames)
2067 $this->_dbi = $request->getDbh();
2068 $this->_pages = $pagenames;
2069 reset($this->_pages);
2074 $c = current($this->_pages);
2075 next($this->_pages);
2076 return $c !== false ? $this->_dbi->getPage($c) : false;
2081 return count($this->_pages);
2086 reset($this->_pages);
2095 reset($this->_pages);
2096 return $this->_pages;
2100 class WikiDB_Array_generic_iter
2102 function WikiDB_Array_generic_iter($result)
2104 // $result may be either an array or a query result
2105 if (is_array($result)) {
2106 $this->_array = $result;
2107 } elseif (is_object($result)) {
2108 $this->_array = $result->asArray();
2110 $this->_array = array();
2112 if (!empty($this->_array))
2113 reset($this->_array);
2118 $c = current($this->_array);
2119 next($this->_array);
2120 return $c !== false ? $c : false;
2125 return count($this->_array);
2130 reset($this->_array);
2139 if (!empty($this->_array))
2140 reset($this->_array);
2141 return $this->_array;
2146 * Data cache used by WikiDB.
2148 * FIXME: Maybe rename this to caching_backend (or some such).
2154 // FIXME: beautify versiondata cache. Cache only limited data?
2156 function WikiDB_cache(&$backend)
2158 $this->_backend = &$backend;
2160 $this->_pagedata_cache = array();
2161 $this->_versiondata_cache = array();
2162 array_push($this->_versiondata_cache, array());
2163 $this->_glv_cache = array();
2164 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2166 if (isset($GLOBALS['request']->_dbi))
2167 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2172 $this->_pagedata_cache = array();
2173 $this->_versiondata_cache = array();
2174 $this->_glv_cache = array();
2175 $this->_id_cache = array();
2178 function get_pagedata($pagename)
2180 assert(is_string($pagename) && $pagename != '');
2182 $cache = &$this->_pagedata_cache;
2183 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2184 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2185 if (empty($cache[$pagename]))
2186 $cache[$pagename] = array();
2188 return $cache[$pagename];
2190 return $this->_backend->get_pagedata($pagename);
2194 function update_pagedata($pagename, $newdata)
2196 assert(is_string($pagename) && $pagename != '');
2197 if (!empty($this->readonly)) {
2198 trigger_error("readonly database", E_USER_WARNING);
2202 $this->_backend->update_pagedata($pagename, $newdata);
2205 if (!empty($this->_pagedata_cache[$pagename])
2206 and is_array($this->_pagedata_cache[$pagename])
2208 $cachedata = &$this->_pagedata_cache[$pagename];
2209 foreach ($newdata as $key => $val)
2210 $cachedata[$key] = $val;
2212 $this->_pagedata_cache[$pagename] = $newdata;
2216 function invalidate_cache($pagename)
2218 unset ($this->_pagedata_cache[$pagename]);
2219 unset ($this->_versiondata_cache[$pagename]);
2220 unset ($this->_glv_cache[$pagename]);
2221 unset ($this->_id_cache[$pagename]);
2222 //unset ($this->_backend->_page_data);
2225 function delete_page($pagename)
2227 if (!empty($this->readonly)) {
2228 trigger_error("readonly database", E_USER_WARNING);
2231 $result = $this->_backend->delete_page($pagename);
2232 $this->invalidate_cache($pagename);
2236 function purge_page($pagename)
2238 if (!empty($this->readonly)) {
2239 trigger_error("readonly database", E_USER_WARNING);
2242 $result = $this->_backend->purge_page($pagename);
2243 $this->invalidate_cache($pagename);
2247 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2248 function cache_data($data)
2251 //if (isset($data['pagedata']))
2252 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2255 function get_versiondata($pagename, $version, $need_content = false)
2257 // FIXME: Seriously ugly hackage
2259 if (USECACHE) { //temporary - for debugging
2260 assert(is_string($pagename) && $pagename != '');
2261 // There is a bug here somewhere which results in an assertion failure at line 105
2262 // of ArchiveCleaner.php It goes away if we use the next line.
2263 //$need_content = true;
2264 $nc = $need_content ? '1' : '0';
2265 $cache = &$this->_versiondata_cache;
2266 if (!isset($cache[$pagename][$version][$nc])
2267 || !(is_array($cache[$pagename]))
2268 || !(is_array($cache[$pagename][$version]))
2270 $cache[$pagename][$version][$nc] =
2271 $this->_backend->get_versiondata($pagename, $version, $need_content);
2273 // If we have retrieved all data, we may as well set the cache for
2274 // $need_content = false
2275 if ($need_content) {
2276 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2279 $vdata = $cache[$pagename][$version][$nc];
2281 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2284 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2285 if (empty($this->_pagedata_cache))
2286 $this->_pagedata_cache = array();
2287 /* 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 */
2288 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2293 function set_versiondata($pagename, $version, $data)
2295 //unset($this->_versiondata_cache[$pagename][$version]);
2297 if (!empty($this->readonly)) {
2298 trigger_error("readonly database", E_USER_WARNING);
2301 $this->_backend->set_versiondata($pagename, $version, $data);
2303 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2304 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2305 // Is this necessary?
2306 unset($this->_glv_cache[$pagename]);
2309 function update_versiondata($pagename, $version, $data)
2311 if (!empty($this->readonly)) {
2312 trigger_error("readonly database", E_USER_WARNING);
2315 $this->_backend->update_versiondata($pagename, $version, $data);
2317 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2319 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2320 // Is this necessary?
2321 unset($this->_glv_cache[$pagename]);
2324 function delete_versiondata($pagename, $version)
2326 if (!empty($this->readonly)) {
2327 trigger_error("readonly database", E_USER_WARNING);
2330 $this->_backend->delete_versiondata($pagename, $version);
2331 if (isset($this->_versiondata_cache[$pagename][$version]))
2332 unset ($this->_versiondata_cache[$pagename][$version]);
2333 // dirty latest version cache only if latest version gets deleted
2334 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2335 unset ($this->_glv_cache[$pagename]);
2338 function get_latest_version($pagename)
2341 assert(is_string($pagename) && $pagename != '');
2342 $cache = &$this->_glv_cache;
2343 if (!isset($cache[$pagename])) {
2344 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2345 if (empty($cache[$pagename]))
2346 $cache[$pagename] = 0;
2348 return $cache[$pagename];
2350 return $this->_backend->get_latest_version($pagename);
2355 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2360 $stamp = strftime("%y%m%d-%H%M%S");
2361 $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2362 register_shutdown_function("_sql_debuglog_shutdown_function");
2363 } elseif ($shutdown) {
2367 if ($newline) fputs($fp, "[$i++] $msg");
2368 else fwrite($fp, $msg);
2371 function _sql_debuglog_shutdown_function()
2373 _sql_debuglog('', false, true);
2379 // c-basic-offset: 4
2380 // c-hanging-comment-ender-p: nil
2381 // indent-tabs-mode: nil