2 rcs_id('$Id: WikiDB.php,v 1.30 2004-01-27 23:23:39 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);
220 * Retrieve all pages.
222 * Gets the set of all pages with non-default contents.
224 * FIXME: do we need this? I think so. The simple searches
229 * @param boolean $include_defaulted Normally pages whose most
230 * recent revision has empty content are considered to be
231 * non-existant. Unless $include_defaulted is set to true, those
232 * pages will not be returned.
234 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
235 * in the WikiDB which have non-default contents.
237 function getAllPages($include_defaulted = false, $orderby = 'pagename') {
238 $result = $this->_backend->get_all_pages($include_defaulted,$orderby);
239 return new WikiDB_PageIterator($this, $result);
245 * Search for pages containing (or not containing) certain words
248 * Pages are returned in alphabetical order whenever it is
249 * practical to do so.
251 * FIXME: should titleSearch and fullSearch be combined? I think so.
254 * @param TextSearchQuery $search A TextSearchQuery object
255 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
256 * @see TextSearchQuery
258 function titleSearch($search) {
259 $result = $this->_backend->text_search($search);
260 return new WikiDB_PageIterator($this, $result);
266 * Search for pages containing (or not containing) certain words
267 * in their entire text (this includes the page content and the
270 * Pages are returned in alphabetical order whenever it is
271 * practical to do so.
275 * @param TextSearchQuery $search A TextSearchQuery object.
276 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
277 * @see TextSearchQuery
279 function fullSearch($search) {
280 $result = $this->_backend->text_search($search, 'full_text');
281 return new WikiDB_PageIterator($this, $result);
285 * Find the pages with the greatest hit counts.
287 * Pages are returned in reverse order by hit count.
291 * @param integer $limit The maximum number of pages to return.
292 * Set $limit to zero to return all pages. If $limit < 0, pages will
293 * be sorted in decreasing order of popularity.
295 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
298 function mostPopular($limit = 20) {
299 $result = $this->_backend->most_popular($limit);
300 return new WikiDB_PageIterator($this, $result);
304 * Find recent page revisions.
306 * Revisions are returned in reverse order by creation time.
310 * @param hash $params This hash is used to specify various optional
314 * <dd> (integer) At most this many revisions will be returned.
316 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
317 * <dt> include_minor_revisions
318 * <dd> (boolean) Also include minor revisions. (Default is not to.)
319 * <dt> exclude_major_revisions
320 * <dd> (boolean) Don't include non-minor revisions.
321 * (Exclude_major_revisions implies include_minor_revisions.)
322 * <dt> include_all_revisions
323 * <dd> (boolean) Return all matching revisions for each page.
324 * Normally only the most recent matching revision is returned
328 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
329 * matching revisions.
331 function mostRecent($params = false) {
332 $result = $this->_backend->most_recent($params);
333 return new WikiDB_PageRevisionIterator($this, $result);
337 * Blog search. (experimental)
339 * Search for blog entries related to a certain page.
341 * FIXME: with pagetype support and perhaps a RegexpSearchQuery
342 * we can make sure we are returning *ONLY* blog pages to the
343 * main routine. Currently, we just use titleSearch which requires
344 * some furher checking in lib/plugin/WikiBlog.php (BAD).
348 * @param string $order 'normal' (chronological) or 'reverse'
349 * @param string $page Find blog entries related to this page.
350 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
352 // Deleting until such time as this is properly implemented...
353 // (As long as it's just a title search, just use titleSearch.)
354 //function blogSearch($page, $order) {
355 // //FIXME: implement ordering
357 // require_once('lib/TextSearchQuery.php');
358 // $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
360 // return $this->titleSearch($query);
363 /** Get timestamp when database was last modified.
365 * @return string A string consisting of two integers,
366 * separated by a space. The first is the time in
367 * unix timestamp format, the second is a modification
368 * count for the database.
370 * The idea is that you can cast the return value to an
371 * int to get a timestamp, or you can use the string value
372 * as a good hash for the entire database.
374 function getTimestamp() {
375 $ts = $this->get('_timestamp');
376 return sprintf("%d %d", $ts[0], $ts[1]);
380 * Update the database timestamp.
384 $ts = $this->get('_timestamp');
385 $this->set('_timestamp', array(time(), $ts[1] + 1));
390 * Access WikiDB global meta-data.
392 * NOTE: this is currently implemented in a hackish and
393 * not very efficient manner.
397 * @param string $key Which meta data to get.
398 * Some reserved meta-data keys are:
400 * <dt>'_timestamp' <dd> Data used by getTimestamp().
403 * @return scalar The requested value, or false if the requested data
407 if (!$key || $key[0] == '%')
410 * Hack Alert: We can use any page (existing or not) to store
411 * this data (as long as we always use the same one.)
413 $gd = $this->getPage('global_data');
414 $data = $gd->get('__global');
416 if ($data && isset($data[$key]))
423 * Set global meta-data.
425 * NOTE: this is currently implemented in a hackish and
426 * not very efficient manner.
431 * @param string $key Meta-data key to set.
432 * @param string $newval New value.
434 function set($key, $newval) {
435 if (!$key || $key[0] == '%')
438 $gd = $this->getPage('global_data');
440 $data = $gd->get('__global');
447 $data[$key] = $newval;
449 $gd->set('__global', $data);
455 * An abstract base class which representing a wiki-page within a
458 * A WikiDB_Page contains a number (at least one) of
459 * WikiDB_PageRevisions.
463 function WikiDB_Page(&$wikidb, $pagename) {
464 $this->_wikidb = &$wikidb;
465 $this->_pagename = $pagename;
466 assert(!empty($this->_pagename));
470 * Get the name of the wiki page.
474 * @return string The page name.
477 return $this->_pagename;
482 * Delete an old revision of a WikiDB_Page.
484 * Deletes the specified revision of the page.
485 * It is a fatal error to attempt to delete the current revision.
489 * @param integer $version Which revision to delete. (You can also
490 * use a WikiDB_PageRevision object here.)
492 function deleteRevision($version) {
493 $backend = &$this->_wikidb->_backend;
494 $cache = &$this->_wikidb->_cache;
495 $pagename = &$this->_pagename;
497 $version = $this->_coerce_to_version($version);
502 $latestversion = $cache->get_latest_version($pagename);
503 if ($latestversion && $version == $latestversion) {
505 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
506 $pagename), E_USER_ERROR);
510 $cache->delete_versiondata($pagename, $version);
516 * Delete a revision, or possibly merge it with a previous
520 * Suppose an author make a (major) edit to a page. Shortly
521 * after that the same author makes a minor edit (e.g. to fix
522 * spelling mistakes he just made.)
524 * Now some time later, where cleaning out old saved revisions,
525 * and would like to delete his minor revision (since there's
526 * really no point in keeping minor revisions around for a long
529 * Note that the text after the minor revision probably represents
530 * what the author intended to write better than the text after
531 * the preceding major edit.
533 * So what we really want to do is merge the minor edit with the
536 * We will only do this when:
538 * <li>The revision being deleted is a minor one, and
539 * <li>It has the same author as the immediately preceding revision.
542 function mergeRevision($version) {
543 $backend = &$this->_wikidb->_backend;
544 $cache = &$this->_wikidb->_cache;
545 $pagename = &$this->_pagename;
547 $version = $this->_coerce_to_version($version);
552 $latestversion = $backend->get_latest_version($pagename);
553 if ($latestversion && $version == $latestversion) {
555 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
556 $pagename), E_USER_ERROR);
560 $versiondata = $cache->get_versiondata($pagename, $version, true);
562 // Not there? ... we're done!
567 if ($versiondata['is_minor_edit']) {
568 $previous = $backend->get_previous_version($pagename, $version);
570 $prevdata = $cache->get_versiondata($pagename, $previous);
571 if ($prevdata['author_id'] == $versiondata['author_id']) {
572 // This is a minor revision, previous version is
573 // by the same author. We will merge the
575 $cache->update_versiondata($pagename, $previous,
576 array('%content' => $versiondata['%content'],
577 '_supplanted' => $versiondata['_supplanted']));
582 $cache->delete_versiondata($pagename, $version);
588 * Create a new revision of a {@link WikiDB_Page}.
592 * @param int $version Version number for new revision.
593 * To ensure proper serialization of edits, $version must be
594 * exactly one higher than the current latest version.
595 * (You can defeat this check by setting $version to
596 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
598 * @param string $content Contents of new revision.
600 * @param hash $metadata Metadata for new revision.
601 * All values in the hash should be scalars (strings or integers).
603 * @param array $links List of pagenames which this page links to.
605 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
606 * $version was incorrect, returns false
608 function createRevision($version, &$content, $metadata, $links) {
609 $backend = &$this->_wikidb->_backend;
610 $cache = &$this->_wikidb->_cache;
611 $pagename = &$this->_pagename;
615 $latestversion = $backend->get_latest_version($pagename);
616 $newversion = $latestversion + 1;
617 assert($newversion >= 1);
619 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
626 foreach ($data as $key => $val) {
627 if (empty($val) || $key[0] == '_' || $key[0] == '%')
631 assert(!empty($data['author_id']));
632 if (empty($data['author_id']))
633 @$data['author_id'] = $data['author'];
635 if (empty($data['mtime']))
636 $data['mtime'] = time();
638 if ($latestversion) {
639 // Ensure mtimes are monotonic.
640 $pdata = $cache->get_versiondata($pagename, $latestversion);
641 if ($data['mtime'] < $pdata['mtime']) {
642 trigger_error(sprintf(_("%s: Date of new revision is %s"),
643 $pagename,"'non-monotonic'"),
645 $data['orig_mtime'] = $data['mtime'];
646 $data['mtime'] = $pdata['mtime'];
649 // FIXME: use (possibly user specified) 'mtime' time or
651 $cache->update_versiondata($pagename, $latestversion,
652 array('_supplanted' => $data['mtime']));
655 $data['%content'] = &$content;
657 $cache->set_versiondata($pagename, $newversion, $data);
659 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
660 //':deleted' => empty($content)));
662 $backend->set_links($pagename, $links);
666 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
670 /** A higher-level interface to createRevision.
672 * This takes care of computing the links, and storing
673 * a cached version of the transformed wiki-text.
675 * @param string $wikitext The page content.
677 * @param int $version Version number for new revision.
678 * To ensure proper serialization of edits, $version must be
679 * exactly one higher than the current latest version.
680 * (You can defeat this check by setting $version to
681 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
683 * @param hash $meta Meta-data for new revision.
685 function save($wikitext, $version, $meta) {
686 $formatted = new TransformedText($this, $wikitext, $meta);
687 $type = $formatted->getType();
688 $meta['pagetype'] = $type->getName();
689 $links = $formatted->getWikiPageLinks();
691 $backend = &$this->_wikidb->_backend;
693 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
695 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
696 $this->set('_cached_html', $formatted->pack());
699 // FIXME: probably should have some global state information
700 // in the backend to control when to optimize.
702 // We're doing this here rather than in createRevision because
703 // postgres can't optimize while locked.
704 if (time() % 50 == 0) {
705 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
706 $backend->optimize();
709 $newrevision->_transformedContent = $formatted;
714 * Get the most recent revision of a page.
718 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
720 function getCurrentRevision() {
721 $backend = &$this->_wikidb->_backend;
722 $cache = &$this->_wikidb->_cache;
723 $pagename = &$this->_pagename;
726 $version = $cache->get_latest_version($pagename);
727 $revision = $this->getRevision($version);
734 * Get a specific revision of a WikiDB_Page.
738 * @param integer $version Which revision to get.
740 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
741 * false if the requested revision does not exist in the {@link WikiDB}.
742 * Note that version zero of any page always exists.
744 function getRevision($version) {
745 $cache = &$this->_wikidb->_cache;
746 $pagename = &$this->_pagename;
749 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
751 assert($version > 0);
752 $vdata = $cache->get_versiondata($pagename, $version);
755 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
760 * Get previous page revision.
762 * This method find the most recent revision before a specified
767 * @param integer $version Find most recent revision before this version.
768 * You can also use a WikiDB_PageRevision object to specify the $version.
770 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
771 * requested revision does not exist in the {@link WikiDB}. Note that
772 * unless $version is greater than zero, a revision (perhaps version zero,
773 * the default revision) will always be found.
775 function getRevisionBefore($version) {
776 $backend = &$this->_wikidb->_backend;
777 $pagename = &$this->_pagename;
779 $version = $this->_coerce_to_version($version);
784 $previous = $backend->get_previous_version($pagename, $version);
785 $revision = $this->getRevision($previous);
792 * Get all revisions of the WikiDB_Page.
794 * This does not include the version zero (default) revision in the
795 * returned revision set.
797 * @return WikiDB_PageRevisionIterator A
798 * WikiDB_PageRevisionIterator containing all revisions of this
799 * WikiDB_Page in reverse order by version number.
801 function getAllRevisions() {
802 $backend = &$this->_wikidb->_backend;
803 $revs = $backend->get_all_revisions($this->_pagename);
804 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
808 * Find pages which link to or are linked from a page.
812 * @param boolean $reversed Which links to find: true for backlinks (default).
814 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
815 * all matching pages.
817 function getLinks($reversed = true) {
818 $backend = &$this->_wikidb->_backend;
819 $result = $backend->get_links($this->_pagename, $reversed);
820 return new WikiDB_PageIterator($this->_wikidb, $result);
824 * Access WikiDB_Page meta-data.
828 * @param string $key Which meta data to get.
829 * Some reserved meta-data keys are:
831 * <dt>'locked'<dd> Is page locked?
832 * <dt>'hits' <dd> Page hit counter.
833 * <dt>'pref' <dd> Users preferences, stored in homepages.
834 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
836 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
837 * page-headers and content.
838 * <dt>'score' <dd> Page score (not yet implement, do we need?)
841 * @return scalar The requested value, or false if the requested data
845 $cache = &$this->_wikidb->_cache;
846 if (!$key || $key[0] == '%')
848 $data = $cache->get_pagedata($this->_pagename);
849 return isset($data[$key]) ? $data[$key] : false;
853 * Get all the page meta-data as a hash.
855 * @return hash The page meta-data.
857 function getMetaData() {
858 $cache = &$this->_wikidb->_cache;
859 $data = $cache->get_pagedata($this->_pagename);
861 foreach ($data as $key => $val) {
862 if (/*!empty($val) &&*/ $key[0] != '%')
869 * Set page meta-data.
874 * @param string $key Meta-data key to set.
875 * @param string $newval New value.
877 function set($key, $newval) {
878 $cache = &$this->_wikidb->_cache;
879 $pagename = &$this->_pagename;
881 assert($key && $key[0] != '%');
883 $data = $cache->get_pagedata($pagename);
885 if (!empty($newval)) {
886 if (!empty($data[$key]) && $data[$key] == $newval)
887 return; // values identical, skip update.
890 if (empty($data[$key]))
891 return; // values identical, skip update.
894 $cache->update_pagedata($pagename, array($key => $newval));
898 * Increase page hit count.
900 * FIXME: IS this needed? Probably not.
902 * This is a convenience function.
903 * <pre> $page->increaseHitCount(); </pre>
904 * is functionally identical to
905 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
907 * Note that this method may be implemented in more efficient ways
908 * in certain backends.
912 function increaseHitCount() {
913 @$newhits = $this->get('hits') + 1;
914 $this->set('hits', $newhits);
918 * Return a string representation of the WikiDB_Page
920 * This is really only for debugging.
924 * @return string Printable representation of the WikiDB_Page.
926 function asString () {
928 printf("[%s:%s\n", get_class($this), $this->getName());
929 print_r($this->getMetaData());
931 $strval = ob_get_contents();
939 * @param integer_or_object $version_or_pagerevision
940 * Takes either the version number (and int) or a WikiDB_PageRevision
942 * @return integer The version number.
944 function _coerce_to_version($version_or_pagerevision) {
945 if (method_exists($version_or_pagerevision, "getContent"))
946 $version = $version_or_pagerevision->getVersion();
948 $version = (int) $version_or_pagerevision;
950 assert($version >= 0);
954 function isUserPage ($include_empty = true) {
955 if ($include_empty) {
956 $current = $this->getCurrentRevision();
957 if ($current->hasDefaultContents()) {
961 return $this->get('pref') ? true : false;
967 * This class represents a specific revision of a WikiDB_Page within
970 * A WikiDB_PageRevision has read-only semantics. You may only create
971 * new revisions (and delete old ones) --- you cannot modify existing
974 class WikiDB_PageRevision
976 var $_transformedContent = false; // set by WikiDB_Page::save()
978 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
979 $versiondata = false)
981 $this->_wikidb = &$wikidb;
982 $this->_pagename = $pagename;
983 $this->_version = $version;
984 $this->_data = $versiondata ? $versiondata : array();
988 * Get the WikiDB_Page which this revision belongs to.
992 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
995 return new WikiDB_Page($this->_wikidb, $this->_pagename);
999 * Get the version number of this revision.
1003 * @return integer The version number of this revision.
1005 function getVersion() {
1006 return $this->_version;
1010 * Determine whether this revision has defaulted content.
1012 * The default revision (version 0) of each page, as well as any
1013 * pages which are created with empty content have their content
1014 * defaulted to something like:
1016 * Describe [ThisPage] here.
1021 * @return boolean Returns true if the page has default content.
1023 function hasDefaultContents() {
1024 $data = &$this->_data;
1025 return empty($data['%content']);
1029 * Get the content as an array of lines.
1033 * @return array An array of lines.
1034 * The lines should contain no trailing white space.
1036 function getContent() {
1037 return explode("\n", $this->getPackedContent());
1041 * Get the pagename of the revision.
1045 * @return string pagename.
1047 function getPageName() {
1048 return $this->_pagename;
1052 * Determine whether revision is the latest.
1056 * @return boolean True iff the revision is the latest (most recent) one.
1058 function isCurrent() {
1059 if (!isset($this->_iscurrent)) {
1060 $page = $this->getPage();
1061 $current = $page->getCurrentRevision();
1062 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1064 return $this->_iscurrent;
1068 * Get the transformed content of a page.
1070 * @param string $pagetype Override the page-type of the revision.
1072 * @return object An XmlContent-like object containing the page transformed
1075 function getTransformedContent($pagetype_override=false) {
1076 $backend = &$this->_wikidb->_backend;
1078 if ($pagetype_override) {
1079 // Figure out the normal page-type for this page.
1080 $type = PageType::GetPageType($this->get('pagetype'));
1081 if ($type->getName() == $pagetype_override)
1082 $pagetype_override = false; // Not really an override...
1085 if ($pagetype_override) {
1086 // Overriden page type, don't cache (or check cache).
1087 return new TransformedText($this->getPage(),
1088 $this->getPackedContent(),
1089 $this->getMetaData(),
1090 $pagetype_override);
1093 $possibly_cache_results = true;
1095 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1096 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1097 // flush cache for this page.
1098 $page = $this->getPage();
1099 $page->set('_cached_html', false);
1101 $possibly_cache_results = false;
1103 elseif (!$this->_transformedContent) {
1105 if ($this->isCurrent()) {
1106 $page = $this->getPage();
1107 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1110 $possibly_cache_results = false;
1115 if (!$this->_transformedContent) {
1116 $this->_transformedContent
1117 = new TransformedText($this->getPage(),
1118 $this->getPackedContent(),
1119 $this->getMetaData());
1121 if ($possibly_cache_results) {
1122 // If we're still the current version, cache the transfomed page.
1124 if ($this->isCurrent()) {
1125 $page->set('_cached_html', $this->_transformedContent->pack());
1131 return $this->_transformedContent;
1135 * Get the content as a string.
1139 * @return string The page content.
1140 * Lines are separated by new-lines.
1142 function getPackedContent() {
1143 $data = &$this->_data;
1146 if (empty($data['%content'])) {
1147 include_once('lib/InlineParser.php');
1148 // Replace empty content with default value.
1149 return sprintf(_("Describe %s here."),
1150 "[" . WikiEscape($this->_pagename) . "]");
1153 // There is (non-default) content.
1154 assert($this->_version > 0);
1156 if (!is_string($data['%content'])) {
1157 // Content was not provided to us at init time.
1158 // (This is allowed because for some backends, fetching
1159 // the content may be expensive, and often is not wanted
1162 // In any case, now we need to get it.
1163 $data['%content'] = $this->_get_content();
1164 assert(is_string($data['%content']));
1167 return $data['%content'];
1170 function _get_content() {
1171 $cache = &$this->_wikidb->_cache;
1172 $pagename = $this->_pagename;
1173 $version = $this->_version;
1175 assert($version > 0);
1177 $newdata = $cache->get_versiondata($pagename, $version, true);
1179 assert(is_string($newdata['%content']));
1180 return $newdata['%content'];
1183 // else revision has been deleted... What to do?
1184 return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
1185 $version, $pagename);
1190 * Get meta-data for this revision.
1195 * @param string $key Which meta-data to access.
1197 * Some reserved revision meta-data keys are:
1199 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1200 * The 'mtime' meta-value is normally set automatically by the database
1201 * backend, but it may be specified explicitly when creating a new revision.
1203 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1204 * of a page must be monotonically increasing. If an attempt is
1205 * made to create a new revision with an mtime less than that of
1206 * the preceeding revision, the new revisions timestamp is force
1207 * to be equal to that of the preceeding revision. In that case,
1208 * the originally requested mtime is preserved in 'orig_mtime'.
1209 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1210 * This meta-value is <em>always</em> automatically maintained by the database
1211 * backend. (It is set from the 'mtime' meta-value of the superceding
1212 * revision.) '_supplanted' has a value of 'false' for the current revision.
1214 * FIXME: this could be refactored:
1216 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1218 * <dd> Authenticated author of a page. This is used to identify
1219 * the distinctness of authors when cleaning old revisions from
1221 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1222 * <dt> 'summary' <dd> Short change summary entered by page author.
1225 * Meta-data keys must be valid C identifers (they have to start with a letter
1226 * or underscore, and can contain only alphanumerics and underscores.)
1228 * @return string The requested value, or false if the requested value
1231 function get($key) {
1232 if (!$key || $key[0] == '%')
1234 $data = &$this->_data;
1235 return isset($data[$key]) ? $data[$key] : false;
1239 * Get all the revision page meta-data as a hash.
1241 * @return hash The revision meta-data.
1243 function getMetaData() {
1245 foreach ($this->_data as $key => $val) {
1246 if (!empty($val) && $key[0] != '%')
1254 * Return a string representation of the revision.
1256 * This is really only for debugging.
1260 * @return string Printable representation of the WikiDB_Page.
1262 function asString () {
1264 printf("[%s:%d\n", get_class($this), $this->get('version'));
1265 print_r($this->_data);
1266 echo $this->getPackedContent() . "\n]\n";
1267 $strval = ob_get_contents();
1275 * A class which represents a sequence of WikiDB_Pages.
1277 class WikiDB_PageIterator
1279 function WikiDB_PageIterator(&$wikidb, &$pages) {
1280 $this->_pages = $pages;
1281 $this->_wikidb = &$wikidb;
1285 * Get next WikiDB_Page in sequence.
1289 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1292 if ( ! ($next = $this->_pages->next()) )
1295 $pagename = &$next['pagename'];
1296 if (isset($next['pagedata']))
1297 $this->_wikidb->_cache->cache_data($next);
1299 return new WikiDB_Page($this->_wikidb, $pagename);
1303 * Release resources held by this iterator.
1305 * The iterator may not be used after free() is called.
1307 * There is no need to call free(), if next() has returned false.
1308 * (I.e. if you iterate through all the pages in the sequence,
1309 * you do not need to call free() --- you only need to call it
1310 * if you stop before the end of the iterator is reached.)
1315 $this->_pages->free();
1319 function setSortby ($arg = false) {
1321 $arg = @$_GET['sortby'];
1323 $sortby = substr($arg,1);
1324 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1327 if (is_array($arg)) { // array('mtime' => 'desc')
1334 // available column types to sort by:
1335 // todo: we must provide access methods for the generic dumb/iterator
1336 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1337 if (in_array($sortby,$this->_types))
1338 $this->_options['sortby'] = $sortby;
1340 trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1341 if (in_array(strtoupper($order),'ASC','DESC'))
1342 $this->_options['order'] = strtoupper($order);
1344 trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1350 * A class which represents a sequence of WikiDB_PageRevisions.
1352 class WikiDB_PageRevisionIterator
1354 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1355 $this->_revisions = $revisions;
1356 $this->_wikidb = &$wikidb;
1360 * Get next WikiDB_PageRevision in sequence.
1364 * @return WikiDB_PageRevision
1365 * The next WikiDB_PageRevision in the sequence.
1368 if ( ! ($next = $this->_revisions->next()) )
1371 $this->_wikidb->_cache->cache_data($next);
1373 $pagename = $next['pagename'];
1374 $version = $next['version'];
1375 $versiondata = $next['versiondata'];
1376 assert(!empty($pagename));
1377 assert(is_array($versiondata));
1378 assert($version > 0);
1380 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1385 * Release resources held by this iterator.
1387 * The iterator may not be used after free() is called.
1389 * There is no need to call free(), if next() has returned false.
1390 * (I.e. if you iterate through all the revisions in the sequence,
1391 * you do not need to call free() --- you only need to call it
1392 * if you stop before the end of the iterator is reached.)
1397 $this->_revisions->free();
1403 * Data cache used by WikiDB.
1405 * FIXME: Maybe rename this to caching_backend (or some such).
1411 // FIXME: beautify versiondata cache. Cache only limited data?
1413 function WikiDB_cache (&$backend) {
1414 $this->_backend = &$backend;
1416 $this->_pagedata_cache = array();
1417 $this->_versiondata_cache = array();
1418 array_push ($this->_versiondata_cache, array());
1419 $this->_glv_cache = array();
1423 $this->_pagedata_cache = false;
1424 $this->_versiondata_cache = false;
1425 $this->_glv_cache = false;
1428 function get_pagedata($pagename) {
1429 assert(is_string($pagename) && $pagename);
1430 $cache = &$this->_pagedata_cache;
1432 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1433 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1434 if (empty($cache[$pagename]))
1435 $cache[$pagename] = array();
1438 return $cache[$pagename];
1441 function update_pagedata($pagename, $newdata) {
1442 assert(is_string($pagename) && $pagename);
1444 $this->_backend->update_pagedata($pagename, $newdata);
1446 if (is_array($this->_pagedata_cache[$pagename])) {
1447 $cachedata = &$this->_pagedata_cache[$pagename];
1448 foreach($newdata as $key => $val)
1449 $cachedata[$key] = $val;
1453 function invalidate_cache($pagename) {
1454 unset ($this->_pagedata_cache[$pagename]);
1455 unset ($this->_versiondata_cache[$pagename]);
1456 unset ($this->_glv_cache[$pagename]);
1459 function delete_page($pagename) {
1460 $this->_backend->delete_page($pagename);
1461 unset ($this->_pagedata_cache[$pagename]);
1462 unset ($this->_glv_cache[$pagename]);
1466 function cache_data($data) {
1467 if (isset($data['pagedata']))
1468 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1471 function get_versiondata($pagename, $version, $need_content = false) {
1472 // FIXME: Seriously ugly hackage
1473 if (defined ('USECACHE')){ //temporary - for debugging
1474 assert(is_string($pagename) && $pagename);
1475 // there is a bug here somewhere which results in an assertion failure at line 105
1476 // of ArchiveCleaner.php It goes away if we use the next line.
1477 $need_content = true;
1478 $nc = $need_content ? '1':'0';
1479 $cache = &$this->_versiondata_cache;
1480 if (!isset($cache[$pagename][$version][$nc])||
1481 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1482 $cache[$pagename][$version][$nc] =
1483 $this->_backend->get_versiondata($pagename,$version, $need_content);
1484 // If we have retrieved all data, we may as well set the cache for $need_content = false
1486 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1489 $vdata = $cache[$pagename][$version][$nc];
1493 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1496 if ($vdata && !empty($vdata['%pagedata']))
1497 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1501 function set_versiondata($pagename, $version, $data) {
1502 $new = $this->_backend->
1503 set_versiondata($pagename, $version, $data);
1505 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1507 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1508 // Is this necessary?
1509 unset($this->_glv_cache[$pagename]);
1513 function update_versiondata($pagename, $version, $data) {
1514 $new = $this->_backend->
1515 update_versiondata($pagename, $version, $data);
1517 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1519 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1520 // Is this necessary?
1521 unset($this->_glv_cache[$pagename]);
1525 function delete_versiondata($pagename, $version) {
1526 $new = $this->_backend->
1527 delete_versiondata($pagename, $version);
1528 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1529 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1530 unset ($this->_glv_cache[$pagename]);
1533 function get_latest_version($pagename) {
1534 if(defined('USECACHE')){
1535 assert (is_string($pagename) && $pagename);
1536 $cache = &$this->_glv_cache;
1537 if (!isset($cache[$pagename])) {
1538 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1539 if (empty($cache[$pagename]))
1540 $cache[$pagename] = 0;
1542 return $cache[$pagename];}
1544 return $this->_backend->get_latest_version($pagename);
1551 * FIXME! Class for externally authenticated users.
1553 * We might have read-only access to the password and/or group membership,
1554 * or we might even be able to update the entries.
1556 * FIXME: This was written before we stored prefs as %pagedata, so
1558 * FIXME: I believe this is not currently used.
1560 // class WikiDB_User
1565 // function WikiDB_User($userid, $authlevel = false) {
1567 // $this->_authdb = new WikiAuthDB($GLOBALS['DBAuthParams']);
1568 // $this->_authmethod = 'AuthDB';
1569 // WikiUser::WikiUser($request, $userid, $authlevel);
1573 // function getPreferences() {
1574 // // external prefs override internal ones?
1575 // if (! $this->_authdb->getPrefs() )
1576 // if ($pref = WikiUser::getPreferences())
1581 // function setPreferences($prefs) {
1582 // if (! $this->_authdb->setPrefs($prefs) )
1583 // return WikiUser::setPreferences();
1587 // function exists() {
1588 // return $this->_authdb->exists($this->UserName());
1591 // // create user and default user homepage
1592 // function createUser ($pref) {
1593 // if ($this->exists()) return;
1594 // if (! $this->_authdb->createUser($pref)) {
1595 // // external auth doesn't allow this.
1596 // // do our policies allow local users instead?
1597 // return WikiUser::createUser($pref);
1601 // function checkPassword($passwd) {
1602 // return $this->_authdb->pwcheck($this->userid, $passwd);
1605 // function changePassword($passwd) {
1606 // if (! $this->mayChangePass() ) {
1607 // trigger_error(sprintf("Attempt to change an external password for '%s'",
1608 // $this->_userid), E_USER_ERROR);
1611 // return $this->_authdb->changePass($this->userid, $passwd);
1614 // function mayChangePass() {
1615 // return $this->_authdb->auth_update;
1620 * FIXME: I believe this is not currently used.
1625 // var $auth_dsn = false, $auth_check = false;
1626 // var $auth_crypt_method = 'crypt', $auth_update = false;
1627 // var $group_members = false, $user_groups = false;
1628 // var $pref_update = false, $pref_select = false;
1631 // function WikiAuthDB($DBAuthParams) {
1632 // foreach ($DBAuthParams as $key => $value) {
1633 // $this->$key = $value;
1635 // if (!$this->auth_dsn) {
1636 // trigger_error(_("no \$DBAuthParams['dsn'] provided"), E_USER_ERROR);
1639 // // compare auth DB to the existing page DB. reuse if it's on the same database.
1640 // if (isa($this->_backend, 'WikiDB_backend_PearDB') and
1641 // $this->_backend->_dsn == $this->auth_dsn) {
1642 // $this->_dbh = &$this->_backend->_dbh;
1643 // return $this->_backend;
1645 // include_once("lib/WikiDB/SQL.php");
1646 // return new WikiDB_SQL($DBAuthParams);
1649 // function param_missing ($param) {
1650 // trigger_error(sprintf(_("No \$DBAuthParams['%s'] provided."), $param), E_USER_ERROR);
1654 // function getPrefs($prefs) {
1655 // if ($this->pref_select) {
1656 // $statement = $this->_backend->Prepare($this->pref_select);
1657 // return unserialize($this->_backend->Execute($statement,
1658 // $prefs->get('userid')));
1660 // param_missing('pref_select');
1665 // function setPrefs($prefs) {
1666 // if ($this->pref_write) {
1667 // $statement = $this->_backend->Prepare($this->pref_write);
1668 // return $this->_backend->Execute($statement,
1669 // $prefs->get('userid'), serialize($prefs->_prefs));
1671 // param_missing('pref_write');
1676 // function createUser ($pref) {
1677 // if ($this->user_create) {
1678 // $statement = $this->_backend->Prepare($this->user_create);
1679 // return $this->_backend->Execute($statement,
1680 // $prefs->get('userid'), serialize($prefs->_prefs));
1682 // param_missing('user_create');
1687 // function exists($userid) {
1688 // if ($this->user_check) {
1689 // $statement = $this->_backend->Prepare($this->user_check);
1690 // return $this->_backend->Execute($statement, $prefs->get('userid'));
1692 // param_missing('user_check');
1697 // function pwcheck($userid, $pass) {
1698 // if ($this->auth_check) {
1699 // $statement = $this->_backend->Prepare($this->auth_check);
1700 // return $this->_backend->Execute($statement, $userid, $pass);
1702 // param_missing('auth_check');
1711 // c-basic-offset: 4
1712 // c-hanging-comment-ender-p: nil
1713 // indent-tabs-mode: nil