2 rcs_id('$Id: WikiDB.php,v 1.51 2004-05-06 17:30:37 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);
172 * Determine whether page exists (in non-default form).
175 * $is_page = $dbi->isWikiPage($pagename);
179 * $page = $dbi->getPage($pagename);
180 * $current = $page->getCurrentRevision();
181 * $is_page = ! $current->hasDefaultContents();
183 * however isWikiPage may be implemented in a more efficient
184 * manner in certain back-ends.
188 * @param string $pagename string Which page to check.
190 * @return boolean True if the page actually exists with
191 * non-default contents in the WikiDataBase.
193 function isWikiPage ($pagename) {
194 $page = $this->getPage($pagename);
195 $current = $page->getCurrentRevision();
196 return ! $current->hasDefaultContents();
200 * Delete page from the WikiDB.
202 * Deletes all revisions of the page from the WikiDB. Also resets
203 * all page meta-data to the default values.
207 * @param string $pagename Name of page to delete.
209 function deletePage($pagename) {
210 $this->_cache->delete_page($pagename);
212 //How to create a RecentChanges entry with explaining summary?
214 $page = $this->getPage($pagename);
215 $current = $page->getCurrentRevision();
216 $meta = $current->_data;
217 $version = $current->getVersion();
218 $meta['summary'] = _("removed");
219 $page->save($current->getPackedContent(), $version + 1, $meta);
224 * Retrieve all pages.
226 * Gets the set of all pages with non-default contents.
228 * FIXME: do we need this? I think so. The simple searches
233 * @param boolean $include_defaulted Normally pages whose most
234 * recent revision has empty content are considered to be
235 * non-existant. Unless $include_defaulted is set to true, those
236 * pages will not be returned.
238 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
239 * in the WikiDB which have non-default contents.
241 function getAllPages($include_defaulted=false, $sortby=false, $limit=false) {
242 $result = $this->_backend->get_all_pages($include_defaulted,$sortby,$limit);
243 return new WikiDB_PageIterator($this, $result);
247 //function nPages() {
249 // Yes, for paging. Renamed.
250 function numPages($filter=false, $exclude='') {
251 if (method_exists($this->_backend,'numPages'))
252 $count = $this->_backend->numPages($filter,$exclude);
254 $iter = $this->getAllPages();
255 $count = $iter->count();
263 * Search for pages containing (or not containing) certain words
266 * Pages are returned in alphabetical order whenever it is
267 * practical to do so.
269 * FIXME: should titleSearch and fullSearch be combined? I think so.
272 * @param TextSearchQuery $search A TextSearchQuery object
273 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
274 * @see TextSearchQuery
276 function titleSearch($search) {
277 $result = $this->_backend->text_search($search);
278 return new WikiDB_PageIterator($this, $result);
284 * Search for pages containing (or not containing) certain words
285 * in their entire text (this includes the page content and the
288 * Pages are returned in alphabetical order whenever it is
289 * practical to do so.
293 * @param TextSearchQuery $search A TextSearchQuery object.
294 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
295 * @see TextSearchQuery
297 function fullSearch($search) {
298 $result = $this->_backend->text_search($search, 'full_text');
299 return new WikiDB_PageIterator($this, $result);
303 * Find the pages with the greatest hit counts.
305 * Pages are returned in reverse order by hit count.
309 * @param integer $limit The maximum number of pages to return.
310 * Set $limit to zero to return all pages. If $limit < 0, pages will
311 * be sorted in decreasing order of popularity.
313 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
316 function mostPopular($limit = 20, $sortby = '') {
317 // we don't support sortby=mtime here
318 if (strstr($sortby,'mtime'))
320 $result = $this->_backend->most_popular($limit, $sortby);
321 return new WikiDB_PageIterator($this, $result);
325 * Find recent page revisions.
327 * Revisions are returned in reverse order by creation time.
331 * @param hash $params This hash is used to specify various optional
335 * <dd> (integer) At most this many revisions will be returned.
337 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
338 * <dt> include_minor_revisions
339 * <dd> (boolean) Also include minor revisions. (Default is not to.)
340 * <dt> exclude_major_revisions
341 * <dd> (boolean) Don't include non-minor revisions.
342 * (Exclude_major_revisions implies include_minor_revisions.)
343 * <dt> include_all_revisions
344 * <dd> (boolean) Return all matching revisions for each page.
345 * Normally only the most recent matching revision is returned
349 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
350 * matching revisions.
352 function mostRecent($params = false) {
353 $result = $this->_backend->most_recent($params);
354 return new WikiDB_PageRevisionIterator($this, $result);
358 * Call the appropriate backend method.
361 * @param string $from Page to rename
362 * @param string $to New name
363 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
364 * @return boolean true or false
366 function renamePage($from, $to, $updateWikiLinks = false) {
367 assert(is_string($from) && $from != '');
368 assert(is_string($to) && $to != '');
370 if (method_exists($this->_backend,'rename_page')) {
371 $oldpage = $this->getPage($from);
372 $newpage = $this->getPage($to);
373 if ($oldpage->exists() and ! $newpage->exists()) {
374 if ($result = $this->_backend->rename_page($from, $to)) {
375 //update all WikiLinks in existing pages
376 if ($updateWikiLinks) {
377 //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
378 require_once('lib/plugin/WikiAdminSearchReplace.php');
379 $links = $oldpage->getLinks();
380 while ($linked_page = $links->next()) {
381 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
383 $links = $newpage->getLinks();
384 while ($linked_page = $links->next()) {
385 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
388 //create a RecentChanges entry with explaining summary
389 $page = $this->getPage($to);
390 $current = $page->getCurrentRevision();
391 $meta = $current->_data;
392 $version = $current->getVersion();
393 $meta['summary'] = sprintf(_("renamed from %s"),$from);
394 $page->save($current->getPackedContent(), $version + 1, $meta);
398 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
403 /** Get timestamp when database was last modified.
405 * @return string A string consisting of two integers,
406 * separated by a space. The first is the time in
407 * unix timestamp format, the second is a modification
408 * count for the database.
410 * The idea is that you can cast the return value to an
411 * int to get a timestamp, or you can use the string value
412 * as a good hash for the entire database.
414 function getTimestamp() {
415 $ts = $this->get('_timestamp');
416 return sprintf("%d %d", $ts[0], $ts[1]);
420 * Update the database timestamp.
424 $ts = $this->get('_timestamp');
425 $this->set('_timestamp', array(time(), $ts[1] + 1));
430 * Access WikiDB global meta-data.
432 * NOTE: this is currently implemented in a hackish and
433 * not very efficient manner.
437 * @param string $key Which meta data to get.
438 * Some reserved meta-data keys are:
440 * <dt>'_timestamp' <dd> Data used by getTimestamp().
443 * @return scalar The requested value, or false if the requested data
447 if (!$key || $key[0] == '%')
450 * Hack Alert: We can use any page (existing or not) to store
451 * this data (as long as we always use the same one.)
453 $gd = $this->getPage('global_data');
454 $data = $gd->get('__global');
456 if ($data && isset($data[$key]))
463 * Set global meta-data.
465 * NOTE: this is currently implemented in a hackish and
466 * not very efficient manner.
471 * @param string $key Meta-data key to set.
472 * @param string $newval New value.
474 function set($key, $newval) {
475 if (!$key || $key[0] == '%')
478 $gd = $this->getPage('global_data');
480 $data = $gd->get('__global');
487 $data[$key] = $newval;
489 $gd->set('__global', $data);
492 // simple select or create/update queries which do trigger_error
493 function simpleQuery($sql) {
495 if ($DBParams['dbtype'] == 'SQL') {
496 $result = $this->_backend->_dbh->query($sql);
497 if (DB::isError($result)) {
498 $msg = $result->getMessage();
499 trigger_error("SQL Error: ".DB::errorMessage($result),E_USER_WARNING);
504 } elseif ($DBParams['dbtype'] == 'ADODB') {
505 if (!($result = $this->_backend->_dbh->Execute($sql))) {
506 trigger_error("SQL Error: ".$this->_backend->_dbh->ErrorMsg(),E_USER_WARNING);
518 * An abstract base class which representing a wiki-page within a
521 * A WikiDB_Page contains a number (at least one) of
522 * WikiDB_PageRevisions.
526 function WikiDB_Page(&$wikidb, $pagename) {
527 $this->_wikidb = &$wikidb;
528 $this->_pagename = $pagename;
529 assert(is_string($pagename) and $pagename != '');
533 * Get the name of the wiki page.
537 * @return string The page name.
540 return $this->_pagename;
544 $current = $this->getCurrentRevision();
545 return ! $current->hasDefaultContents();
549 * Delete an old revision of a WikiDB_Page.
551 * Deletes the specified revision of the page.
552 * It is a fatal error to attempt to delete the current revision.
556 * @param integer $version Which revision to delete. (You can also
557 * use a WikiDB_PageRevision object here.)
559 function deleteRevision($version) {
560 $backend = &$this->_wikidb->_backend;
561 $cache = &$this->_wikidb->_cache;
562 $pagename = &$this->_pagename;
564 $version = $this->_coerce_to_version($version);
568 $backend->lock(array('page','version'));
569 $latestversion = $cache->get_latest_version($pagename);
570 if ($latestversion && $version == $latestversion) {
571 $backend->unlock(array('page','version'));
572 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
573 $pagename), E_USER_ERROR);
577 $cache->delete_versiondata($pagename, $version);
578 $backend->unlock(array('page','version'));
582 * Delete a revision, or possibly merge it with a previous
586 * Suppose an author make a (major) edit to a page. Shortly
587 * after that the same author makes a minor edit (e.g. to fix
588 * spelling mistakes he just made.)
590 * Now some time later, where cleaning out old saved revisions,
591 * and would like to delete his minor revision (since there's
592 * really no point in keeping minor revisions around for a long
595 * Note that the text after the minor revision probably represents
596 * what the author intended to write better than the text after
597 * the preceding major edit.
599 * So what we really want to do is merge the minor edit with the
602 * We will only do this when:
604 * <li>The revision being deleted is a minor one, and
605 * <li>It has the same author as the immediately preceding revision.
608 function mergeRevision($version) {
609 $backend = &$this->_wikidb->_backend;
610 $cache = &$this->_wikidb->_cache;
611 $pagename = &$this->_pagename;
613 $version = $this->_coerce_to_version($version);
617 $backend->lock(array('version'));
618 $latestversion = $backend->get_latest_version($pagename);
619 if ($latestversion && $version == $latestversion) {
620 $backend->unlock(array('version'));
621 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
622 $pagename), E_USER_ERROR);
626 $versiondata = $cache->get_versiondata($pagename, $version, true);
628 // Not there? ... we're done!
629 $backend->unlock(array('version'));
633 if ($versiondata['is_minor_edit']) {
634 $previous = $backend->get_previous_version($pagename, $version);
636 $prevdata = $cache->get_versiondata($pagename, $previous);
637 if ($prevdata['author_id'] == $versiondata['author_id']) {
638 // This is a minor revision, previous version is
639 // by the same author. We will merge the
641 $cache->update_versiondata($pagename, $previous,
642 array('%content' => $versiondata['%content'],
643 '_supplanted' => $versiondata['_supplanted']));
648 $cache->delete_versiondata($pagename, $version);
649 $backend->unlock(array('version'));
654 * Create a new revision of a {@link WikiDB_Page}.
658 * @param int $version Version number for new revision.
659 * To ensure proper serialization of edits, $version must be
660 * exactly one higher than the current latest version.
661 * (You can defeat this check by setting $version to
662 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
664 * @param string $content Contents of new revision.
666 * @param hash $metadata Metadata for new revision.
667 * All values in the hash should be scalars (strings or integers).
669 * @param array $links List of pagenames which this page links to.
671 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
672 * $version was incorrect, returns false
674 function createRevision($version, &$content, $metadata, $links) {
675 $backend = &$this->_wikidb->_backend;
676 $cache = &$this->_wikidb->_cache;
677 $pagename = &$this->_pagename;
679 $backend->lock(array('version','page','recent','links','nonempty'));
681 $latestversion = $backend->get_latest_version($pagename);
682 $newversion = $latestversion + 1;
683 assert($newversion >= 1);
685 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
686 $backend->unlock(array('version','page','recent','links'));
692 foreach ($data as $key => $val) {
693 if (empty($val) || $key[0] == '_' || $key[0] == '%')
697 assert(!empty($data['author']));
698 if (empty($data['author_id']))
699 @$data['author_id'] = $data['author'];
701 if (empty($data['mtime']))
702 $data['mtime'] = time();
704 if ($latestversion) {
705 // Ensure mtimes are monotonic.
706 $pdata = $cache->get_versiondata($pagename, $latestversion);
707 if ($data['mtime'] < $pdata['mtime']) {
708 trigger_error(sprintf(_("%s: Date of new revision is %s"),
709 $pagename,"'non-monotonic'"),
711 $data['orig_mtime'] = $data['mtime'];
712 $data['mtime'] = $pdata['mtime'];
715 // FIXME: use (possibly user specified) 'mtime' time or
717 $cache->update_versiondata($pagename, $latestversion,
718 array('_supplanted' => $data['mtime']));
721 $data['%content'] = &$content;
723 $cache->set_versiondata($pagename, $newversion, $data);
725 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
726 //':deleted' => empty($content)));
728 $backend->set_links($pagename, $links);
730 $backend->unlock(array('version','page','recent','links','nonempty'));
732 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
736 /** A higher-level interface to createRevision.
738 * This takes care of computing the links, and storing
739 * a cached version of the transformed wiki-text.
741 * @param string $wikitext The page content.
743 * @param int $version Version number for new revision.
744 * To ensure proper serialization of edits, $version must be
745 * exactly one higher than the current latest version.
746 * (You can defeat this check by setting $version to
747 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
749 * @param hash $meta Meta-data for new revision.
751 function save($wikitext, $version, $meta) {
752 $formatted = new TransformedText($this, $wikitext, $meta);
753 $type = $formatted->getType();
754 $meta['pagetype'] = $type->getName();
755 $links = $formatted->getWikiPageLinks();
757 $backend = &$this->_wikidb->_backend;
758 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
760 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
761 $this->set('_cached_html', $formatted->pack());
763 // FIXME: probably should have some global state information
764 // in the backend to control when to optimize.
766 // We're doing this here rather than in createRevision because
767 // postgres can't optimize while locked.
768 if (time() % 50 == 0) {
769 if ($backend->optimize())
770 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
773 /* Generate notification emails? */
774 if (isa($newrevision, 'wikidb_pagerevision')) {
775 // Save didn't fail because of concurrent updates.
776 $notify = $this->_wikidb->get('notify');
777 if (!empty($notify) and is_array($notify)) {
778 list($emails,$userids) = $this->getPageChangeEmails($notify);
780 $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
784 $newrevision->_transformedContent = $formatted;
788 function getPageChangeEmails($notify) {
789 $emails = array(); $userids = array();
790 foreach ($notify as $page => $users) {
791 if (glob_match($page,$this->_pagename)) {
792 foreach ($users as $userid => $user) {
793 if (!empty($user['verified']) and !empty($user['email'])) {
794 $emails[] = $user['email'];
795 $userids[] = $userid;
796 } elseif (!empty($user['email'])) {
798 // do a dynamic emailVerified check update
799 $u = $request->getUser();
800 if ($u->UserName() == $userid) {
801 if ($request->_prefs->get('emailVerified')) {
802 $emails[] = $user['email'];
803 $userids[] = $userid;
804 $notify[$page][$userid]['verified'] = 1;
805 $request->_dbi->set('notify',$notify);
808 $u = WikiUser($userid);
809 if ($u->_prefs->get('emailVerified')) {
810 $emails[] = $user['email'];
811 $userids[] = $userid;
812 $notify[$page][$userid]['verified'] = 1;
813 $request->_dbi->set('notify',$notify);
816 // ignore verification
819 if (!in_array($user['email'],$emails))
820 $emails[] = $user['email'];
827 $emails = array_unique($emails);
828 $userids = array_unique($userids);
829 return array($emails,$userids);
832 function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
833 $backend = &$this->_wikidb->_backend;
834 $subject = _("Page change").' '.$this->_pagename;
835 $previous = $backend->get_previous_version($this->_pagename, $version);
836 if (!isset($meta['mtime'])) $meta['mtime'] = time();
838 $difflink = WikiURL($this->_pagename,array('action'=>'diff'),true);
839 $cache = &$this->_wikidb->_cache;
840 $this_content = explode("\n", $wikitext);
841 $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
842 if (empty($prevdata['%content']))
843 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
844 $other_content = explode("\n", $prevdata['%content']);
846 include_once("lib/diff.php");
847 $diff2 = new Diff($other_content, $this_content);
848 $context_lines = max(4, count($other_content) + 1,
849 count($this_content) + 1);
850 $fmt = new UnifiedDiffFormatter($context_lines);
851 $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n";
852 $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
853 $content .= $fmt->format($diff2);
856 $difflink = WikiURL($this->_pagename,array(),true);
857 $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
858 $content .= _("New Page");
860 $editedby = sprintf(_("Edited by: %s"), $meta['author']);
861 $emails = join(',',$emails);
862 if (mail($emails,"[".WIKI_NAME."] ".$subject,
867 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
868 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
870 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
871 $this->_pagename, join(',',$userids)), E_USER_WARNING);
875 * Get the most recent revision of a page.
879 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
881 function getCurrentRevision() {
882 $backend = &$this->_wikidb->_backend;
883 $cache = &$this->_wikidb->_cache;
884 $pagename = &$this->_pagename;
886 // Prevent deadlock in case of memory exhausted errors
887 // Pure selection doesn't really need locking here.
889 // I know it would be better, but with lots of pages this deadlock is more
890 // severe than occasionally get not the latest revision.
892 $version = $cache->get_latest_version($pagename);
893 $revision = $this->getRevision($version);
894 //$backend->unlock();
900 * Get a specific revision of a WikiDB_Page.
904 * @param integer $version Which revision to get.
906 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
907 * false if the requested revision does not exist in the {@link WikiDB}.
908 * Note that version zero of any page always exists.
910 function getRevision($version) {
911 $cache = &$this->_wikidb->_cache;
912 $pagename = &$this->_pagename;
915 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
917 assert($version > 0);
918 $vdata = $cache->get_versiondata($pagename, $version);
921 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
926 * Get previous page revision.
928 * This method find the most recent revision before a specified
933 * @param integer $version Find most recent revision before this version.
934 * You can also use a WikiDB_PageRevision object to specify the $version.
936 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
937 * requested revision does not exist in the {@link WikiDB}. Note that
938 * unless $version is greater than zero, a revision (perhaps version zero,
939 * the default revision) will always be found.
941 function getRevisionBefore($version) {
942 $backend = &$this->_wikidb->_backend;
943 $pagename = &$this->_pagename;
945 $version = $this->_coerce_to_version($version);
950 $previous = $backend->get_previous_version($pagename, $version);
951 $revision = $this->getRevision($previous);
952 //$backend->unlock();
958 * Get all revisions of the WikiDB_Page.
960 * This does not include the version zero (default) revision in the
961 * returned revision set.
963 * @return WikiDB_PageRevisionIterator A
964 * WikiDB_PageRevisionIterator containing all revisions of this
965 * WikiDB_Page in reverse order by version number.
967 function getAllRevisions() {
968 $backend = &$this->_wikidb->_backend;
969 $revs = $backend->get_all_revisions($this->_pagename);
970 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
974 * Find pages which link to or are linked from a page.
978 * @param boolean $reversed Which links to find: true for backlinks (default).
980 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
981 * all matching pages.
983 function getLinks($reversed = true) {
984 $backend = &$this->_wikidb->_backend;
985 $result = $backend->get_links($this->_pagename, $reversed);
986 return new WikiDB_PageIterator($this->_wikidb, $result);
990 * Access WikiDB_Page meta-data.
994 * @param string $key Which meta data to get.
995 * Some reserved meta-data keys are:
997 * <dt>'locked'<dd> Is page locked?
998 * <dt>'hits' <dd> Page hit counter.
999 * <dt>'pref' <dd> Users preferences, stored in homepages.
1000 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1001 * E.g. "owner.users"
1002 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1003 * page-headers and content.
1004 * <dt>'score' <dd> Page score (not yet implement, do we need?)
1007 * @return scalar The requested value, or false if the requested data
1010 function get($key) {
1011 $cache = &$this->_wikidb->_cache;
1012 if (!$key || $key[0] == '%')
1014 $data = $cache->get_pagedata($this->_pagename);
1015 return isset($data[$key]) ? $data[$key] : false;
1019 * Get all the page meta-data as a hash.
1021 * @return hash The page meta-data.
1023 function getMetaData() {
1024 $cache = &$this->_wikidb->_cache;
1025 $data = $cache->get_pagedata($this->_pagename);
1027 foreach ($data as $key => $val) {
1028 if (/*!empty($val) &&*/ $key[0] != '%')
1035 * Set page meta-data.
1040 * @param string $key Meta-data key to set.
1041 * @param string $newval New value.
1043 function set($key, $newval) {
1044 $cache = &$this->_wikidb->_cache;
1045 $pagename = &$this->_pagename;
1047 assert($key && $key[0] != '%');
1049 $data = $cache->get_pagedata($pagename);
1051 if (!empty($newval)) {
1052 if (!empty($data[$key]) && $data[$key] == $newval)
1053 return; // values identical, skip update.
1056 if (empty($data[$key]))
1057 return; // values identical, skip update.
1060 $cache->update_pagedata($pagename, array($key => $newval));
1064 * Increase page hit count.
1066 * FIXME: IS this needed? Probably not.
1068 * This is a convenience function.
1069 * <pre> $page->increaseHitCount(); </pre>
1070 * is functionally identical to
1071 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1073 * Note that this method may be implemented in more efficient ways
1074 * in certain backends.
1078 function increaseHitCount() {
1079 @$newhits = $this->get('hits') + 1;
1080 $this->set('hits', $newhits);
1084 * Return a string representation of the WikiDB_Page
1086 * This is really only for debugging.
1090 * @return string Printable representation of the WikiDB_Page.
1092 function asString () {
1094 printf("[%s:%s\n", get_class($this), $this->getName());
1095 print_r($this->getMetaData());
1097 $strval = ob_get_contents();
1105 * @param integer_or_object $version_or_pagerevision
1106 * Takes either the version number (and int) or a WikiDB_PageRevision
1108 * @return integer The version number.
1110 function _coerce_to_version($version_or_pagerevision) {
1111 if (method_exists($version_or_pagerevision, "getContent"))
1112 $version = $version_or_pagerevision->getVersion();
1114 $version = (int) $version_or_pagerevision;
1116 assert($version >= 0);
1120 function isUserPage ($include_empty = true) {
1121 if ($include_empty) {
1122 $current = $this->getCurrentRevision();
1123 if ($current->hasDefaultContents()) {
1127 return $this->get('pref') ? true : false;
1133 * This class represents a specific revision of a WikiDB_Page within
1136 * A WikiDB_PageRevision has read-only semantics. You may only create
1137 * new revisions (and delete old ones) --- you cannot modify existing
1140 class WikiDB_PageRevision
1142 var $_transformedContent = false; // set by WikiDB_Page::save()
1144 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1145 $versiondata = false)
1147 $this->_wikidb = &$wikidb;
1148 $this->_pagename = $pagename;
1149 $this->_version = $version;
1150 $this->_data = $versiondata ? $versiondata : array();
1154 * Get the WikiDB_Page which this revision belongs to.
1158 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1160 function getPage() {
1161 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1165 * Get the version number of this revision.
1169 * @return integer The version number of this revision.
1171 function getVersion() {
1172 return $this->_version;
1176 * Determine whether this revision has defaulted content.
1178 * The default revision (version 0) of each page, as well as any
1179 * pages which are created with empty content have their content
1180 * defaulted to something like:
1182 * Describe [ThisPage] here.
1187 * @return boolean Returns true if the page has default content.
1189 function hasDefaultContents() {
1190 $data = &$this->_data;
1191 return empty($data['%content']);
1195 * Get the content as an array of lines.
1199 * @return array An array of lines.
1200 * The lines should contain no trailing white space.
1202 function getContent() {
1203 return explode("\n", $this->getPackedContent());
1207 * Get the pagename of the revision.
1211 * @return string pagename.
1213 function getPageName() {
1214 return $this->_pagename;
1218 * Determine whether revision is the latest.
1222 * @return boolean True iff the revision is the latest (most recent) one.
1224 function isCurrent() {
1225 if (!isset($this->_iscurrent)) {
1226 $page = $this->getPage();
1227 $current = $page->getCurrentRevision();
1228 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1230 return $this->_iscurrent;
1234 * Get the transformed content of a page.
1236 * @param string $pagetype Override the page-type of the revision.
1238 * @return object An XmlContent-like object containing the page transformed
1241 function getTransformedContent($pagetype_override=false) {
1242 $backend = &$this->_wikidb->_backend;
1244 if ($pagetype_override) {
1245 // Figure out the normal page-type for this page.
1246 $type = PageType::GetPageType($this->get('pagetype'));
1247 if ($type->getName() == $pagetype_override)
1248 $pagetype_override = false; // Not really an override...
1251 if ($pagetype_override) {
1252 // Overriden page type, don't cache (or check cache).
1253 return new TransformedText($this->getPage(),
1254 $this->getPackedContent(),
1255 $this->getMetaData(),
1256 $pagetype_override);
1259 $possibly_cache_results = true;
1261 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1262 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1263 // flush cache for this page.
1264 $page = $this->getPage();
1265 $page->set('_cached_html', false);
1267 $possibly_cache_results = false;
1269 elseif (!$this->_transformedContent) {
1271 if ($this->isCurrent()) {
1272 $page = $this->getPage();
1273 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1276 $possibly_cache_results = false;
1278 //$backend->unlock();
1281 if (!$this->_transformedContent) {
1282 $this->_transformedContent
1283 = new TransformedText($this->getPage(),
1284 $this->getPackedContent(),
1285 $this->getMetaData());
1287 if ($possibly_cache_results) {
1288 // If we're still the current version, cache the transfomed page.
1290 if ($this->isCurrent()) {
1291 $page->set('_cached_html', $this->_transformedContent->pack());
1293 //$backend->unlock();
1297 return $this->_transformedContent;
1301 * Get the content as a string.
1305 * @return string The page content.
1306 * Lines are separated by new-lines.
1308 function getPackedContent() {
1309 $data = &$this->_data;
1312 if (empty($data['%content'])) {
1313 include_once('lib/InlineParser.php');
1314 // Replace empty content with default value.
1315 return sprintf(_("Describe %s here."),
1316 "[" . WikiEscape($this->_pagename) . "]");
1319 // There is (non-default) content.
1320 assert($this->_version > 0);
1322 if (!is_string($data['%content'])) {
1323 // Content was not provided to us at init time.
1324 // (This is allowed because for some backends, fetching
1325 // the content may be expensive, and often is not wanted
1328 // In any case, now we need to get it.
1329 $data['%content'] = $this->_get_content();
1330 assert(is_string($data['%content']));
1333 return $data['%content'];
1336 function _get_content() {
1337 $cache = &$this->_wikidb->_cache;
1338 $pagename = $this->_pagename;
1339 $version = $this->_version;
1341 assert($version > 0);
1343 $newdata = $cache->get_versiondata($pagename, $version, true);
1345 assert(is_string($newdata['%content']));
1346 return $newdata['%content'];
1349 // else revision has been deleted... What to do?
1350 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1351 $version, $pagename);
1356 * Get meta-data for this revision.
1361 * @param string $key Which meta-data to access.
1363 * Some reserved revision meta-data keys are:
1365 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1366 * The 'mtime' meta-value is normally set automatically by the database
1367 * backend, but it may be specified explicitly when creating a new revision.
1369 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1370 * of a page must be monotonically increasing. If an attempt is
1371 * made to create a new revision with an mtime less than that of
1372 * the preceeding revision, the new revisions timestamp is force
1373 * to be equal to that of the preceeding revision. In that case,
1374 * the originally requested mtime is preserved in 'orig_mtime'.
1375 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1376 * This meta-value is <em>always</em> automatically maintained by the database
1377 * backend. (It is set from the 'mtime' meta-value of the superceding
1378 * revision.) '_supplanted' has a value of 'false' for the current revision.
1380 * FIXME: this could be refactored:
1382 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1384 * <dd> Authenticated author of a page. This is used to identify
1385 * the distinctness of authors when cleaning old revisions from
1387 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1388 * <dt> 'summary' <dd> Short change summary entered by page author.
1391 * Meta-data keys must be valid C identifers (they have to start with a letter
1392 * or underscore, and can contain only alphanumerics and underscores.)
1394 * @return string The requested value, or false if the requested value
1397 function get($key) {
1398 if (!$key || $key[0] == '%')
1400 $data = &$this->_data;
1401 return isset($data[$key]) ? $data[$key] : false;
1405 * Get all the revision page meta-data as a hash.
1407 * @return hash The revision meta-data.
1409 function getMetaData() {
1411 foreach ($this->_data as $key => $val) {
1412 if (!empty($val) && $key[0] != '%')
1420 * Return a string representation of the revision.
1422 * This is really only for debugging.
1426 * @return string Printable representation of the WikiDB_Page.
1428 function asString () {
1430 printf("[%s:%d\n", get_class($this), $this->get('version'));
1431 print_r($this->_data);
1432 echo $this->getPackedContent() . "\n]\n";
1433 $strval = ob_get_contents();
1441 * A class which represents a sequence of WikiDB_Pages.
1443 class WikiDB_PageIterator
1445 function WikiDB_PageIterator(&$wikidb, &$pages) {
1446 $this->_pages = $pages;
1447 $this->_wikidb = &$wikidb;
1451 return $this->_pages->count();
1455 * Get next WikiDB_Page in sequence.
1459 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1462 if ( ! ($next = $this->_pages->next()) )
1465 $pagename = &$next['pagename'];
1466 if (isset($next['pagedata']))
1467 $this->_wikidb->_cache->cache_data($next);
1469 return new WikiDB_Page($this->_wikidb, $pagename);
1473 * Release resources held by this iterator.
1475 * The iterator may not be used after free() is called.
1477 * There is no need to call free(), if next() has returned false.
1478 * (I.e. if you iterate through all the pages in the sequence,
1479 * you do not need to call free() --- you only need to call it
1480 * if you stop before the end of the iterator is reached.)
1485 $this->_pages->free();
1489 function asArray() {
1491 while ($page = $this->next())
1497 // Not yet used and problematic. Order should be set in the query, not afterwards.
1498 // See PageList::sortby
1499 function setSortby ($arg = false) {
1501 $arg = @$_GET['sortby'];
1503 $sortby = substr($arg,1);
1504 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1507 if (is_array($arg)) { // array('mtime' => 'desc')
1514 // available column types to sort by:
1515 // todo: we must provide access methods for the generic dumb/iterator
1516 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1517 if (in_array($sortby,$this->_types))
1518 $this->_options['sortby'] = $sortby;
1520 trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1521 if (in_array(strtoupper($order),'ASC','DESC'))
1522 $this->_options['order'] = strtoupper($order);
1524 trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1530 * A class which represents a sequence of WikiDB_PageRevisions.
1532 class WikiDB_PageRevisionIterator
1534 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1535 $this->_revisions = $revisions;
1536 $this->_wikidb = &$wikidb;
1540 return $this->_revisions->count();
1544 * Get next WikiDB_PageRevision in sequence.
1548 * @return WikiDB_PageRevision
1549 * The next WikiDB_PageRevision in the sequence.
1552 if ( ! ($next = $this->_revisions->next()) )
1555 $this->_wikidb->_cache->cache_data($next);
1557 $pagename = $next['pagename'];
1558 $version = $next['version'];
1559 $versiondata = $next['versiondata'];
1560 assert(is_string($pagename) and $pagename != '');
1561 assert(is_array($versiondata));
1562 assert($version > 0);
1564 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1569 * Release resources held by this iterator.
1571 * The iterator may not be used after free() is called.
1573 * There is no need to call free(), if next() has returned false.
1574 * (I.e. if you iterate through all the revisions in the sequence,
1575 * you do not need to call free() --- you only need to call it
1576 * if you stop before the end of the iterator is reached.)
1581 $this->_revisions->free();
1587 * Data cache used by WikiDB.
1589 * FIXME: Maybe rename this to caching_backend (or some such).
1595 // FIXME: beautify versiondata cache. Cache only limited data?
1597 function WikiDB_cache (&$backend) {
1598 $this->_backend = &$backend;
1600 $this->_pagedata_cache = array();
1601 $this->_versiondata_cache = array();
1602 array_push ($this->_versiondata_cache, array());
1603 $this->_glv_cache = array();
1607 $this->_pagedata_cache = false;
1608 $this->_versiondata_cache = false;
1609 $this->_glv_cache = false;
1612 function get_pagedata($pagename) {
1613 assert(is_string($pagename) && $pagename != '');
1614 $cache = &$this->_pagedata_cache;
1616 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1617 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1618 if (empty($cache[$pagename]))
1619 $cache[$pagename] = array();
1622 return $cache[$pagename];
1625 function update_pagedata($pagename, $newdata) {
1626 assert(is_string($pagename) && $pagename != '');
1628 $this->_backend->update_pagedata($pagename, $newdata);
1630 if (is_array($this->_pagedata_cache[$pagename])) {
1631 $cachedata = &$this->_pagedata_cache[$pagename];
1632 foreach($newdata as $key => $val)
1633 $cachedata[$key] = $val;
1637 function invalidate_cache($pagename) {
1638 unset ($this->_pagedata_cache[$pagename]);
1639 unset ($this->_versiondata_cache[$pagename]);
1640 unset ($this->_glv_cache[$pagename]);
1643 function delete_page($pagename) {
1644 $this->_backend->delete_page($pagename);
1645 unset ($this->_pagedata_cache[$pagename]);
1646 unset ($this->_glv_cache[$pagename]);
1650 function cache_data($data) {
1651 if (isset($data['pagedata']))
1652 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1655 function get_versiondata($pagename, $version, $need_content = false) {
1656 // FIXME: Seriously ugly hackage
1657 if (defined ('USECACHE')){ //temporary - for debugging
1658 assert(is_string($pagename) && $pagename != '');
1659 // there is a bug here somewhere which results in an assertion failure at line 105
1660 // of ArchiveCleaner.php It goes away if we use the next line.
1661 $need_content = true;
1662 $nc = $need_content ? '1':'0';
1663 $cache = &$this->_versiondata_cache;
1664 if (!isset($cache[$pagename][$version][$nc])||
1665 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1666 $cache[$pagename][$version][$nc] =
1667 $this->_backend->get_versiondata($pagename,$version, $need_content);
1668 // If we have retrieved all data, we may as well set the cache for $need_content = false
1670 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1673 $vdata = $cache[$pagename][$version][$nc];
1675 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1678 if ($vdata && !empty($vdata['%pagedata']))
1679 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1683 function set_versiondata($pagename, $version, $data) {
1684 $new = $this->_backend->set_versiondata($pagename, $version, $data);
1686 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1688 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1689 // Is this necessary?
1690 unset($this->_glv_cache[$pagename]);
1693 function update_versiondata($pagename, $version, $data) {
1694 $new = $this->_backend->update_versiondata($pagename, $version, $data);
1696 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1698 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1699 // Is this necessary?
1700 unset($this->_glv_cache[$pagename]);
1703 function delete_versiondata($pagename, $version) {
1704 $new = $this->_backend->delete_versiondata($pagename, $version);
1705 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1706 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1707 unset ($this->_glv_cache[$pagename]);
1710 function get_latest_version($pagename) {
1711 if (defined('USECACHE')){
1712 assert (is_string($pagename) && $pagename != '');
1713 $cache = &$this->_glv_cache;
1714 if (!isset($cache[$pagename])) {
1715 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1716 if (empty($cache[$pagename]))
1717 $cache[$pagename] = 0;
1719 return $cache[$pagename];
1721 return $this->_backend->get_latest_version($pagename);
1727 // $Log: not supported by cvs2svn $
1728 // Revision 1.50 2004/05/04 22:34:25 rurban
1731 // Revision 1.49 2004/05/03 11:16:40 rurban
1732 // fixed sendPageChangeNotification
1733 // subject rewording
1735 // Revision 1.48 2004/04/29 23:03:54 rurban
1736 // fixed sf.net bug #940996
1738 // Revision 1.47 2004/04/29 19:39:44 rurban
1739 // special support for formatted plugins (one-liners)
1740 // like <small><plugin BlaBla ></small>
1741 // iter->asArray() helper for PopularNearby
1742 // db_session for older php's (no &func() allowed)
1744 // Revision 1.46 2004/04/26 20:44:34 rurban
1745 // locking table specific for better databases
1747 // Revision 1.45 2004/04/20 00:06:03 rurban
1748 // themable paging support
1750 // Revision 1.44 2004/04/19 18:27:45 rurban
1751 // Prevent from some PHP5 warnings (ref args, no :: object init)
1752 // php5 runs now through, just one wrong XmlElement object init missing
1753 // Removed unneccesary UpgradeUser lines
1754 // Changed WikiLink to omit version if current (RecentChanges)
1756 // Revision 1.43 2004/04/18 01:34:20 rurban
1757 // protect most_popular from sortby=mtime
1759 // Revision 1.42 2004/04/18 01:11:51 rurban
1760 // more numeric pagename fixes.
1761 // fixed action=upload with merge conflict warnings.
1762 // charset changed from constant to global (dynamic utf-8 switching)
1768 // c-basic-offset: 4
1769 // c-hanging-comment-ender-p: nil
1770 // indent-tabs-mode: nil