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.
46 function __construct(&$backend, $dbparams)
49 * @var WikiRequest $request
53 $this->_backend =& $backend;
54 // don't do the following with the auth_dsn!
55 if (isset($dbparams['auth_dsn']))
58 $this->_cache = new WikiDB_cache($backend);
60 $request->_dbi = $this;
62 // If the database doesn't yet have a timestamp, initialize it now.
63 if ($this->get('_timestamp') === false)
67 if ((int)DEBUG & _DEBUG_SQL) {
68 $this->_backend->check();
70 // might be changed when opening the database fails
71 $this->readonly = defined("READONLY") ? READONLY : false;
75 * Open a WikiDB database.
77 * This function inspects its arguments to determine the proper
78 * subclass of WikiDB to instantiate, and then it instantiates it.
80 * @param array $dbparams Database configuration parameters (hash).
81 * Some pertinent parameters are:
84 * <dd> The back-end type. Current supported types are:
87 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
88 * library. (More stable and conservative)
90 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
92 * <dd> Dba based backend. The default and by far the fastest.
100 * <dd> (Used by the SQL and ADODB backends.)
101 * The DSN specifying which database to connect to.
104 * <dd> Prefix to be prepended to database tables (and file names).
107 * <dd> (Used by the dba backend.)
108 * Which directory db files reside in.
111 * <dd> Used only by the dba backend so far.
112 * And: When optimizing mysql it closes timed out mysql processes.
113 * otherwise only used for dba: Timeout in seconds for opening (and
114 * obtaining lock) on the dbm file.
117 * <dd> (Used by the dba backend.)
119 * Which dba handler to use. Good choices are probably either
123 * <dd> Either set by config.ini: READONLY = true or detected automatically
124 * when a database can be read but cannot be updated.
127 * @return WikiDB A WikiDB object.
129 public static function open($dbparams)
131 $dbtype = $dbparams{'dbtype'};
132 include_once("lib/WikiDB/$dbtype.php");
134 $class = 'WikiDB_' . $dbtype;
135 return new $class($dbparams);
139 * Close database connection.
141 * The database may no longer be used after it is closed.
143 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
144 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
145 * which have been obtained from it.
147 public function close()
149 $this->_backend->close();
150 $this->_cache->close();
154 * Get a WikiDB_Page from a WikiDB.
156 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
157 * therefore this method never fails.
159 * @param string $pagename Which page to get.
160 * @return WikiDB_Page The requested WikiDB_Page.
162 public function getPage($pagename)
164 static $error_displayed = false;
165 $pagename = (string)$pagename;
167 if ($pagename === '') {
168 if ($error_displayed) return false;
169 $error_displayed = true;
170 if (function_exists("xdebug_get_function_stack"))
171 var_dump(xdebug_get_function_stack());
172 trigger_error("empty pagename", E_USER_WARNING);
176 assert($pagename != '');
178 return new WikiDB_Page($this, $pagename);
182 * Determine whether page exists (in non-default form).
185 * $is_page = $dbi->isWikiPage($pagename);
189 * $page = $dbi->getPage($pagename);
190 * $current = $page->getCurrentRevision();
191 * $is_page = ! $current->hasDefaultContents();
193 * however isWikiPage may be implemented in a more efficient
194 * manner in certain back-ends.
196 * @param string $pagename string Which page to check.
197 * @return boolean True if the page actually exists with
198 * non-default contents in the WikiDataBase.
200 public function isWikiPage($pagename)
202 $page = $this->getPage($pagename);
203 return ($page and $page->exists());
207 * Delete page from the WikiDB.
209 * Deletes the page from the WikiDB with the possibility to revert and diff.
210 * //Also resets all page meta-data to the default values.
212 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
214 * @param string $pagename Name of page to delete.
218 public function deletePage($pagename)
220 if (!empty($this->readonly)) {
221 trigger_error("readonly database", E_USER_WARNING);
224 // don't create empty revisions of already purged pages.
225 if ($this->_backend->get_latest_version($pagename))
226 $result = $this->_cache->delete_page($pagename);
230 /* Generate notification emails */
231 if (defined('ENABLE_MAILNOTIFY') and ENABLE_MAILNOTIFY) {
232 include_once 'lib/MailNotify.php';
233 $MailNotify = new MailNotify($pagename);
234 $MailNotify->onDeletePage($this, $pagename);
237 //How to create a RecentChanges entry with explaining summary? Dynamically
239 $page = $this->getPage($pagename);
240 $current = $page->getCurrentRevision();
241 $meta = $current->_data;
242 $version = $current->getVersion();
243 $meta['summary'] = _("removed");
244 $page->save($current->getPackedContent(), $version + 1, $meta);
250 * Completely remove the page from the WikiDB, without undo possibility.
251 * @param string $pagename Name of page to delete.
255 public function purgePage($pagename)
257 if (!empty($this->readonly)) {
258 trigger_error("readonly database", E_USER_WARNING);
261 $result = $this->_cache->purge_page($pagename);
262 $this->deletePage($pagename); // just for the notification
267 * Retrieve all pages.
269 * Gets the set of all pages with non-default contents.
271 * @param bool $include_empty Optional. Normally pages whose most
272 * recent revision has empty content are considered to be
273 * non-existant. Unless $include_defaulted is set to true, those
274 * pages will not be returned.
275 * @param string $sortby Optional. "+-column,+-column2".
276 * If false the result is faster in natural order.
277 * @param string $limit Optional. Encoded as "$offset,$count".
278 * $offset defaults to 0.
279 * @param string $exclude Optional comma-separated list of pagenames.
281 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
282 * in the WikiDB which have non-default contents.
284 public function getAllPages($include_empty = false, $sortby = '', $limit = '', $exclude = '')
286 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
288 return new WikiDB_PageIterator($this, $result,
289 array('include_empty' => $include_empty,
290 'exclude' => $exclude,
291 'limit_by_db' => $result->_options['limit_by_db'],
292 'limit' => $result->limit()));
296 * @param boolean $include_empty If true include also empty pages
297 * @param string $exclude: comma-separated list of pagenames.
298 * TBD: array of pagenames
302 public function numPages($include_empty = false, $exclude = '')
304 if (method_exists($this->_backend, 'numPages'))
305 // FIXME: currently are all args ignored.
306 $count = $this->_backend->numPages($include_empty, $exclude);
308 // FIXME: exclude ignored.
309 $iter = $this->getAllPages($include_empty, false, false, $exclude);
310 $count = $iter->count();
319 * Search for pages containing (or not containing) certain words
322 * Pages are returned in alphabetical order whenever it is
323 * practical to do so.
324 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
326 * @param TextSearchQuery $search A TextSearchQuery object
327 * @param string $sortby Optional. "+-column,+-column2".
328 * If false the result is faster in natural order.
329 * @param string $limit Optional. Encoded as "$offset,$count".
330 * $offset defaults to 0.
331 * @param string $exclude Optional comma-separated list of pagenames.
332 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
333 * @see TextSearchQuery
335 public function titleSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
337 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
338 $options = array('exclude' => $exclude,
340 //if (isset($result->_count)) $options['count'] = $result->_count;
341 return new WikiDB_PageIterator($this, $result, $options);
347 * Search for pages containing (or not containing) certain words
348 * in their entire text (this includes the page content and the
351 * Pages are returned in alphabetical order whenever it is
352 * practical to do so.
353 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
355 * @param TextSearchQuery $search A TextSearchQuery object.
356 * @param string $sortby Optional. "+-column,+-column2".
357 * If false the result is faster in natural order.
358 * @param string $limit Optional. Encoded as "$offset,$count".
359 * $offset defaults to 0.
360 * @param string $exclude Optional comma-separated list of pagenames.
361 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
362 * @see TextSearchQuery
364 public function fullSearch($search, $sortby = 'pagename', $limit = '', $exclude = '')
366 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
367 return new WikiDB_PageIterator($this, $result,
368 array('exclude' => $exclude,
370 'stoplisted' => $result->stoplisted
375 * Find the pages with the greatest hit counts.
377 * Pages are returned in reverse order by hit count.
379 * @param int $limit The maximum number of pages to return.
380 * Set $limit to zero to return all pages. If $limit < 0, pages will
381 * be sorted in decreasing order of popularity.
382 * @param string $sortby Optional. "+-column,+-column2".
383 * If false the result is faster in natural order.
385 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
388 public function mostPopular($limit = 20, $sortby = '-hits')
390 $result = $this->_backend->most_popular($limit, $sortby);
391 return new WikiDB_PageIterator($this, $result);
395 * Find recent page revisions.
397 * Revisions are returned in reverse order by creation time.
399 * @param array $params This hash is used to specify various optional
403 * <dd> (integer) At most this many revisions will be returned.
405 * <dd> (integer) Only revisions since this time (unix-timestamp)
407 * <dt> include_minor_revisions
408 * <dd> (boolean) Also include minor revisions. (Default is not to.)
409 * <dt> exclude_major_revisions
410 * <dd> (boolean) Don't include non-minor revisions.
411 * (Exclude_major_revisions implies include_minor_revisions.)
412 * <dt> include_all_revisions
413 * <dd> (boolean) Return all matching revisions for each page.
414 * Normally only the most recent matching revision is returned
418 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
419 * containing the matching revisions.
421 public function mostRecent($params = array())
423 $result = $this->_backend->most_recent($params);
424 return new WikiDB_PageRevisionIterator($this, $result);
428 * @param string $exclude_from
429 * @param string $exclude
430 * @param string $sortby Optional. "+-column,+-column2".
431 * If false the result is faster in natural order.
432 * @param string $limit Optional. Encoded as "$offset,$count".
433 * $offset defaults to 0.
434 * @return Iterator A generic iterator containing rows of
435 * (duplicate) pagename, wantedfrom.
437 public function wantedPages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
439 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
443 * Generic interface to the link table. Esp. useful to search for rdf triples as in
444 * SemanticSearch and ListRelations.
446 * @param object $pages A TextSearchQuery object.
447 * @param object $search A TextSearchQuery object.
448 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
449 * linktype parameter:
452 * <dd> search for simple out-links
454 * <dd> in-links, i.e BackLinks
456 * <dd> the first part in a <>::<> link
458 * <dd> the first part in a <>:=<> link
460 * @param mixed $relation An optional TextSearchQuery to match the
461 * relation name. Ignored on simple in-out links.
463 * @return Iterator A generic iterator containing links to pages or values.
464 * hash of "pagename", "linkname", "linkvalue.
466 public function linkSearch($pages, $search, $linktype, $relation = false)
468 return $this->_backend->link_search($pages, $search, $linktype, $relation);
472 * Return a simple list of all defined relations (and attributes), mainly
473 * for the SemanticSearch autocompletion.
475 * @param bool $also_attributes
476 * @param bool $only_attributes
477 * @param bool $sorted
478 * @return array of strings
480 public function listRelations($also_attributes = false, $only_attributes = false, $sorted = true)
482 if (method_exists($this->_backend, "list_relations"))
483 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
484 // dumb, slow fallback. no iter, so simply define it here.
485 $relations = array();
486 $iter = $this->getAllPages();
487 while ($page = $iter->next()) {
488 $reliter = $page->getRelations();
490 while ($rel = $reliter->next()) {
491 // if there's no pagename it's an attribute
492 $names[] = $rel->getName();
494 $relations = array_merge($relations, $names);
506 * Call the appropriate backend method.
508 * @param string $from Page to rename
509 * @param string $to New name
510 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
511 * @return boolean true or false
513 public function renamePage($from, $to, $updateWikiLinks = false)
516 * @var WikiRequest $request
520 if (!empty($this->readonly)) {
521 trigger_error("readonly database", E_USER_WARNING);
524 assert(is_string($from) && $from != '');
525 assert(is_string($to) && $to != '');
527 if (method_exists($this->_backend, 'rename_page')) {
528 $oldpage = $this->getPage($from);
529 $newpage = $this->getPage($to);
530 //update all WikiLinks in existing pages
531 //non-atomic! i.e. if rename fails the links are not undone
532 if ($updateWikiLinks) {
533 $lookbehind = "/(?<=[\W:])\Q";
534 $lookahead = "\E(?=[\W:])/";
535 require_once 'lib/plugin/WikiAdminSearchReplace.php';
536 $links = $oldpage->getBackLinks();
537 while ($linked_page = $links->next()) {
538 WikiPlugin_WikiAdminSearchReplace::replaceHelper
540 $linked_page->getName(),
541 $lookbehind . $from . $lookahead, $to,
544 // FIXME: Disabled to avoid recursive modification when renaming
545 // a page like 'PageFoo to 'PageFooTwo'
547 $links = $newpage->getBackLinks();
548 while ($linked_page = $links->next()) {
549 WikiPlugin_WikiAdminSearchReplace::replaceHelper
551 $linked_page->getName(),
552 $lookbehind . $from . $lookahead, $to,
557 if ($oldpage->exists() and !$newpage->exists()) {
558 if ($result = $this->_backend->rename_page($from, $to)) {
559 // create a RecentChanges entry with explaining summary
560 $page = $this->getPage($to);
561 $current = $page->getCurrentRevision();
562 $meta = $current->_data;
563 $version = $current->getVersion();
564 $meta['summary'] = sprintf(_("renamed from %s"), $from);
565 unset($meta['mtime']); // force new date
566 $page->save($current->getPackedContent(), $version + 1, $meta);
568 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
569 // if a version 0 exists try it also.
570 $result = $this->_backend->rename_page($from, $to);
573 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
576 /* Generate notification emails? */
577 if ($result and ENABLE_MAILNOTIFY and !is_a($request, 'MockRequest')) {
578 $notify = $this->get('notify');
579 if (!empty($notify) and is_array($notify)) {
580 include_once 'lib/MailNotify.php';
581 $MailNotify = new MailNotify($from);
582 $MailNotify->onRenamePage($this, $from, $to);
588 /** Get timestamp when database was last modified.
590 * @return string A string consisting of two integers,
591 * separated by a space. The first is the time in
592 * unix timestamp format, the second is a modification
593 * count for the database.
595 * The idea is that you can cast the return value to an
596 * int to get a timestamp, or you can use the string value
597 * as a good hash for the entire database.
599 function getTimestamp()
601 $ts = $this->get('_timestamp');
602 return sprintf("%d %d", $ts[0], $ts[1]);
606 * Update the database timestamp.
610 $ts = $this->get('_timestamp');
611 $this->set('_timestamp', array(time(), $ts[1] + 1));
615 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
617 function get_db_version()
619 return (float)$this->get('_db_version');
622 function set_db_version($ver)
624 $this->set('_db_version', (float)$ver);
628 * Access WikiDB global meta-data.
630 * NOTE: this is currently implemented in a hackish and
631 * not very efficient manner.
633 * @param string $key Which meta data to get.
634 * Some reserved meta-data keys are:
636 * <dt>'_timestamp' <dd> Data used by getTimestamp().
639 * @return mixed The requested value, or false if the requested data
642 public function get($key)
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.
667 * @param string $key Meta-data key to set.
668 * @param string $newval New value.
670 public function set($key, $newval)
672 if (!empty($this->readonly)) {
673 trigger_error("readonly database", E_USER_WARNING);
676 if (!$key || $key[0] == '%')
679 $gd = $this->getPage('global_data');
680 $data = $gd->get('__global');
687 $data[$key] = $newval;
689 $gd->set('__global', $data);
692 /* TODO: these are really backend methods */
694 // SQL result: for simple select or create/update queries
695 // returns the database specific resource type
696 function genericSqlQuery($sql, $args = false)
699 printSimpleTrace(debug_backtrace());
701 trigger_error("no SQL database", E_USER_ERROR);
705 // SQL iter: for simple select or create/update queries
706 // returns the generic iterator object (count,next)
707 function genericSqlIter($sql, $field_list = NULL)
710 printSimpleTrace(debug_backtrace());
712 trigger_error("no SQL database", E_USER_ERROR);
716 // see backend upstream methods
717 // ADODB adds surrounding quotes, SQL not yet!
725 return false; /* so far only needed for sql so false it.
726 later we have to check dba also */
729 function getParam($param)
732 if (isset($DBParams[$param]))
733 return $DBParams[$param];
734 elseif ($param == 'prefix')
740 function getAuthParam($param)
742 global $DBAuthParams;
743 if (isset($DBAuthParams[$param]))
744 return $DBAuthParams[$param];
745 elseif ($param == 'USER_AUTH_ORDER')
746 return $GLOBALS['USER_AUTH_ORDER'];
747 elseif ($param == 'USER_AUTH_POLICY')
748 return $GLOBALS['USER_AUTH_POLICY'];
755 * A base class which representing a wiki-page within a
758 * A WikiDB_Page contains a number (at least one) of
759 * WikiDB_PageRevisions.
767 function __construct(&$wikidb, $pagename)
769 $this->_wikidb = &$wikidb;
770 $this->_pagename = $pagename;
772 if (!(is_string($pagename) and $pagename != '')) {
773 if (function_exists("xdebug_get_function_stack")) {
774 echo "xdebug_get_function_stack(): ";
775 var_dump(xdebug_get_function_stack());
777 printSimpleTrace(debug_backtrace());
779 trigger_error("empty pagename", E_USER_WARNING);
783 assert(is_string($pagename) and $pagename != '');
788 * Get the name of the wiki page.
790 * @return string The page name.
792 public function getName()
794 return $this->_pagename;
797 // To reduce the memory footprint for larger sets of pagelists,
798 // we don't cache the content (only true or false) and
799 // we purge the pagedata (_cached_html) also
802 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
803 $current = $this->getCurrentRevision(false);
804 if (!$current) return false;
805 return !$current->hasDefaultContents();
809 * Delete an old revision of a WikiDB_Page.
811 * Deletes the specified revision of the page.
812 * It is a fatal error to attempt to delete the current revision.
814 * @param integer $version Which revision to delete. (You can also
815 * use a WikiDB_PageRevision object here.)
817 public function deleteRevision($version)
819 if ($this->_wikidb->readonly) {
820 trigger_error("readonly database", E_USER_WARNING);
823 $backend = &$this->_wikidb->_backend;
824 $cache = &$this->_wikidb->_cache;
825 $pagename = &$this->_pagename;
827 $version = $this->_coerce_to_version($version);
831 $backend->lock(array('page', 'version'));
832 $latestversion = $cache->get_latest_version($pagename);
833 if ($latestversion && ($version == $latestversion)) {
834 $backend->unlock(array('page', 'version'));
835 trigger_error(sprintf("Attempt to delete most recent revision of “%s”",
836 $pagename), E_USER_ERROR);
840 $cache->delete_versiondata($pagename, $version);
841 $backend->unlock(array('page', 'version'));
845 * Delete a revision, or possibly merge it with a previous
849 * Suppose an author make a (major) edit to a page. Shortly
850 * after that the same author makes a minor edit (e.g. to fix
851 * spelling mistakes he just made.)
853 * Now some time later, where cleaning out old saved revisions,
854 * and would like to delete his minor revision (since there's
855 * really no point in keeping minor revisions around for a long
858 * Note that the text after the minor revision probably represents
859 * what the author intended to write better than the text after
860 * the preceding major edit.
862 * So what we really want to do is merge the minor edit with the
865 * We will only do this when:
867 * <li>The revision being deleted is a minor one, and
868 * <li>It has the same author as the immediately preceding revision.
871 function mergeRevision($version)
873 if ($this->_wikidb->readonly) {
874 trigger_error("readonly database", E_USER_WARNING);
877 $backend = &$this->_wikidb->_backend;
878 $cache = &$this->_wikidb->_cache;
879 $pagename = &$this->_pagename;
881 $version = $this->_coerce_to_version($version);
885 $backend->lock(array('version'));
886 $latestversion = $cache->get_latest_version($pagename);
887 if ($latestversion && $version == $latestversion) {
888 $backend->unlock(array('version'));
889 trigger_error(sprintf("Attempt to merge most recent revision of “%s”",
890 $pagename), E_USER_ERROR);
894 $versiondata = $cache->get_versiondata($pagename, $version, true);
896 // Not there? ... we're done!
897 $backend->unlock(array('version'));
901 if ($versiondata['is_minor_edit']) {
902 $previous = $backend->get_previous_version($pagename, $version);
904 $prevdata = $cache->get_versiondata($pagename, $previous);
905 if ($prevdata['author_id'] == $versiondata['author_id']) {
906 // This is a minor revision, previous version is
907 // by the same author. We will merge the
909 $cache->update_versiondata($pagename, $previous,
910 array('%content' => $versiondata['%content'],
911 '_supplanted' => $versiondata['_supplanted']));
916 $cache->delete_versiondata($pagename, $version);
917 $backend->unlock(array('version'));
921 * Create a new revision of a {@link WikiDB_Page}.
923 * @param int $version Version number for new revision.
924 * To ensure proper serialization of edits, $version must be
925 * exactly one higher than the current latest version.
926 * (You can defeat this check by setting $version to
927 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
929 * @param string $content Contents of new revision.
931 * @param array $metadata Metadata for new revision (hash).
932 * All values in the hash should be scalars (strings or integers).
934 * @param array $links List of linkto=>pagename, relation=>pagename which this page links to (hash).
936 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
937 * $version was incorrect, returns false
939 public function createRevision($version, &$content, $metadata, $links)
941 if ($this->_wikidb->readonly) {
942 trigger_error("readonly database", E_USER_WARNING);
945 $backend = &$this->_wikidb->_backend;
946 $cache = &$this->_wikidb->_cache;
947 $pagename = &$this->_pagename;
948 $cache->invalidate_cache($pagename);
950 $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
952 $latestversion = $backend->get_latest_version($pagename);
953 $newversion = ($latestversion ? $latestversion : 0) + 1;
954 assert($newversion >= 1);
956 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
957 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
963 foreach ($data as $key => $val) {
964 if (empty($val) || $key[0] == '_' || $key[0] == '%')
968 assert(!empty($data['author']));
969 if (empty($data['author_id']))
970 @$data['author_id'] = $data['author'];
972 if (empty($data['mtime']))
973 $data['mtime'] = time();
975 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
976 // Ensure mtimes are monotonic.
977 $pdata = $cache->get_versiondata($pagename, $latestversion);
978 if ($data['mtime'] < $pdata['mtime']) {
979 trigger_error(sprintf(_("%s: Date of new revision is %s"),
980 $pagename, "'non-monotonic'"),
982 $data['orig_mtime'] = $data['mtime'];
983 $data['mtime'] = $pdata['mtime'];
986 // FIXME: use (possibly user specified) 'mtime' time or
988 $cache->update_versiondata($pagename, $latestversion,
989 array('_supplanted' => $data['mtime']));
992 $data['%content'] = &$content;
994 $cache->set_versiondata($pagename, $newversion, $data);
996 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
997 //':deleted' => empty($content)));
999 $backend->set_links($pagename, $links);
1001 $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
1003 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion, $data);
1006 /** A higher-level interface to createRevision.
1008 * This takes care of computing the links, and storing
1009 * a cached version of the transformed wiki-text.
1011 * @param string $wikitext The page content.
1013 * @param int $version Version number for new revision.
1014 * To ensure proper serialization of edits, $version must be
1015 * exactly one higher than the current latest version.
1016 * (You can defeat this check by setting $version to
1017 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
1019 * @param array $meta Meta-data for new revision.
1021 * @param mixed $formatted
1025 function save($wikitext, $version, $meta, $formatted = null)
1028 * @var WikiRequest $request
1032 if ($this->_wikidb->readonly) {
1033 trigger_error("readonly database", E_USER_WARNING);
1036 if (is_null($formatted))
1037 $formatted = new TransformedText($this, $wikitext, $meta);
1038 $type = $formatted->getType();
1039 $meta['pagetype'] = $type->getName();
1040 $links = $formatted->getWikiPageLinks(); // linkto => relation
1041 $attributes = array();
1042 foreach ($links as $link) {
1043 if ($link['linkto'] === "" and !empty($link['relation'])) {
1044 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1047 $meta['attribute'] = $attributes;
1049 $backend = &$this->_wikidb->_backend;
1050 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1051 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1052 $this->set('_cached_html', $formatted->pack());
1054 // FIXME: probably should have some global state information
1055 // in the backend to control when to optimize.
1057 // We're doing this here rather than in createRevision because
1058 // postgresql can't optimize while locked.
1059 if (((int)DEBUG & _DEBUG_SQL)
1060 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1061 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1063 if ($backend->optimize()) {
1065 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1070 /* Generate notification emails? */
1071 if (ENABLE_MAILNOTIFY and is_a($newrevision, 'WikiDB_PageRevision')) {
1072 // Save didn't fail because of concurrent updates.
1073 $notify = $this->_wikidb->get('notify');
1075 and is_array($notify)
1076 and !is_a($request, 'MockRequest')
1078 include_once 'lib/MailNotify.php';
1079 $MailNotify = new MailNotify($newrevision->getName());
1080 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1082 $newrevision->_transformedContent = $formatted;
1084 // more pagechange callbacks: (in a hackish manner for now)
1085 if (ENABLE_RECENTCHANGESBOX
1086 and empty($meta['is_minor_edit'])
1087 and !in_array($request->getArg('action'),
1088 array('loadfile', 'upgrade'))
1090 require_once 'lib/WikiPlugin.php';
1091 $w = new WikiPluginLoader();
1092 $p = $w->getPlugin("RecentChangesCached", false);
1093 $p->box_update(false, $request, $this->_pagename);
1095 return $newrevision;
1099 * Get the most recent revision of a page.
1101 * @param bool $need_content
1102 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1104 public function getCurrentRevision($need_content = true)
1106 $cache = &$this->_wikidb->_cache;
1107 $pagename = &$this->_pagename;
1109 // Prevent deadlock in case of memory exhausted errors
1110 // Pure selection doesn't really need locking here.
1111 // sf.net bug#927395
1112 // I know it would be better to lock, but with lots of pages this deadlock is more
1113 // severe than occasionally get not the latest revision.
1114 // In spirit to wikiwiki: read fast, edit slower.
1116 $version = $cache->get_latest_version($pagename);
1117 // getRevision gets the content also!
1118 $revision = $this->getRevision($version, $need_content);
1119 //$backend->unlock();
1125 * Get a specific revision of a WikiDB_Page.
1127 * @param int $version Which revision to get.
1128 * @param bool $need_content
1129 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1130 * false if the requested revision does not exist in the {@link WikiDB}.
1131 * Note that version zero of any page always exists.
1133 public function getRevision($version, $need_content = true)
1135 $cache = &$this->_wikidb->_cache;
1136 $pagename = &$this->_pagename;
1138 if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1139 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1142 assert($version > 0);
1143 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1145 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1147 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1152 * Get previous page revision.
1154 * This method find the most recent revision before a specified
1157 * @param bool|int|WikiDB_PageRevision $version Find most recent revision before this version.
1159 * @param bool $need_content
1161 * @return WikiDB_PageRevision|bool The requested WikiDB_PageRevision object, or false if the
1162 * requested revision does not exist in the {@link WikiDB}. Note that
1163 * unless $version is greater than zero, a revision (perhaps version zero,
1164 * the default revision) will always be found.
1166 public function getRevisionBefore($version = false, $need_content = true)
1168 $backend = &$this->_wikidb->_backend;
1169 $pagename = &$this->_pagename;
1170 if ($version === false)
1171 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1173 $version = $this->_coerce_to_version($version);
1178 $previous = $backend->get_previous_version($pagename, $version);
1179 $revision = $this->getRevision($previous, $need_content);
1180 //$backend->unlock();
1186 * Get all revisions of the WikiDB_Page.
1188 * This does not include the version zero (default) revision in the
1189 * returned revision set.
1191 * @return WikiDB_PageRevisionIterator A
1192 * WikiDB_PageRevisionIterator containing all revisions of this
1193 * WikiDB_Page in reverse order by version number.
1195 function getAllRevisions()
1197 $backend = &$this->_wikidb->_backend;
1198 $revs = $backend->get_all_revisions($this->_pagename);
1199 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1203 * Find pages which link to or are linked from a page.
1204 * relations: $backend->get_links is responsible to add the relation to the pagehash
1205 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1206 * if (isset($next['linkrelation']))
1208 * @param bool $reversed Which links to find: true for backlinks (default).
1209 * @param bool $include_empty
1210 * @param string $sortby
1211 * @param string $limit
1212 * @param string $sortby
1213 * @param string $exclude
1214 * @param bool $want_relations
1215 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1216 * all matching pages.
1218 public function getLinks($reversed = true, $include_empty = false, $sortby = '',
1219 $limit = '', $exclude = '', $want_relations = false)
1221 $backend = &$this->_wikidb->_backend;
1222 $result = $backend->get_links($this->_pagename, $reversed,
1223 $include_empty, $sortby, $limit, $exclude,
1225 return new WikiDB_PageIterator($this->_wikidb, $result,
1226 array('include_empty' => $include_empty,
1227 'sortby' => $sortby,
1229 'exclude' => $exclude,
1230 'want_relations' => $want_relations));
1234 * All Links from other pages to this page.
1236 function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1238 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1242 * Forward Links: All Links from this page to other pages.
1244 function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1246 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1250 * Relations: All links from this page to other pages with relation <> 0.
1251 * is_a:=page or population:=number
1253 function getRelations($sortby = '', $limit = '', $exclude = '')
1255 $backend = &$this->_wikidb->_backend;
1256 $result = $backend->get_links($this->_pagename, false, true,
1257 $sortby, $limit, $exclude,
1259 // we do not care for the linked page versiondata, just the pagename and linkrelation
1260 return new WikiDB_PageIterator($this->_wikidb, $result,
1261 array('include_empty' => true,
1262 'sortby' => $sortby,
1264 'exclude' => $exclude,
1265 'want_relations' => true));
1269 * possibly faster link existance check. not yet accelerated.
1271 function existLink($link, $reversed = false)
1273 $backend = &$this->_wikidb->_backend;
1274 if (method_exists($backend, 'exists_link'))
1275 return $backend->exists_link($this->_pagename, $link, $reversed);
1276 //$cache = &$this->_wikidb->_cache;
1277 // TODO: check cache if it is possible
1278 $iter = $this->getLinks($reversed, false);
1279 while ($page = $iter->next()) {
1280 if ($page->getName() == $link)
1287 /* Semantic relations are links with the relation pointing to another page,
1288 the so-called "RDF Triple".
1289 [San Diego] is%20a::city
1290 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1293 /* Semantic attributes for a page.
1294 [San Diego] population:=1,305,736
1295 Attributes are links with the relation pointing to another page.
1299 * Access WikiDB_Page non version-specific meta-data.
1301 * @param string $key Which meta data to get.
1302 * Some reserved meta-data keys are:
1304 * <dt>'date' <dd> Created as unixtime
1305 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1306 * <dt>'hits' <dd> Page hit counter.
1307 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1308 * In SQL stored now in an extra column.
1310 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1311 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1312 * E.g. "owner.users"
1313 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1314 * page-headers and content.
1315 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1316 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1319 * @return mixed The requested value, or false if the requested data
1322 public function get($key)
1324 $cache = &$this->_wikidb->_cache;
1325 $backend = &$this->_wikidb->_backend;
1326 if (!$key || $key[0] == '%')
1328 // several new SQL backends optimize this.
1329 if (!WIKIDB_NOCACHE_MARKUP
1330 and $key == '_cached_html'
1331 and method_exists($backend, 'get_cached_html')
1333 return $backend->get_cached_html($this->_pagename);
1335 $data = $cache->get_pagedata($this->_pagename);
1336 return isset($data[$key]) ? $data[$key] : false;
1340 * Get all the page meta-data as a hash.
1342 * @return array The page meta-data (hash).
1344 function getMetaData()
1346 $cache = &$this->_wikidb->_cache;
1347 $data = $cache->get_pagedata($this->_pagename);
1349 foreach ($data as $key => $val) {
1350 if ( /*!empty($val) &&*/
1359 * Set page meta-data.
1363 * @param string $key Meta-data key to set.
1364 * @param string $newval New value.
1366 public function set($key, $newval)
1368 $cache = &$this->_wikidb->_cache;
1369 $backend = &$this->_wikidb->_backend;
1370 $pagename = &$this->_pagename;
1372 assert($key && $key[0] != '%');
1374 // several new SQL backends optimize this.
1375 if (!WIKIDB_NOCACHE_MARKUP
1376 and $key == '_cached_html'
1377 and method_exists($backend, 'set_cached_html')
1379 if ($this->_wikidb->readonly) {
1380 trigger_error("readonly database", E_USER_WARNING);
1383 $backend->set_cached_html($pagename, $newval);
1387 $data = $cache->get_pagedata($pagename);
1389 if (!empty($newval)) {
1390 if (!empty($data[$key]) && $data[$key] == $newval)
1391 return; // values identical, skip update.
1393 if (empty($data[$key]))
1394 return; // values identical, skip update.
1397 if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1398 trigger_error("readonly database", E_USER_WARNING);
1401 $cache->update_pagedata($pagename, array($key => $newval));
1405 * Increase page hit count.
1407 * FIXME: IS this needed? Probably not.
1409 * This is a convenience function.
1410 * <pre> $page->increaseHitCount(); </pre>
1411 * is functionally identical to
1412 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1413 * but less expensive (ignores the pagadata string)
1415 * Note that this method may be implemented in more efficient ways
1416 * in certain backends.
1418 public function increaseHitCount()
1420 if ($this->_wikidb->readonly) {
1421 trigger_error("readonly database", E_USER_NOTICE);
1424 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1425 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1427 @$newhits = $this->get('hits') + 1;
1428 $this->set('hits', $newhits);
1433 * Return a string representation of the WikiDB_Page
1435 * This is really only for debugging.
1437 * @return string Printable representation of the WikiDB_Page.
1439 public function asString()
1442 printf("[%s:%s\n", get_class($this), $this->getName());
1443 print_r($this->getMetaData());
1445 $strval = ob_get_contents();
1451 * @param int|object $version_or_pagerevision
1452 * Takes either the version number (and int) or a WikiDB_PageRevision
1454 * @return integer The version number.
1456 private function _coerce_to_version($version_or_pagerevision)
1458 if (method_exists($version_or_pagerevision, "getContent"))
1459 $version = $version_or_pagerevision->getVersion();
1461 $version = (int)$version_or_pagerevision;
1463 assert($version >= 0);
1467 function isUserPage($include_empty = true)
1469 if (!$include_empty and !$this->exists()) return false;
1470 return $this->get('pref') ? true : false;
1473 // May be empty. Either the stored owner (/Chown), or the first authorized author
1476 if ($owner = $this->get('owner'))
1478 // check all revisions forwards for the first author_id
1479 $backend = &$this->_wikidb->_backend;
1480 $pagename = &$this->_pagename;
1481 $latestversion = $backend->get_latest_version($pagename);
1482 for ($v = 1; $v <= $latestversion; $v++) {
1483 $rev = $this->getRevision($v, false);
1484 if ($rev and $owner = $rev->get('author_id')) {
1491 // The authenticated author of the first revision or empty if not authenticated then.
1492 function getCreator()
1494 if ($current = $this->getRevision(1, false))
1495 return $current->get('author_id');
1500 // The authenticated author of the current revision.
1501 function getAuthor()
1503 if ($current = $this->getCurrentRevision(false))
1504 return $current->get('author_id');
1509 /* Semantic Web value, not stored in the links.
1510 * todo: unify with some unit knowledge
1512 function setAttribute($relation, $value)
1514 $attr = $this->get('attributes');
1516 $attr = array($relation => $value);
1518 $attr[$relation] = $value;
1519 $this->set('attributes', $attr);
1522 function getAttribute($relation)
1524 $meta = $this->get('attributes');
1528 return $meta[$relation];
1534 * This class represents a specific revision of a WikiDB_Page within
1537 * A WikiDB_PageRevision has read-only semantics. You may only create
1538 * new revisions (and delete old ones) --- you cannot modify existing
1541 class WikiDB_PageRevision
1547 public $_transformedContent = false; // set by WikiDB_Page::save()
1549 function __construct(&$wikidb, $pagename, $version, $versiondata = array())
1551 $this->_wikidb = &$wikidb;
1552 $this->_pagename = $pagename;
1553 $this->_version = $version;
1554 $this->_data = $versiondata ? $versiondata : array();
1555 $this->_transformedContent = false; // set by WikiDB_Page::save()
1559 * Get the WikiDB_Page which this revision belongs to.
1561 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1563 public function getPage()
1565 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1569 * Get the version number of this revision.
1571 * @return int The version number of this revision.
1573 public function getVersion()
1575 return $this->_version;
1579 * Determine whether this revision has defaulted content.
1581 * The default revision (version 0) of each page, as well as any
1582 * pages which are created with empty content have their content
1583 * defaulted to something like:
1585 * Describe [ThisPage] here.
1588 * @return boolean Returns true if the page has default content.
1590 public function hasDefaultContents()
1592 $data = &$this->_data;
1593 if (!isset($data['%content'])) return true;
1594 if ($data['%content'] === true) return false;
1595 return $data['%content'] === false or $data['%content'] === "";
1599 * Get the content as an array of lines.
1601 * @return array An array of lines.
1602 * The lines should contain no trailing white space.
1604 public function getContent()
1606 return explode("\n", $this->getPackedContent());
1610 * Get the pagename of the revision.
1612 * @return string pagename.
1614 public function getPageName()
1616 return $this->_pagename;
1621 return $this->_pagename;
1625 * Determine whether revision is the latest.
1627 * @return boolean True iff the revision is the latest (most recent) one.
1629 public function isCurrent()
1631 if (!isset($this->_iscurrent)) {
1632 $page = $this->getPage();
1633 $current = $page->getCurrentRevision(false);
1634 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1636 return $this->_iscurrent;
1640 * Get the transformed content of a page.
1642 * @param bool $pagetype_override
1643 * @return object An XmlContent-like object containing the page transformed
1646 function getTransformedContent($pagetype_override = false)
1648 if ($pagetype_override) {
1649 // Figure out the normal page-type for this page.
1650 $type = PageType::GetPageType($this->get('pagetype'));
1651 if ($type->getName() == $pagetype_override)
1652 $pagetype_override = false; // Not really an override...
1655 if ($pagetype_override) {
1656 // Overriden page type, don't cache (or check cache).
1657 return new TransformedText($this->getPage(),
1658 $this->getPackedContent(),
1659 $this->getMetaData(),
1660 $pagetype_override);
1663 $possibly_cache_results = true;
1665 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1666 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1667 // flush cache for this page.
1668 $page = $this->getPage();
1669 $page->set('_cached_html', ''); // ignored with !USECACHE
1671 $possibly_cache_results = false;
1672 } elseif (USECACHE and !$this->_transformedContent) {
1674 if ($this->isCurrent()) {
1675 $page = $this->getPage();
1676 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1678 $possibly_cache_results = false;
1680 //$backend->unlock();
1683 if (!$this->_transformedContent) {
1684 $this->_transformedContent
1685 = new TransformedText($this->getPage(),
1686 $this->getPackedContent(),
1687 $this->getMetaData());
1689 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1690 // If we're still the current version, cache the transfomed page.
1692 if ($this->isCurrent()) {
1693 $page->set('_cached_html', $this->_transformedContent->pack());
1695 //$backend->unlock();
1699 return $this->_transformedContent;
1703 * Get the content as a string.
1705 * @return string The page content.
1706 * Lines are separated by new-lines.
1708 public function getPackedContent()
1711 * @var WikiRequest $request
1715 $data = &$this->_data;
1717 if (empty($data['%content'])
1718 || (!$this->_wikidb->isWikiPage($this->_pagename)
1719 && $this->isCurrent())
1721 include_once 'lib/InlineParser.php';
1723 // A feature similar to taglines at http://www.wlug.org.nz/
1724 // Lib from http://www.aasted.org/quote/
1725 if (defined('FORTUNE_DIR')
1726 and is_dir(FORTUNE_DIR)
1727 and in_array($request->getArg('action'),
1728 array('create', 'edit'))
1730 include_once 'lib/fortune.php';
1731 $fortune = new Fortune();
1732 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1734 $quote = "<verbatim>\n"
1735 . str_replace("\n<br>", "\n", $quote)
1736 . "</verbatim>\n\n";
1740 . sprintf(_("Describe %s here."),
1741 "[" . WikiEscape($this->_pagename) . "]");
1743 // Replace empty content with default value.
1744 return sprintf(_("Describe %s here."),
1745 "[" . WikiEscape($this->_pagename) . "]");
1748 // There is (non-default) content.
1749 assert($this->_version > 0);
1751 if (!is_string($data['%content'])) {
1752 // Content was not provided to us at init time.
1753 // (This is allowed because for some backends, fetching
1754 // the content may be expensive, and often is not wanted
1757 // In any case, now we need to get it.
1758 $data['%content'] = $this->_get_content();
1759 assert(is_string($data['%content']));
1762 return $data['%content'];
1765 function _get_content()
1767 $cache = &$this->_wikidb->_cache;
1768 $pagename = $this->_pagename;
1769 $version = $this->_version;
1771 assert($version > 0);
1773 $newdata = $cache->get_versiondata($pagename, $version, true);
1775 assert(is_string($newdata['%content']));
1776 return $newdata['%content'];
1778 // else revision has been deleted... What to do?
1779 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1780 $version, $pagename);
1785 * Get meta-data for this revision.
1787 * @param string $key Which meta-data to access.
1789 * Some reserved revision meta-data keys are:
1791 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1792 * The 'mtime' meta-value is normally set automatically by the database
1793 * backend, but it may be specified explicitly when creating a new revision.
1795 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1796 * of a page must be monotonically increasing. If an attempt is
1797 * made to create a new revision with an mtime less than that of
1798 * the preceeding revision, the new revisions timestamp is force
1799 * to be equal to that of the preceeding revision. In that case,
1800 * the originally requested mtime is preserved in 'orig_mtime'.
1801 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1802 * This meta-value is <em>always</em> automatically maintained by the database
1803 * backend. (It is set from the 'mtime' meta-value of the superceding
1804 * revision.) '_supplanted' has a value of 'false' for the current revision.
1806 * FIXME: this could be refactored:
1808 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1810 * <dd> Authenticated author of a page. This is used to identify
1811 * the distinctness of authors when cleaning old revisions from
1813 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1814 * <dt> 'summary' <dd> Short change summary entered by page author.
1817 * Meta-data keys must be valid C identifers (they have to start with a letter
1818 * or underscore, and can contain only alphanumerics and underscores.)
1820 * @return string The requested value, or false if the requested value
1823 public function get($key)
1825 if (!$key || $key[0] == '%')
1827 $data = &$this->_data;
1828 return isset($data[$key]) ? $data[$key] : false;
1832 * Get all the revision page meta-data as a hash.
1834 * @return array The revision meta-data.
1836 function getMetaData()
1839 foreach ($this->_data as $key => $val) {
1840 if (!empty($val) && $key[0] != '%')
1847 * Return a string representation of the revision.
1849 * This is really only for debugging.
1851 * @return string Printable representation of the WikiDB_Page.
1853 public function asString()
1856 printf("[%s:%d\n", get_class($this), $this->get('version'));
1857 print_r($this->_data);
1858 echo $this->getPackedContent() . "\n]\n";
1859 $strval = ob_get_contents();
1866 * Class representing a sequence of WikiDB_Pages.
1867 * TODO: Enhance to php5 iterators
1869 * apply filters for options like 'sortby', 'limit', 'exclude'
1870 * for simple queries like titleSearch, where the backend is not ready yet.
1872 class WikiDB_PageIterator
1878 function __construct(&$wikidb, &$iter, $options = array())
1880 $this->_iter = $iter; // a WikiDB_backend_iterator
1881 $this->_wikidb = &$wikidb;
1882 $this->_options = $options;
1887 return $this->_iter->count();
1892 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1896 * Get next WikiDB_Page in sequence.
1898 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1900 public function next()
1902 if (!($next = $this->_iter->next())) {
1906 $pagename = &$next['pagename'];
1907 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1908 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1912 if (isset($next['linkrelation'])
1913 or isset($next['pagedata']['linkrelation'])
1919 // There's always hits, but we cache only if more
1920 // (well not with file, cvs and dba)
1921 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1922 $this->_wikidb->_cache->cache_data($next);
1923 // cache existing page id's since we iterate over all links in GleanDescription
1924 // and need them later for LinkExistingWord
1925 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1926 and !$this->_options['include_empty'] and isset($next['id'])
1928 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1930 $page = new WikiDB_Page($this->_wikidb, $pagename);
1931 if (isset($next['linkrelation']))
1932 $page->set('linkrelation', $next['linkrelation']);
1933 if (isset($next['score']))
1934 $page->score = $next['score'];
1939 * Release resources held by this iterator.
1941 * The iterator may not be used after free() is called.
1943 * There is no need to call free(), if next() has returned false.
1944 * (I.e. if you iterate through all the pages in the sequence,
1945 * you do not need to call free() --- you only need to call it
1946 * if you stop before the end of the iterator is reached.)
1948 public function free()
1950 // $this->_iter->free();
1955 $this->_iter->reset();
1961 while ($page = $this->next())
1968 * Apply filters for options like 'sortby', 'limit', 'exclude'
1969 * for simple queries like titleSearch, where the backend is not ready yet.
1970 * Since iteration is usually destructive for SQL results,
1971 * we have to generate a copy.
1973 function applyFilters($options = false)
1975 if (!$options) $options = $this->_options;
1976 if (isset($options['sortby'])) {
1978 /* this is destructive */
1979 while ($page = $this->next())
1980 $result[] = $page->getName();
1981 $this->_doSort($array, $options['sortby']);
1983 /* the rest is not destructive.
1984 * reconstruct a new iterator
1986 $pagenames = array();
1988 if (isset($options['limit']))
1989 $limit = $options['limit'];
1992 if (isset($options['exclude']))
1993 $exclude = $options['exclude'];
1994 if (is_string($exclude) and !is_array($exclude))
1995 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1996 foreach ($array as $pagename) {
1997 if ($limit and $i++ > $limit)
1998 return new WikiDB_Array_PageIterator($pagenames);
1999 if (!empty($exclude) and !in_array($pagename, $exclude))
2000 $pagenames[] = $pagename;
2001 elseif (empty($exclude))
2002 $pagenames[] = $pagename;
2004 return new WikiDB_Array_PageIterator($pagenames);
2008 function _doSort(&$array, $sortby)
2010 $sortby = PageList::sortby($sortby, 'init');
2011 if ($sortby == '+pagename')
2012 sort($array, SORT_STRING);
2013 elseif ($sortby == '-pagename')
2014 rsort($array, SORT_STRING);
2021 * A class which represents a sequence of WikiDB_PageRevisions.
2022 * TODO: Enhance to php5 iterators
2024 class WikiDB_PageRevisionIterator
2030 function __construct(&$wikidb, &$revisions, $options = false)
2032 $this->_revisions = $revisions;
2033 $this->_wikidb = &$wikidb;
2034 $this->_options = $options;
2039 return $this->_revisions->count();
2043 * Get next WikiDB_PageRevision in sequence.
2045 * @return WikiDB_PageRevision
2046 * The next WikiDB_PageRevision in the sequence.
2048 public function next()
2050 if (!($next = $this->_revisions->next()))
2053 //$this->_wikidb->_cache->cache_data($next);
2055 $pagename = $next['pagename'];
2056 $version = $next['version'];
2057 $versiondata = $next['versiondata'];
2059 if (!(is_string($pagename) and $pagename != '')) {
2060 trigger_error("empty pagename", E_USER_WARNING);
2063 } else assert(is_string($pagename) and $pagename != '');
2065 if (!is_array($versiondata)) {
2066 trigger_error("empty versiondata", E_USER_WARNING);
2069 } else assert(is_array($versiondata));
2071 if (!($version > 0)) {
2072 trigger_error("invalid version", E_USER_WARNING);
2075 } else assert($version > 0);
2077 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version, $versiondata);
2081 * Release resources held by this iterator.
2083 * The iterator may not be used after free() is called.
2085 * There is no need to call free(), if next() has returned false.
2086 * (I.e. if you iterate through all the revisions in the sequence,
2087 * you do not need to call free() --- you only need to call it
2088 * if you stop before the end of the iterator is reached.)
2090 public function free()
2092 $this->_revisions->free();
2098 while ($rev = $this->next())
2107 class WikiDB_Array_PageIterator
2112 function __construct ($pagenames)
2115 * @var WikiRequest $request
2119 $this->_dbi = $request->getDbh();
2120 $this->_pages = $pagenames;
2121 reset($this->_pages);
2126 $c = current($this->_pages);
2127 next($this->_pages);
2128 return $c !== false ? $this->_dbi->getPage($c) : false;
2133 return count($this->_pages);
2138 reset($this->_pages);
2147 reset($this->_pages);
2148 return $this->_pages;
2152 class WikiDB_Array_generic_iter
2156 function __construct($result)
2158 // $result may be either an array or a query result
2159 if (is_array($result)) {
2160 $this->_array = $result;
2161 } elseif (is_object($result)) {
2162 $this->_array = $result->asArray();
2164 $this->_array = array();
2166 if (!empty($this->_array))
2167 reset($this->_array);
2172 $c = current($this->_array);
2173 next($this->_array);
2174 return $c !== false ? $c : false;
2179 return count($this->_array);
2184 reset($this->_array);
2193 if (!empty($this->_array))
2194 reset($this->_array);
2195 return $this->_array;
2200 * Data cache used by WikiDB.
2202 * FIXME: Maybe rename this to caching_backend (or some such).
2208 // FIXME: beautify versiondata cache. Cache only limited data?
2211 public $_pagedata_cache;
2212 public $_versiondata_cache;
2217 function __construct(&$backend)
2220 * @var WikiRequest $request
2224 $this->_backend = &$backend;
2225 $this->_pagedata_cache = array();
2226 $this->_versiondata_cache = array();
2227 array_push($this->_versiondata_cache, array());
2228 $this->_glv_cache = array();
2229 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2231 if (isset($request->_dbi))
2232 $this->readonly = $request->_dbi->readonly;
2237 $this->_pagedata_cache = array();
2238 $this->_versiondata_cache = array();
2239 $this->_glv_cache = array();
2240 $this->_id_cache = array();
2243 function get_pagedata($pagename)
2245 assert(is_string($pagename) && $pagename != '');
2247 $cache = &$this->_pagedata_cache;
2248 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2249 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2250 if (empty($cache[$pagename]))
2251 $cache[$pagename] = array();
2253 return $cache[$pagename];
2255 return $this->_backend->get_pagedata($pagename);
2259 function update_pagedata($pagename, $newdata)
2261 assert(is_string($pagename) && $pagename != '');
2262 if (!empty($this->readonly)) {
2263 trigger_error("readonly database", E_USER_WARNING);
2267 $this->_backend->update_pagedata($pagename, $newdata);
2270 if (!empty($this->_pagedata_cache[$pagename])
2271 and is_array($this->_pagedata_cache[$pagename])
2273 $cachedata = &$this->_pagedata_cache[$pagename];
2274 foreach ($newdata as $key => $val)
2275 $cachedata[$key] = $val;
2277 $this->_pagedata_cache[$pagename] = $newdata;
2281 function invalidate_cache($pagename)
2283 unset ($this->_pagedata_cache[$pagename]);
2284 unset ($this->_versiondata_cache[$pagename]);
2285 unset ($this->_glv_cache[$pagename]);
2286 unset ($this->_id_cache[$pagename]);
2287 //unset ($this->_backend->_page_data);
2290 function delete_page($pagename)
2292 if (!empty($this->readonly)) {
2293 trigger_error("readonly database", E_USER_WARNING);
2296 $result = $this->_backend->delete_page($pagename);
2297 $this->invalidate_cache($pagename);
2301 function purge_page($pagename)
2303 if (!empty($this->readonly)) {
2304 trigger_error("readonly database", E_USER_WARNING);
2307 $result = $this->_backend->purge_page($pagename);
2308 $this->invalidate_cache($pagename);
2312 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2313 function cache_data($data)
2316 //if (isset($data['pagedata']))
2317 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2320 function get_versiondata($pagename, $version, $need_content = false)
2322 // FIXME: Seriously ugly hackage
2324 if (USECACHE) { //temporary - for debugging
2325 assert(is_string($pagename) && $pagename != '');
2326 // There is a bug here somewhere which results in an assertion failure at line 105
2327 // of ArchiveCleaner.php It goes away if we use the next line.
2328 //$need_content = true;
2329 $nc = $need_content ? '1' : '0';
2330 $cache = &$this->_versiondata_cache;
2331 if (!isset($cache[$pagename][$version][$nc])
2332 || !(is_array($cache[$pagename]))
2333 || !(is_array($cache[$pagename][$version]))
2335 $cache[$pagename][$version][$nc] =
2336 $this->_backend->get_versiondata($pagename, $version, $need_content);
2338 // If we have retrieved all data, we may as well set the cache for
2339 // $need_content = false
2340 if ($need_content) {
2341 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2344 $vdata = $cache[$pagename][$version][$nc];
2346 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2349 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2350 if (empty($this->_pagedata_cache))
2351 $this->_pagedata_cache = array();
2352 /* 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 */
2353 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2358 function set_versiondata($pagename, $version, $data)
2360 //unset($this->_versiondata_cache[$pagename][$version]);
2362 if (!empty($this->readonly)) {
2363 trigger_error("readonly database", E_USER_WARNING);
2366 $this->_backend->set_versiondata($pagename, $version, $data);
2368 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2369 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2370 // Is this necessary?
2371 unset($this->_glv_cache[$pagename]);
2374 function update_versiondata($pagename, $version, $data)
2376 if (!empty($this->readonly)) {
2377 trigger_error("readonly database", E_USER_WARNING);
2380 $this->_backend->update_versiondata($pagename, $version, $data);
2382 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2384 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2385 // Is this necessary?
2386 unset($this->_glv_cache[$pagename]);
2389 function delete_versiondata($pagename, $version)
2391 if (!empty($this->readonly)) {
2392 trigger_error("readonly database", E_USER_WARNING);
2395 $this->_backend->delete_versiondata($pagename, $version);
2396 if (isset($this->_versiondata_cache[$pagename][$version]))
2397 unset ($this->_versiondata_cache[$pagename][$version]);
2398 // dirty latest version cache only if latest version gets deleted
2399 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2400 unset ($this->_glv_cache[$pagename]);
2403 function get_latest_version($pagename)
2406 assert(is_string($pagename) && $pagename != '');
2407 $cache = &$this->_glv_cache;
2408 if (!isset($cache[$pagename])) {
2409 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2410 if (empty($cache[$pagename]))
2411 $cache[$pagename] = 0;
2413 return $cache[$pagename];
2415 return $this->_backend->get_latest_version($pagename);
2420 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2425 $stamp = strftime("%y%m%d-%H%M%S");
2426 $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2427 register_shutdown_function("_sql_debuglog_shutdown_function");
2428 } elseif ($shutdown) {
2432 if ($newline) fputs($fp, "[$i++] $msg");
2433 else fwrite($fp, $msg);
2436 function _sql_debuglog_shutdown_function()
2438 _sql_debuglog('', false, true);
2444 // c-basic-offset: 4
2445 // c-hanging-comment-ender-p: nil
2446 // indent-tabs-mode: nil