2 rcs_id('$Id: WikiDB.php,v 1.17 2002-09-15 03:56:22 dairiki Exp $');
4 //FIXME: arg on get*Revision to hint that content is wanted.
7 * The classes in the file define the interface to the
11 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
15 * Force the creation of a new revision.
16 * @see WikiDB_Page::createRevision()
18 define('WIKIDB_FORCE_CREATE', -1);
20 // FIXME: used for debugging only. Comment out if cache does not work
21 define('USECACHE', 1);
24 * Abstract base class for the database used by PhpWiki.
26 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
27 * turn contain <tt>WikiDB_PageRevision</tt>s.
29 * Conceptually a <tt>WikiDB</tt> contains all possible
30 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
31 * Since all possible pages are already contained in a WikiDB, a call
32 * to WikiDB::getPage() will never fail (barring bugs and
33 * e.g. filesystem or SQL database problems.)
35 * Also each <tt>WikiDB_Page</tt> always contains at least one
36 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
37 * [PageName] here."). This default content has a version number of
40 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
41 * only create new revisions or delete old ones --- one can not modify
42 * an existing revision.
46 * Open a WikiDB database.
48 * This is a static member function. This function inspects its
49 * arguments to determine the proper subclass of WikiDB to
50 * instantiate, and then it instantiates it.
54 * @param hash $dbparams Database configuration parameters.
55 * Some pertinent paramters are:
58 * <dd> The back-end type. Current supported types are:
61 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
64 * <dd> Dba based backend.
68 * <dd> (Used by the SQL backend.)
69 * The DSN specifying which database to connect to.
72 * <dd> Prefix to be prepended to database table (and file names).
75 * <dd> (Used by the dba backend.)
76 * Which directory db files reside in.
79 * <dd> (Used by the dba backend.)
80 * Timeout in seconds for opening (and obtaining lock) on the
84 * <dd> (Used by the dba backend.)
86 * Which dba handler to use. Good choices are probably either
90 * @return WikiDB A WikiDB object.
92 function open ($dbparams) {
93 $dbtype = $dbparams{'dbtype'};
94 include_once("lib/WikiDB/$dbtype.php");
96 $class = 'WikiDB_' . $dbtype;
97 return new $class ($dbparams);
107 function WikiDB ($backend, $dbparams) {
108 $this->_backend = &$backend;
109 $this->_cache = new WikiDB_cache($backend);
111 //FIXME: devel checking.
112 //$this->_backend->check();
116 * Get any user-level warnings about this WikiDB.
118 * Some back-ends, e.g. by default create there data files in the
119 * global /tmp directory. We would like to warn the user when this
120 * happens (since /tmp files tend to get wiped periodically.)
121 * Warnings such as these may be communicated from specific
122 * back-ends through this method.
126 * @return string A warning message (or <tt>false</tt> if there is
129 function genericWarnings() {
134 * Close database connection.
136 * The database may no longer be used after it is closed.
138 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
139 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
140 * which have been obtained from it.
145 $this->_backend->close();
146 $this->_cache->close();
150 * Get a WikiDB_Page from a WikiDB.
152 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
153 * therefore this method never fails.
156 * @param string $pagename Which page to get.
157 * @return WikiDB_Page The requested WikiDB_Page.
159 function getPage($pagename) {
160 assert(is_string($pagename) && $pagename);
161 return new WikiDB_Page($this, $pagename);
166 //function nPages() {
171 * Determine whether page exists (in non-default form).
174 * $is_page = $dbi->isWikiPage($pagename);
178 * $page = $dbi->getPage($pagename);
179 * $current = $page->getCurrentRevision();
180 * $is_page = ! $current->hasDefaultContents();
182 * however isWikiPage may be implemented in a more efficient
183 * manner in certain back-ends.
187 * @param string $pagename string Which page to check.
189 * @return boolean True if the page actually exists with
190 * non-default contents in the WikiDataBase.
192 function isWikiPage ($pagename) {
193 $page = $this->getPage($pagename);
194 $current = $page->getCurrentRevision();
195 return ! $current->hasDefaultContents();
199 * Delete page from the WikiDB.
201 * Deletes all revisions of the page from the WikiDB. Also resets
202 * all page meta-data to the default values.
206 * @param string $pagename Name of page to delete.
208 function deletePage($pagename) {
209 $this->_cache->delete_page($pagename);
210 $this->_backend->set_links($pagename, false);
214 * Retrieve all pages.
216 * Gets the set of all pages with non-default contents.
218 * FIXME: do we need this? I think so. The simple searches
223 * @param boolean $include_defaulted Normally pages whose most
224 * recent revision has empty content are considered to be
225 * non-existant. Unless $include_defaulted is set to true, those
226 * pages will not be returned.
228 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
229 * in the WikiDB which have non-default contents.
231 function getAllPages($include_defaulted = false) {
232 $result = $this->_backend->get_all_pages($include_defaulted);
233 return new WikiDB_PageIterator($this, $result);
239 * Search for pages containing (or not containing) certain words
242 * Pages are returned in alphabetical order whenever it is
243 * practical to do so.
245 * FIXME: should titleSearch and fullSearch be combined? I think so.
248 * @param TextSearchQuery $search A TextSearchQuery object
249 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
250 * @see TextSearchQuery
252 function titleSearch($search) {
253 $result = $this->_backend->text_search($search);
254 return new WikiDB_PageIterator($this, $result);
260 * Search for pages containing (or not containing) certain words
261 * in their entire text (this includes the page content and the
264 * Pages are returned in alphabetical order whenever it is
265 * practical to do so.
269 * @param TextSearchQuery $search A TextSearchQuery object.
270 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
271 * @see TextSearchQuery
273 function fullSearch($search) {
274 $result = $this->_backend->text_search($search, 'full_text');
275 return new WikiDB_PageIterator($this, $result);
279 * Find the pages with the greatest hit counts.
281 * Pages are returned in reverse order by hit count.
285 * @param integer $limit The maximum number of pages to return.
286 * Set $limit to zero to return all pages. If $limit < 0, pages will
287 * be sorted in decreasing order of popularity.
289 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
292 function mostPopular($limit = 20) {
293 $result = $this->_backend->most_popular($limit);
294 return new WikiDB_PageIterator($this, $result);
298 * Find recent page revisions.
300 * Revisions are returned in reverse order by creation time.
304 * @param hash $params This hash is used to specify various optional
308 * <dd> (integer) At most this many revisions will be returned.
310 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
311 * <dt> include_minor_revisions
312 * <dd> (boolean) Also include minor revisions. (Default is not to.)
313 * <dt> exclude_major_revisions
314 * <dd> (boolean) Don't include non-minor revisions.
315 * (Exclude_major_revisions implies include_minor_revisions.)
316 * <dt> include_all_revisions
317 * <dd> (boolean) Return all matching revisions for each page.
318 * Normally only the most recent matching revision is returned
322 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
323 * matching revisions.
325 function mostRecent($params = false) {
326 $result = $this->_backend->most_recent($params);
327 return new WikiDB_PageRevisionIterator($this, $result);
331 * Blog search. (experimental)
333 * Search for blog entries related to a certain page.
335 * FIXME: with pagetype support and perhaps a RegexpSearchQuery
336 * we can make sure we are returning *ONLY* blog pages to the
337 * main routine. Currently, we just use titleSearch which requires
338 * some furher checking in lib/plugin/WikiBlog.php (BAD).
342 * @param string $order 'normal' (chronological) or 'reverse'
343 * @param string $page Find blog entries related to this page.
344 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
346 function blogSearch($page, $order) {
347 //FIXME: implement ordering
349 require_once('lib/TextSearchQuery.php');
350 $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
352 return $this->titleSearch($query);
359 * An abstract base class which representing a wiki-page within a
362 * A WikiDB_Page contains a number (at least one) of
363 * WikiDB_PageRevisions.
367 function WikiDB_Page(&$wikidb, $pagename) {
368 $this->_wikidb = &$wikidb;
369 $this->_pagename = $pagename;
370 assert(!empty($this->_pagename));
374 * Get the name of the wiki page.
378 * @return string The page name.
381 return $this->_pagename;
386 * Delete an old revision of a WikiDB_Page.
388 * Deletes the specified revision of the page.
389 * It is a fatal error to attempt to delete the current revision.
393 * @param integer $version Which revision to delete. (You can also
394 * use a WikiDB_PageRevision object here.)
396 function deleteRevision($version) {
397 $backend = &$this->_wikidb->_backend;
398 $cache = &$this->_wikidb->_cache;
399 $pagename = &$this->_pagename;
401 $version = $this->_coerce_to_version($version);
406 $latestversion = $cache->get_latest_version($pagename);
407 if ($latestversion && $version == $latestversion) {
409 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
410 $pagename), E_USER_ERROR);
414 $cache->delete_versiondata($pagename, $version);
420 * Delete a revision, or possibly merge it with a previous
424 * Suppose an author make a (major) edit to a page. Shortly
425 * after that the same author makes a minor edit (e.g. to fix
426 * spelling mistakes he just made.)
428 * Now some time later, where cleaning out old saved revisions,
429 * and would like to delete his minor revision (since there's
430 * really no point in keeping minor revisions around for a long
433 * Note that the text after the minor revision probably represents
434 * what the author intended to write better than the text after
435 * the preceding major edit.
437 * So what we really want to do is merge the minor edit with the
440 * We will only do this when:
442 * <li>The revision being deleted is a minor one, and
443 * <li>It has the same author as the immediately preceding revision.
446 function mergeRevision($version) {
447 $backend = &$this->_wikidb->_backend;
448 $cache = &$this->_wikidb->_cache;
449 $pagename = &$this->_pagename;
451 $version = $this->_coerce_to_version($version);
456 $latestversion = $backend->get_latest_version($pagename);
457 if ($latestversion && $version == $latestversion) {
459 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
460 $pagename), E_USER_ERROR);
464 $versiondata = $cache->get_versiondata($pagename, $version, true);
466 // Not there? ... we're done!
471 if ($versiondata['is_minor_edit']) {
472 $previous = $backend->get_previous_version($pagename, $version);
474 $prevdata = $cache->get_versiondata($pagename, $previous);
475 if ($prevdata['author_id'] == $versiondata['author_id']) {
476 // This is a minor revision, previous version is
477 // by the same author. We will merge the
479 $cache->update_versiondata($pagename, $previous,
480 array('%content' => $versiondata['%content'],
481 '_supplanted' => $versiondata['_supplanted']));
486 $cache->delete_versiondata($pagename, $version);
492 * Create a new revision of a {@link WikiDB_Page}.
496 * @param int $version Version number for new revision.
497 * To ensure proper serialization of edits, $version must be
498 * exactly one higher than the current latest version.
499 * (You can defeat this check by setting $version to
500 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
502 * @param string $content Contents of new revision.
504 * @param hash $metadata Metadata for new revision.
505 * All values in the hash should be scalars (strings or integers).
507 * @param array $links List of pagenames which this page links to.
509 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
510 * $version was incorrect, returns false
512 function createRevision($version, &$content, $metadata, $links) {
513 $backend = &$this->_wikidb->_backend;
514 $cache = &$this->_wikidb->_cache;
515 $pagename = &$this->_pagename;
519 $latestversion = $backend->get_latest_version($pagename);
520 $newversion = $latestversion + 1;
521 assert($newversion >= 1);
523 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
530 foreach ($data as $key => $val) {
531 if (empty($val) || $key[0] == '_' || $key[0] == '%')
535 assert(!empty($data['author_id']));
536 if (empty($data['author_id']))
537 @$data['author_id'] = $data['author'];
539 if (empty($data['mtime']))
540 $data['mtime'] = time();
542 if ($latestversion) {
543 // Ensure mtimes are monotonic.
544 $pdata = $cache->get_versiondata($pagename, $latestversion);
545 if ($data['mtime'] < $pdata['mtime']) {
546 trigger_error(sprintf(_("%s: Date of new revision is %s"),
547 $pagename,"'non-monotonic'"),
549 $data['orig_mtime'] = $data['mtime'];
550 $data['mtime'] = $pdata['mtime'];
553 // FIXME: use (possibly user specified) 'mtime' time or
555 $cache->update_versiondata($pagename, $latestversion,
556 array('_supplanted' => $data['mtime']));
559 $data['%content'] = &$content;
561 $cache->set_versiondata($pagename, $newversion, $data);
563 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
564 //':deleted' => empty($content)));
566 $backend->set_links($pagename, $links);
570 // FIXME: probably should have some global state information
571 // in the backend to control when to optimize.
572 if (time() % 50 == 0) {
573 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
574 $backend->optimize();
577 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
582 * Get the most recent revision of a page.
586 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
588 function getCurrentRevision() {
589 $backend = &$this->_wikidb->_backend;
590 $cache = &$this->_wikidb->_cache;
591 $pagename = &$this->_pagename;
594 $version = $cache->get_latest_version($pagename);
595 $revision = $this->getRevision($version);
602 * Get a specific revision of a WikiDB_Page.
606 * @param integer $version Which revision to get.
608 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
609 * false if the requested revision does not exist in the {@link WikiDB}.
610 * Note that version zero of any page always exists.
612 function getRevision($version) {
613 $cache = &$this->_wikidb->_cache;
614 $pagename = &$this->_pagename;
617 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
619 assert($version > 0);
620 $vdata = $cache->get_versiondata($pagename, $version);
623 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
628 * Get previous page revision.
630 * This method find the most recent revision before a specified
635 * @param integer $version Find most recent revision before this version.
636 * You can also use a WikiDB_PageRevision object to specify the $version.
638 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
639 * requested revision does not exist in the {@link WikiDB}. Note that
640 * unless $version is greater than zero, a revision (perhaps version zero,
641 * the default revision) will always be found.
643 function getRevisionBefore($version) {
644 $backend = &$this->_wikidb->_backend;
645 $pagename = &$this->_pagename;
647 $version = $this->_coerce_to_version($version);
652 $previous = $backend->get_previous_version($pagename, $version);
653 $revision = $this->getRevision($previous);
660 * Get all revisions of the WikiDB_Page.
662 * This does not include the version zero (default) revision in the
663 * returned revision set.
665 * @return WikiDB_PageRevisionIterator A
666 * WikiDB_PageRevisionIterator containing all revisions of this
667 * WikiDB_Page in reverse order by version number.
669 function getAllRevisions() {
670 $backend = &$this->_wikidb->_backend;
671 $revs = $backend->get_all_revisions($this->_pagename);
672 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
676 * Find pages which link to or are linked from a page.
680 * @param boolean $reversed Which links to find: true for backlinks (default).
682 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
683 * all matching pages.
685 function getLinks($reversed = true) {
686 $backend = &$this->_wikidb->_backend;
687 $result = $backend->get_links($this->_pagename, $reversed);
688 return new WikiDB_PageIterator($this->_wikidb, $result);
692 * Access WikiDB_Page meta-data.
696 * @param string $key Which meta data to get.
697 * Some reserved meta-data keys are:
699 * <dt>'locked'<dd> Is page locked?
700 * <dt>'hits' <dd> Page hit counter.
701 * <dt>'pref' <dd> Users preferences, stored in homepages.
702 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
704 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
705 * page-headers and content.
706 * <dt>'score' <dd> Page score (not yet implement, do we need?)
709 * @return scalar The requested value, or false if the requested data
713 $cache = &$this->_wikidb->_cache;
714 if (!$key || $key[0] == '%')
716 $data = $cache->get_pagedata($this->_pagename);
717 return isset($data[$key]) ? $data[$key] : false;
721 * Get all the page meta-data as a hash.
723 * @return hash The page meta-data.
725 function getMetaData() {
726 $cache = &$this->_wikidb->_cache;
727 $data = $cache->get_pagedata($this->_pagename);
729 foreach ($data as $key => $val) {
730 if (!empty($val) && $key[0] != '%')
737 * Set page meta-data.
742 * @param string $key Meta-data key to set.
743 * @param string $newval New value.
745 function set($key, $newval) {
746 $cache = &$this->_wikidb->_cache;
747 $pagename = &$this->_pagename;
749 assert($key && $key[0] != '%');
751 $data = $cache->get_pagedata($pagename);
753 if (!empty($newval)) {
754 if (!empty($data[$key]) && $data[$key] == $newval)
755 return; // values identical, skip update.
758 if (empty($data[$key]))
759 return; // values identical, skip update.
762 // special handling of sensitive pref data or upgrades from older versions:
763 if ($key == 'pref') {
764 if (!empty($newval['userid'])) unset($newval['userid']);
765 //if ($GLOBALS['user']->isAdmin()) unset($newval['passwd']);
767 $cache->update_pagedata($pagename, array($key => $newval));
771 * Increase page hit count.
773 * FIXME: IS this needed? Probably not.
775 * This is a convenience function.
776 * <pre> $page->increaseHitCount(); </pre>
777 * is functionally identical to
778 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
780 * Note that this method may be implemented in more efficient ways
781 * in certain backends.
785 function increaseHitCount() {
786 @$newhits = $this->get('hits') + 1;
787 $this->set('hits', $newhits);
791 * Return a string representation of the WikiDB_Page
793 * This is really only for debugging.
797 * @return string Printable representation of the WikiDB_Page.
799 function asString () {
801 printf("[%s:%s\n", get_class($this), $this->getName());
802 print_r($this->getMetaData());
804 $strval = ob_get_contents();
812 * @param integer_or_object $version_or_pagerevision
813 * Takes either the version number (and int) or a WikiDB_PageRevision
815 * @return integer The version number.
817 function _coerce_to_version($version_or_pagerevision) {
818 if (method_exists($version_or_pagerevision, "getContent"))
819 $version = $version_or_pagerevision->getVersion();
821 $version = (int) $version_or_pagerevision;
823 assert($version >= 0);
827 function isUserPage ($include_empty = true) {
828 return $this->get('pref') ? true : false;
831 $current = $this->getCurrentRevision();
832 return ! $current->hasDefaultContents();
838 * This class represents a specific revision of a WikiDB_Page within
841 * A WikiDB_PageRevision has read-only semantics. You may only create
842 * new revisions (and delete old ones) --- you cannot modify existing
845 class WikiDB_PageRevision
847 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
848 $versiondata = false)
850 $this->_wikidb = &$wikidb;
851 $this->_pagename = $pagename;
852 $this->_version = $version;
853 $this->_data = $versiondata ? $versiondata : array();
857 * Get the WikiDB_Page which this revision belongs to.
861 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
864 return new WikiDB_Page($this->_wikidb, $this->_pagename);
868 * Get the version number of this revision.
872 * @return integer The version number of this revision.
874 function getVersion() {
875 return $this->_version;
879 * Determine whether this revision has defaulted content.
881 * The default revision (version 0) of each page, as well as any
882 * pages which are created with empty content have their content
883 * defaulted to something like:
885 * Describe [ThisPage] here.
890 * @return boolean Returns true if the page has default content.
892 function hasDefaultContents() {
893 $data = &$this->_data;
894 return empty($data['%content']);
898 * Get the content as an array of lines.
902 * @return array An array of lines.
903 * The lines should contain no trailing white space.
905 function getContent() {
906 return explode("\n", $this->getPackedContent());
910 * Get the pagename of the revision.
914 * @return string pagename.
916 function getPageName() {
917 return $this->_pagename;
921 * Determine whether revision is the latest.
925 * @return boolean True iff the revision is the latest (most recent) one.
927 function isCurrent() {
928 if (!isset($this->_iscurrent)) {
929 $page = $this->getPage();
930 $current = $page->getCurrentRevision();
931 $this->_iscurrent = $this->getVersion() == $current->getVersion();
933 return $this->_iscurrent;
937 * Get the content as a string.
941 * @return string The page content.
942 * Lines are separated by new-lines.
944 function getPackedContent() {
945 $data = &$this->_data;
948 if (empty($data['%content'])) {
949 // Replace empty content with default value.
950 return sprintf(_("Describe %s here."),
951 "[". $this->_pagename ."]");
954 // There is (non-default) content.
955 assert($this->_version > 0);
957 if (!is_string($data['%content'])) {
958 // Content was not provided to us at init time.
959 // (This is allowed because for some backends, fetching
960 // the content may be expensive, and often is not wanted
963 // In any case, now we need to get it.
964 $data['%content'] = $this->_get_content();
965 assert(is_string($data['%content']));
968 return $data['%content'];
971 function _get_content() {
972 $cache = &$this->_wikidb->_cache;
973 $pagename = $this->_pagename;
974 $version = $this->_version;
976 assert($version > 0);
978 $newdata = $cache->get_versiondata($pagename, $version, true);
980 assert(is_string($newdata['%content']));
981 return $newdata['%content'];
984 // else revision has been deleted... What to do?
985 return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
986 $version, $pagename);
991 * Get meta-data for this revision.
996 * @param string $key Which meta-data to access.
998 * Some reserved revision meta-data keys are:
1000 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1001 * The 'mtime' meta-value is normally set automatically by the database
1002 * backend, but it may be specified explicitly when creating a new revision.
1004 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1005 * of a page must be monotonically increasing. If an attempt is
1006 * made to create a new revision with an mtime less than that of
1007 * the preceeding revision, the new revisions timestamp is force
1008 * to be equal to that of the preceeding revision. In that case,
1009 * the originally requested mtime is preserved in 'orig_mtime'.
1010 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1011 * This meta-value is <em>always</em> automatically maintained by the database
1012 * backend. (It is set from the 'mtime' meta-value of the superceding
1013 * revision.) '_supplanted' has a value of 'false' for the current revision.
1015 * FIXME: this could be refactored:
1017 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1019 * <dd> Authenticated author of a page. This is used to identify
1020 * the distinctness of authors when cleaning old revisions from
1022 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1023 * <dt> 'summary' <dd> Short change summary entered by page author.
1026 * Meta-data keys must be valid C identifers (they have to start with a letter
1027 * or underscore, and can contain only alphanumerics and underscores.)
1029 * @return string The requested value, or false if the requested value
1032 function get($key) {
1033 if (!$key || $key[0] == '%')
1035 $data = &$this->_data;
1036 return isset($data[$key]) ? $data[$key] : false;
1040 * Get all the revision page meta-data as a hash.
1042 * @return hash The revision meta-data.
1044 function getMetaData() {
1046 foreach ($this->_data as $key => $val) {
1047 if (!empty($val) && $key[0] != '%')
1055 * Return a string representation of the revision.
1057 * This is really only for debugging.
1061 * @return string Printable representation of the WikiDB_Page.
1063 function asString () {
1065 printf("[%s:%d\n", get_class($this), $this->get('version'));
1066 print_r($this->_data);
1067 echo $this->getPackedContent() . "\n]\n";
1068 $strval = ob_get_contents();
1076 * A class which represents a sequence of WikiDB_Pages.
1078 class WikiDB_PageIterator
1080 function WikiDB_PageIterator(&$wikidb, &$pages) {
1081 $this->_pages = $pages;
1082 $this->_wikidb = &$wikidb;
1086 * Get next WikiDB_Page in sequence.
1090 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1093 if ( ! ($next = $this->_pages->next()) )
1096 $pagename = &$next['pagename'];
1097 if (isset($next['pagedata']))
1098 $this->_wikidb->_cache->cache_data($next);
1100 return new WikiDB_Page($this->_wikidb, $pagename);
1104 * Release resources held by this iterator.
1106 * The iterator may not be used after free() is called.
1108 * There is no need to call free(), if next() has returned false.
1109 * (I.e. if you iterate through all the pages in the sequence,
1110 * you do not need to call free() --- you only need to call it
1111 * if you stop before the end of the iterator is reached.)
1116 $this->_pages->free();
1120 function setSortby ($arg = false) {
1122 $arg = @$_GET['sortby'];
1124 $sortby = substr($arg,1);
1125 $order = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1128 if (is_array($arg)) { // array('mtime' => 'desc')
1135 // available column types to sort by:
1136 // todo: we must provide access methods for the generic dumb/iterator
1137 $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1138 if (in_array($sortby,$this->_types))
1139 $this->_options['sortby'] = $sortby;
1141 trigger_error(fmt("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1142 if (in_array(strtoupper($order),'ASC','DESC'))
1143 $this->_options['order'] = strtoupper($order);
1145 trigger_error(fmt("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1151 * A class which represents a sequence of WikiDB_PageRevisions.
1153 class WikiDB_PageRevisionIterator
1155 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1156 $this->_revisions = $revisions;
1157 $this->_wikidb = &$wikidb;
1161 * Get next WikiDB_PageRevision in sequence.
1165 * @return WikiDB_PageRevision
1166 * The next WikiDB_PageRevision in the sequence.
1169 if ( ! ($next = $this->_revisions->next()) )
1172 $this->_wikidb->_cache->cache_data($next);
1174 $pagename = $next['pagename'];
1175 $version = $next['version'];
1176 $versiondata = $next['versiondata'];
1177 assert(!empty($pagename));
1178 assert(is_array($versiondata));
1179 assert($version > 0);
1181 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1186 * Release resources held by this iterator.
1188 * The iterator may not be used after free() is called.
1190 * There is no need to call free(), if next() has returned false.
1191 * (I.e. if you iterate through all the revisions in the sequence,
1192 * you do not need to call free() --- you only need to call it
1193 * if you stop before the end of the iterator is reached.)
1198 $this->_revisions->free();
1204 * Data cache used by WikiDB.
1206 * FIXME: Maybe rename this to caching_backend (or some such).
1212 // FIXME: beautify versiondata cache. Cache only limited data?
1214 function WikiDB_cache (&$backend) {
1215 $this->_backend = &$backend;
1217 $this->_pagedata_cache = array();
1218 $this->_versiondata_cache = array();
1219 array_push ($this->_versiondata_cache, array());
1220 $this->_glv_cache = array();
1224 $this->_pagedata_cache = false;
1225 $this->_versiondata_cache = false;
1226 $this->_glv_cache = false;
1229 function get_pagedata($pagename) {
1230 assert(is_string($pagename) && $pagename);
1231 $cache = &$this->_pagedata_cache;
1233 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1234 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1235 if (empty($cache[$pagename]))
1236 $cache[$pagename] = array();
1239 return $cache[$pagename];
1242 function update_pagedata($pagename, $newdata) {
1243 assert(is_string($pagename) && $pagename);
1245 $this->_backend->update_pagedata($pagename, $newdata);
1247 if (is_array($this->_pagedata_cache[$pagename])) {
1248 $cachedata = &$this->_pagedata_cache[$pagename];
1249 foreach($newdata as $key => $val)
1250 $cachedata[$key] = $val;
1254 function invalidate_cache($pagename) {
1255 unset ($this->_pagedata_cache[$pagename]);
1256 unset ($this->_versiondata_cache[$pagename]);
1257 unset ($this->_glv_cache[$pagename]);
1260 function delete_page($pagename) {
1261 $this->_backend->delete_page($pagename);
1262 unset ($this->_pagedata_cache[$pagename]);
1263 unset ($this->_glv_cache[$pagename]);
1267 function cache_data($data) {
1268 if (isset($data['pagedata']))
1269 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1272 function get_versiondata($pagename, $version, $need_content = false) {
1273 // FIXME: Seriously ugly hackage
1274 if (defined ('USECACHE')){ //temporary - for debugging
1275 assert(is_string($pagename) && $pagename);
1276 // there is a bug here somewhere which results in an assertion failure at line 105
1277 // of ArchiveCleaner.php It goes away if we use the next line.
1278 $need_content = true;
1279 $nc = $need_content ? '1':'0';
1280 $cache = &$this->_versiondata_cache;
1281 if (!isset($cache[$pagename][$version][$nc])||
1282 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1283 $cache[$pagename][$version][$nc] =
1284 $this->_backend->get_versiondata($pagename,$version, $need_content);
1285 // If we have retrieved all data, we may as well set the cache for $need_content = false
1287 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1290 $vdata = $cache[$pagename][$version][$nc];
1294 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1297 if ($vdata && !empty($vdata['%pagedata']))
1298 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1302 function set_versiondata($pagename, $version, $data) {
1303 $new = $this->_backend->
1304 set_versiondata($pagename, $version, $data);
1306 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1308 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1309 // Is this necessary?
1310 unset($this->_glv_cache[$pagename]);
1314 function update_versiondata($pagename, $version, $data) {
1315 $new = $this->_backend->
1316 update_versiondata($pagename, $version, $data);
1318 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1320 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1321 // Is this necessary?
1322 unset($this->_glv_cache[$pagename]);
1326 function delete_versiondata($pagename, $version) {
1327 $new = $this->_backend->
1328 delete_versiondata($pagename, $version);
1329 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1330 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1331 unset ($this->_glv_cache[$pagename]);
1334 function get_latest_version($pagename) {
1335 if(defined('USECACHE')){
1336 assert (is_string($pagename) && $pagename);
1337 $cache = &$this->_glv_cache;
1338 if (!isset($cache[$pagename])) {
1339 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1340 if (empty($cache[$pagename]))
1341 $cache[$pagename] = 0;
1343 return $cache[$pagename];}
1345 return $this->_backend->get_latest_version($pagename);
1352 * FIXME! Class for externally authenticated users.
1354 * We might have read-only access to the password and/or group membership,
1355 * or we might even be able to update the entries.
1357 * FIXME: This was written before we stored prefs as %pagedata, so
1364 function WikiDB_User($userid, $authlevel = false) {
1365 $this->_authdb = new WikiAuthDB($GLOBALS['DBAuthParams']);
1366 $this->_authmethod = 'AuthDB';
1367 WikiUser::WikiUser($userid, $authlevel);
1371 function getPreferences() {
1372 // external prefs override internal ones?
1373 if (! $this->_authdb->getPrefs() )
1374 if ($pref = WikiUser::getPreferences())
1379 function setPreferences($prefs) {
1380 if (! $this->_authdb->setPrefs($prefs) )
1381 return WikiUser::setPreferences();
1386 return $this->_authdb->exists($this->_userid);
1389 // create user and default user homepage
1390 function createUser ($pref) {
1391 if ($this->exists()) return;
1392 if (! $this->_authdb->createUser($pref)) {
1393 // external auth doesn't allow this.
1394 // do our policies allow local users instead?
1395 return WikiUser::createUser($pref);
1399 function checkPassword($passwd) {
1400 return $this->_authdb->pwcheck($this->userid, $passwd);
1403 function changePassword($passwd) {
1404 if (! $this->mayChangePassword() ) {
1405 trigger_error(sprintf("Attempt to change an external password for '%s'",
1406 $this->_userid), E_USER_ERROR);
1409 return $this->_authdb->changePass($this->userid, $passwd);
1412 function mayChangePassword() {
1413 return $this->_authdb->auth_update;
1420 var $auth_dsn = false, $auth_check = false;
1421 var $auth_crypt_method = 'crypt', $auth_update = false;
1422 var $group_members = false, $user_groups = false;
1423 var $pref_update = false, $pref_select = false;
1426 function WikiAuthDB($DBAuthParams) {
1427 foreach ($DBAuthParams as $key => $value) {
1428 $this->$key = $value;
1430 if (!$this->auth_dsn) {
1431 trigger_error(_("no \$DBAuthParams['dsn'] provided"), E_USER_ERROR);
1434 // compare auth DB to the existing page DB. reuse if it's on the same database.
1435 if (isa($this->_backend, 'WikiDB_backend_PearDB') and
1436 $this->_backend->_dsn == $this->auth_dsn) {
1437 $this->_dbh = &$this->_backend->_dbh;
1438 return $this->_backend;
1440 include_once("lib/WikiDB/SQL.php");
1441 return new WikiDB_SQL($DBAuthParams);
1444 function param_missing ($param) {
1445 trigger_error(sprintf(_("No \$DBAuthParams['%s'] provided."), $param), E_USER_ERROR);
1449 function getPrefs($prefs) {
1450 if ($this->pref_select) {
1451 $statement = $this->_backend->Prepare($this->pref_select);
1452 return unserialize($this->_backend->Execute($statement,
1453 $prefs->get('userid')));
1455 param_missing('pref_select');
1460 function setPrefs($prefs) {
1461 if ($this->pref_write) {
1462 $statement = $this->_backend->Prepare($this->pref_write);
1463 return $this->_backend->Execute($statement,
1464 $prefs->get('userid'), serialize($prefs->_prefs));
1466 param_missing('pref_write');
1471 function createUser ($pref) {
1472 if ($this->user_create) {
1473 $statement = $this->_backend->Prepare($this->user_create);
1474 return $this->_backend->Execute($statement,
1475 $prefs->get('userid'), serialize($prefs->_prefs));
1477 param_missing('user_create');
1482 function exists($userid) {
1483 if ($this->user_check) {
1484 $statement = $this->_backend->Prepare($this->user_check);
1485 return $this->_backend->Execute($statement, $prefs->get('userid'));
1487 param_missing('user_check');
1492 function pwcheck($userid, $pass) {
1493 if ($this->auth_check) {
1494 $statement = $this->_backend->Prepare($this->auth_check);
1495 return $this->_backend->Execute($statement, $userid, $pass);
1497 param_missing('auth_check');
1506 // c-basic-offset: 4
1507 // c-hanging-comment-ender-p: nil
1508 // indent-tabs-mode: nil