2 rcs_id('$Id: WikiDB.php,v 1.44 2004-04-19 18:27: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) and $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 // we don't support sortby=mtime here
310 if (strstr($sortby,'mtime'))
312 $result = $this->_backend->most_popular($limit, $sortby);
313 return new WikiDB_PageIterator($this, $result);
317 * Find recent page revisions.
319 * Revisions are returned in reverse order by creation time.
323 * @param hash $params This hash is used to specify various optional
327 * <dd> (integer) At most this many revisions will be returned.
329 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
330 * <dt> include_minor_revisions
331 * <dd> (boolean) Also include minor revisions. (Default is not to.)
332 * <dt> exclude_major_revisions
333 * <dd> (boolean) Don't include non-minor revisions.
334 * (Exclude_major_revisions implies include_minor_revisions.)
335 * <dt> include_all_revisions
336 * <dd> (boolean) Return all matching revisions for each page.
337 * Normally only the most recent matching revision is returned
341 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
342 * matching revisions.
344 function mostRecent($params = false) {
345 $result = $this->_backend->most_recent($params);
346 return new WikiDB_PageRevisionIterator($this, $result);
350 * Blog search. (experimental)
352 * Search for blog entries related to a certain page.
354 * FIXME: with pagetype support and perhaps a RegexpSearchQuery
355 * we can make sure we are returning *ONLY* blog pages to the
356 * main routine. Currently, we just use titleSearch which requires
357 * some further checking in lib/plugin/WikiBlog.php (BAD).
361 * @param string $order 'normal' (chronological) or 'reverse'
362 * @param string $page Find blog entries related to this page.
363 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
365 // Deleting until such time as this is properly implemented...
366 // (As long as it's just a title search, just use titleSearch.)
367 //function blogSearch($page, $order) {
368 // //FIXME: implement ordering
370 // require_once('lib/TextSearchQuery.php');
371 // $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
373 // return $this->titleSearch($query);
377 * Call the appropriate backend method.
380 * @param string $from Page to rename
381 * @param string $to New name
382 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
383 * @return boolean true or false
385 function renamePage($from, $to, $updateWikiLinks = false) {
386 assert(is_string($from) && $from != '');
387 assert(is_string($to) && $to != '');
389 if (method_exists($this->_backend,'rename_page')) {
390 $oldpage = $this->getPage($from);
391 $newpage = $this->getPage($to);
392 if ($oldpage->exists() and ! $newpage->exists()) {
393 if ($result = $this->_backend->rename_page($from, $to)) {
394 //update all WikiLinks in existing pages
395 if ($updateWikiLinks) {
396 //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
397 require_once('lib/plugin/WikiAdminSearchReplace.php');
398 $links = $oldpage->getLinks();
399 while ($linked_page = $links->next()) {
400 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
403 //create a RecentChanges entry with explaining summary
404 $page = $this->getPage($to);
405 $current = $page->getCurrentRevision();
406 $meta = $current->_data;
407 $version = $current->getVersion();
408 $meta['summary'] = sprintf(_("renamed from %s"),$from);
409 $page->save($current->getPackedContent(), $version + 1, $meta);
413 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
418 /** Get timestamp when database was last modified.
420 * @return string A string consisting of two integers,
421 * separated by a space. The first is the time in
422 * unix timestamp format, the second is a modification
423 * count for the database.
425 * The idea is that you can cast the return value to an
426 * int to get a timestamp, or you can use the string value
427 * as a good hash for the entire database.
429 function getTimestamp() {
430 $ts = $this->get('_timestamp');
431 return sprintf("%d %d", $ts[0], $ts[1]);
435 * Update the database timestamp.
439 $ts = $this->get('_timestamp');
440 $this->set('_timestamp', array(time(), $ts[1] + 1));
445 * Access WikiDB global meta-data.
447 * NOTE: this is currently implemented in a hackish and
448 * not very efficient manner.
452 * @param string $key Which meta data to get.
453 * Some reserved meta-data keys are:
455 * <dt>'_timestamp' <dd> Data used by getTimestamp().
458 * @return scalar The requested value, or false if the requested data
462 if (!$key || $key[0] == '%')
465 * Hack Alert: We can use any page (existing or not) to store
466 * this data (as long as we always use the same one.)
468 $gd = $this->getPage('global_data');
469 $data = $gd->get('__global');
471 if ($data && isset($data[$key]))
478 * Set global meta-data.
480 * NOTE: this is currently implemented in a hackish and
481 * not very efficient manner.
486 * @param string $key Meta-data key to set.
487 * @param string $newval New value.
489 function set($key, $newval) {
490 if (!$key || $key[0] == '%')
493 $gd = $this->getPage('global_data');
495 $data = $gd->get('__global');
502 $data[$key] = $newval;
504 $gd->set('__global', $data);
510 * An abstract base class which representing a wiki-page within a
513 * A WikiDB_Page contains a number (at least one) of
514 * WikiDB_PageRevisions.
518 function WikiDB_Page(&$wikidb, $pagename) {
519 $this->_wikidb = &$wikidb;
520 $this->_pagename = $pagename;
521 assert(is_string($pagename) and $pagename != '');
525 * Get the name of the wiki page.
529 * @return string The page name.
532 return $this->_pagename;
536 $current = $this->getCurrentRevision();
537 return ! $current->hasDefaultContents();
541 * Delete an old revision of a WikiDB_Page.
543 * Deletes the specified revision of the page.
544 * It is a fatal error to attempt to delete the current revision.
548 * @param integer $version Which revision to delete. (You can also
549 * use a WikiDB_PageRevision object here.)
551 function deleteRevision($version) {
552 $backend = &$this->_wikidb->_backend;
553 $cache = &$this->_wikidb->_cache;
554 $pagename = &$this->_pagename;
556 $version = $this->_coerce_to_version($version);
561 $latestversion = $cache->get_latest_version($pagename);
562 if ($latestversion && $version == $latestversion) {
564 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
565 $pagename), E_USER_ERROR);
569 $cache->delete_versiondata($pagename, $version);
575 * Delete a revision, or possibly merge it with a previous
579 * Suppose an author make a (major) edit to a page. Shortly
580 * after that the same author makes a minor edit (e.g. to fix
581 * spelling mistakes he just made.)
583 * Now some time later, where cleaning out old saved revisions,
584 * and would like to delete his minor revision (since there's
585 * really no point in keeping minor revisions around for a long
588 * Note that the text after the minor revision probably represents
589 * what the author intended to write better than the text after
590 * the preceding major edit.
592 * So what we really want to do is merge the minor edit with the
595 * We will only do this when:
597 * <li>The revision being deleted is a minor one, and
598 * <li>It has the same author as the immediately preceding revision.
601 function mergeRevision($version) {
602 $backend = &$this->_wikidb->_backend;
603 $cache = &$this->_wikidb->_cache;
604 $pagename = &$this->_pagename;
606 $version = $this->_coerce_to_version($version);
611 $latestversion = $backend->get_latest_version($pagename);
612 if ($latestversion && $version == $latestversion) {
614 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
615 $pagename), E_USER_ERROR);
619 $versiondata = $cache->get_versiondata($pagename, $version, true);
621 // Not there? ... we're done!
626 if ($versiondata['is_minor_edit']) {
627 $previous = $backend->get_previous_version($pagename, $version);
629 $prevdata = $cache->get_versiondata($pagename, $previous);
630 if ($prevdata['author_id'] == $versiondata['author_id']) {
631 // This is a minor revision, previous version is
632 // by the same author. We will merge the
634 $cache->update_versiondata($pagename, $previous,
635 array('%content' => $versiondata['%content'],
636 '_supplanted' => $versiondata['_supplanted']));
641 $cache->delete_versiondata($pagename, $version);
647 * Create a new revision of a {@link WikiDB_Page}.
651 * @param int $version Version number for new revision.
652 * To ensure proper serialization of edits, $version must be
653 * exactly one higher than the current latest version.
654 * (You can defeat this check by setting $version to
655 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
657 * @param string $content Contents of new revision.
659 * @param hash $metadata Metadata for new revision.
660 * All values in the hash should be scalars (strings or integers).
662 * @param array $links List of pagenames which this page links to.
664 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
665 * $version was incorrect, returns false
667 function createRevision($version, &$content, $metadata, $links) {
668 $backend = &$this->_wikidb->_backend;
669 $cache = &$this->_wikidb->_cache;
670 $pagename = &$this->_pagename;
674 $latestversion = $backend->get_latest_version($pagename);
675 $newversion = $latestversion + 1;
676 assert($newversion >= 1);
678 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
685 foreach ($data as $key => $val) {
686 if (empty($val) || $key[0] == '_' || $key[0] == '%')
690 assert(!empty($data['author']));
691 if (empty($data['author_id']))
692 @$data['author_id'] = $data['author'];
694 if (empty($data['mtime']))
695 $data['mtime'] = time();
697 if ($latestversion) {
698 // Ensure mtimes are monotonic.
699 $pdata = $cache->get_versiondata($pagename, $latestversion);
700 if ($data['mtime'] < $pdata['mtime']) {
701 trigger_error(sprintf(_("%s: Date of new revision is %s"),
702 $pagename,"'non-monotonic'"),
704 $data['orig_mtime'] = $data['mtime'];
705 $data['mtime'] = $pdata['mtime'];
708 // FIXME: use (possibly user specified) 'mtime' time or
710 $cache->update_versiondata($pagename, $latestversion,
711 array('_supplanted' => $data['mtime']));
714 $data['%content'] = &$content;
716 $cache->set_versiondata($pagename, $newversion, $data);
718 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
719 //':deleted' => empty($content)));
721 $backend->set_links($pagename, $links);
725 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
729 /** A higher-level interface to createRevision.
731 * This takes care of computing the links, and storing
732 * a cached version of the transformed wiki-text.
734 * @param string $wikitext The page content.
736 * @param int $version Version number for new revision.
737 * To ensure proper serialization of edits, $version must be
738 * exactly one higher than the current latest version.
739 * (You can defeat this check by setting $version to
740 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
742 * @param hash $meta Meta-data for new revision.
744 function save($wikitext, $version, $meta) {
745 $formatted = new TransformedText($this, $wikitext, $meta);
746 $type = $formatted->getType();
747 $meta['pagetype'] = $type->getName();
748 $links = $formatted->getWikiPageLinks();
750 $backend = &$this->_wikidb->_backend;
752 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
754 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
755 $this->set('_cached_html', $formatted->pack());
758 // FIXME: probably should have some global state information
759 // in the backend to control when to optimize.
761 // We're doing this here rather than in createRevision because
762 // postgres can't optimize while locked.
763 if (time() % 50 == 0) {
764 if ($backend->optimize())
765 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
768 /* Generate notification emails? */
769 if (isa($newrevision, 'wikidb_pagerevision')) {
770 // Save didn't fail because of concurrent updates.
771 $notify = $this->_wikidb->get('notify');
772 if (!empty($notify) and is_array($notify)) {
773 list($emails,$userids) = $this->getPageChangeEmails($notify);
775 $this->sendPageChangeNotification($emails,$userids);
779 $newrevision->_transformedContent = $formatted;
783 function getPageChangeEmails($notify) {
784 $emails = array(); $userids = array();
785 foreach ($notify as $page => $users) {
786 if (glob_match($page,$this->_pagename)) {
787 foreach ($users as $userid => $user) {
788 if (!empty($user['verified']) and !empty($user['email'])) {
789 $emails[] = $user['email'];
790 $userids[] = $userid;
791 } elseif (!empty($user['email'])) {
793 // do a dynamic emailVerified check update
794 $u = $request->getUser();
795 if ($u->UserName() == $userid) {
796 if ($request->_prefs->get('emailVerified')) {
797 $emails[] = $user['email'];
798 $userids[] = $userid;
799 $notify[$page][$userid]['verified'] = 1;
800 $request->_dbi->set('notify',$notify);
803 $u = WikiUser($userid);
804 if ($u->_prefs->get('emailVerified')) {
805 $emails[] = $user['email'];
806 $userids[] = $userid;
807 $notify[$page][$userid]['verified'] = 1;
808 $request->_dbi->set('notify',$notify);
811 // ignore verification
814 if (!in_array($user['email'],$emails))
815 $emails[] = $user['email'];
822 $emails = array_unique($emails);
823 $userids = array_unique($userids);
824 return array($emails,$userids);
827 function sendPageChangeNotification($emails, $userids) {
828 $subject = sprintf(_("PageChange Notification %s"),$this->_pagename);
829 $previous = $backend->get_previous_version($this->_pagename, $version);
831 $difflink = WikiUrl($this->_pagename,array('action'=>'diff'),true);
832 $cache = &$this->_wikidb->_cache;
833 $this_content = explode("\n", $wikitext);
834 $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
835 if (empty($prevdata['%content']))
836 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
837 $other_content = explode("\n", $prevdata['%content']);
839 include_once("lib/diff.php");
840 $diff2 = new Diff($other_content, $this_content);
841 $context_lines = max(4, count($other_content) + 1,
842 count($this_content) + 1);
843 $fmt = new UnifiedDiffFormatter($context_lines);
844 $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n";
845 $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
846 $content .= $fmt->format($diff2);
849 $difflink = WikiUrl($this->_pagename,array(),true);
850 if (!isset($meta['mtime'])) $meta['mtime'] = time();
851 $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
852 $content .= _("New Page");
854 $editedby = sprintf(_("Edited by: %s"), $meta['author']);
855 $emails = join(',',$emails);
856 if (mail($emails,"[".WIKI_NAME."] ".$subject,
861 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
862 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
864 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
865 $this->_pagename, join(',',$userids)), E_USER_WARNING);
869 * Get the most recent revision of a page.
873 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
875 function getCurrentRevision() {
876 $backend = &$this->_wikidb->_backend;
877 $cache = &$this->_wikidb->_cache;
878 $pagename = &$this->_pagename;
880 // Prevent deadlock in case of memory exhausted errors
881 // Pure selection doesn't really need locking here.
883 // I know it would be better, but with lots of pages this deadlock is more
884 // severe than occasionally get not the latest revision.
886 $version = $cache->get_latest_version($pagename);
887 $revision = $this->getRevision($version);
888 //$backend->unlock();
894 * Get a specific revision of a WikiDB_Page.
898 * @param integer $version Which revision to get.
900 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
901 * false if the requested revision does not exist in the {@link WikiDB}.
902 * Note that version zero of any page always exists.
904 function getRevision($version) {
905 $cache = &$this->_wikidb->_cache;
906 $pagename = &$this->_pagename;
909 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
911 assert($version > 0);
912 $vdata = $cache->get_versiondata($pagename, $version);
915 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
920 * Get previous page revision.
922 * This method find the most recent revision before a specified
927 * @param integer $version Find most recent revision before this version.
928 * You can also use a WikiDB_PageRevision object to specify the $version.
930 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
931 * requested revision does not exist in the {@link WikiDB}. Note that
932 * unless $version is greater than zero, a revision (perhaps version zero,
933 * the default revision) will always be found.
935 function getRevisionBefore($version) {
936 $backend = &$this->_wikidb->_backend;
937 $pagename = &$this->_pagename;
939 $version = $this->_coerce_to_version($version);
944 $previous = $backend->get_previous_version($pagename, $version);
945 $revision = $this->getRevision($previous);
946 //$backend->unlock();
952 * Get all revisions of the WikiDB_Page.
954 * This does not include the version zero (default) revision in the
955 * returned revision set.
957 * @return WikiDB_PageRevisionIterator A
958 * WikiDB_PageRevisionIterator containing all revisions of this
959 * WikiDB_Page in reverse order by version number.
961 function getAllRevisions() {
962 $backend = &$this->_wikidb->_backend;
963 $revs = $backend->get_all_revisions($this->_pagename);
964 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
968 * Find pages which link to or are linked from a page.
972 * @param boolean $reversed Which links to find: true for backlinks (default).
974 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
975 * all matching pages.
977 function getLinks($reversed = true) {
978 $backend = &$this->_wikidb->_backend;
979 $result = $backend->get_links($this->_pagename, $reversed);
980 return new WikiDB_PageIterator($this->_wikidb, $result);
984 * Access WikiDB_Page meta-data.
988 * @param string $key Which meta data to get.
989 * Some reserved meta-data keys are:
991 * <dt>'locked'<dd> Is page locked?
992 * <dt>'hits' <dd> Page hit counter.
993 * <dt>'pref' <dd> Users preferences, stored in homepages.
994 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
996 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
997 * page-headers and content.
998 * <dt>'score' <dd> Page score (not yet implement, do we need?)
1001 * @return scalar The requested value, or false if the requested data
1004 function get($key) {
1005 $cache = &$this->_wikidb->_cache;
1006 if (!$key || $key[0] == '%')
1008 $data = $cache->get_pagedata($this->_pagename);
1009 return isset($data[$key]) ? $data[$key] : false;
1013 * Get all the page meta-data as a hash.
1015 * @return hash The page meta-data.
1017 function getMetaData() {
1018 $cache = &$this->_wikidb->_cache;
1019 $data = $cache->get_pagedata($this->_pagename);
1021 foreach ($data as $key => $val) {
1022 if (/*!empty($val) &&*/ $key[0] != '%')
1029 * Set page meta-data.
1034 * @param string $key Meta-data key to set.
1035 * @param string $newval New value.
1037 function set($key, $newval) {
1038 $cache = &$this->_wikidb->_cache;
1039 $pagename = &$this->_pagename;
1041 assert($key && $key[0] != '%');
1043 $data = $cache->get_pagedata($pagename);
1045 if (!empty($newval)) {
1046 if (!empty($data[$key]) && $data[$key] == $newval)
1047 return; // values identical, skip update.
1050 if (empty($data[$key]))
1051 return; // values identical, skip update.
1054 $cache->update_pagedata($pagename, array($key => $newval));
1058 * Increase page hit count.
1060 * FIXME: IS this needed? Probably not.
1062 * This is a convenience function.
1063 * <pre> $page->increaseHitCount(); </pre>
1064 * is functionally identical to
1065 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1067 * Note that this method may be implemented in more efficient ways
1068 * in certain backends.
1072 function increaseHitCount() {
1073 @$newhits = $this->get('hits') + 1;
1074 $this->set('hits', $newhits);
1078 * Return a string representation of the WikiDB_Page
1080 * This is really only for debugging.
1084 * @return string Printable representation of the WikiDB_Page.
1086 function asString () {
1088 printf("[%s:%s\n", get_class($this), $this->getName());
1089 print_r($this->getMetaData());
1091 $strval = ob_get_contents();
1099 * @param integer_or_object $version_or_pagerevision
1100 * Takes either the version number (and int) or a WikiDB_PageRevision
1102 * @return integer The version number.
1104 function _coerce_to_version($version_or_pagerevision) {
1105 if (method_exists($version_or_pagerevision, "getContent"))
1106 $version = $version_or_pagerevision->getVersion();
1108 $version = (int) $version_or_pagerevision;
1110 assert($version >= 0);
1114 function isUserPage ($include_empty = true) {
1115 if ($include_empty) {
1116 $current = $this->getCurrentRevision();
1117 if ($current->hasDefaultContents()) {
1121 return $this->get('pref') ? true : false;
1127 * This class represents a specific revision of a WikiDB_Page within
1130 * A WikiDB_PageRevision has read-only semantics. You may only create
1131 * new revisions (and delete old ones) --- you cannot modify existing
1134 class WikiDB_PageRevision
1136 var $_transformedContent = false; // set by WikiDB_Page::save()
1138 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1139 $versiondata = false)
1141 $this->_wikidb = &$wikidb;
1142 $this->_pagename = $pagename;
1143 $this->_version = $version;
1144 $this->_data = $versiondata ? $versiondata : array();
1148 * Get the WikiDB_Page which this revision belongs to.
1152 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1154 function getPage() {
1155 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1159 * Get the version number of this revision.
1163 * @return integer The version number of this revision.
1165 function getVersion() {
1166 return $this->_version;
1170 * Determine whether this revision has defaulted content.
1172 * The default revision (version 0) of each page, as well as any
1173 * pages which are created with empty content have their content
1174 * defaulted to something like:
1176 * Describe [ThisPage] here.
1181 * @return boolean Returns true if the page has default content.
1183 function hasDefaultContents() {
1184 $data = &$this->_data;
1185 return empty($data['%content']);
1189 * Get the content as an array of lines.
1193 * @return array An array of lines.
1194 * The lines should contain no trailing white space.
1196 function getContent() {
1197 return explode("\n", $this->getPackedContent());
1201 * Get the pagename of the revision.
1205 * @return string pagename.
1207 function getPageName() {
1208 return $this->_pagename;
1212 * Determine whether revision is the latest.
1216 * @return boolean True iff the revision is the latest (most recent) one.
1218 function isCurrent() {
1219 if (!isset($this->_iscurrent)) {
1220 $page = $this->getPage();
1221 $current = $page->getCurrentRevision();
1222 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1224 return $this->_iscurrent;
1228 * Get the transformed content of a page.
1230 * @param string $pagetype Override the page-type of the revision.
1232 * @return object An XmlContent-like object containing the page transformed
1235 function getTransformedContent($pagetype_override=false) {
1236 $backend = &$this->_wikidb->_backend;
1238 if ($pagetype_override) {
1239 // Figure out the normal page-type for this page.
1240 $type = PageType::GetPageType($this->get('pagetype'));
1241 if ($type->getName() == $pagetype_override)
1242 $pagetype_override = false; // Not really an override...
1245 if ($pagetype_override) {
1246 // Overriden page type, don't cache (or check cache).
1247 return new TransformedText($this->getPage(),
1248 $this->getPackedContent(),
1249 $this->getMetaData(),
1250 $pagetype_override);
1253 $possibly_cache_results = true;
1255 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1256 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1257 // flush cache for this page.
1258 $page = $this->getPage();
1259 $page->set('_cached_html', false);
1261 $possibly_cache_results = false;
1263 elseif (!$this->_transformedContent) {
1265 if ($this->isCurrent()) {
1266 $page = $this->getPage();
1267 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1270 $possibly_cache_results = false;
1272 //$backend->unlock();
1275 if (!$this->_transformedContent) {
1276 $this->_transformedContent
1277 = new TransformedText($this->getPage(),
1278 $this->getPackedContent(),
1279 $this->getMetaData());
1281 if ($possibly_cache_results) {
1282 // If we're still the current version, cache the transfomed page.
1284 if ($this->isCurrent()) {
1285 $page->set('_cached_html', $this->_transformedContent->pack());
1287 //$backend->unlock();
1291 return $this->_transformedContent;
1295 * Get the content as a string.
1299 * @return string The page content.
1300 * Lines are separated by new-lines.
1302 function getPackedContent() {
1303 $data = &$this->_data;
1306 if (empty($data['%content'])) {
1307 include_once('lib/InlineParser.php');
1308 // Replace empty content with default value.
1309 return sprintf(_("Describe %s here."),
1310 "[" . WikiEscape($this->_pagename) . "]");
1313 // There is (non-default) content.
1314 assert($this->_version > 0);
1316 if (!is_string($data['%content'])) {
1317 // Content was not provided to us at init time.
1318 // (This is allowed because for some backends, fetching
1319 // the content may be expensive, and often is not wanted
1322 // In any case, now we need to get it.
1323 $data['%content'] = $this->_get_content();
1324 assert(is_string($data['%content']));
1327 return $data['%content'];
1330 function _get_content() {
1331 $cache = &$this->_wikidb->_cache;
1332 $pagename = $this->_pagename;
1333 $version = $this->_version;
1335 assert($version > 0);
1337 $newdata = $cache->get_versiondata($pagename, $version, true);
1339 assert(is_string($newdata['%content']));
1340 return $newdata['%content'];
1343 // else revision has been deleted... What to do?
1344 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1345 $version, $pagename);
1350 * Get meta-data for this revision.
1355 * @param string $key Which meta-data to access.
1357 * Some reserved revision meta-data keys are:
1359 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1360 * The 'mtime' meta-value is normally set automatically by the database
1361 * backend, but it may be specified explicitly when creating a new revision.
1363 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1364 * of a page must be monotonically increasing. If an attempt is
1365 * made to create a new revision with an mtime less than that of
1366 * the preceeding revision, the new revisions timestamp is force
1367 * to be equal to that of the preceeding revision. In that case,
1368 * the originally requested mtime is preserved in 'orig_mtime'.
1369 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1370 * This meta-value is <em>always</em> automatically maintained by the database
1371 * backend. (It is set from the 'mtime' meta-value of the superceding
1372 * revision.) '_supplanted' has a value of 'false' for the current revision.
1374 * FIXME: this could be refactored:
1376 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1378 * <dd> Authenticated author of a page. This is used to identify
1379 * the distinctness of authors when cleaning old revisions from
1381 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1382 * <dt> 'summary' <dd> Short change summary entered by page author.
1385 * Meta-data keys must be valid C identifers (they have to start with a letter
1386 * or underscore, and can contain only alphanumerics and underscores.)
1388 * @return string The requested value, or false if the requested value
1391 function get($key) {
1392 if (!$key || $key[0] == '%')
1394 $data = &$this->_data;
1395 return isset($data[$key]) ? $data[$key] : false;
1399 * Get all the revision page meta-data as a hash.
1401 * @return hash The revision meta-data.
1403 function getMetaData() {
1405 foreach ($this->_data as $key => $val) {
1406 if (!empty($val) && $key[0] != '%')
1414 * Return a string representation of the revision.
1416 * This is really only for debugging.
1420 * @return string Printable representation of the WikiDB_Page.
1422 function asString () {
1424 printf("[%s:%d\n", get_class($this), $this->get('version'));
1425 print_r($this->_data);
1426 echo $this->getPackedContent() . "\n]\n";
1427 $strval = ob_get_contents();
1435 * A class which represents a sequence of WikiDB_Pages.
1437 class WikiDB_PageIterator
1439 function WikiDB_PageIterator(&$wikidb, &$pages) {
1440 $this->_pages = $pages;
1441 $this->_wikidb = &$wikidb;
1445 return $this->_pages->count();
1449 * Get next WikiDB_Page in sequence.
1453 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1456 if ( ! ($next = $this->_pages->next()) )
1459 $pagename = &$next['pagename'];
1460 if (isset($next['pagedata']))
1461 $this->_wikidb->_cache->cache_data($next);
1463 return new WikiDB_Page($this->_wikidb, $pagename);
1467 * Release resources held by this iterator.
1469 * The iterator may not be used after free() is called.
1471 * There is no need to call free(), if next() has returned false.
1472 * (I.e. if you iterate through all the pages in the sequence,
1473 * you do not need to call free() --- you only need to call it
1474 * if you stop before the end of the iterator is reached.)
1479 $this->_pages->free();
1482 // Not yet used and problematic. Order should be set in the query, not afterwards.
1483 // See PageList::sortby
1484 function setSortby ($arg = false) {
1486 $arg = @$_GET['sortby'];
1488 $sortby = substr($arg,1);
1489 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1492 if (is_array($arg)) { // array('mtime' => 'desc')
1499 // available column types to sort by:
1500 // todo: we must provide access methods for the generic dumb/iterator
1501 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1502 if (in_array($sortby,$this->_types))
1503 $this->_options['sortby'] = $sortby;
1505 trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1506 if (in_array(strtoupper($order),'ASC','DESC'))
1507 $this->_options['order'] = strtoupper($order);
1509 trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1515 * A class which represents a sequence of WikiDB_PageRevisions.
1517 class WikiDB_PageRevisionIterator
1519 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1520 $this->_revisions = $revisions;
1521 $this->_wikidb = &$wikidb;
1525 return $this->_revisions->count();
1529 * Get next WikiDB_PageRevision in sequence.
1533 * @return WikiDB_PageRevision
1534 * The next WikiDB_PageRevision in the sequence.
1537 if ( ! ($next = $this->_revisions->next()) )
1540 $this->_wikidb->_cache->cache_data($next);
1542 $pagename = $next['pagename'];
1543 $version = $next['version'];
1544 $versiondata = $next['versiondata'];
1545 assert(is_string($pagename) and $pagename != '');
1546 assert(is_array($versiondata));
1547 assert($version > 0);
1549 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1554 * Release resources held by this iterator.
1556 * The iterator may not be used after free() is called.
1558 * There is no need to call free(), if next() has returned false.
1559 * (I.e. if you iterate through all the revisions in the sequence,
1560 * you do not need to call free() --- you only need to call it
1561 * if you stop before the end of the iterator is reached.)
1566 $this->_revisions->free();
1572 * Data cache used by WikiDB.
1574 * FIXME: Maybe rename this to caching_backend (or some such).
1580 // FIXME: beautify versiondata cache. Cache only limited data?
1582 function WikiDB_cache (&$backend) {
1583 $this->_backend = &$backend;
1585 $this->_pagedata_cache = array();
1586 $this->_versiondata_cache = array();
1587 array_push ($this->_versiondata_cache, array());
1588 $this->_glv_cache = array();
1592 $this->_pagedata_cache = false;
1593 $this->_versiondata_cache = false;
1594 $this->_glv_cache = false;
1597 function get_pagedata($pagename) {
1598 assert(is_string($pagename) && $pagename != '');
1599 $cache = &$this->_pagedata_cache;
1601 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1602 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1603 if (empty($cache[$pagename]))
1604 $cache[$pagename] = array();
1607 return $cache[$pagename];
1610 function update_pagedata($pagename, $newdata) {
1611 assert(is_string($pagename) && $pagename != '');
1613 $this->_backend->update_pagedata($pagename, $newdata);
1615 if (is_array($this->_pagedata_cache[$pagename])) {
1616 $cachedata = &$this->_pagedata_cache[$pagename];
1617 foreach($newdata as $key => $val)
1618 $cachedata[$key] = $val;
1622 function invalidate_cache($pagename) {
1623 unset ($this->_pagedata_cache[$pagename]);
1624 unset ($this->_versiondata_cache[$pagename]);
1625 unset ($this->_glv_cache[$pagename]);
1628 function delete_page($pagename) {
1629 $this->_backend->delete_page($pagename);
1630 unset ($this->_pagedata_cache[$pagename]);
1631 unset ($this->_glv_cache[$pagename]);
1635 function cache_data($data) {
1636 if (isset($data['pagedata']))
1637 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1640 function get_versiondata($pagename, $version, $need_content = false) {
1641 // FIXME: Seriously ugly hackage
1642 if (defined ('USECACHE')){ //temporary - for debugging
1643 assert(is_string($pagename) && $pagename != '');
1644 // there is a bug here somewhere which results in an assertion failure at line 105
1645 // of ArchiveCleaner.php It goes away if we use the next line.
1646 $need_content = true;
1647 $nc = $need_content ? '1':'0';
1648 $cache = &$this->_versiondata_cache;
1649 if (!isset($cache[$pagename][$version][$nc])||
1650 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1651 $cache[$pagename][$version][$nc] =
1652 $this->_backend->get_versiondata($pagename,$version, $need_content);
1653 // If we have retrieved all data, we may as well set the cache for $need_content = false
1655 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1658 $vdata = $cache[$pagename][$version][$nc];
1660 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1663 if ($vdata && !empty($vdata['%pagedata']))
1664 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1668 function set_versiondata($pagename, $version, $data) {
1669 $new = $this->_backend->set_versiondata($pagename, $version, $data);
1671 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1673 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1674 // Is this necessary?
1675 unset($this->_glv_cache[$pagename]);
1678 function update_versiondata($pagename, $version, $data) {
1679 $new = $this->_backend->update_versiondata($pagename, $version, $data);
1681 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1683 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1684 // Is this necessary?
1685 unset($this->_glv_cache[$pagename]);
1688 function delete_versiondata($pagename, $version) {
1689 $new = $this->_backend->delete_versiondata($pagename, $version);
1690 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1691 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1692 unset ($this->_glv_cache[$pagename]);
1695 function get_latest_version($pagename) {
1696 if (defined('USECACHE')){
1697 assert (is_string($pagename) && $pagename != '');
1698 $cache = &$this->_glv_cache;
1699 if (!isset($cache[$pagename])) {
1700 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1701 if (empty($cache[$pagename]))
1702 $cache[$pagename] = 0;
1704 return $cache[$pagename];
1706 return $this->_backend->get_latest_version($pagename);
1712 // $Log: not supported by cvs2svn $
1713 // Revision 1.43 2004/04/18 01:34:20 rurban
1714 // protect most_popular from sortby=mtime
1716 // Revision 1.42 2004/04/18 01:11:51 rurban
1717 // more numeric pagename fixes.
1718 // fixed action=upload with merge conflict warnings.
1719 // charset changed from constant to global (dynamic utf-8 switching)
1725 // c-basic-offset: 4
1726 // c-hanging-comment-ender-p: nil
1727 // indent-tabs-mode: nil