1 <?php //rcs_id('$Id$');
2 require_once('lib/PageType.php');
5 * The classes in the file define the interface to the
9 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
10 * Minor enhancements by Reini Urban
14 * Force the creation of a new revision.
15 * @see WikiDB_Page::createRevision()
17 if (!defined('WIKIDB_FORCE_CREATE'))
18 define('WIKIDB_FORCE_CREATE', -1);
21 * Abstract base class for the database used by PhpWiki.
23 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
24 * turn contain <tt>WikiDB_PageRevision</tt>s.
26 * Conceptually a <tt>WikiDB</tt> contains all possible
27 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
28 * Since all possible pages are already contained in a WikiDB, a call
29 * to WikiDB::getPage() will never fail (barring bugs and
30 * e.g. filesystem or SQL database problems.)
32 * Also each <tt>WikiDB_Page</tt> always contains at least one
33 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
34 * [PageName] here."). This default content has a version number of
37 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
38 * only create new revisions or delete old ones --- one can not modify
39 * an existing revision.
43 * Open a WikiDB database.
45 * This is a static member function. This function inspects its
46 * arguments to determine the proper subclass of WikiDB to
47 * instantiate, and then it instantiates it.
51 * @param hash $dbparams Database configuration parameters.
52 * Some pertinent parameters are:
55 * <dd> The back-end type. Current supported types are:
58 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
59 * library. (More stable and conservative)
61 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
63 * <dd> Dba based backend. The default and by far the fastest.
71 * <dd> (Used by the SQL and ADODB backends.)
72 * The DSN specifying which database to connect to.
75 * <dd> Prefix to be prepended to database tables (and file names).
78 * <dd> (Used by the dba backend.)
79 * Which directory db files reside in.
82 * <dd> Used only by the dba backend so far.
83 * And: When optimizing mysql it closes timed out mysql processes.
84 * otherwise only used for dba: Timeout in seconds for opening (and
85 * obtaining lock) on the dbm file.
88 * <dd> (Used by the dba backend.)
90 * Which dba handler to use. Good choices are probably either
94 * <dd> Either set by config.ini: READONLY = true or detected automatically
95 * when a database can be read but cannot be updated.
98 * @return WikiDB A WikiDB object.
100 function open ($dbparams) {
101 $dbtype = $dbparams{'dbtype'};
102 include_once("lib/WikiDB/$dbtype.php");
104 $class = 'WikiDB_' . $dbtype;
105 return new $class ($dbparams);
115 function WikiDB (&$backend, $dbparams) {
116 $this->_backend =& $backend;
117 // don't do the following with the auth_dsn!
118 if (isset($dbparams['auth_dsn'])) return;
120 $this->_cache = new WikiDB_cache($backend);
121 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
123 // If the database doesn't yet have a timestamp, initialize it now.
124 if ($this->get('_timestamp') === false)
128 if ((int)DEBUG & _DEBUG_SQL) {
129 $this->_backend->check();
131 // might be changed when opening the database fails
132 $this->readonly = defined("READONLY") ? READONLY : false;
136 * Close database connection.
138 * The database may no longer be used after it is closed.
140 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
141 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
142 * which have been obtained from it.
147 $this->_backend->close();
148 $this->_cache->close();
152 * Get a WikiDB_Page from a WikiDB.
154 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
155 * therefore this method never fails.
158 * @param string $pagename Which page to get.
159 * @return WikiDB_Page The requested WikiDB_Page.
161 function getPage($pagename) {
162 static $error_displayed = false;
163 $pagename = (string) $pagename;
165 if ($pagename === '') {
166 if ($error_displayed) return false;
167 $error_displayed = true;
168 if (function_exists("xdebug_get_function_stack"))
169 var_dump(xdebug_get_function_stack());
170 trigger_error("empty pagename", E_USER_WARNING);
174 assert($pagename != '');
176 return new WikiDB_Page($this, $pagename);
180 * Determine whether page exists (in non-default form).
183 * $is_page = $dbi->isWikiPage($pagename);
187 * $page = $dbi->getPage($pagename);
188 * $current = $page->getCurrentRevision();
189 * $is_page = ! $current->hasDefaultContents();
191 * however isWikiPage may be implemented in a more efficient
192 * manner in certain back-ends.
195 * @param string $pagename string Which page to check.
196 * @return boolean True if the page actually exists with
197 * non-default contents in the WikiDataBase.
199 function isWikiPage ($pagename) {
200 $page = $this->getPage($pagename);
201 return ($page and $page->exists());
205 * Delete page from the WikiDB.
207 * Deletes the page from the WikiDB with the possibility to revert and diff.
208 * //Also resets all page meta-data to the default values.
210 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
213 * @param string $pagename Name of page to delete.
216 function deletePage($pagename) {
217 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
218 // don't create empty revisions of already purged pages.
219 if ($this->_backend->get_latest_version($pagename))
220 $result = $this->_cache->delete_page($pagename);
224 /* Generate notification emails */
225 if (ENABLE_MAILNOTIFY) {
226 include_once("lib/MailNotify.php");
227 $MailNotify = new MailNotify($pagename);
228 $MailNotify->onDeletePage ($this, $pagename);
231 //How to create a RecentChanges entry with explaining summary? Dynamically
233 $page = $this->getPage($pagename);
234 $current = $page->getCurrentRevision();
235 $meta = $current->_data;
236 $version = $current->getVersion();
237 $meta['summary'] = _("removed");
238 $page->save($current->getPackedContent(), $version + 1, $meta);
244 * Completely remove the page from the WikiDB, without undo possibility.
246 * @param string $pagename Name of page to delete.
249 function purgePage($pagename) {
250 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
251 $result = $this->_cache->purge_page($pagename);
252 $this->deletePage($pagename); // just for the notification
257 * Retrieve all pages.
259 * Gets the set of all pages with non-default contents.
263 * @param boolean $include_empty Optional. Normally pages whose most
264 * recent revision has empty content are considered to be
265 * non-existant. Unless $include_defaulted is set to true, those
266 * pages will not be returned.
267 * @param string or false $sortby Optional. "+-column,+-column2".
268 * If false the result is faster in natural order.
269 * @param string or false $limit Optional. Encoded as "$offset,$count".
270 * $offset defaults to 0.
271 * @param string $exclude: Optional comma-seperated list of pagenames.
273 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
274 * in the WikiDB which have non-default contents.
276 function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
278 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
280 return new WikiDB_PageIterator($this, $result,
281 array('include_empty' => $include_empty,
282 'exclude' => $exclude,
283 'limit' => $result->limit()));
289 * @param boolean $include_empty If true include also empty pages
290 * @param string $exclude: comma-seperated list of pagenames.
291 * TBD: array of pagenames
295 function numPages($include_empty=false, $exclude='') {
296 if (method_exists($this->_backend, 'numPages'))
297 // FIXME: currently are all args ignored.
298 $count = $this->_backend->numPages($include_empty, $exclude);
300 // FIXME: exclude ignored.
301 $iter = $this->getAllPages($include_empty, false, false, $exclude);
302 $count = $iter->count();
311 * Search for pages containing (or not containing) certain words
314 * Pages are returned in alphabetical order whenever it is
315 * practical to do so.
316 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
319 * @param TextSearchQuery $search A TextSearchQuery object
320 * @param string or false $sortby Optional. "+-column,+-column2".
321 * If false the result is faster in natural order.
322 * @param string or false $limit Optional. Encoded as "$offset,$count".
323 * $offset defaults to 0.
324 * @param string $exclude: Optional comma-seperated list of pagenames.
325 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
326 * @see TextSearchQuery
328 function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
329 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
330 $options = array('exclude' => $exclude,
332 //if (isset($result->_count)) $options['count'] = $result->_count;
333 return new WikiDB_PageIterator($this, $result, $options);
339 * Search for pages containing (or not containing) certain words
340 * in their entire text (this includes the page content and the
343 * Pages are returned in alphabetical order whenever it is
344 * practical to do so.
345 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
349 * @param TextSearchQuery $search A TextSearchQuery object.
350 * @param string or false $sortby Optional. "+-column,+-column2".
351 * If false the result is faster in natural order.
352 * @param string or false $limit Optional. Encoded as "$offset,$count".
353 * $offset defaults to 0.
354 * @param string $exclude: Optional comma-seperated list of pagenames.
355 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
356 * @see TextSearchQuery
358 function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
359 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
360 return new WikiDB_PageIterator($this, $result,
361 array('exclude' => $exclude,
363 'stoplisted' => $result->stoplisted
368 * Find the pages with the greatest hit counts.
370 * Pages are returned in reverse order by hit count.
374 * @param integer $limit The maximum number of pages to return.
375 * Set $limit to zero to return all pages. If $limit < 0, pages will
376 * be sorted in decreasing order of popularity.
377 * @param string or false $sortby Optional. "+-column,+-column2".
378 * If false the result is faster in natural order.
380 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
383 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.
395 * @param hash $params This hash is used to specify various optional
399 * <dd> (integer) At most this many revisions will be returned.
401 * <dd> (integer) Only revisions since this time (unix-timestamp)
403 * <dt> include_minor_revisions
404 * <dd> (boolean) Also include minor revisions. (Default is not to.)
405 * <dt> exclude_major_revisions
406 * <dd> (boolean) Don't include non-minor revisions.
407 * (Exclude_major_revisions implies include_minor_revisions.)
408 * <dt> include_all_revisions
409 * <dd> (boolean) Return all matching revisions for each page.
410 * Normally only the most recent matching revision is returned
414 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
415 * containing the matching revisions.
417 function mostRecent($params = false) {
418 $result = $this->_backend->most_recent($params);
419 return new WikiDB_PageRevisionIterator($this, $result);
425 * @param string or false $sortby Optional. "+-column,+-column2".
426 * If false the result is faster in natural order.
427 * @param string or false $limit Optional. Encoded as "$offset,$count".
428 * $offset defaults to 0.
429 * @return Iterator A generic iterator containing rows of
430 * (duplicate) pagename, wantedfrom.
432 function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
433 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
434 //return new WikiDB_PageIterator($this, $result);
438 * Generic interface to the link table. Esp. useful to search for rdf triples as in
439 * SemanticSearch and ListRelations.
443 * @param $pages object A TextSearchQuery object.
444 * @param $search object A TextSearchQuery object.
445 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
446 * linktype parameter:
449 * <dd> search for simple out-links
451 * <dd> in-links, i.e BackLinks
453 * <dd> the first part in a <>::<> link
455 * <dd> the first part in a <>:=<> link
457 * @param $relation object An optional TextSearchQuery to match the
458 * relation name. Ignored on simple in-out links.
460 * @return Iterator A generic iterator containing links to pages or values.
461 * hash of "pagename", "linkname", "linkvalue.
463 function linkSearch($pages, $search, $linktype, $relation=false) {
464 return $this->_backend->link_search($pages, $search, $linktype, $relation);
468 * Return a simple list of all defined relations (and attributes), mainly
469 * for the SemanticSearch autocompletion.
473 * @return array of strings
475 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.
503 * @param string $from Page to rename
504 * @param string $to New name
505 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
506 * @return boolean true or false
508 function renamePage($from, $to, $updateWikiLinks = false) {
509 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
510 assert(is_string($from) && $from != '');
511 assert(is_string($to) && $to != '');
513 if (method_exists($this->_backend, 'rename_page')) {
514 $oldpage = $this->getPage($from);
515 $newpage = $this->getPage($to);
516 //update all WikiLinks in existing pages
517 //non-atomic! i.e. if rename fails the links are not undone
518 if ($updateWikiLinks) {
519 $lookbehind = "/(?<=[\W:])\Q";
520 $lookahead = "\E(?=[\W:])/";
521 require_once('lib/plugin/WikiAdminSearchReplace.php');
522 $links = $oldpage->getBackLinks();
523 while ($linked_page = $links->next()) {
524 WikiPlugin_WikiAdminSearchReplace::replaceHelper
526 $linked_page->getName(),
527 $lookbehind.$from.$lookahead, $to,
530 // FIXME: Disabled to avoid recursive modification when renaming
531 // a page like 'PageFoo to 'PageFooTwo'
533 $links = $newpage->getBackLinks();
534 while ($linked_page = $links->next()) {
535 WikiPlugin_WikiAdminSearchReplace::replaceHelper
537 $linked_page->getName(),
538 $lookbehind.$from.$lookahead, $to,
543 if ($oldpage->exists() and ! $newpage->exists()) {
544 if ($result = $this->_backend->rename_page($from, $to)) {
545 // create a RecentChanges entry with explaining summary
546 $page = $this->getPage($to);
547 $current = $page->getCurrentRevision();
548 $meta = $current->_data;
549 $version = $current->getVersion();
550 $meta['summary'] = sprintf(_("renamed from %s"), $from);
551 unset($meta['mtime']); // force new date
552 $page->save($current->getPackedContent(), $version + 1, $meta);
554 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
555 // if a version 0 exists try it also.
556 $result = $this->_backend->rename_page($from, $to);
559 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
562 /* Generate notification emails? */
563 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
564 $notify = $this->get('notify');
565 if (!empty($notify) and is_array($notify)) {
566 include_once("lib/MailNotify.php");
567 $MailNotify = new MailNotify($from);
568 $MailNotify->onRenamePage ($this, $from, $to);
574 /** Get timestamp when database was last modified.
576 * @return string A string consisting of two integers,
577 * separated by a space. The first is the time in
578 * unix timestamp format, the second is a modification
579 * count for the database.
581 * The idea is that you can cast the return value to an
582 * int to get a timestamp, or you can use the string value
583 * as a good hash for the entire database.
585 function getTimestamp() {
586 $ts = $this->get('_timestamp');
587 return sprintf("%d %d", $ts[0], $ts[1]);
591 * Update the database timestamp.
595 $ts = $this->get('_timestamp');
596 $this->set('_timestamp', array(time(), $ts[1] + 1));
600 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
602 function get_db_version() {
603 return (float) $this->get('_db_version');
605 function set_db_version($ver) {
606 return $this->set('_db_version', (float)$ver);
610 * Access WikiDB global meta-data.
612 * NOTE: this is currently implemented in a hackish and
613 * not very efficient manner.
617 * @param string $key Which meta data to get.
618 * Some reserved meta-data keys are:
620 * <dt>'_timestamp' <dd> Data used by getTimestamp().
623 * @return scalar The requested value, or false if the requested data
627 if (!$key || $key[0] == '%')
630 * Hack Alert: We can use any page (existing or not) to store
631 * this data (as long as we always use the same one.)
633 $gd = $this->getPage('global_data');
634 $data = $gd->get('__global');
636 if ($data && isset($data[$key]))
643 * Set global meta-data.
645 * NOTE: this is currently implemented in a hackish and
646 * not very efficient manner.
651 * @param string $key Meta-data key to set.
652 * @param string $newval New value.
654 function set($key, $newval) {
655 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
656 if (!$key || $key[0] == '%')
659 $gd = $this->getPage('global_data');
660 $data = $gd->get('__global');
667 $data[$key] = $newval;
669 $gd->set('__global', $data);
672 /* TODO: these are really backend methods */
674 // SQL result: for simple select or create/update queries
675 // returns the database specific resource type
676 function genericSqlQuery($sql, $args=false) {
677 if (function_exists('debug_backtrace')) { // >= 4.3.0
678 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
680 trigger_error("no SQL database", E_USER_ERROR);
684 // SQL iter: for simple select or create/update queries
685 // returns the generic iterator object (count,next)
686 function genericSqlIter($sql, $field_list = NULL) {
687 if (function_exists('debug_backtrace')) { // >= 4.3.0
688 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
690 trigger_error("no SQL database", E_USER_ERROR);
694 // see backend upstream methods
695 // ADODB adds surrounding quotes, SQL not yet!
696 function quote ($s) {
702 if (!$request->_dbi) return false;
703 else return false; /* so far only needed for sql so false it.
704 later we have to check dba also */
707 function getParam($param) {
709 if (isset($DBParams[$param])) return $DBParams[$param];
710 elseif ($param == 'prefix') return '';
714 function getAuthParam($param) {
715 global $DBAuthParams;
716 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
717 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
718 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
725 * A base class which representing a wiki-page within a
728 * A WikiDB_Page contains a number (at least one) of
729 * WikiDB_PageRevisions.
733 function WikiDB_Page(&$wikidb, $pagename) {
734 $this->_wikidb = &$wikidb;
735 $this->_pagename = $pagename;
737 if (!(is_string($pagename) and $pagename != '')) {
738 if (function_exists("xdebug_get_function_stack")) {
739 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
740 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
741 printSimpleTrace(debug_backtrace());
743 trigger_error("empty pagename", E_USER_WARNING);
747 assert(is_string($pagename) and $pagename != '');
752 * Get the name of the wiki page.
756 * @return string The page name.
759 return $this->_pagename;
762 // To reduce the memory footprint for larger sets of pagelists,
763 // we don't cache the content (only true or false) and
764 // we purge the pagedata (_cached_html) also
766 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
767 $current = $this->getCurrentRevision(false);
768 if (!$current) return false;
769 return ! $current->hasDefaultContents();
773 * Delete an old revision of a WikiDB_Page.
775 * Deletes the specified revision of the page.
776 * It is a fatal error to attempt to delete the current revision.
780 * @param integer $version Which revision to delete. (You can also
781 * use a WikiDB_PageRevision object here.)
783 function deleteRevision($version) {
784 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
785 $backend = &$this->_wikidb->_backend;
786 $cache = &$this->_wikidb->_cache;
787 $pagename = &$this->_pagename;
789 $version = $this->_coerce_to_version($version);
793 $backend->lock(array('page','version'));
794 $latestversion = $cache->get_latest_version($pagename);
795 if ($latestversion && ($version == $latestversion)) {
796 $backend->unlock(array('page','version'));
797 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
798 $pagename), E_USER_ERROR);
802 $cache->delete_versiondata($pagename, $version);
803 $backend->unlock(array('page','version'));
807 * Delete a revision, or possibly merge it with a previous
811 * Suppose an author make a (major) edit to a page. Shortly
812 * after that the same author makes a minor edit (e.g. to fix
813 * spelling mistakes he just made.)
815 * Now some time later, where cleaning out old saved revisions,
816 * and would like to delete his minor revision (since there's
817 * really no point in keeping minor revisions around for a long
820 * Note that the text after the minor revision probably represents
821 * what the author intended to write better than the text after
822 * the preceding major edit.
824 * So what we really want to do is merge the minor edit with the
827 * We will only do this when:
829 * <li>The revision being deleted is a minor one, and
830 * <li>It has the same author as the immediately preceding revision.
833 function mergeRevision($version) {
834 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
835 $backend = &$this->_wikidb->_backend;
836 $cache = &$this->_wikidb->_cache;
837 $pagename = &$this->_pagename;
839 $version = $this->_coerce_to_version($version);
843 $backend->lock(array('version'));
844 $latestversion = $cache->get_latest_version($pagename);
845 if ($latestversion && $version == $latestversion) {
846 $backend->unlock(array('version'));
847 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
848 $pagename), E_USER_ERROR);
852 $versiondata = $cache->get_versiondata($pagename, $version, true);
854 // Not there? ... we're done!
855 $backend->unlock(array('version'));
859 if ($versiondata['is_minor_edit']) {
860 $previous = $backend->get_previous_version($pagename, $version);
862 $prevdata = $cache->get_versiondata($pagename, $previous);
863 if ($prevdata['author_id'] == $versiondata['author_id']) {
864 // This is a minor revision, previous version is
865 // by the same author. We will merge the
867 $cache->update_versiondata($pagename, $previous,
868 array('%content' => $versiondata['%content'],
869 '_supplanted' => $versiondata['_supplanted']));
874 $cache->delete_versiondata($pagename, $version);
875 $backend->unlock(array('version'));
880 * Create a new revision of a {@link WikiDB_Page}.
884 * @param int $version Version number for new revision.
885 * To ensure proper serialization of edits, $version must be
886 * exactly one higher than the current latest version.
887 * (You can defeat this check by setting $version to
888 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
890 * @param string $content Contents of new revision.
892 * @param hash $metadata Metadata for new revision.
893 * All values in the hash should be scalars (strings or integers).
895 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
897 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
898 * $version was incorrect, returns false
900 function createRevision($version, &$content, $metadata, $links) {
901 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
902 $backend = &$this->_wikidb->_backend;
903 $cache = &$this->_wikidb->_cache;
904 $pagename = &$this->_pagename;
905 $cache->invalidate_cache($pagename);
907 $backend->lock(array('version','page','recent','link','nonempty'));
909 $latestversion = $backend->get_latest_version($pagename);
910 $newversion = ($latestversion ? $latestversion : 0) + 1;
911 assert($newversion >= 1);
913 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
914 $backend->unlock(array('version','page','recent','link','nonempty'));
920 foreach ($data as $key => $val) {
921 if (empty($val) || $key[0] == '_' || $key[0] == '%')
925 assert(!empty($data['author']));
926 if (empty($data['author_id']))
927 @$data['author_id'] = $data['author'];
929 if (empty($data['mtime']))
930 $data['mtime'] = time();
932 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
933 // Ensure mtimes are monotonic.
934 $pdata = $cache->get_versiondata($pagename, $latestversion);
935 if ($data['mtime'] < $pdata['mtime']) {
936 trigger_error(sprintf(_("%s: Date of new revision is %s"),
937 $pagename,"'non-monotonic'"),
939 $data['orig_mtime'] = $data['mtime'];
940 $data['mtime'] = $pdata['mtime'];
943 // FIXME: use (possibly user specified) 'mtime' time or
945 $cache->update_versiondata($pagename, $latestversion,
946 array('_supplanted' => $data['mtime']));
949 $data['%content'] = &$content;
951 $cache->set_versiondata($pagename, $newversion, $data);
953 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
954 //':deleted' => empty($content)));
956 $backend->set_links($pagename, $links);
958 $backend->unlock(array('version','page','recent','link','nonempty'));
960 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
964 /** A higher-level interface to createRevision.
966 * This takes care of computing the links, and storing
967 * a cached version of the transformed wiki-text.
969 * @param string $wikitext The page content.
971 * @param int $version Version number for new revision.
972 * To ensure proper serialization of edits, $version must be
973 * exactly one higher than the current latest version.
974 * (You can defeat this check by setting $version to
975 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
977 * @param hash $meta Meta-data for new revision.
979 function save($wikitext, $version, $meta, $formatted = null) {
980 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
981 if (is_null($formatted))
982 $formatted = new TransformedText($this, $wikitext, $meta);
983 $type = $formatted->getType();
984 $meta['pagetype'] = $type->getName();
985 $links = $formatted->getWikiPageLinks(); // linkto => relation
986 $attributes = array();
987 foreach ($links as $link) {
988 if ($link['linkto'] === "" and !empty($link['relation'])) {
989 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
992 $meta['attribute'] = $attributes;
994 $backend = &$this->_wikidb->_backend;
995 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
996 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
997 $this->set('_cached_html', $formatted->pack());
999 // FIXME: probably should have some global state information
1000 // in the backend to control when to optimize.
1002 // We're doing this here rather than in createRevision because
1003 // postgresql can't optimize while locked.
1004 if (((int)DEBUG & _DEBUG_SQL)
1005 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1006 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1007 if ($backend->optimize()) {
1009 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1013 /* Generate notification emails? */
1014 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1015 // Save didn't fail because of concurrent updates.
1016 $notify = $this->_wikidb->get('notify');
1018 and is_array($notify)
1019 and !isa($GLOBALS['request'],'MockRequest'))
1021 include_once("lib/MailNotify.php");
1022 $MailNotify = new MailNotify($newrevision->getName());
1023 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1025 $newrevision->_transformedContent = $formatted;
1027 // more pagechange callbacks: (in a hackish manner for now)
1028 if (ENABLE_RECENTCHANGESBOX
1029 and empty($meta['is_minor_edit'])
1030 and !in_array($GLOBALS['request']->getArg('action'),
1031 array('loadfile','upgrade')))
1033 require_once("lib/WikiPlugin.php");
1034 $w = new WikiPluginLoader;
1035 $p = $w->getPlugin("RecentChangesCached", false);
1036 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1038 return $newrevision;
1042 * Get the most recent revision of a page.
1046 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1048 function getCurrentRevision ($need_content=true) {
1049 $backend = &$this->_wikidb->_backend;
1050 $cache = &$this->_wikidb->_cache;
1051 $pagename = &$this->_pagename;
1053 // Prevent deadlock in case of memory exhausted errors
1054 // Pure selection doesn't really need locking here.
1055 // sf.net bug#927395
1056 // I know it would be better to lock, but with lots of pages this deadlock is more
1057 // severe than occasionally get not the latest revision.
1058 // In spirit to wikiwiki: read fast, edit slower.
1060 $version = $cache->get_latest_version($pagename);
1061 // getRevision gets the content also!
1062 $revision = $this->getRevision($version, $need_content);
1063 //$backend->unlock();
1069 * Get a specific revision of a WikiDB_Page.
1073 * @param integer $version Which revision to get.
1075 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1076 * false if the requested revision does not exist in the {@link WikiDB}.
1077 * Note that version zero of any page always exists.
1079 function getRevision ($version, $need_content=true) {
1080 $cache = &$this->_wikidb->_cache;
1081 $pagename = &$this->_pagename;
1083 if (! $version or $version == -1) // 0 or false
1084 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1086 assert($version > 0);
1087 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1089 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1091 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1096 * Get previous page revision.
1098 * This method find the most recent revision before a specified
1103 * @param integer $version Find most recent revision before this version.
1104 * You can also use a WikiDB_PageRevision object to specify the $version.
1106 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1107 * requested revision does not exist in the {@link WikiDB}. Note that
1108 * unless $version is greater than zero, a revision (perhaps version zero,
1109 * the default revision) will always be found.
1111 function getRevisionBefore ($version=false, $need_content=true) {
1112 $backend = &$this->_wikidb->_backend;
1113 $pagename = &$this->_pagename;
1114 if ($version === false)
1115 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1117 $version = $this->_coerce_to_version($version);
1122 $previous = $backend->get_previous_version($pagename, $version);
1123 $revision = $this->getRevision($previous, $need_content);
1124 //$backend->unlock();
1130 * Get all revisions of the WikiDB_Page.
1132 * This does not include the version zero (default) revision in the
1133 * returned revision set.
1135 * @return WikiDB_PageRevisionIterator A
1136 * WikiDB_PageRevisionIterator containing all revisions of this
1137 * WikiDB_Page in reverse order by version number.
1139 function getAllRevisions() {
1140 $backend = &$this->_wikidb->_backend;
1141 $revs = $backend->get_all_revisions($this->_pagename);
1142 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1146 * Find pages which link to or are linked from a page.
1147 * relations: $backend->get_links is responsible to add the relation to the pagehash
1148 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1149 * if (isset($next['linkrelation']))
1153 * @param boolean $reversed Which links to find: true for backlinks (default).
1155 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1156 * all matching pages.
1158 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1159 $limit='', $exclude='', $want_relations=false)
1161 $backend = &$this->_wikidb->_backend;
1162 $result = $backend->get_links($this->_pagename, $reversed,
1163 $include_empty, $sortby, $limit, $exclude,
1165 return new WikiDB_PageIterator($this->_wikidb, $result,
1166 array('include_empty' => $include_empty,
1167 'sortby' => $sortby,
1169 'exclude' => $exclude,
1170 'want_relations'=> $want_relations));
1174 * All Links from other pages to this page.
1176 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1177 $want_relations=false)
1179 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1182 * Forward Links: All Links from this page to other pages.
1184 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1185 $want_relations=false)
1187 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1190 * Relations: All links from this page to other pages with relation <> 0.
1191 * is_a:=page or population:=number
1193 function getRelations($sortby='', $limit='', $exclude='') {
1194 $backend = &$this->_wikidb->_backend;
1195 $result = $backend->get_links($this->_pagename, false, true,
1196 $sortby, $limit, $exclude,
1198 // we do not care for the linked page versiondata, just the pagename and linkrelation
1199 return new WikiDB_PageIterator($this->_wikidb, $result,
1200 array('include_empty' => true,
1201 'sortby' => $sortby,
1203 'exclude' => $exclude,
1204 'want_relations'=> true));
1208 * possibly faster link existance check. not yet accelerated.
1210 function existLink($link, $reversed=false) {
1211 $backend = &$this->_wikidb->_backend;
1212 if (method_exists($backend,'exists_link'))
1213 return $backend->exists_link($this->_pagename, $link, $reversed);
1214 //$cache = &$this->_wikidb->_cache;
1215 // TODO: check cache if it is possible
1216 $iter = $this->getLinks($reversed, false);
1217 while ($page = $iter->next()) {
1218 if ($page->getName() == $link)
1225 /* Semantic relations are links with the relation pointing to another page,
1226 the so-called "RDF Triple".
1227 [San Diego] is%20a::city
1228 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1231 /* Semantic attributes for a page.
1232 [San Diego] population:=1,305,736
1233 Attributes are links with the relation pointing to another page.
1237 * Access WikiDB_Page non version-specific meta-data.
1241 * @param string $key Which meta data to get.
1242 * Some reserved meta-data keys are:
1244 * <dt>'date' <dd> Created as unixtime
1245 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1246 * <dt>'hits' <dd> Page hit counter.
1247 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1248 * In SQL stored now in an extra column.
1250 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1251 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1252 * E.g. "owner.users"
1253 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1254 * page-headers and content.
1255 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1256 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1259 * @return scalar The requested value, or false if the requested data
1262 function get($key) {
1263 $cache = &$this->_wikidb->_cache;
1264 $backend = &$this->_wikidb->_backend;
1265 if (!$key || $key[0] == '%')
1267 // several new SQL backends optimize this.
1268 if (!WIKIDB_NOCACHE_MARKUP
1269 and $key == '_cached_html'
1270 and method_exists($backend, 'get_cached_html'))
1272 return $backend->get_cached_html($this->_pagename);
1274 $data = $cache->get_pagedata($this->_pagename);
1275 return isset($data[$key]) ? $data[$key] : false;
1279 * Get all the page meta-data as a hash.
1281 * @return hash The page meta-data.
1283 function getMetaData() {
1284 $cache = &$this->_wikidb->_cache;
1285 $data = $cache->get_pagedata($this->_pagename);
1287 foreach ($data as $key => $val) {
1288 if (/*!empty($val) &&*/ $key[0] != '%')
1295 * Set page meta-data.
1300 * @param string $key Meta-data key to set.
1301 * @param string $newval New value.
1303 function set($key, $newval) {
1304 $cache = &$this->_wikidb->_cache;
1305 $backend = &$this->_wikidb->_backend;
1306 $pagename = &$this->_pagename;
1308 assert($key && $key[0] != '%');
1310 // several new SQL backends optimize this.
1311 if (!WIKIDB_NOCACHE_MARKUP
1312 and $key == '_cached_html'
1313 and method_exists($backend, 'set_cached_html'))
1315 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1316 return $backend->set_cached_html($pagename, $newval);
1319 $data = $cache->get_pagedata($pagename);
1321 if (!empty($newval)) {
1322 if (!empty($data[$key]) && $data[$key] == $newval)
1323 return; // values identical, skip update.
1326 if (empty($data[$key]))
1327 return; // values identical, skip update.
1330 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1331 $cache->update_pagedata($pagename, array($key => $newval));
1335 * Increase page hit count.
1337 * FIXME: IS this needed? Probably not.
1339 * This is a convenience function.
1340 * <pre> $page->increaseHitCount(); </pre>
1341 * is functionally identical to
1342 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1343 * but less expensive (ignores the pagadata string)
1345 * Note that this method may be implemented in more efficient ways
1346 * in certain backends.
1350 function increaseHitCount() {
1351 if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; }
1352 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1353 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1355 @$newhits = $this->get('hits') + 1;
1356 $this->set('hits', $newhits);
1361 * Return a string representation of the WikiDB_Page
1363 * This is really only for debugging.
1367 * @return string Printable representation of the WikiDB_Page.
1369 function asString () {
1371 printf("[%s:%s\n", get_class($this), $this->getName());
1372 print_r($this->getMetaData());
1374 $strval = ob_get_contents();
1382 * @param integer_or_object $version_or_pagerevision
1383 * Takes either the version number (and int) or a WikiDB_PageRevision
1385 * @return integer The version number.
1387 function _coerce_to_version($version_or_pagerevision) {
1388 if (method_exists($version_or_pagerevision, "getContent"))
1389 $version = $version_or_pagerevision->getVersion();
1391 $version = (int) $version_or_pagerevision;
1393 assert($version >= 0);
1397 function isUserPage ($include_empty = true) {
1398 if (!$include_empty and !$this->exists()) return false;
1399 return $this->get('pref') ? true : false;
1402 // May be empty. Either the stored owner (/Chown), or the first authorized author
1403 function getOwner() {
1404 if ($owner = $this->get('owner'))
1406 // check all revisions forwards for the first author_id
1407 $backend = &$this->_wikidb->_backend;
1408 $pagename = &$this->_pagename;
1409 $latestversion = $backend->get_latest_version($pagename);
1410 for ($v=1; $v <= $latestversion; $v++) {
1411 $rev = $this->getRevision($v,false);
1412 if ($rev and $owner = $rev->get('author_id')) {
1419 // The authenticated author of the first revision or empty if not authenticated then.
1420 function getCreator() {
1421 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1425 // The authenticated author of the current revision.
1426 function getAuthor() {
1427 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1431 /* Semantic Web value, not stored in the links.
1432 * todo: unify with some unit knowledge
1434 function setAttribute($relation, $value) {
1435 $attr = $this->get('attributes');
1437 $attr = array($relation => $value);
1439 $attr[$relation] = $value;
1440 $this->set('attributes', $attr);
1443 function getAttribute($relation) {
1444 $meta = $this->get('attributes');
1448 return $meta[$relation];
1454 * This class represents a specific revision of a WikiDB_Page within
1457 * A WikiDB_PageRevision has read-only semantics. You may only create
1458 * new revisions (and delete old ones) --- you cannot modify existing
1461 class WikiDB_PageRevision
1463 //var $_transformedContent = false; // set by WikiDB_Page::save()
1465 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1466 $versiondata = false)
1468 $this->_wikidb = &$wikidb;
1469 $this->_pagename = $pagename;
1470 $this->_version = $version;
1471 $this->_data = $versiondata ? $versiondata : array();
1472 $this->_transformedContent = false; // set by WikiDB_Page::save()
1476 * Get the WikiDB_Page which this revision belongs to.
1480 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1482 function getPage() {
1483 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1487 * Get the version number of this revision.
1491 * @return integer The version number of this revision.
1493 function getVersion() {
1494 return $this->_version;
1498 * Determine whether this revision has defaulted content.
1500 * The default revision (version 0) of each page, as well as any
1501 * pages which are created with empty content have their content
1502 * defaulted to something like:
1504 * Describe [ThisPage] here.
1509 * @return boolean Returns true if the page has default content.
1511 function hasDefaultContents() {
1512 $data = &$this->_data;
1513 if (!isset($data['%content'])) return true;
1514 if ($data['%content'] === true) return false;
1515 return $data['%content'] === false or $data['%content'] === "";
1519 * Get the content as an array of lines.
1523 * @return array An array of lines.
1524 * The lines should contain no trailing white space.
1526 function getContent() {
1527 return explode("\n", $this->getPackedContent());
1531 * Get the pagename of the revision.
1535 * @return string pagename.
1537 function getPageName() {
1538 return $this->_pagename;
1540 function getName() {
1541 return $this->_pagename;
1545 * Determine whether revision is the latest.
1549 * @return boolean True iff the revision is the latest (most recent) one.
1551 function isCurrent() {
1552 if (!isset($this->_iscurrent)) {
1553 $page = $this->getPage();
1554 $current = $page->getCurrentRevision(false);
1555 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1557 return $this->_iscurrent;
1561 * Get the transformed content of a page.
1563 * @param string $pagetype Override the page-type of the revision.
1565 * @return object An XmlContent-like object containing the page transformed
1568 function getTransformedContent($pagetype_override=false) {
1569 $backend = &$this->_wikidb->_backend;
1571 if ($pagetype_override) {
1572 // Figure out the normal page-type for this page.
1573 $type = PageType::GetPageType($this->get('pagetype'));
1574 if ($type->getName() == $pagetype_override)
1575 $pagetype_override = false; // Not really an override...
1578 if ($pagetype_override) {
1579 // Overriden page type, don't cache (or check cache).
1580 return new TransformedText($this->getPage(),
1581 $this->getPackedContent(),
1582 $this->getMetaData(),
1583 $pagetype_override);
1586 $possibly_cache_results = true;
1588 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1589 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1590 // flush cache for this page.
1591 $page = $this->getPage();
1592 $page->set('_cached_html', ''); // ignored with !USECACHE
1594 $possibly_cache_results = false;
1596 elseif (USECACHE and !$this->_transformedContent) {
1598 if ($this->isCurrent()) {
1599 $page = $this->getPage();
1600 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1603 $possibly_cache_results = false;
1605 //$backend->unlock();
1608 if (!$this->_transformedContent) {
1609 $this->_transformedContent
1610 = new TransformedText($this->getPage(),
1611 $this->getPackedContent(),
1612 $this->getMetaData());
1614 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1615 // If we're still the current version, cache the transfomed page.
1617 if ($this->isCurrent()) {
1618 $page->set('_cached_html', $this->_transformedContent->pack());
1620 //$backend->unlock();
1624 return $this->_transformedContent;
1628 * Get the content as a string.
1632 * @return string The page content.
1633 * Lines are separated by new-lines.
1635 function getPackedContent() {
1636 $data = &$this->_data;
1638 if (empty($data['%content'])
1639 || (!$this->_wikidb->isWikiPage($this->_pagename)
1640 && $this->isCurrent())) {
1641 include_once('lib/InlineParser.php');
1643 // A feature similar to taglines at http://www.wlug.org.nz/
1644 // Lib from http://www.aasted.org/quote/
1645 if (defined('FORTUNE_DIR')
1646 and is_dir(FORTUNE_DIR)
1647 and in_array($GLOBALS['request']->getArg('action'),
1648 array('create','edit')))
1650 include_once("lib/fortune.php");
1651 $fortune = new Fortune();
1652 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1654 $quote = "<verbatim>\n"
1655 . str_replace("\n<br>","\n", $quote)
1656 . "</verbatim>\n\n";
1660 . sprintf(_("Describe %s here."),
1661 "[" . WikiEscape($this->_pagename) . "]");
1663 // Replace empty content with default value.
1664 return sprintf(_("Describe %s here."),
1665 "[" . WikiEscape($this->_pagename) . "]");
1668 // There is (non-default) content.
1669 assert($this->_version > 0);
1671 if (!is_string($data['%content'])) {
1672 // Content was not provided to us at init time.
1673 // (This is allowed because for some backends, fetching
1674 // the content may be expensive, and often is not wanted
1677 // In any case, now we need to get it.
1678 $data['%content'] = $this->_get_content();
1679 assert(is_string($data['%content']));
1682 return $data['%content'];
1685 function _get_content() {
1686 $cache = &$this->_wikidb->_cache;
1687 $pagename = $this->_pagename;
1688 $version = $this->_version;
1690 assert($version > 0);
1692 $newdata = $cache->get_versiondata($pagename, $version, true);
1694 assert(is_string($newdata['%content']));
1695 return $newdata['%content'];
1698 // else revision has been deleted... What to do?
1699 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1700 $version, $pagename);
1705 * Get meta-data for this revision.
1710 * @param string $key Which meta-data to access.
1712 * Some reserved revision meta-data keys are:
1714 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1715 * The 'mtime' meta-value is normally set automatically by the database
1716 * backend, but it may be specified explicitly when creating a new revision.
1718 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1719 * of a page must be monotonically increasing. If an attempt is
1720 * made to create a new revision with an mtime less than that of
1721 * the preceeding revision, the new revisions timestamp is force
1722 * to be equal to that of the preceeding revision. In that case,
1723 * the originally requested mtime is preserved in 'orig_mtime'.
1724 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1725 * This meta-value is <em>always</em> automatically maintained by the database
1726 * backend. (It is set from the 'mtime' meta-value of the superceding
1727 * revision.) '_supplanted' has a value of 'false' for the current revision.
1729 * FIXME: this could be refactored:
1731 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1733 * <dd> Authenticated author of a page. This is used to identify
1734 * the distinctness of authors when cleaning old revisions from
1736 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1737 * <dt> 'summary' <dd> Short change summary entered by page author.
1740 * Meta-data keys must be valid C identifers (they have to start with a letter
1741 * or underscore, and can contain only alphanumerics and underscores.)
1743 * @return string The requested value, or false if the requested value
1746 function get($key) {
1747 if (!$key || $key[0] == '%')
1749 $data = &$this->_data;
1750 return isset($data[$key]) ? $data[$key] : false;
1754 * Get all the revision page meta-data as a hash.
1756 * @return hash The revision meta-data.
1758 function getMetaData() {
1760 foreach ($this->_data as $key => $val) {
1761 if (!empty($val) && $key[0] != '%')
1769 * Return a string representation of the revision.
1771 * This is really only for debugging.
1775 * @return string Printable representation of the WikiDB_Page.
1777 function asString () {
1779 printf("[%s:%d\n", get_class($this), $this->get('version'));
1780 print_r($this->_data);
1781 echo $this->getPackedContent() . "\n]\n";
1782 $strval = ob_get_contents();
1790 * Class representing a sequence of WikiDB_Pages.
1791 * TODO: Enhance to php5 iterators
1793 * apply filters for options like 'sortby', 'limit', 'exclude'
1794 * for simple queries like titleSearch, where the backend is not ready yet.
1796 class WikiDB_PageIterator
1798 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1799 $this->_iter = $iter; // a WikiDB_backend_iterator
1800 $this->_wikidb = &$wikidb;
1801 $this->_options = $options;
1805 return $this->_iter->count();
1808 return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1812 * Get next WikiDB_Page in sequence.
1816 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1819 if ( ! ($next = $this->_iter->next()) )
1822 $pagename = &$next['pagename'];
1823 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1824 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1825 $pagename = $pagename['linkto'];
1827 $pagename = strval($pagename);*/
1828 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1831 if (isset($next['linkrelation'])
1832 or isset($next['pagedata']['linkrelation'])) return false;
1833 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1837 // There's always hits, but we cache only if more
1838 // (well not with file, cvs and dba)
1839 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1840 $this->_wikidb->_cache->cache_data($next);
1841 // cache existing page id's since we iterate over all links in GleanDescription
1842 // and need them later for LinkExistingWord
1843 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1844 and !$this->_options['include_empty'] and isset($next['id'])) {
1845 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1847 $page = new WikiDB_Page($this->_wikidb, $pagename);
1848 if (isset($next['linkrelation']))
1849 $page->set('linkrelation', $next['linkrelation']);
1850 if (isset($next['score']))
1851 $page->score = $next['score'];
1856 * Release resources held by this iterator.
1858 * The iterator may not be used after free() is called.
1860 * There is no need to call free(), if next() has returned false.
1861 * (I.e. if you iterate through all the pages in the sequence,
1862 * you do not need to call free() --- you only need to call it
1863 * if you stop before the end of the iterator is reached.)
1868 $this->_iter->free();
1871 $this->_iter->reset();
1873 function asArray() {
1875 while ($page = $this->next())
1882 * Apply filters for options like 'sortby', 'limit', 'exclude'
1883 * for simple queries like titleSearch, where the backend is not ready yet.
1884 * Since iteration is usually destructive for SQL results,
1885 * we have to generate a copy.
1887 function applyFilters($options = false) {
1888 if (!$options) $options = $this->_options;
1889 if (isset($options['sortby'])) {
1891 /* this is destructive */
1892 while ($page = $this->next())
1893 $result[] = $page->getName();
1894 $this->_doSort($array, $options['sortby']);
1896 /* the rest is not destructive.
1897 * reconstruct a new iterator
1899 $pagenames = array(); $i = 0;
1900 if (isset($options['limit']))
1901 $limit = $options['limit'];
1904 if (isset($options['exclude']))
1905 $exclude = $options['exclude'];
1906 if (is_string($exclude) and !is_array($exclude))
1907 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1908 foreach($array as $pagename) {
1909 if ($limit and $i++ > $limit)
1910 return new WikiDB_Array_PageIterator($pagenames);
1911 if (!empty($exclude) and !in_array($pagename, $exclude))
1912 $pagenames[] = $pagename;
1913 elseif (empty($exclude))
1914 $pagenames[] = $pagename;
1916 return new WikiDB_Array_PageIterator($pagenames);
1920 function _doSort(&$array, $sortby) {
1921 $sortby = PageList::sortby($sortby, 'init');
1922 if ($sortby == '+pagename')
1923 sort($array, SORT_STRING);
1924 elseif ($sortby == '-pagename')
1925 rsort($array, SORT_STRING);
1932 * A class which represents a sequence of WikiDB_PageRevisions.
1933 * TODO: Enhance to php5 iterators
1935 class WikiDB_PageRevisionIterator
1937 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1938 $this->_revisions = $revisions;
1939 $this->_wikidb = &$wikidb;
1940 $this->_options = $options;
1944 return $this->_revisions->count();
1948 * Get next WikiDB_PageRevision in sequence.
1952 * @return WikiDB_PageRevision
1953 * The next WikiDB_PageRevision in the sequence.
1956 if ( ! ($next = $this->_revisions->next()) )
1959 //$this->_wikidb->_cache->cache_data($next);
1961 $pagename = $next['pagename'];
1962 $version = $next['version'];
1963 $versiondata = $next['versiondata'];
1965 if (!(is_string($pagename) and $pagename != '')) {
1966 trigger_error("empty pagename",E_USER_WARNING);
1969 } else assert(is_string($pagename) and $pagename != '');
1971 if (!is_array($versiondata)) {
1972 trigger_error("empty versiondata",E_USER_WARNING);
1975 } else assert(is_array($versiondata));
1977 if (!($version > 0)) {
1978 trigger_error("invalid version",E_USER_WARNING);
1981 } else assert($version > 0);
1983 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1988 * Release resources held by this iterator.
1990 * The iterator may not be used after free() is called.
1992 * There is no need to call free(), if next() has returned false.
1993 * (I.e. if you iterate through all the revisions in the sequence,
1994 * you do not need to call free() --- you only need to call it
1995 * if you stop before the end of the iterator is reached.)
2000 $this->_revisions->free();
2003 function asArray() {
2005 while ($rev = $this->next())
2014 class WikiDB_Array_PageIterator
2016 function WikiDB_Array_PageIterator($pagenames) {
2018 $this->_dbi = $request->getDbh();
2019 $this->_pages = $pagenames;
2020 reset($this->_pages);
2023 $c = current($this->_pages);
2024 next($this->_pages);
2025 return $c !== false ? $this->_dbi->getPage($c) : false;
2028 return count($this->_pages);
2031 reset($this->_pages);
2034 function asArray() {
2035 reset($this->_pages);
2036 return $this->_pages;
2040 class WikiDB_Array_generic_iter
2042 function WikiDB_Array_generic_iter($result) {
2043 // $result may be either an array or a query result
2044 if (is_array($result)) {
2045 $this->_array = $result;
2046 } elseif (is_object($result)) {
2047 $this->_array = $result->asArray();
2049 $this->_array = array();
2051 if (!empty($this->_array))
2052 reset($this->_array);
2055 $c = current($this->_array);
2056 next($this->_array);
2057 return $c !== false ? $c : false;
2060 return count($this->_array);
2063 reset($this->_array);
2066 function asArray() {
2067 if (!empty($this->_array))
2068 reset($this->_array);
2069 return $this->_array;
2074 * Data cache used by WikiDB.
2076 * FIXME: Maybe rename this to caching_backend (or some such).
2082 // FIXME: beautify versiondata cache. Cache only limited data?
2084 function WikiDB_cache (&$backend) {
2085 $this->_backend = &$backend;
2087 $this->_pagedata_cache = array();
2088 $this->_versiondata_cache = array();
2089 array_push ($this->_versiondata_cache, array());
2090 $this->_glv_cache = array();
2091 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2093 if (isset($GLOBALS['request']->_dbi))
2094 $this->readonly = $GLOBALS['request']->_dbi->readonly;
2098 $this->_pagedata_cache = array();
2099 $this->_versiondata_cache = array();
2100 $this->_glv_cache = array();
2101 $this->_id_cache = array();
2104 function get_pagedata($pagename) {
2105 assert(is_string($pagename) && $pagename != '');
2107 $cache = &$this->_pagedata_cache;
2108 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2109 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2110 if (empty($cache[$pagename]))
2111 $cache[$pagename] = array();
2113 return $cache[$pagename];
2115 return $this->_backend->get_pagedata($pagename);
2119 function update_pagedata($pagename, $newdata) {
2120 assert(is_string($pagename) && $pagename != '');
2121 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2123 $this->_backend->update_pagedata($pagename, $newdata);
2126 if (!empty($this->_pagedata_cache[$pagename])
2127 and is_array($this->_pagedata_cache[$pagename]))
2129 $cachedata = &$this->_pagedata_cache[$pagename];
2130 foreach($newdata as $key => $val)
2131 $cachedata[$key] = $val;
2133 $this->_pagedata_cache[$pagename] = $newdata;
2137 function invalidate_cache($pagename) {
2138 unset ($this->_pagedata_cache[$pagename]);
2139 unset ($this->_versiondata_cache[$pagename]);
2140 unset ($this->_glv_cache[$pagename]);
2141 unset ($this->_id_cache[$pagename]);
2142 //unset ($this->_backend->_page_data);
2145 function delete_page($pagename) {
2146 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2147 $result = $this->_backend->delete_page($pagename);
2148 $this->invalidate_cache($pagename);
2152 function purge_page($pagename) {
2153 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2154 $result = $this->_backend->purge_page($pagename);
2155 $this->invalidate_cache($pagename);
2159 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2160 function cache_data($data) {
2162 //if (isset($data['pagedata']))
2163 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2166 function get_versiondata($pagename, $version, $need_content = false) {
2167 // FIXME: Seriously ugly hackage
2169 if (USECACHE) { //temporary - for debugging
2170 assert(is_string($pagename) && $pagename != '');
2171 // There is a bug here somewhere which results in an assertion failure at line 105
2172 // of ArchiveCleaner.php It goes away if we use the next line.
2173 //$need_content = true;
2174 $nc = $need_content ? '1':'0';
2175 $cache = &$this->_versiondata_cache;
2176 if (!isset($cache[$pagename][$version][$nc])
2177 || !(is_array ($cache[$pagename]))
2178 || !(is_array ($cache[$pagename][$version])))
2180 $cache[$pagename][$version][$nc] =
2181 $this->_backend->get_versiondata($pagename, $version, $need_content);
2183 // If we have retrieved all data, we may as well set the cache for
2184 // $need_content = false
2186 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2189 $vdata = $cache[$pagename][$version][$nc];
2191 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2194 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2195 if (empty($this->_pagedata_cache))
2196 $this->_pagedata_cache = array();
2197 /* 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 */
2198 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2203 function set_versiondata($pagename, $version, $data) {
2204 //unset($this->_versiondata_cache[$pagename][$version]);
2206 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2207 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2209 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2210 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2211 // Is this necessary?
2212 unset($this->_glv_cache[$pagename]);
2215 function update_versiondata($pagename, $version, $data) {
2216 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2217 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2219 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2221 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2222 // Is this necessary?
2223 unset($this->_glv_cache[$pagename]);
2226 function delete_versiondata($pagename, $version) {
2227 if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2228 $new = $this->_backend->delete_versiondata($pagename, $version);
2229 if (isset($this->_versiondata_cache[$pagename][$version]))
2230 unset ($this->_versiondata_cache[$pagename][$version]);
2231 // dirty latest version cache only if latest version gets deleted
2232 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2233 unset ($this->_glv_cache[$pagename]);
2236 function get_latest_version($pagename) {
2238 assert (is_string($pagename) && $pagename != '');
2239 $cache = &$this->_glv_cache;
2240 if (!isset($cache[$pagename])) {
2241 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2242 if (empty($cache[$pagename]))
2243 $cache[$pagename] = 0;
2245 return $cache[$pagename];
2247 return $this->_backend->get_latest_version($pagename);
2252 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2256 $stamp = strftime("%y%m%d-%H%M%S");
2257 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2258 register_shutdown_function("_sql_debuglog_shutdown_function");
2259 } elseif ($shutdown) {
2263 if ($newline) fputs($fp, "[$i++] $msg");
2264 else fwrite($fp, $msg);
2267 function _sql_debuglog_shutdown_function() {
2268 _sql_debuglog('',false,true);
2274 // c-basic-offset: 4
2275 // c-hanging-comment-ender-p: nil
2276 // indent-tabs-mode: nil