2 rcs_id('$Id: WikiDB.php,v 1.37 2004-03-01 13:48:45 rurban Exp $');
4 require_once('lib/stdlib.php');
5 require_once('lib/PageType.php');
7 //FIXME: arg on get*Revision to hint that content is wanted.
10 * The classes in the file define the interface to the
14 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
18 * Force the creation of a new revision.
19 * @see WikiDB_Page::createRevision()
21 define('WIKIDB_FORCE_CREATE', -1);
23 // FIXME: used for debugging only. Comment out if cache does not work
24 define('USECACHE', 1);
27 * Abstract base class for the database used by PhpWiki.
29 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
30 * turn contain <tt>WikiDB_PageRevision</tt>s.
32 * Conceptually a <tt>WikiDB</tt> contains all possible
33 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
34 * Since all possible pages are already contained in a WikiDB, a call
35 * to WikiDB::getPage() will never fail (barring bugs and
36 * e.g. filesystem or SQL database problems.)
38 * Also each <tt>WikiDB_Page</tt> always contains at least one
39 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
40 * [PageName] here."). This default content has a version number of
43 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
44 * only create new revisions or delete old ones --- one can not modify
45 * an existing revision.
49 * Open a WikiDB database.
51 * This is a static member function. This function inspects its
52 * arguments to determine the proper subclass of WikiDB to
53 * instantiate, and then it instantiates it.
57 * @param hash $dbparams Database configuration parameters.
58 * Some pertinent paramters are:
61 * <dd> The back-end type. Current supported types are:
64 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
67 * <dd> Dba based backend.
71 * <dd> (Used by the SQL backend.)
72 * The DSN specifying which database to connect to.
75 * <dd> Prefix to be prepended to database table (and file names).
78 * <dd> (Used by the dba backend.)
79 * Which directory db files reside in.
82 * <dd> (Used by the dba backend.)
83 * Timeout in seconds for opening (and obtaining lock) on the
87 * <dd> (Used by the dba backend.)
89 * Which dba handler to use. Good choices are probably either
93 * @return WikiDB A WikiDB object.
95 function open ($dbparams) {
96 $dbtype = $dbparams{'dbtype'};
97 include_once("lib/WikiDB/$dbtype.php");
99 $class = 'WikiDB_' . $dbtype;
100 return new $class ($dbparams);
110 function WikiDB (&$backend, $dbparams) {
111 $this->_backend = &$backend;
112 $this->_cache = new WikiDB_cache($backend);
114 // If the database doesn't yet have a timestamp, initialize it now.
115 if ($this->get('_timestamp') === false)
118 //FIXME: devel checking.
119 //$this->_backend->check();
123 * Get any user-level warnings about this WikiDB.
125 * Some back-ends, e.g. by default create there data files in the
126 * global /tmp directory. We would like to warn the user when this
127 * happens (since /tmp files tend to get wiped periodically.)
128 * Warnings such as these may be communicated from specific
129 * back-ends through this method.
133 * @return string A warning message (or <tt>false</tt> if there is
136 function genericWarnings() {
141 * Close database connection.
143 * The database may no longer be used after it is closed.
145 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
146 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
147 * which have been obtained from it.
152 $this->_backend->close();
153 $this->_cache->close();
157 * Get a WikiDB_Page from a WikiDB.
159 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
160 * therefore this method never fails.
163 * @param string $pagename Which page to get.
164 * @return WikiDB_Page The requested WikiDB_Page.
166 function getPage($pagename) {
167 assert(is_string($pagename) && $pagename);
168 return new WikiDB_Page($this, $pagename);
173 //function nPages() {
178 * Determine whether page exists (in non-default form).
181 * $is_page = $dbi->isWikiPage($pagename);
185 * $page = $dbi->getPage($pagename);
186 * $current = $page->getCurrentRevision();
187 * $is_page = ! $current->hasDefaultContents();
189 * however isWikiPage may be implemented in a more efficient
190 * manner in certain back-ends.
194 * @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 $current = $page->getCurrentRevision();
202 return ! $current->hasDefaultContents();
206 * Delete page from the WikiDB.
208 * Deletes all revisions of the page from the WikiDB. Also resets
209 * all page meta-data to the default values.
213 * @param string $pagename Name of page to delete.
215 function deletePage($pagename) {
216 $this->_cache->delete_page($pagename);
218 //How to create a RecentChanges entry with explaining summary?
220 $page = $this->getPage($pagename);
221 $current = $page->getCurrentRevision();
222 $meta = $current->_data;
223 $version = $current->getVersion();
224 $meta['summary'] = sprintf(_("renamed from %s"),$from);
225 $page->save($current->getPackedContent(), $version + 1, $meta);
230 * Retrieve all pages.
232 * Gets the set of all pages with non-default contents.
234 * FIXME: do we need this? I think so. The simple searches
239 * @param boolean $include_defaulted Normally pages whose most
240 * recent revision has empty content are considered to be
241 * non-existant. Unless $include_defaulted is set to true, those
242 * pages will not be returned.
244 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
245 * in the WikiDB which have non-default contents.
247 function getAllPages($include_defaulted=false, $sortby=false, $limit=false) {
248 $result = $this->_backend->get_all_pages($include_defaulted,$sortby,$limit);
249 return new WikiDB_PageIterator($this, $result);
255 * Search for pages containing (or not containing) certain words
258 * Pages are returned in alphabetical order whenever it is
259 * practical to do so.
261 * FIXME: should titleSearch and fullSearch be combined? I think so.
264 * @param TextSearchQuery $search A TextSearchQuery object
265 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
266 * @see TextSearchQuery
268 function titleSearch($search) {
269 $result = $this->_backend->text_search($search);
270 return new WikiDB_PageIterator($this, $result);
276 * Search for pages containing (or not containing) certain words
277 * in their entire text (this includes the page content and the
280 * Pages are returned in alphabetical order whenever it is
281 * practical to do so.
285 * @param TextSearchQuery $search A TextSearchQuery object.
286 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
287 * @see TextSearchQuery
289 function fullSearch($search) {
290 $result = $this->_backend->text_search($search, 'full_text');
291 return new WikiDB_PageIterator($this, $result);
295 * Find the pages with the greatest hit counts.
297 * Pages are returned in reverse order by hit count.
301 * @param integer $limit The maximum number of pages to return.
302 * Set $limit to zero to return all pages. If $limit < 0, pages will
303 * be sorted in decreasing order of popularity.
305 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
308 function mostPopular($limit = 20, $sortby = '') {
309 $result = $this->_backend->most_popular($limit, $sortby);
310 return new WikiDB_PageIterator($this, $result);
314 * Find recent page revisions.
316 * Revisions are returned in reverse order by creation time.
320 * @param hash $params This hash is used to specify various optional
324 * <dd> (integer) At most this many revisions will be returned.
326 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
327 * <dt> include_minor_revisions
328 * <dd> (boolean) Also include minor revisions. (Default is not to.)
329 * <dt> exclude_major_revisions
330 * <dd> (boolean) Don't include non-minor revisions.
331 * (Exclude_major_revisions implies include_minor_revisions.)
332 * <dt> include_all_revisions
333 * <dd> (boolean) Return all matching revisions for each page.
334 * Normally only the most recent matching revision is returned
338 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
339 * matching revisions.
341 function mostRecent($params = false) {
342 $result = $this->_backend->most_recent($params);
343 return new WikiDB_PageRevisionIterator($this, $result);
347 * Blog search. (experimental)
349 * Search for blog entries related to a certain page.
351 * FIXME: with pagetype support and perhaps a RegexpSearchQuery
352 * we can make sure we are returning *ONLY* blog pages to the
353 * main routine. Currently, we just use titleSearch which requires
354 * some further checking in lib/plugin/WikiBlog.php (BAD).
358 * @param string $order 'normal' (chronological) or 'reverse'
359 * @param string $page Find blog entries related to this page.
360 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
362 // Deleting until such time as this is properly implemented...
363 // (As long as it's just a title search, just use titleSearch.)
364 //function blogSearch($page, $order) {
365 // //FIXME: implement ordering
367 // require_once('lib/TextSearchQuery.php');
368 // $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
370 // return $this->titleSearch($query);
374 * Call the appropriate backend method.
377 * @param string $from Page to rename
378 * @param string $to New name
379 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
380 * @return boolean true or false
382 function renamePage($from, $to, $updateWikiLinks = false) {
383 assert(is_string($from) && $from);
384 assert(is_string($to) && $to);
386 if (method_exists($this->_backend,'rename_page')) {
387 $oldpage = $this->getPage($from);
388 $newpage = $this->getPage($to);
389 if ($oldpage->exists() and ! $newpage->exists()) {
390 if ($result = $this->_backend->rename_page($from, $to)) {
391 //update all WikiLinks in existing pages
392 if ($updateWikiLinks) {
393 //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
394 require_once('lib/plugin/WikiAdminSearchReplace.php');
395 $links = $oldpage->getLinks();
396 while ($linked_page = $links->next()) {
397 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
400 //create a RecentChanges entry with explaining summary
401 $page = $this->getPage($to);
402 $current = $page->getCurrentRevision();
403 $meta = $current->_data;
404 $version = $current->getVersion();
405 $meta['summary'] = sprintf(_("renamed from %s"),$from);
406 $page->save($current->getPackedContent(), $version + 1, $meta);
410 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
415 /** Get timestamp when database was last modified.
417 * @return string A string consisting of two integers,
418 * separated by a space. The first is the time in
419 * unix timestamp format, the second is a modification
420 * count for the database.
422 * The idea is that you can cast the return value to an
423 * int to get a timestamp, or you can use the string value
424 * as a good hash for the entire database.
426 function getTimestamp() {
427 $ts = $this->get('_timestamp');
428 return sprintf("%d %d", $ts[0], $ts[1]);
432 * Update the database timestamp.
436 $ts = $this->get('_timestamp');
437 $this->set('_timestamp', array(time(), $ts[1] + 1));
442 * Access WikiDB global meta-data.
444 * NOTE: this is currently implemented in a hackish and
445 * not very efficient manner.
449 * @param string $key Which meta data to get.
450 * Some reserved meta-data keys are:
452 * <dt>'_timestamp' <dd> Data used by getTimestamp().
455 * @return scalar The requested value, or false if the requested data
459 if (!$key || $key[0] == '%')
462 * Hack Alert: We can use any page (existing or not) to store
463 * this data (as long as we always use the same one.)
465 $gd = $this->getPage('global_data');
466 $data = $gd->get('__global');
468 if ($data && isset($data[$key]))
475 * Set global meta-data.
477 * NOTE: this is currently implemented in a hackish and
478 * not very efficient manner.
483 * @param string $key Meta-data key to set.
484 * @param string $newval New value.
486 function set($key, $newval) {
487 if (!$key || $key[0] == '%')
490 $gd = $this->getPage('global_data');
492 $data = $gd->get('__global');
499 $data[$key] = $newval;
501 $gd->set('__global', $data);
507 * An abstract base class which representing a wiki-page within a
510 * A WikiDB_Page contains a number (at least one) of
511 * WikiDB_PageRevisions.
515 function WikiDB_Page(&$wikidb, $pagename) {
516 $this->_wikidb = &$wikidb;
517 $this->_pagename = $pagename;
518 assert(!empty($this->_pagename));
522 * Get the name of the wiki page.
526 * @return string The page name.
529 return $this->_pagename;
533 $current = $this->getCurrentRevision();
534 return ! $current->hasDefaultContents();
538 * Delete an old revision of a WikiDB_Page.
540 * Deletes the specified revision of the page.
541 * It is a fatal error to attempt to delete the current revision.
545 * @param integer $version Which revision to delete. (You can also
546 * use a WikiDB_PageRevision object here.)
548 function deleteRevision($version) {
549 $backend = &$this->_wikidb->_backend;
550 $cache = &$this->_wikidb->_cache;
551 $pagename = &$this->_pagename;
553 $version = $this->_coerce_to_version($version);
558 $latestversion = $cache->get_latest_version($pagename);
559 if ($latestversion && $version == $latestversion) {
561 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
562 $pagename), E_USER_ERROR);
566 $cache->delete_versiondata($pagename, $version);
572 * Delete a revision, or possibly merge it with a previous
576 * Suppose an author make a (major) edit to a page. Shortly
577 * after that the same author makes a minor edit (e.g. to fix
578 * spelling mistakes he just made.)
580 * Now some time later, where cleaning out old saved revisions,
581 * and would like to delete his minor revision (since there's
582 * really no point in keeping minor revisions around for a long
585 * Note that the text after the minor revision probably represents
586 * what the author intended to write better than the text after
587 * the preceding major edit.
589 * So what we really want to do is merge the minor edit with the
592 * We will only do this when:
594 * <li>The revision being deleted is a minor one, and
595 * <li>It has the same author as the immediately preceding revision.
598 function mergeRevision($version) {
599 $backend = &$this->_wikidb->_backend;
600 $cache = &$this->_wikidb->_cache;
601 $pagename = &$this->_pagename;
603 $version = $this->_coerce_to_version($version);
608 $latestversion = $backend->get_latest_version($pagename);
609 if ($latestversion && $version == $latestversion) {
611 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
612 $pagename), E_USER_ERROR);
616 $versiondata = $cache->get_versiondata($pagename, $version, true);
618 // Not there? ... we're done!
623 if ($versiondata['is_minor_edit']) {
624 $previous = $backend->get_previous_version($pagename, $version);
626 $prevdata = $cache->get_versiondata($pagename, $previous);
627 if ($prevdata['author_id'] == $versiondata['author_id']) {
628 // This is a minor revision, previous version is
629 // by the same author. We will merge the
631 $cache->update_versiondata($pagename, $previous,
632 array('%content' => $versiondata['%content'],
633 '_supplanted' => $versiondata['_supplanted']));
638 $cache->delete_versiondata($pagename, $version);
644 * Create a new revision of a {@link WikiDB_Page}.
648 * @param int $version Version number for new revision.
649 * To ensure proper serialization of edits, $version must be
650 * exactly one higher than the current latest version.
651 * (You can defeat this check by setting $version to
652 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
654 * @param string $content Contents of new revision.
656 * @param hash $metadata Metadata for new revision.
657 * All values in the hash should be scalars (strings or integers).
659 * @param array $links List of pagenames which this page links to.
661 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
662 * $version was incorrect, returns false
664 function createRevision($version, &$content, $metadata, $links) {
665 $backend = &$this->_wikidb->_backend;
666 $cache = &$this->_wikidb->_cache;
667 $pagename = &$this->_pagename;
671 $latestversion = $backend->get_latest_version($pagename);
672 $newversion = $latestversion + 1;
673 assert($newversion >= 1);
675 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
682 foreach ($data as $key => $val) {
683 if (empty($val) || $key[0] == '_' || $key[0] == '%')
687 assert(!empty($data['author']));
688 if (empty($data['author_id']))
689 @$data['author_id'] = $data['author'];
691 if (empty($data['mtime']))
692 $data['mtime'] = time();
694 if ($latestversion) {
695 // Ensure mtimes are monotonic.
696 $pdata = $cache->get_versiondata($pagename, $latestversion);
697 if ($data['mtime'] < $pdata['mtime']) {
698 trigger_error(sprintf(_("%s: Date of new revision is %s"),
699 $pagename,"'non-monotonic'"),
701 $data['orig_mtime'] = $data['mtime'];
702 $data['mtime'] = $pdata['mtime'];
705 // FIXME: use (possibly user specified) 'mtime' time or
707 $cache->update_versiondata($pagename, $latestversion,
708 array('_supplanted' => $data['mtime']));
711 $data['%content'] = &$content;
713 $cache->set_versiondata($pagename, $newversion, $data);
715 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
716 //':deleted' => empty($content)));
718 $backend->set_links($pagename, $links);
722 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
726 /** A higher-level interface to createRevision.
728 * This takes care of computing the links, and storing
729 * a cached version of the transformed wiki-text.
731 * @param string $wikitext The page content.
733 * @param int $version Version number for new revision.
734 * To ensure proper serialization of edits, $version must be
735 * exactly one higher than the current latest version.
736 * (You can defeat this check by setting $version to
737 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
739 * @param hash $meta Meta-data for new revision.
741 function save($wikitext, $version, $meta) {
742 $formatted = new TransformedText($this, $wikitext, $meta);
743 $type = $formatted->getType();
744 $meta['pagetype'] = $type->getName();
745 $links = $formatted->getWikiPageLinks();
747 $backend = &$this->_wikidb->_backend;
749 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
751 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
752 $this->set('_cached_html', $formatted->pack());
755 // FIXME: probably should have some global state information
756 // in the backend to control when to optimize.
758 // We're doing this here rather than in createRevision because
759 // postgres can't optimize while locked.
760 if (time() % 50 == 0) {
761 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
762 $backend->optimize();
765 $newrevision->_transformedContent = $formatted;
770 * Get the most recent revision of a page.
774 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
776 function getCurrentRevision() {
777 $backend = &$this->_wikidb->_backend;
778 $cache = &$this->_wikidb->_cache;
779 $pagename = &$this->_pagename;
782 $version = $cache->get_latest_version($pagename);
783 $revision = $this->getRevision($version);
790 * Get a specific revision of a WikiDB_Page.
794 * @param integer $version Which revision to get.
796 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
797 * false if the requested revision does not exist in the {@link WikiDB}.
798 * Note that version zero of any page always exists.
800 function getRevision($version) {
801 $cache = &$this->_wikidb->_cache;
802 $pagename = &$this->_pagename;
805 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
807 assert($version > 0);
808 $vdata = $cache->get_versiondata($pagename, $version);
811 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
816 * Get previous page revision.
818 * This method find the most recent revision before a specified
823 * @param integer $version Find most recent revision before this version.
824 * You can also use a WikiDB_PageRevision object to specify the $version.
826 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
827 * requested revision does not exist in the {@link WikiDB}. Note that
828 * unless $version is greater than zero, a revision (perhaps version zero,
829 * the default revision) will always be found.
831 function getRevisionBefore($version) {
832 $backend = &$this->_wikidb->_backend;
833 $pagename = &$this->_pagename;
835 $version = $this->_coerce_to_version($version);
840 $previous = $backend->get_previous_version($pagename, $version);
841 $revision = $this->getRevision($previous);
848 * Get all revisions of the WikiDB_Page.
850 * This does not include the version zero (default) revision in the
851 * returned revision set.
853 * @return WikiDB_PageRevisionIterator A
854 * WikiDB_PageRevisionIterator containing all revisions of this
855 * WikiDB_Page in reverse order by version number.
857 function getAllRevisions() {
858 $backend = &$this->_wikidb->_backend;
859 $revs = $backend->get_all_revisions($this->_pagename);
860 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
864 * Find pages which link to or are linked from a page.
868 * @param boolean $reversed Which links to find: true for backlinks (default).
870 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
871 * all matching pages.
873 function getLinks($reversed = true) {
874 $backend = &$this->_wikidb->_backend;
875 $result = $backend->get_links($this->_pagename, $reversed);
876 return new WikiDB_PageIterator($this->_wikidb, $result);
880 * Access WikiDB_Page meta-data.
884 * @param string $key Which meta data to get.
885 * Some reserved meta-data keys are:
887 * <dt>'locked'<dd> Is page locked?
888 * <dt>'hits' <dd> Page hit counter.
889 * <dt>'pref' <dd> Users preferences, stored in homepages.
890 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
892 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
893 * page-headers and content.
894 * <dt>'score' <dd> Page score (not yet implement, do we need?)
897 * @return scalar The requested value, or false if the requested data
901 $cache = &$this->_wikidb->_cache;
902 if (!$key || $key[0] == '%')
904 $data = $cache->get_pagedata($this->_pagename);
905 return isset($data[$key]) ? $data[$key] : false;
909 * Get all the page meta-data as a hash.
911 * @return hash The page meta-data.
913 function getMetaData() {
914 $cache = &$this->_wikidb->_cache;
915 $data = $cache->get_pagedata($this->_pagename);
917 foreach ($data as $key => $val) {
918 if (/*!empty($val) &&*/ $key[0] != '%')
925 * Set page meta-data.
930 * @param string $key Meta-data key to set.
931 * @param string $newval New value.
933 function set($key, $newval) {
934 $cache = &$this->_wikidb->_cache;
935 $pagename = &$this->_pagename;
937 assert($key && $key[0] != '%');
939 $data = $cache->get_pagedata($pagename);
941 if (!empty($newval)) {
942 if (!empty($data[$key]) && $data[$key] == $newval)
943 return; // values identical, skip update.
946 if (empty($data[$key]))
947 return; // values identical, skip update.
950 $cache->update_pagedata($pagename, array($key => $newval));
954 * Increase page hit count.
956 * FIXME: IS this needed? Probably not.
958 * This is a convenience function.
959 * <pre> $page->increaseHitCount(); </pre>
960 * is functionally identical to
961 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
963 * Note that this method may be implemented in more efficient ways
964 * in certain backends.
968 function increaseHitCount() {
969 @$newhits = $this->get('hits') + 1;
970 $this->set('hits', $newhits);
974 * Return a string representation of the WikiDB_Page
976 * This is really only for debugging.
980 * @return string Printable representation of the WikiDB_Page.
982 function asString () {
984 printf("[%s:%s\n", get_class($this), $this->getName());
985 print_r($this->getMetaData());
987 $strval = ob_get_contents();
995 * @param integer_or_object $version_or_pagerevision
996 * Takes either the version number (and int) or a WikiDB_PageRevision
998 * @return integer The version number.
1000 function _coerce_to_version($version_or_pagerevision) {
1001 if (method_exists($version_or_pagerevision, "getContent"))
1002 $version = $version_or_pagerevision->getVersion();
1004 $version = (int) $version_or_pagerevision;
1006 assert($version >= 0);
1010 function isUserPage ($include_empty = true) {
1011 if ($include_empty) {
1012 $current = $this->getCurrentRevision();
1013 if ($current->hasDefaultContents()) {
1017 return $this->get('pref') ? true : false;
1023 * This class represents a specific revision of a WikiDB_Page within
1026 * A WikiDB_PageRevision has read-only semantics. You may only create
1027 * new revisions (and delete old ones) --- you cannot modify existing
1030 class WikiDB_PageRevision
1032 var $_transformedContent = false; // set by WikiDB_Page::save()
1034 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1035 $versiondata = false)
1037 $this->_wikidb = &$wikidb;
1038 $this->_pagename = $pagename;
1039 $this->_version = $version;
1040 $this->_data = $versiondata ? $versiondata : array();
1044 * Get the WikiDB_Page which this revision belongs to.
1048 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1050 function getPage() {
1051 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1055 * Get the version number of this revision.
1059 * @return integer The version number of this revision.
1061 function getVersion() {
1062 return $this->_version;
1066 * Determine whether this revision has defaulted content.
1068 * The default revision (version 0) of each page, as well as any
1069 * pages which are created with empty content have their content
1070 * defaulted to something like:
1072 * Describe [ThisPage] here.
1077 * @return boolean Returns true if the page has default content.
1079 function hasDefaultContents() {
1080 $data = &$this->_data;
1081 return empty($data['%content']);
1085 * Get the content as an array of lines.
1089 * @return array An array of lines.
1090 * The lines should contain no trailing white space.
1092 function getContent() {
1093 return explode("\n", $this->getPackedContent());
1097 * Get the pagename of the revision.
1101 * @return string pagename.
1103 function getPageName() {
1104 return $this->_pagename;
1108 * Determine whether revision is the latest.
1112 * @return boolean True iff the revision is the latest (most recent) one.
1114 function isCurrent() {
1115 if (!isset($this->_iscurrent)) {
1116 $page = $this->getPage();
1117 $current = $page->getCurrentRevision();
1118 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1120 return $this->_iscurrent;
1124 * Get the transformed content of a page.
1126 * @param string $pagetype Override the page-type of the revision.
1128 * @return object An XmlContent-like object containing the page transformed
1131 function getTransformedContent($pagetype_override=false) {
1132 $backend = &$this->_wikidb->_backend;
1134 if ($pagetype_override) {
1135 // Figure out the normal page-type for this page.
1136 $type = PageType::GetPageType($this->get('pagetype'));
1137 if ($type->getName() == $pagetype_override)
1138 $pagetype_override = false; // Not really an override...
1141 if ($pagetype_override) {
1142 // Overriden page type, don't cache (or check cache).
1143 return new TransformedText($this->getPage(),
1144 $this->getPackedContent(),
1145 $this->getMetaData(),
1146 $pagetype_override);
1149 $possibly_cache_results = true;
1151 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1152 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1153 // flush cache for this page.
1154 $page = $this->getPage();
1155 $page->set('_cached_html', false);
1157 $possibly_cache_results = false;
1159 elseif (!$this->_transformedContent) {
1161 if ($this->isCurrent()) {
1162 $page = $this->getPage();
1163 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1166 $possibly_cache_results = false;
1171 if (!$this->_transformedContent) {
1172 $this->_transformedContent
1173 = new TransformedText($this->getPage(),
1174 $this->getPackedContent(),
1175 $this->getMetaData());
1177 if ($possibly_cache_results) {
1178 // If we're still the current version, cache the transfomed page.
1180 if ($this->isCurrent()) {
1181 $page->set('_cached_html', $this->_transformedContent->pack());
1187 return $this->_transformedContent;
1191 * Get the content as a string.
1195 * @return string The page content.
1196 * Lines are separated by new-lines.
1198 function getPackedContent() {
1199 $data = &$this->_data;
1202 if (empty($data['%content'])) {
1203 include_once('lib/InlineParser.php');
1204 // Replace empty content with default value.
1205 return sprintf(_("Describe %s here."),
1206 "[" . WikiEscape($this->_pagename) . "]");
1209 // There is (non-default) content.
1210 assert($this->_version > 0);
1212 if (!is_string($data['%content'])) {
1213 // Content was not provided to us at init time.
1214 // (This is allowed because for some backends, fetching
1215 // the content may be expensive, and often is not wanted
1218 // In any case, now we need to get it.
1219 $data['%content'] = $this->_get_content();
1220 assert(is_string($data['%content']));
1223 return $data['%content'];
1226 function _get_content() {
1227 $cache = &$this->_wikidb->_cache;
1228 $pagename = $this->_pagename;
1229 $version = $this->_version;
1231 assert($version > 0);
1233 $newdata = $cache->get_versiondata($pagename, $version, true);
1235 assert(is_string($newdata['%content']));
1236 return $newdata['%content'];
1239 // else revision has been deleted... What to do?
1240 return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
1241 $version, $pagename);
1246 * Get meta-data for this revision.
1251 * @param string $key Which meta-data to access.
1253 * Some reserved revision meta-data keys are:
1255 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1256 * The 'mtime' meta-value is normally set automatically by the database
1257 * backend, but it may be specified explicitly when creating a new revision.
1259 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1260 * of a page must be monotonically increasing. If an attempt is
1261 * made to create a new revision with an mtime less than that of
1262 * the preceeding revision, the new revisions timestamp is force
1263 * to be equal to that of the preceeding revision. In that case,
1264 * the originally requested mtime is preserved in 'orig_mtime'.
1265 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1266 * This meta-value is <em>always</em> automatically maintained by the database
1267 * backend. (It is set from the 'mtime' meta-value of the superceding
1268 * revision.) '_supplanted' has a value of 'false' for the current revision.
1270 * FIXME: this could be refactored:
1272 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1274 * <dd> Authenticated author of a page. This is used to identify
1275 * the distinctness of authors when cleaning old revisions from
1277 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1278 * <dt> 'summary' <dd> Short change summary entered by page author.
1281 * Meta-data keys must be valid C identifers (they have to start with a letter
1282 * or underscore, and can contain only alphanumerics and underscores.)
1284 * @return string The requested value, or false if the requested value
1287 function get($key) {
1288 if (!$key || $key[0] == '%')
1290 $data = &$this->_data;
1291 return isset($data[$key]) ? $data[$key] : false;
1295 * Get all the revision page meta-data as a hash.
1297 * @return hash The revision meta-data.
1299 function getMetaData() {
1301 foreach ($this->_data as $key => $val) {
1302 if (!empty($val) && $key[0] != '%')
1310 * Return a string representation of the revision.
1312 * This is really only for debugging.
1316 * @return string Printable representation of the WikiDB_Page.
1318 function asString () {
1320 printf("[%s:%d\n", get_class($this), $this->get('version'));
1321 print_r($this->_data);
1322 echo $this->getPackedContent() . "\n]\n";
1323 $strval = ob_get_contents();
1331 * A class which represents a sequence of WikiDB_Pages.
1333 class WikiDB_PageIterator
1335 function WikiDB_PageIterator(&$wikidb, &$pages) {
1336 $this->_pages = $pages;
1337 $this->_wikidb = &$wikidb;
1341 * Get next WikiDB_Page in sequence.
1345 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1348 if ( ! ($next = $this->_pages->next()) )
1351 $pagename = &$next['pagename'];
1352 if (isset($next['pagedata']))
1353 $this->_wikidb->_cache->cache_data($next);
1355 return new WikiDB_Page($this->_wikidb, $pagename);
1359 * Release resources held by this iterator.
1361 * The iterator may not be used after free() is called.
1363 * There is no need to call free(), if next() has returned false.
1364 * (I.e. if you iterate through all the pages in the sequence,
1365 * you do not need to call free() --- you only need to call it
1366 * if you stop before the end of the iterator is reached.)
1371 $this->_pages->free();
1375 function setSortby ($arg = false) {
1377 $arg = @$_GET['sortby'];
1379 $sortby = substr($arg,1);
1380 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1383 if (is_array($arg)) { // array('mtime' => 'desc')
1390 // available column types to sort by:
1391 // todo: we must provide access methods for the generic dumb/iterator
1392 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1393 if (in_array($sortby,$this->_types))
1394 $this->_options['sortby'] = $sortby;
1396 trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1397 if (in_array(strtoupper($order),'ASC','DESC'))
1398 $this->_options['order'] = strtoupper($order);
1400 trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1406 * A class which represents a sequence of WikiDB_PageRevisions.
1408 class WikiDB_PageRevisionIterator
1410 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1411 $this->_revisions = $revisions;
1412 $this->_wikidb = &$wikidb;
1416 * Get next WikiDB_PageRevision in sequence.
1420 * @return WikiDB_PageRevision
1421 * The next WikiDB_PageRevision in the sequence.
1424 if ( ! ($next = $this->_revisions->next()) )
1427 $this->_wikidb->_cache->cache_data($next);
1429 $pagename = $next['pagename'];
1430 $version = $next['version'];
1431 $versiondata = $next['versiondata'];
1432 assert(!empty($pagename));
1433 assert(is_array($versiondata));
1434 assert($version > 0);
1436 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1441 * Release resources held by this iterator.
1443 * The iterator may not be used after free() is called.
1445 * There is no need to call free(), if next() has returned false.
1446 * (I.e. if you iterate through all the revisions in the sequence,
1447 * you do not need to call free() --- you only need to call it
1448 * if you stop before the end of the iterator is reached.)
1453 $this->_revisions->free();
1459 * Data cache used by WikiDB.
1461 * FIXME: Maybe rename this to caching_backend (or some such).
1467 // FIXME: beautify versiondata cache. Cache only limited data?
1469 function WikiDB_cache (&$backend) {
1470 $this->_backend = &$backend;
1472 $this->_pagedata_cache = array();
1473 $this->_versiondata_cache = array();
1474 array_push ($this->_versiondata_cache, array());
1475 $this->_glv_cache = array();
1479 $this->_pagedata_cache = false;
1480 $this->_versiondata_cache = false;
1481 $this->_glv_cache = false;
1484 function get_pagedata($pagename) {
1485 assert(is_string($pagename) && $pagename);
1486 $cache = &$this->_pagedata_cache;
1488 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1489 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1490 if (empty($cache[$pagename]))
1491 $cache[$pagename] = array();
1494 return $cache[$pagename];
1497 function update_pagedata($pagename, $newdata) {
1498 assert(is_string($pagename) && $pagename);
1500 $this->_backend->update_pagedata($pagename, $newdata);
1502 if (is_array($this->_pagedata_cache[$pagename])) {
1503 $cachedata = &$this->_pagedata_cache[$pagename];
1504 foreach($newdata as $key => $val)
1505 $cachedata[$key] = $val;
1509 function invalidate_cache($pagename) {
1510 unset ($this->_pagedata_cache[$pagename]);
1511 unset ($this->_versiondata_cache[$pagename]);
1512 unset ($this->_glv_cache[$pagename]);
1515 function delete_page($pagename) {
1516 $this->_backend->delete_page($pagename);
1517 unset ($this->_pagedata_cache[$pagename]);
1518 unset ($this->_glv_cache[$pagename]);
1522 function cache_data($data) {
1523 if (isset($data['pagedata']))
1524 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1527 function get_versiondata($pagename, $version, $need_content = false) {
1528 // FIXME: Seriously ugly hackage
1529 if (defined ('USECACHE')){ //temporary - for debugging
1530 assert(is_string($pagename) && $pagename);
1531 // there is a bug here somewhere which results in an assertion failure at line 105
1532 // of ArchiveCleaner.php It goes away if we use the next line.
1533 $need_content = true;
1534 $nc = $need_content ? '1':'0';
1535 $cache = &$this->_versiondata_cache;
1536 if (!isset($cache[$pagename][$version][$nc])||
1537 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1538 $cache[$pagename][$version][$nc] =
1539 $this->_backend->get_versiondata($pagename,$version, $need_content);
1540 // If we have retrieved all data, we may as well set the cache for $need_content = false
1542 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1545 $vdata = $cache[$pagename][$version][$nc];
1549 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1552 if ($vdata && !empty($vdata['%pagedata']))
1553 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1557 function set_versiondata($pagename, $version, $data) {
1558 $new = $this->_backend->
1559 set_versiondata($pagename, $version, $data);
1561 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1563 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1564 // Is this necessary?
1565 unset($this->_glv_cache[$pagename]);
1569 function update_versiondata($pagename, $version, $data) {
1570 $new = $this->_backend->
1571 update_versiondata($pagename, $version, $data);
1573 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1575 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1576 // Is this necessary?
1577 unset($this->_glv_cache[$pagename]);
1581 function delete_versiondata($pagename, $version) {
1582 $new = $this->_backend->
1583 delete_versiondata($pagename, $version);
1584 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1585 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1586 unset ($this->_glv_cache[$pagename]);
1589 function get_latest_version($pagename) {
1590 if(defined('USECACHE')){
1591 assert (is_string($pagename) && $pagename);
1592 $cache = &$this->_glv_cache;
1593 if (!isset($cache[$pagename])) {
1594 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1595 if (empty($cache[$pagename]))
1596 $cache[$pagename] = 0;
1598 return $cache[$pagename];}
1600 return $this->_backend->get_latest_version($pagename);
1609 // c-basic-offset: 4
1610 // c-hanging-comment-ender-p: nil
1611 // indent-tabs-mode: nil