2 rcs_id('$Id: WikiDB.php,v 1.53 2004-05-08 14:06:12 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 static $error_displayed = false;
169 if (!(is_string($pagename) and $pagename != '')) {
170 if ($error_displayed) return false;
171 $error_displayed = true;
172 if (function_exists("xdebug_get_function_stack"))
173 var_dump(xdebug_get_function_stack());
174 trigger_error("empty pagename",E_USER_WARNING);
178 assert(is_string($pagename) and $pagename != '');
179 return new WikiDB_Page($this, $pagename);
183 * Determine whether page exists (in non-default form).
186 * $is_page = $dbi->isWikiPage($pagename);
190 * $page = $dbi->getPage($pagename);
191 * $current = $page->getCurrentRevision();
192 * $is_page = ! $current->hasDefaultContents();
194 * however isWikiPage may be implemented in a more efficient
195 * manner in certain back-ends.
199 * @param string $pagename string Which page to check.
201 * @return boolean True if the page actually exists with
202 * non-default contents in the WikiDataBase.
204 function isWikiPage ($pagename) {
205 $page = $this->getPage($pagename);
206 $current = $page->getCurrentRevision();
207 return ! $current->hasDefaultContents();
211 * Delete page from the WikiDB.
213 * Deletes all revisions of the page from the WikiDB. Also resets
214 * all page meta-data to the default values.
218 * @param string $pagename Name of page to delete.
220 function deletePage($pagename) {
221 $this->_cache->delete_page($pagename);
223 //How to create a RecentChanges entry with explaining summary?
225 $page = $this->getPage($pagename);
226 $current = $page->getCurrentRevision();
227 $meta = $current->_data;
228 $version = $current->getVersion();
229 $meta['summary'] = _("removed");
230 $page->save($current->getPackedContent(), $version + 1, $meta);
235 * Retrieve all pages.
237 * Gets the set of all pages with non-default contents.
239 * FIXME: do we need this? I think so. The simple searches
244 * @param boolean $include_defaulted Normally pages whose most
245 * recent revision has empty content are considered to be
246 * non-existant. Unless $include_defaulted is set to true, those
247 * pages will not be returned.
249 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
250 * in the WikiDB which have non-default contents.
252 function getAllPages($include_defaulted=false, $sortby=false, $limit=false) {
253 $result = $this->_backend->get_all_pages($include_defaulted,$sortby,$limit);
254 return new WikiDB_PageIterator($this, $result);
258 //function nPages() {
260 // Yes, for paging. Renamed.
261 function numPages($filter=false, $exclude='') {
262 if (method_exists($this->_backend,'numPages'))
263 $count = $this->_backend->numPages($filter,$exclude);
265 $iter = $this->getAllPages();
266 $count = $iter->count();
274 * Search for pages containing (or not containing) certain words
277 * Pages are returned in alphabetical order whenever it is
278 * practical to do so.
280 * FIXME: should titleSearch and fullSearch be combined? I think so.
283 * @param TextSearchQuery $search A TextSearchQuery object
284 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
285 * @see TextSearchQuery
287 function titleSearch($search) {
288 $result = $this->_backend->text_search($search);
289 return new WikiDB_PageIterator($this, $result);
295 * Search for pages containing (or not containing) certain words
296 * in their entire text (this includes the page content and the
299 * Pages are returned in alphabetical order whenever it is
300 * practical to do so.
304 * @param TextSearchQuery $search A TextSearchQuery object.
305 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
306 * @see TextSearchQuery
308 function fullSearch($search) {
309 $result = $this->_backend->text_search($search, 'full_text');
310 return new WikiDB_PageIterator($this, $result);
314 * Find the pages with the greatest hit counts.
316 * Pages are returned in reverse order by hit count.
320 * @param integer $limit The maximum number of pages to return.
321 * Set $limit to zero to return all pages. If $limit < 0, pages will
322 * be sorted in decreasing order of popularity.
324 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
327 function mostPopular($limit = 20, $sortby = '') {
328 // we don't support sortby=mtime here
329 if (strstr($sortby,'mtime'))
331 $result = $this->_backend->most_popular($limit, $sortby);
332 return new WikiDB_PageIterator($this, $result);
336 * Find recent page revisions.
338 * Revisions are returned in reverse order by creation time.
342 * @param hash $params This hash is used to specify various optional
346 * <dd> (integer) At most this many revisions will be returned.
348 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
349 * <dt> include_minor_revisions
350 * <dd> (boolean) Also include minor revisions. (Default is not to.)
351 * <dt> exclude_major_revisions
352 * <dd> (boolean) Don't include non-minor revisions.
353 * (Exclude_major_revisions implies include_minor_revisions.)
354 * <dt> include_all_revisions
355 * <dd> (boolean) Return all matching revisions for each page.
356 * Normally only the most recent matching revision is returned
360 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
361 * matching revisions.
363 function mostRecent($params = false) {
364 $result = $this->_backend->most_recent($params);
365 return new WikiDB_PageRevisionIterator($this, $result);
369 * Call the appropriate backend method.
372 * @param string $from Page to rename
373 * @param string $to New name
374 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
375 * @return boolean true or false
377 function renamePage($from, $to, $updateWikiLinks = false) {
378 assert(is_string($from) && $from != '');
379 assert(is_string($to) && $to != '');
381 if (method_exists($this->_backend,'rename_page')) {
382 $oldpage = $this->getPage($from);
383 $newpage = $this->getPage($to);
384 if ($oldpage->exists() and ! $newpage->exists()) {
385 if ($result = $this->_backend->rename_page($from, $to)) {
386 //update all WikiLinks in existing pages
387 if ($updateWikiLinks) {
388 //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
389 require_once('lib/plugin/WikiAdminSearchReplace.php');
390 $links = $oldpage->getLinks();
391 while ($linked_page = $links->next()) {
392 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
394 $links = $newpage->getLinks();
395 while ($linked_page = $links->next()) {
396 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
399 //create a RecentChanges entry with explaining summary
400 $page = $this->getPage($to);
401 $current = $page->getCurrentRevision();
402 $meta = $current->_data;
403 $version = $current->getVersion();
404 $meta['summary'] = sprintf(_("renamed from %s"),$from);
405 $page->save($current->getPackedContent(), $version + 1, $meta);
409 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
414 /** Get timestamp when database was last modified.
416 * @return string A string consisting of two integers,
417 * separated by a space. The first is the time in
418 * unix timestamp format, the second is a modification
419 * count for the database.
421 * The idea is that you can cast the return value to an
422 * int to get a timestamp, or you can use the string value
423 * as a good hash for the entire database.
425 function getTimestamp() {
426 $ts = $this->get('_timestamp');
427 return sprintf("%d %d", $ts[0], $ts[1]);
431 * Update the database timestamp.
435 $ts = $this->get('_timestamp');
436 $this->set('_timestamp', array(time(), $ts[1] + 1));
441 * Access WikiDB global meta-data.
443 * NOTE: this is currently implemented in a hackish and
444 * not very efficient manner.
448 * @param string $key Which meta data to get.
449 * Some reserved meta-data keys are:
451 * <dt>'_timestamp' <dd> Data used by getTimestamp().
454 * @return scalar The requested value, or false if the requested data
458 if (!$key || $key[0] == '%')
461 * Hack Alert: We can use any page (existing or not) to store
462 * this data (as long as we always use the same one.)
464 $gd = $this->getPage('global_data');
465 $data = $gd->get('__global');
467 if ($data && isset($data[$key]))
474 * Set global meta-data.
476 * NOTE: this is currently implemented in a hackish and
477 * not very efficient manner.
482 * @param string $key Meta-data key to set.
483 * @param string $newval New value.
485 function set($key, $newval) {
486 if (!$key || $key[0] == '%')
489 $gd = $this->getPage('global_data');
491 $data = $gd->get('__global');
498 $data[$key] = $newval;
500 $gd->set('__global', $data);
503 // simple select or create/update queries which do trigger_error
504 function simpleQuery($sql) {
506 if ($DBParams['dbtype'] == 'SQL') {
507 $result = $this->_backend->_dbh->query($sql);
508 if (DB::isError($result)) {
509 $msg = $result->getMessage();
510 trigger_error("SQL Error: ".DB::errorMessage($result),E_USER_WARNING);
515 } elseif ($DBParams['dbtype'] == 'ADODB') {
516 if (!($result = $this->_backend->_dbh->Execute($sql))) {
517 trigger_error("SQL Error: ".$this->_backend->_dbh->ErrorMsg(),E_USER_WARNING);
529 * An abstract base class which representing a wiki-page within a
532 * A WikiDB_Page contains a number (at least one) of
533 * WikiDB_PageRevisions.
537 function WikiDB_Page(&$wikidb, $pagename) {
538 $this->_wikidb = &$wikidb;
539 $this->_pagename = $pagename;
541 if (!(is_string($pagename) and $pagename != '')) {
542 if (function_exists("xdebug_get_function_stack")) {
543 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
546 trigger_error("empty pagename",E_USER_WARNING);
549 } else assert(is_string($pagename) and $pagename != '');
553 * Get the name of the wiki page.
557 * @return string The page name.
560 return $this->_pagename;
564 $current = $this->getCurrentRevision();
565 return ! $current->hasDefaultContents();
569 * Delete an old revision of a WikiDB_Page.
571 * Deletes the specified revision of the page.
572 * It is a fatal error to attempt to delete the current revision.
576 * @param integer $version Which revision to delete. (You can also
577 * use a WikiDB_PageRevision object here.)
579 function deleteRevision($version) {
580 $backend = &$this->_wikidb->_backend;
581 $cache = &$this->_wikidb->_cache;
582 $pagename = &$this->_pagename;
584 $version = $this->_coerce_to_version($version);
588 $backend->lock(array('page','version'));
589 $latestversion = $cache->get_latest_version($pagename);
590 if ($latestversion && $version == $latestversion) {
591 $backend->unlock(array('page','version'));
592 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
593 $pagename), E_USER_ERROR);
597 $cache->delete_versiondata($pagename, $version);
598 $backend->unlock(array('page','version'));
602 * Delete a revision, or possibly merge it with a previous
606 * Suppose an author make a (major) edit to a page. Shortly
607 * after that the same author makes a minor edit (e.g. to fix
608 * spelling mistakes he just made.)
610 * Now some time later, where cleaning out old saved revisions,
611 * and would like to delete his minor revision (since there's
612 * really no point in keeping minor revisions around for a long
615 * Note that the text after the minor revision probably represents
616 * what the author intended to write better than the text after
617 * the preceding major edit.
619 * So what we really want to do is merge the minor edit with the
622 * We will only do this when:
624 * <li>The revision being deleted is a minor one, and
625 * <li>It has the same author as the immediately preceding revision.
628 function mergeRevision($version) {
629 $backend = &$this->_wikidb->_backend;
630 $cache = &$this->_wikidb->_cache;
631 $pagename = &$this->_pagename;
633 $version = $this->_coerce_to_version($version);
637 $backend->lock(array('version'));
638 $latestversion = $backend->get_latest_version($pagename);
639 if ($latestversion && $version == $latestversion) {
640 $backend->unlock(array('version'));
641 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
642 $pagename), E_USER_ERROR);
646 $versiondata = $cache->get_versiondata($pagename, $version, true);
648 // Not there? ... we're done!
649 $backend->unlock(array('version'));
653 if ($versiondata['is_minor_edit']) {
654 $previous = $backend->get_previous_version($pagename, $version);
656 $prevdata = $cache->get_versiondata($pagename, $previous);
657 if ($prevdata['author_id'] == $versiondata['author_id']) {
658 // This is a minor revision, previous version is
659 // by the same author. We will merge the
661 $cache->update_versiondata($pagename, $previous,
662 array('%content' => $versiondata['%content'],
663 '_supplanted' => $versiondata['_supplanted']));
668 $cache->delete_versiondata($pagename, $version);
669 $backend->unlock(array('version'));
674 * Create a new revision of a {@link WikiDB_Page}.
678 * @param int $version Version number for new revision.
679 * To ensure proper serialization of edits, $version must be
680 * exactly one higher than the current latest version.
681 * (You can defeat this check by setting $version to
682 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
684 * @param string $content Contents of new revision.
686 * @param hash $metadata Metadata for new revision.
687 * All values in the hash should be scalars (strings or integers).
689 * @param array $links List of pagenames which this page links to.
691 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
692 * $version was incorrect, returns false
694 function createRevision($version, &$content, $metadata, $links) {
695 $backend = &$this->_wikidb->_backend;
696 $cache = &$this->_wikidb->_cache;
697 $pagename = &$this->_pagename;
699 $backend->lock(array('version','page','recent','links','nonempty'));
701 $latestversion = $backend->get_latest_version($pagename);
702 $newversion = $latestversion + 1;
703 assert($newversion >= 1);
705 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
706 $backend->unlock(array('version','page','recent','links'));
712 foreach ($data as $key => $val) {
713 if (empty($val) || $key[0] == '_' || $key[0] == '%')
717 assert(!empty($data['author']));
718 if (empty($data['author_id']))
719 @$data['author_id'] = $data['author'];
721 if (empty($data['mtime']))
722 $data['mtime'] = time();
724 if ($latestversion) {
725 // Ensure mtimes are monotonic.
726 $pdata = $cache->get_versiondata($pagename, $latestversion);
727 if ($data['mtime'] < $pdata['mtime']) {
728 trigger_error(sprintf(_("%s: Date of new revision is %s"),
729 $pagename,"'non-monotonic'"),
731 $data['orig_mtime'] = $data['mtime'];
732 $data['mtime'] = $pdata['mtime'];
735 // FIXME: use (possibly user specified) 'mtime' time or
737 $cache->update_versiondata($pagename, $latestversion,
738 array('_supplanted' => $data['mtime']));
741 $data['%content'] = &$content;
743 $cache->set_versiondata($pagename, $newversion, $data);
745 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
746 //':deleted' => empty($content)));
748 $backend->set_links($pagename, $links);
750 $backend->unlock(array('version','page','recent','links','nonempty'));
752 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
756 /** A higher-level interface to createRevision.
758 * This takes care of computing the links, and storing
759 * a cached version of the transformed wiki-text.
761 * @param string $wikitext The page content.
763 * @param int $version Version number for new revision.
764 * To ensure proper serialization of edits, $version must be
765 * exactly one higher than the current latest version.
766 * (You can defeat this check by setting $version to
767 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
769 * @param hash $meta Meta-data for new revision.
771 function save($wikitext, $version, $meta) {
772 $formatted = new TransformedText($this, $wikitext, $meta);
773 $type = $formatted->getType();
774 $meta['pagetype'] = $type->getName();
775 $links = $formatted->getWikiPageLinks();
777 $backend = &$this->_wikidb->_backend;
778 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
780 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
781 $this->set('_cached_html', $formatted->pack());
783 // FIXME: probably should have some global state information
784 // in the backend to control when to optimize.
786 // We're doing this here rather than in createRevision because
787 // postgres can't optimize while locked.
788 if (time() % 50 == 0) {
789 if ($backend->optimize())
790 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
793 /* Generate notification emails? */
794 if (isa($newrevision, 'wikidb_pagerevision')) {
795 // Save didn't fail because of concurrent updates.
796 $notify = $this->_wikidb->get('notify');
797 if (!empty($notify) and is_array($notify)) {
798 list($emails,$userids) = $this->getPageChangeEmails($notify);
800 $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
804 $newrevision->_transformedContent = $formatted;
808 function getPageChangeEmails($notify) {
809 $emails = array(); $userids = array();
810 foreach ($notify as $page => $users) {
811 if (glob_match($page,$this->_pagename)) {
812 foreach ($users as $userid => $user) {
813 if (!empty($user['verified']) and !empty($user['email'])) {
814 $emails[] = $user['email'];
815 $userids[] = $userid;
816 } elseif (!empty($user['email'])) {
818 // do a dynamic emailVerified check update
819 $u = $request->getUser();
820 if ($u->UserName() == $userid) {
821 if ($request->_prefs->get('emailVerified')) {
822 $emails[] = $user['email'];
823 $userids[] = $userid;
824 $notify[$page][$userid]['verified'] = 1;
825 $request->_dbi->set('notify',$notify);
828 $u = WikiUser($userid);
829 if ($u->_prefs->get('emailVerified')) {
830 $emails[] = $user['email'];
831 $userids[] = $userid;
832 $notify[$page][$userid]['verified'] = 1;
833 $request->_dbi->set('notify',$notify);
836 // ignore verification
839 if (!in_array($user['email'],$emails))
840 $emails[] = $user['email'];
847 $emails = array_unique($emails);
848 $userids = array_unique($userids);
849 return array($emails,$userids);
852 function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
853 $backend = &$this->_wikidb->_backend;
854 $subject = _("Page change").' '.$this->_pagename;
855 $previous = $backend->get_previous_version($this->_pagename, $version);
856 if (!isset($meta['mtime'])) $meta['mtime'] = time();
858 $difflink = WikiURL($this->_pagename,array('action'=>'diff'),true);
859 $cache = &$this->_wikidb->_cache;
860 $this_content = explode("\n", $wikitext);
861 $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
862 if (empty($prevdata['%content']))
863 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
864 $other_content = explode("\n", $prevdata['%content']);
866 include_once("lib/diff.php");
867 $diff2 = new Diff($other_content, $this_content);
868 $context_lines = max(4, count($other_content) + 1,
869 count($this_content) + 1);
870 $fmt = new UnifiedDiffFormatter($context_lines);
871 $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n";
872 $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
873 $content .= $fmt->format($diff2);
876 $difflink = WikiURL($this->_pagename,array(),true);
877 $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
878 $content .= _("New Page");
880 $editedby = sprintf(_("Edited by: %s"), $meta['author']);
881 $emails = join(',',$emails);
882 if (mail($emails,"[".WIKI_NAME."] ".$subject,
887 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
888 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
890 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
891 $this->_pagename, join(',',$userids)), E_USER_WARNING);
895 * Get the most recent revision of a page.
899 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
901 function getCurrentRevision() {
902 $backend = &$this->_wikidb->_backend;
903 $cache = &$this->_wikidb->_cache;
904 $pagename = &$this->_pagename;
906 // Prevent deadlock in case of memory exhausted errors
907 // Pure selection doesn't really need locking here.
909 // I know it would be better, but with lots of pages this deadlock is more
910 // severe than occasionally get not the latest revision.
912 $version = $cache->get_latest_version($pagename);
913 $revision = $this->getRevision($version);
914 //$backend->unlock();
920 * Get a specific revision of a WikiDB_Page.
924 * @param integer $version Which revision to get.
926 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
927 * false if the requested revision does not exist in the {@link WikiDB}.
928 * Note that version zero of any page always exists.
930 function getRevision($version) {
931 $cache = &$this->_wikidb->_cache;
932 $pagename = &$this->_pagename;
935 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
937 assert($version > 0);
938 $vdata = $cache->get_versiondata($pagename, $version);
941 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
946 * Get previous page revision.
948 * This method find the most recent revision before a specified
953 * @param integer $version Find most recent revision before this version.
954 * You can also use a WikiDB_PageRevision object to specify the $version.
956 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
957 * requested revision does not exist in the {@link WikiDB}. Note that
958 * unless $version is greater than zero, a revision (perhaps version zero,
959 * the default revision) will always be found.
961 function getRevisionBefore($version) {
962 $backend = &$this->_wikidb->_backend;
963 $pagename = &$this->_pagename;
965 $version = $this->_coerce_to_version($version);
970 $previous = $backend->get_previous_version($pagename, $version);
971 $revision = $this->getRevision($previous);
972 //$backend->unlock();
978 * Get all revisions of the WikiDB_Page.
980 * This does not include the version zero (default) revision in the
981 * returned revision set.
983 * @return WikiDB_PageRevisionIterator A
984 * WikiDB_PageRevisionIterator containing all revisions of this
985 * WikiDB_Page in reverse order by version number.
987 function getAllRevisions() {
988 $backend = &$this->_wikidb->_backend;
989 $revs = $backend->get_all_revisions($this->_pagename);
990 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
994 * Find pages which link to or are linked from a page.
998 * @param boolean $reversed Which links to find: true for backlinks (default).
1000 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1001 * all matching pages.
1003 function getLinks($reversed = true) {
1004 $backend = &$this->_wikidb->_backend;
1005 $result = $backend->get_links($this->_pagename, $reversed);
1006 return new WikiDB_PageIterator($this->_wikidb, $result);
1010 * Access WikiDB_Page meta-data.
1014 * @param string $key Which meta data to get.
1015 * Some reserved meta-data keys are:
1017 * <dt>'locked'<dd> Is page locked?
1018 * <dt>'hits' <dd> Page hit counter.
1019 * <dt>'pref' <dd> Users preferences, stored in homepages.
1020 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1021 * E.g. "owner.users"
1022 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1023 * page-headers and content.
1024 * <dt>'score' <dd> Page score (not yet implement, do we need?)
1027 * @return scalar The requested value, or false if the requested data
1030 function get($key) {
1031 $cache = &$this->_wikidb->_cache;
1032 if (!$key || $key[0] == '%')
1034 $data = $cache->get_pagedata($this->_pagename);
1035 return isset($data[$key]) ? $data[$key] : false;
1039 * Get all the page meta-data as a hash.
1041 * @return hash The page meta-data.
1043 function getMetaData() {
1044 $cache = &$this->_wikidb->_cache;
1045 $data = $cache->get_pagedata($this->_pagename);
1047 foreach ($data as $key => $val) {
1048 if (/*!empty($val) &&*/ $key[0] != '%')
1055 * Set page meta-data.
1060 * @param string $key Meta-data key to set.
1061 * @param string $newval New value.
1063 function set($key, $newval) {
1064 $cache = &$this->_wikidb->_cache;
1065 $pagename = &$this->_pagename;
1067 assert($key && $key[0] != '%');
1069 $data = $cache->get_pagedata($pagename);
1071 if (!empty($newval)) {
1072 if (!empty($data[$key]) && $data[$key] == $newval)
1073 return; // values identical, skip update.
1076 if (empty($data[$key]))
1077 return; // values identical, skip update.
1080 $cache->update_pagedata($pagename, array($key => $newval));
1084 * Increase page hit count.
1086 * FIXME: IS this needed? Probably not.
1088 * This is a convenience function.
1089 * <pre> $page->increaseHitCount(); </pre>
1090 * is functionally identical to
1091 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1093 * Note that this method may be implemented in more efficient ways
1094 * in certain backends.
1098 function increaseHitCount() {
1099 @$newhits = $this->get('hits') + 1;
1100 $this->set('hits', $newhits);
1104 * Return a string representation of the WikiDB_Page
1106 * This is really only for debugging.
1110 * @return string Printable representation of the WikiDB_Page.
1112 function asString () {
1114 printf("[%s:%s\n", get_class($this), $this->getName());
1115 print_r($this->getMetaData());
1117 $strval = ob_get_contents();
1125 * @param integer_or_object $version_or_pagerevision
1126 * Takes either the version number (and int) or a WikiDB_PageRevision
1128 * @return integer The version number.
1130 function _coerce_to_version($version_or_pagerevision) {
1131 if (method_exists($version_or_pagerevision, "getContent"))
1132 $version = $version_or_pagerevision->getVersion();
1134 $version = (int) $version_or_pagerevision;
1136 assert($version >= 0);
1140 function isUserPage ($include_empty = true) {
1141 if ($include_empty) {
1142 $current = $this->getCurrentRevision();
1143 if ($current->hasDefaultContents()) {
1147 return $this->get('pref') ? true : false;
1153 * This class represents a specific revision of a WikiDB_Page within
1156 * A WikiDB_PageRevision has read-only semantics. You may only create
1157 * new revisions (and delete old ones) --- you cannot modify existing
1160 class WikiDB_PageRevision
1162 var $_transformedContent = false; // set by WikiDB_Page::save()
1164 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1165 $versiondata = false)
1167 $this->_wikidb = &$wikidb;
1168 $this->_pagename = $pagename;
1169 $this->_version = $version;
1170 $this->_data = $versiondata ? $versiondata : array();
1174 * Get the WikiDB_Page which this revision belongs to.
1178 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1180 function getPage() {
1181 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1185 * Get the version number of this revision.
1189 * @return integer The version number of this revision.
1191 function getVersion() {
1192 return $this->_version;
1196 * Determine whether this revision has defaulted content.
1198 * The default revision (version 0) of each page, as well as any
1199 * pages which are created with empty content have their content
1200 * defaulted to something like:
1202 * Describe [ThisPage] here.
1207 * @return boolean Returns true if the page has default content.
1209 function hasDefaultContents() {
1210 $data = &$this->_data;
1211 return empty($data['%content']);
1215 * Get the content as an array of lines.
1219 * @return array An array of lines.
1220 * The lines should contain no trailing white space.
1222 function getContent() {
1223 return explode("\n", $this->getPackedContent());
1227 * Get the pagename of the revision.
1231 * @return string pagename.
1233 function getPageName() {
1234 return $this->_pagename;
1238 * Determine whether revision is the latest.
1242 * @return boolean True iff the revision is the latest (most recent) one.
1244 function isCurrent() {
1245 if (!isset($this->_iscurrent)) {
1246 $page = $this->getPage();
1247 $current = $page->getCurrentRevision();
1248 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1250 return $this->_iscurrent;
1254 * Get the transformed content of a page.
1256 * @param string $pagetype Override the page-type of the revision.
1258 * @return object An XmlContent-like object containing the page transformed
1261 function getTransformedContent($pagetype_override=false) {
1262 $backend = &$this->_wikidb->_backend;
1264 if ($pagetype_override) {
1265 // Figure out the normal page-type for this page.
1266 $type = PageType::GetPageType($this->get('pagetype'));
1267 if ($type->getName() == $pagetype_override)
1268 $pagetype_override = false; // Not really an override...
1271 if ($pagetype_override) {
1272 // Overriden page type, don't cache (or check cache).
1273 return new TransformedText($this->getPage(),
1274 $this->getPackedContent(),
1275 $this->getMetaData(),
1276 $pagetype_override);
1279 $possibly_cache_results = true;
1281 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1282 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1283 // flush cache for this page.
1284 $page = $this->getPage();
1285 $page->set('_cached_html', false);
1287 $possibly_cache_results = false;
1289 elseif (!$this->_transformedContent) {
1291 if ($this->isCurrent()) {
1292 $page = $this->getPage();
1293 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1296 $possibly_cache_results = false;
1298 //$backend->unlock();
1301 if (!$this->_transformedContent) {
1302 $this->_transformedContent
1303 = new TransformedText($this->getPage(),
1304 $this->getPackedContent(),
1305 $this->getMetaData());
1307 if ($possibly_cache_results) {
1308 // If we're still the current version, cache the transfomed page.
1310 if ($this->isCurrent()) {
1311 $page->set('_cached_html', $this->_transformedContent->pack());
1313 //$backend->unlock();
1317 return $this->_transformedContent;
1321 * Get the content as a string.
1325 * @return string The page content.
1326 * Lines are separated by new-lines.
1328 function getPackedContent() {
1329 $data = &$this->_data;
1332 if (empty($data['%content'])) {
1333 include_once('lib/InlineParser.php');
1334 // Replace empty content with default value.
1335 return sprintf(_("Describe %s here."),
1336 "[" . WikiEscape($this->_pagename) . "]");
1339 // There is (non-default) content.
1340 assert($this->_version > 0);
1342 if (!is_string($data['%content'])) {
1343 // Content was not provided to us at init time.
1344 // (This is allowed because for some backends, fetching
1345 // the content may be expensive, and often is not wanted
1348 // In any case, now we need to get it.
1349 $data['%content'] = $this->_get_content();
1350 assert(is_string($data['%content']));
1353 return $data['%content'];
1356 function _get_content() {
1357 $cache = &$this->_wikidb->_cache;
1358 $pagename = $this->_pagename;
1359 $version = $this->_version;
1361 assert($version > 0);
1363 $newdata = $cache->get_versiondata($pagename, $version, true);
1365 assert(is_string($newdata['%content']));
1366 return $newdata['%content'];
1369 // else revision has been deleted... What to do?
1370 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1371 $version, $pagename);
1376 * Get meta-data for this revision.
1381 * @param string $key Which meta-data to access.
1383 * Some reserved revision meta-data keys are:
1385 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1386 * The 'mtime' meta-value is normally set automatically by the database
1387 * backend, but it may be specified explicitly when creating a new revision.
1389 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1390 * of a page must be monotonically increasing. If an attempt is
1391 * made to create a new revision with an mtime less than that of
1392 * the preceeding revision, the new revisions timestamp is force
1393 * to be equal to that of the preceeding revision. In that case,
1394 * the originally requested mtime is preserved in 'orig_mtime'.
1395 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1396 * This meta-value is <em>always</em> automatically maintained by the database
1397 * backend. (It is set from the 'mtime' meta-value of the superceding
1398 * revision.) '_supplanted' has a value of 'false' for the current revision.
1400 * FIXME: this could be refactored:
1402 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1404 * <dd> Authenticated author of a page. This is used to identify
1405 * the distinctness of authors when cleaning old revisions from
1407 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1408 * <dt> 'summary' <dd> Short change summary entered by page author.
1411 * Meta-data keys must be valid C identifers (they have to start with a letter
1412 * or underscore, and can contain only alphanumerics and underscores.)
1414 * @return string The requested value, or false if the requested value
1417 function get($key) {
1418 if (!$key || $key[0] == '%')
1420 $data = &$this->_data;
1421 return isset($data[$key]) ? $data[$key] : false;
1425 * Get all the revision page meta-data as a hash.
1427 * @return hash The revision meta-data.
1429 function getMetaData() {
1431 foreach ($this->_data as $key => $val) {
1432 if (!empty($val) && $key[0] != '%')
1440 * Return a string representation of the revision.
1442 * This is really only for debugging.
1446 * @return string Printable representation of the WikiDB_Page.
1448 function asString () {
1450 printf("[%s:%d\n", get_class($this), $this->get('version'));
1451 print_r($this->_data);
1452 echo $this->getPackedContent() . "\n]\n";
1453 $strval = ob_get_contents();
1461 * A class which represents a sequence of WikiDB_Pages.
1463 class WikiDB_PageIterator
1465 function WikiDB_PageIterator(&$wikidb, &$pages) {
1466 $this->_pages = $pages;
1467 $this->_wikidb = &$wikidb;
1471 return $this->_pages->count();
1475 * Get next WikiDB_Page in sequence.
1479 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1482 if ( ! ($next = $this->_pages->next()) )
1485 $pagename = &$next['pagename'];
1487 trigger_error(__FILE__.':'.__LINE__.' empty pagename in WikiDB_PageIterator::next()',E_USER_WARNING);
1491 if (isset($next['pagedata']))
1492 $this->_wikidb->_cache->cache_data($next);
1494 return new WikiDB_Page($this->_wikidb, $pagename);
1498 * Release resources held by this iterator.
1500 * The iterator may not be used after free() is called.
1502 * There is no need to call free(), if next() has returned false.
1503 * (I.e. if you iterate through all the pages in the sequence,
1504 * you do not need to call free() --- you only need to call it
1505 * if you stop before the end of the iterator is reached.)
1510 $this->_pages->free();
1514 function asArray() {
1516 while ($page = $this->next())
1522 // Not yet used and problematic. Order should be set in the query, not afterwards.
1523 // See PageList::sortby
1524 function setSortby ($arg = false) {
1526 $arg = @$_GET['sortby'];
1528 $sortby = substr($arg,1);
1529 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1532 if (is_array($arg)) { // array('mtime' => 'desc')
1539 // available column types to sort by:
1540 // todo: we must provide access methods for the generic dumb/iterator
1541 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1542 if (in_array($sortby,$this->_types))
1543 $this->_options['sortby'] = $sortby;
1545 trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1546 if (in_array(strtoupper($order),'ASC','DESC'))
1547 $this->_options['order'] = strtoupper($order);
1549 trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1555 * A class which represents a sequence of WikiDB_PageRevisions.
1557 class WikiDB_PageRevisionIterator
1559 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1560 $this->_revisions = $revisions;
1561 $this->_wikidb = &$wikidb;
1565 return $this->_revisions->count();
1569 * Get next WikiDB_PageRevision in sequence.
1573 * @return WikiDB_PageRevision
1574 * The next WikiDB_PageRevision in the sequence.
1577 if ( ! ($next = $this->_revisions->next()) )
1580 $this->_wikidb->_cache->cache_data($next);
1582 $pagename = $next['pagename'];
1583 $version = $next['version'];
1584 $versiondata = $next['versiondata'];
1586 if (!(is_string($pagename) and $pagename != '')) {
1587 trigger_error("empty pagename",E_USER_WARNING);
1590 } else assert(is_string($pagename) and $pagename != '');
1592 if (!is_array($versiondata)) {
1593 trigger_error("empty versiondata",E_USER_WARNING);
1596 } else assert(is_array($versiondata));
1598 if (!($version > 0)) {
1599 trigger_error("invalid version",E_USER_WARNING);
1602 } else assert($version > 0);
1604 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1609 * Release resources held by this iterator.
1611 * The iterator may not be used after free() is called.
1613 * There is no need to call free(), if next() has returned false.
1614 * (I.e. if you iterate through all the revisions in the sequence,
1615 * you do not need to call free() --- you only need to call it
1616 * if you stop before the end of the iterator is reached.)
1621 $this->_revisions->free();
1627 * Data cache used by WikiDB.
1629 * FIXME: Maybe rename this to caching_backend (or some such).
1635 // FIXME: beautify versiondata cache. Cache only limited data?
1637 function WikiDB_cache (&$backend) {
1638 $this->_backend = &$backend;
1640 $this->_pagedata_cache = array();
1641 $this->_versiondata_cache = array();
1642 array_push ($this->_versiondata_cache, array());
1643 $this->_glv_cache = array();
1647 $this->_pagedata_cache = false;
1648 $this->_versiondata_cache = false;
1649 $this->_glv_cache = false;
1652 function get_pagedata($pagename) {
1653 assert(is_string($pagename) && $pagename != '');
1654 $cache = &$this->_pagedata_cache;
1656 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1657 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1658 if (empty($cache[$pagename]))
1659 $cache[$pagename] = array();
1662 return $cache[$pagename];
1665 function update_pagedata($pagename, $newdata) {
1666 assert(is_string($pagename) && $pagename != '');
1668 $this->_backend->update_pagedata($pagename, $newdata);
1670 if (is_array($this->_pagedata_cache[$pagename])) {
1671 $cachedata = &$this->_pagedata_cache[$pagename];
1672 foreach($newdata as $key => $val)
1673 $cachedata[$key] = $val;
1677 function invalidate_cache($pagename) {
1678 unset ($this->_pagedata_cache[$pagename]);
1679 unset ($this->_versiondata_cache[$pagename]);
1680 unset ($this->_glv_cache[$pagename]);
1683 function delete_page($pagename) {
1684 $this->_backend->delete_page($pagename);
1685 unset ($this->_pagedata_cache[$pagename]);
1686 unset ($this->_glv_cache[$pagename]);
1690 function cache_data($data) {
1691 if (isset($data['pagedata']))
1692 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1695 function get_versiondata($pagename, $version, $need_content = false) {
1696 // FIXME: Seriously ugly hackage
1697 if (defined ('USECACHE')){ //temporary - for debugging
1698 assert(is_string($pagename) && $pagename != '');
1699 // there is a bug here somewhere which results in an assertion failure at line 105
1700 // of ArchiveCleaner.php It goes away if we use the next line.
1701 $need_content = true;
1702 $nc = $need_content ? '1':'0';
1703 $cache = &$this->_versiondata_cache;
1704 if (!isset($cache[$pagename][$version][$nc])||
1705 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1706 $cache[$pagename][$version][$nc] =
1707 $this->_backend->get_versiondata($pagename,$version, $need_content);
1708 // If we have retrieved all data, we may as well set the cache for $need_content = false
1710 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1713 $vdata = $cache[$pagename][$version][$nc];
1715 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1718 if ($vdata && !empty($vdata['%pagedata']))
1719 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1723 function set_versiondata($pagename, $version, $data) {
1724 $new = $this->_backend->set_versiondata($pagename, $version, $data);
1726 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1728 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1729 // Is this necessary?
1730 unset($this->_glv_cache[$pagename]);
1733 function update_versiondata($pagename, $version, $data) {
1734 $new = $this->_backend->update_versiondata($pagename, $version, $data);
1736 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1738 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1739 // Is this necessary?
1740 unset($this->_glv_cache[$pagename]);
1743 function delete_versiondata($pagename, $version) {
1744 $new = $this->_backend->delete_versiondata($pagename, $version);
1745 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1746 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1747 unset ($this->_glv_cache[$pagename]);
1750 function get_latest_version($pagename) {
1751 if (defined('USECACHE')){
1752 assert (is_string($pagename) && $pagename != '');
1753 $cache = &$this->_glv_cache;
1754 if (!isset($cache[$pagename])) {
1755 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1756 if (empty($cache[$pagename]))
1757 $cache[$pagename] = 0;
1759 return $cache[$pagename];
1761 return $this->_backend->get_latest_version($pagename);
1767 // $Log: not supported by cvs2svn $
1768 // Revision 1.52 2004/05/06 19:26:16 rurban
1769 // improve stability, trying to find the InlineParser endless loop on sf.net
1771 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1773 // Revision 1.51 2004/05/06 17:30:37 rurban
1774 // CategoryGroup: oops, dos2unix eol
1775 // improved phpwiki_version:
1776 // pre -= .0001 (1.3.10pre: 1030.099)
1777 // -p1 += .001 (1.3.9-p1: 1030.091)
1778 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1779 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1780 // backend->backendType(), backend->database(),
1781 // backend->listOfFields(),
1782 // backend->listOfTables(),
1784 // Revision 1.50 2004/05/04 22:34:25 rurban
1787 // Revision 1.49 2004/05/03 11:16:40 rurban
1788 // fixed sendPageChangeNotification
1789 // subject rewording
1791 // Revision 1.48 2004/04/29 23:03:54 rurban
1792 // fixed sf.net bug #940996
1794 // Revision 1.47 2004/04/29 19:39:44 rurban
1795 // special support for formatted plugins (one-liners)
1796 // like <small><plugin BlaBla ></small>
1797 // iter->asArray() helper for PopularNearby
1798 // db_session for older php's (no &func() allowed)
1800 // Revision 1.46 2004/04/26 20:44:34 rurban
1801 // locking table specific for better databases
1803 // Revision 1.45 2004/04/20 00:06:03 rurban
1804 // themable paging support
1806 // Revision 1.44 2004/04/19 18:27:45 rurban
1807 // Prevent from some PHP5 warnings (ref args, no :: object init)
1808 // php5 runs now through, just one wrong XmlElement object init missing
1809 // Removed unneccesary UpgradeUser lines
1810 // Changed WikiLink to omit version if current (RecentChanges)
1812 // Revision 1.43 2004/04/18 01:34:20 rurban
1813 // protect most_popular from sortby=mtime
1815 // Revision 1.42 2004/04/18 01:11:51 rurban
1816 // more numeric pagename fixes.
1817 // fixed action=upload with merge conflict warnings.
1818 // charset changed from constant to global (dynamic utf-8 switching)
1824 // c-basic-offset: 4
1825 // c-hanging-comment-ender-p: nil
1826 // indent-tabs-mode: nil