2 rcs_id('$Id: WikiDB.php,v 1.93 2004-10-14 17:17:57 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
25 if (!defined('USECACHE'))
26 define('USECACHE', 1);
29 * Abstract base class for the database used by PhpWiki.
31 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
32 * turn contain <tt>WikiDB_PageRevision</tt>s.
34 * Conceptually a <tt>WikiDB</tt> contains all possible
35 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
36 * Since all possible pages are already contained in a WikiDB, a call
37 * to WikiDB::getPage() will never fail (barring bugs and
38 * e.g. filesystem or SQL database problems.)
40 * Also each <tt>WikiDB_Page</tt> always contains at least one
41 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
42 * [PageName] here."). This default content has a version number of
45 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
46 * only create new revisions or delete old ones --- one can not modify
47 * an existing revision.
51 * Open a WikiDB database.
53 * This is a static member function. This function inspects its
54 * arguments to determine the proper subclass of WikiDB to
55 * instantiate, and then it instantiates it.
59 * @param hash $dbparams Database configuration parameters.
60 * Some pertinent paramters are:
63 * <dd> The back-end type. Current supported types are:
66 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
67 * library. (More stable and conservative)
69 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
71 * <dd> Dba based backend. The default and by far the fastest.
79 * <dd> (Used by the SQL and ADODB backends.)
80 * The DSN specifying which database to connect to.
83 * <dd> Prefix to be prepended to database tables (and file names).
86 * <dd> (Used by the dba backend.)
87 * Which directory db files reside in.
90 * <dd> Used only by the dba backend so far.
91 * And: When optimizing mysql it closes timed out mysql processes.
92 * otherwise only used for dba: Timeout in seconds for opening (and
93 * obtaining lock) on the dbm file.
96 * <dd> (Used by the dba backend.)
98 * Which dba handler to use. Good choices are probably either
102 * @return WikiDB A WikiDB object.
104 function open ($dbparams) {
105 $dbtype = $dbparams{'dbtype'};
106 include_once("lib/WikiDB/$dbtype.php");
108 $class = 'WikiDB_' . $dbtype;
109 return new $class ($dbparams);
119 function WikiDB (&$backend, $dbparams) {
120 $this->_backend = &$backend;
121 // don't do the following with the auth_dsn!
122 if (isset($dbparams['auth_dsn'])) return;
124 $this->_cache = new WikiDB_cache($backend);
125 // If the database doesn't yet have a timestamp, initialize it now.
126 $GLOBALS['request']->_dbi = $this;
127 if ($this->get('_timestamp') === false)
130 //FIXME: devel checking.
131 //$this->_backend->check();
135 * Get any user-level warnings about this WikiDB.
137 * Some back-ends, e.g. by default create there data files in the
138 * global /tmp directory. We would like to warn the user when this
139 * happens (since /tmp files tend to get wiped periodically.)
140 * Warnings such as these may be communicated from specific
141 * back-ends through this method.
145 * @return string A warning message (or <tt>false</tt> if there is
148 function genericWarnings() {
153 * Close database connection.
155 * The database may no longer be used after it is closed.
157 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
158 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
159 * which have been obtained from it.
164 $this->_backend->close();
165 $this->_cache->close();
169 * Get a WikiDB_Page from a WikiDB.
171 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
172 * therefore this method never fails.
175 * @param string $pagename Which page to get.
176 * @return WikiDB_Page The requested WikiDB_Page.
178 function getPage($pagename) {
179 static $error_displayed = false;
180 $pagename = (string) $pagename;
182 if ($pagename === '') {
183 if ($error_displayed) return false;
184 $error_displayed = true;
185 if (function_exists("xdebug_get_function_stack"))
186 var_dump(xdebug_get_function_stack());
187 trigger_error("empty pagename",E_USER_WARNING);
191 assert($pagename != '');
193 return new WikiDB_Page(/*$this,*/ $pagename);
197 * Determine whether page exists (in non-default form).
200 * $is_page = $dbi->isWikiPage($pagename);
204 * $page = $dbi->getPage($pagename);
205 * $current = $page->getCurrentRevision();
206 * $is_page = ! $current->hasDefaultContents();
208 * however isWikiPage may be implemented in a more efficient
209 * manner in certain back-ends.
213 * @param string $pagename string Which page to check.
215 * @return boolean True if the page actually exists with
216 * non-default contents in the WikiDataBase.
218 function isWikiPage ($pagename) {
219 $page = $this->getPage($pagename);
220 return $page->exists();
224 * Delete page from the WikiDB.
226 * Deletes all revisions of the page from the WikiDB. Also resets
227 * all page meta-data to the default values.
231 * @param string $pagename Name of page to delete.
233 function deletePage($pagename) {
234 $this->_cache->delete_page($pagename);
236 /* Generate notification emails? */
237 if (! $this->isWikiPage($pagename) ) {
238 $notify = $this->get('notify');
239 if (!empty($notify) and is_array($notify)) {
240 //TODO: deferr it (quite a massive load if you remove some pages).
241 //TODO: notification class which catches all changes,
242 // and decides at the end of the request what to mail. (type, page, who, what, users, emails)
243 // could be used for PageModeration also.
244 list($emails, $userids) = WikiDB_Page::getPageChangeEmails($notify);
245 if (!empty($emails)) {
246 $editedby = sprintf(_("Edited by: %s"), $GLOBALS['request']->UserName()); // Todo: host_id
247 $emails = join(',', $emails);
248 $subject = sprintf(_("Page deleted %s"), $pagename);
249 if (mail($emails,"[".WIKI_NAME."] ".$subject,
252 "Deleted $pagename"))
253 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
254 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
256 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
257 $this->_pagename, join(',',$userids)), E_USER_WARNING);
262 //How to create a RecentChanges entry with explaining summary?
264 $page = $this->getPage($pagename);
265 $current = $page->getCurrentRevision();
266 $meta = $current->_data;
267 $version = $current->getVersion();
268 $meta['summary'] = _("removed");
269 $page->save($current->getPackedContent(), $version + 1, $meta);
274 * Retrieve all pages.
276 * Gets the set of all pages with non-default contents.
280 * @param boolean $include_defaulted Normally pages whose most
281 * recent revision has empty content are considered to be
282 * non-existant. Unless $include_defaulted is set to true, those
283 * pages will not be returned.
285 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
286 * in the WikiDB which have non-default contents.
288 function getAllPages($include_empty=false, $sortby=false, $limit=false) {
289 // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
290 $mem = ini_get("memory_limit");
291 if (ini_get("memory_limit") and !$limit and !isWindows() and !check_php_version(4,3)) {
293 $GLOBALS['request']->setArg('limit',$limit);
294 $GLOBALS['request']->setArg('paging','auto');
296 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit);
297 return new WikiDB_PageIterator($this, $result);
301 //function nPages() {
304 * Yes, for paging. Renamed.
306 * filter = true: include also empty pages
307 * exclude: comma-seperated list pagenames
309 function numPages($filter=false, $exclude='') {
310 if (method_exists($this->_backend, 'numPages'))
311 // FIXME: currently are all args ignored.
312 $count = $this->_backend->numPages($filter, $exclude);
314 // FIXME: exclude ignored.
315 $iter = $this->getAllPages($filter);
316 $count = $iter->count();
325 * Search for pages containing (or not containing) certain words
328 * Pages are returned in alphabetical order whenever it is
329 * practical to do so.
331 * FIXME: should titleSearch and fullSearch be combined? I think so.
334 * @param TextSearchQuery $search A TextSearchQuery object
335 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
336 * @see TextSearchQuery
338 function titleSearch($search) {
339 $result = $this->_backend->text_search($search);
340 return new WikiDB_PageIterator($this, $result);
346 * Search for pages containing (or not containing) certain words
347 * in their entire text (this includes the page content and the
350 * Pages are returned in alphabetical order whenever it is
351 * practical to do so.
355 * @param TextSearchQuery $search A TextSearchQuery object.
356 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
357 * @see TextSearchQuery
359 function fullSearch($search) {
360 $result = $this->_backend->text_search($search, 'full_text');
361 return new WikiDB_PageIterator($this, $result);
365 * Find the pages with the greatest hit counts.
367 * Pages are returned in reverse order by hit count.
371 * @param integer $limit The maximum number of pages to return.
372 * Set $limit to zero to return all pages. If $limit < 0, pages will
373 * be sorted in decreasing order of popularity.
375 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
378 function mostPopular($limit = 20, $sortby = '-hits') {
379 $result = $this->_backend->most_popular($limit, $sortby);
380 return new WikiDB_PageIterator($this, $result);
384 * Find recent page revisions.
386 * Revisions are returned in reverse order by creation time.
390 * @param hash $params This hash is used to specify various optional
394 * <dd> (integer) At most this many revisions will be returned.
396 * <dd> (integer) Only revisions since this time (unix-timestamp) will be returned.
397 * <dt> include_minor_revisions
398 * <dd> (boolean) Also include minor revisions. (Default is not to.)
399 * <dt> exclude_major_revisions
400 * <dd> (boolean) Don't include non-minor revisions.
401 * (Exclude_major_revisions implies include_minor_revisions.)
402 * <dt> include_all_revisions
403 * <dd> (boolean) Return all matching revisions for each page.
404 * Normally only the most recent matching revision is returned
408 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
409 * matching revisions.
411 function mostRecent($params = false) {
412 $result = $this->_backend->most_recent($params);
413 return new WikiDB_PageRevisionIterator($this, $result);
417 * Call the appropriate backend method.
420 * @param string $from Page to rename
421 * @param string $to New name
422 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
423 * @return boolean true or false
425 function renamePage($from, $to, $updateWikiLinks = false) {
426 assert(is_string($from) && $from != '');
427 assert(is_string($to) && $to != '');
429 if (method_exists($this->_backend,'rename_page')) {
430 $oldpage = $this->getPage($from);
431 $newpage = $this->getPage($to);
432 //update all WikiLinks in existing pages
433 //non-atomic! i.e. if rename fails the links are not undone
434 if ($updateWikiLinks) {
435 require_once('lib/plugin/WikiAdminSearchReplace.php');
436 $links = $oldpage->getBackLinks();
437 while ($linked_page = $links->next()) {
438 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
440 $links = $newpage->getBackLinks();
441 while ($linked_page = $links->next()) {
442 WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
445 if ($oldpage->exists() and ! $newpage->exists()) {
446 if ($result = $this->_backend->rename_page($from, $to)) {
447 //create a RecentChanges entry with explaining summary
448 $page = $this->getPage($to);
449 $current = $page->getCurrentRevision();
450 $meta = $current->_data;
451 $version = $current->getVersion();
452 $meta['summary'] = sprintf(_("renamed from %s"), $from);
453 $page->save($current->getPackedContent(), $version + 1, $meta);
455 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
456 // if a version 0 exists try it also.
457 $result = $this->_backend->rename_page($from, $to);
460 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
463 /* Generate notification emails? */
465 $notify = $this->get('notify');
466 if (!empty($notify) and is_array($notify)) {
467 list($emails, $userids) = WikiDB_Page::getPageChangeEmails($notify);
468 if (!empty($emails)) {
469 $editedby = sprintf(_("Edited by: %s"), $meta['author']) . ' ' . $meta['author_id'];
470 $emails = join(',',$emails);
471 $subject = sprintf(_("Page rename %s to %s"),$from,$to);
472 $link = WikiURL($to, true);
473 if (mail($emails,"[".WIKI_NAME."] ".$subject,
477 "Renamed $from to $to"))
478 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
479 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
481 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
482 $this->_pagename, join(',',$userids)), E_USER_WARNING);
489 /** Get timestamp when database was last modified.
491 * @return string A string consisting of two integers,
492 * separated by a space. The first is the time in
493 * unix timestamp format, the second is a modification
494 * count for the database.
496 * The idea is that you can cast the return value to an
497 * int to get a timestamp, or you can use the string value
498 * as a good hash for the entire database.
500 function getTimestamp() {
501 $ts = $this->get('_timestamp');
502 return sprintf("%d %d", $ts[0], $ts[1]);
506 * Update the database timestamp.
510 $ts = $this->get('_timestamp');
511 $this->set('_timestamp', array(time(), $ts[1] + 1));
516 * Access WikiDB global meta-data.
518 * NOTE: this is currently implemented in a hackish and
519 * not very efficient manner.
523 * @param string $key Which meta data to get.
524 * Some reserved meta-data keys are:
526 * <dt>'_timestamp' <dd> Data used by getTimestamp().
529 * @return scalar The requested value, or false if the requested data
533 if (!$key || $key[0] == '%')
536 * Hack Alert: We can use any page (existing or not) to store
537 * this data (as long as we always use the same one.)
539 $gd = $this->getPage('global_data');
540 $data = $gd->get('__global');
542 if ($data && isset($data[$key]))
549 * Set global meta-data.
551 * NOTE: this is currently implemented in a hackish and
552 * not very efficient manner.
557 * @param string $key Meta-data key to set.
558 * @param string $newval New value.
560 function set($key, $newval) {
561 if (!$key || $key[0] == '%')
564 $gd = $this->getPage('global_data');
566 $data = $gd->get('__global');
573 $data[$key] = $newval;
575 $gd->set('__global', $data);
578 // SQL result: for simple select or create/update queries
579 // returns the database specific resource type
580 function genericSqlQuery($sql) {
582 if ($DBParams['dbtype'] == 'SQL') {
583 $result = $this->_backend->_dbh->query($sql);
584 if (DB::isError($result)) {
585 $msg = $result->getMessage();
586 trigger_error("SQL Error: ".DB::errorMessage($result), E_USER_WARNING);
591 } elseif ($DBParams['dbtype'] == 'ADODB') {
592 if (!($result = $this->_backend->_dbh->Execute($sql))) {
593 trigger_error("SQL Error: ".$this->_backend->_dbh->ErrorMsg(), E_USER_WARNING);
602 // SQL iter: for simple select or create/update queries
603 // returns the generic iterator object (count,next)
604 function genericSqlIter($sql) {
605 $result = $this->genericSqlQuery($sql);
606 if ($this->getParam('dbtype') == 'ADODB') {
607 return new WikiDB_backend_ADODB_generic_iter($this->_backend, $result);
609 return new WikiDB_backend_PearDB_generic_iter($this->_backend, $result);
613 function getParam($param) {
615 if (isset($DBParams[$param])) return $DBParams[$param];
616 elseif ($param == 'prefix') return '';
620 function getAuthParam($param) {
621 global $DBAuthParams;
622 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
623 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
624 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
631 * An abstract base class which representing a wiki-page within a
634 * A WikiDB_Page contains a number (at least one) of
635 * WikiDB_PageRevisions.
639 function WikiDB_Page(/*&$wikidb,*/ $pagename) {
640 //$this->_wikidb = &$wikidb;
641 $this->_pagename = $pagename;
643 if (!(is_string($pagename) and $pagename != '')) {
644 if (function_exists("xdebug_get_function_stack")) {
645 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
648 trigger_error("empty pagename", E_USER_WARNING);
652 assert(is_string($pagename) and $pagename != '');
656 * Get the name of the wiki page.
660 * @return string The page name.
663 return $this->_pagename;
666 // To reduce the memory footprint for larger sets of pagelists,
667 // we don't cache the content (only true or false) and
668 // we purge the pagedata (_cached_html) also
670 $current = $this->getCurrentRevision(false);
671 unset($GLOBALS['request']->_dbi->_cache->_pagedata_cache[$this->_pagename]);
672 $exists = ! $current->hasDefaultContents();
673 unset($current->_data->{'%pagedata'});
678 * Delete an old revision of a WikiDB_Page.
680 * Deletes the specified revision of the page.
681 * It is a fatal error to attempt to delete the current revision.
685 * @param integer $version Which revision to delete. (You can also
686 * use a WikiDB_PageRevision object here.)
688 function deleteRevision($version) {
689 $backend = &$GLOBALS['request']->_dbi->_backend;
690 $cache = &$GLOBALS['request']->_dbi->_cache;
691 $pagename = &$this->_pagename;
693 $version = $this->_coerce_to_version($version);
697 $backend->lock(array('page','version'));
698 $latestversion = $cache->get_latest_version($pagename);
699 if ($latestversion && $version == $latestversion) {
700 $backend->unlock(array('page','version'));
701 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
702 $pagename), E_USER_ERROR);
706 $cache->delete_versiondata($pagename, $version);
707 $backend->unlock(array('page','version'));
711 * Delete a revision, or possibly merge it with a previous
715 * Suppose an author make a (major) edit to a page. Shortly
716 * after that the same author makes a minor edit (e.g. to fix
717 * spelling mistakes he just made.)
719 * Now some time later, where cleaning out old saved revisions,
720 * and would like to delete his minor revision (since there's
721 * really no point in keeping minor revisions around for a long
724 * Note that the text after the minor revision probably represents
725 * what the author intended to write better than the text after
726 * the preceding major edit.
728 * So what we really want to do is merge the minor edit with the
731 * We will only do this when:
733 * <li>The revision being deleted is a minor one, and
734 * <li>It has the same author as the immediately preceding revision.
737 function mergeRevision($version) {
738 $backend = &$GLOBALS['request']->_dbi->_backend;
739 $cache = &$GLOBALS['request']->_dbi->_cache;
740 $pagename = &$this->_pagename;
742 $version = $this->_coerce_to_version($version);
746 $backend->lock(array('version'));
747 $latestversion = $backend->get_latest_version($pagename);
748 if ($latestversion && $version == $latestversion) {
749 $backend->unlock(array('version'));
750 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
751 $pagename), E_USER_ERROR);
755 $versiondata = $cache->get_versiondata($pagename, $version, true);
757 // Not there? ... we're done!
758 $backend->unlock(array('version'));
762 if ($versiondata['is_minor_edit']) {
763 $previous = $backend->get_previous_version($pagename, $version);
765 $prevdata = $cache->get_versiondata($pagename, $previous);
766 if ($prevdata['author_id'] == $versiondata['author_id']) {
767 // This is a minor revision, previous version is
768 // by the same author. We will merge the
770 $cache->update_versiondata($pagename, $previous,
771 array('%content' => $versiondata['%content'],
772 '_supplanted' => $versiondata['_supplanted']));
777 $cache->delete_versiondata($pagename, $version);
778 $backend->unlock(array('version'));
783 * Create a new revision of a {@link WikiDB_Page}.
787 * @param int $version Version number for new revision.
788 * To ensure proper serialization of edits, $version must be
789 * exactly one higher than the current latest version.
790 * (You can defeat this check by setting $version to
791 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
793 * @param string $content Contents of new revision.
795 * @param hash $metadata Metadata for new revision.
796 * All values in the hash should be scalars (strings or integers).
798 * @param array $links List of pagenames which this page links to.
800 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
801 * $version was incorrect, returns false
803 function createRevision($version, &$content, $metadata, $links) {
804 $backend = &$GLOBALS['request']->_dbi->_backend;
805 $cache = &$GLOBALS['request']->_dbi->_cache;
806 $pagename = &$this->_pagename;
808 $backend->lock(array('version','page','recent','link','nonempty'));
810 $latestversion = $backend->get_latest_version($pagename);
811 $newversion = $latestversion + 1;
812 assert($newversion >= 1);
814 if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
815 $backend->unlock(array('version','page','recent','link','nonempty'));
821 foreach ($data as $key => $val) {
822 if (empty($val) || $key[0] == '_' || $key[0] == '%')
826 assert(!empty($data['author']));
827 if (empty($data['author_id']))
828 @$data['author_id'] = $data['author'];
830 if (empty($data['mtime']))
831 $data['mtime'] = time();
833 if ($latestversion) {
834 // Ensure mtimes are monotonic.
835 $pdata = $cache->get_versiondata($pagename, $latestversion);
836 if ($data['mtime'] < $pdata['mtime']) {
837 trigger_error(sprintf(_("%s: Date of new revision is %s"),
838 $pagename,"'non-monotonic'"),
840 $data['orig_mtime'] = $data['mtime'];
841 $data['mtime'] = $pdata['mtime'];
844 // FIXME: use (possibly user specified) 'mtime' time or
846 $cache->update_versiondata($pagename, $latestversion,
847 array('_supplanted' => $data['mtime']));
850 $data['%content'] = &$content;
852 $cache->set_versiondata($pagename, $newversion, $data);
854 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
855 //':deleted' => empty($content)));
857 $backend->set_links($pagename, $links);
859 $backend->unlock(array('version','page','recent','link','nonempty'));
861 return new WikiDB_PageRevision($GLOBALS['request']->_dbi, $pagename, $newversion,
865 /** A higher-level interface to createRevision.
867 * This takes care of computing the links, and storing
868 * a cached version of the transformed wiki-text.
870 * @param string $wikitext The page content.
872 * @param int $version Version number for new revision.
873 * To ensure proper serialization of edits, $version must be
874 * exactly one higher than the current latest version.
875 * (You can defeat this check by setting $version to
876 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
878 * @param hash $meta Meta-data for new revision.
880 function save(&$wikitext, $version, $meta) {
881 $formatted = new TransformedText($this, $wikitext, $meta);
882 $type = $formatted->getType();
883 $meta['pagetype'] = $type->getName();
884 $links = $formatted->getWikiPageLinks();
886 $backend = &$GLOBALS['request']->_dbi->_backend;
887 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
889 if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
890 $this->set('_cached_html', $formatted->pack());
892 // FIXME: probably should have some global state information
893 // in the backend to control when to optimize.
895 // We're doing this here rather than in createRevision because
896 // postgres can't optimize while locked.
897 if (DEBUG or (time() % 50 == 0)) {
898 if ($backend->optimize())
899 trigger_error(_("Optimizing database"), E_USER_NOTICE);
902 /* Generate notification emails? */
903 if (isa($newrevision, 'wikidb_pagerevision')) {
904 // Save didn't fail because of concurrent updates.
905 $notify = $GLOBALS['request']->_dbi->get('notify');
906 if (!empty($notify) and is_array($notify)) {
907 list($emails, $userids) = $this->getPageChangeEmails($notify);
908 if (!empty($emails)) {
909 if (@is_array($GLOBALS['deferredPageChangeNotification'])) {
910 $GLOBALS['deferredPageChangeNotification'][] = array($this->_pagename, $emails, $userids);
912 $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
918 $newrevision->_transformedContent = $formatted;
922 function getPageChangeEmails($notify) {
923 $emails = array(); $userids = array();
924 foreach ($notify as $page => $users) {
925 if (glob_match($page, $this->_pagename)) {
926 foreach ($users as $userid => $user) {
927 if (!empty($user['verified']) and !empty($user['email'])) {
928 $emails[] = $user['email'];
929 $userids[] = $userid;
930 } elseif (!empty($user['email'])) {
932 // do a dynamic emailVerified check update
933 $u = $request->getUser();
934 if ($u->UserName() == $userid) {
935 if ($request->_prefs->get('emailVerified')) {
936 $emails[] = $user['email'];
937 $userids[] = $userid;
938 $notify[$page][$userid]['verified'] = 1;
939 $request->_dbi->set('notify', $notify);
942 $u = WikiUser($userid);
943 $u->getPreferences();
944 if ($u->_prefs->get('emailVerified')) {
945 $emails[] = $user['email'];
946 $userids[] = $userid;
947 $notify[$page][$userid]['verified'] = 1;
948 $request->_dbi->set('notify', $notify);
951 // ignore verification
954 if (!in_array($user['email'],$emails))
955 $emails[] = $user['email'];
962 $emails = array_unique($emails);
963 $userids = array_unique($userids);
964 return array($emails,$userids);
967 function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
968 $backend = &$GLOBALS['request']->_dbi->_backend;
969 $subject = _("Page change").' '.$this->_pagename;
970 $previous = $backend->get_previous_version($this->_pagename, $version);
971 if (!isset($meta['mtime'])) $meta['mtime'] = time();
973 $difflink = WikiURL($this->_pagename, array('action'=>'diff'),true);
974 $cache = &$GLOBALS['request']->_dbi->_cache;
975 $this_content = explode("\n", $wikitext);
976 $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
977 if (empty($prevdata['%content']))
978 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
979 $other_content = explode("\n", $prevdata['%content']);
981 include_once("lib/diff.php");
982 $diff2 = new Diff($other_content, $this_content);
983 $context_lines = max(4, count($other_content) + 1,
984 count($this_content) + 1);
985 $fmt = new UnifiedDiffFormatter($context_lines);
986 $content = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n";
987 $content .= $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
988 $content .= $fmt->format($diff2);
991 $difflink = WikiURL($this->_pagename,array(),true);
992 $content = $this->_pagename . " " . $version . " " . Iso8601DateTime($meta['mtime']) . "\n";
993 $content .= _("New Page");
995 $editedby = sprintf(_("Edited by: %s"), $meta['author']);
996 $emails = join(',',$emails);
997 if (mail($emails,"[".WIKI_NAME."] ".$subject,
1002 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
1003 $this->_pagename, join(',',$userids)), E_USER_NOTICE);
1005 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
1006 $this->_pagename, join(',',$userids)), E_USER_WARNING);
1010 * Get the most recent revision of a page.
1014 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1016 function getCurrentRevision($need_content = true) {
1017 $backend = &$GLOBALS['request']->_dbi->_backend;
1018 $cache = &$GLOBALS['request']->_dbi->_cache;
1019 $pagename = &$this->_pagename;
1021 // Prevent deadlock in case of memory exhausted errors
1022 // Pure selection doesn't really need locking here.
1023 // sf.net bug#927395
1024 // I know it would be better, but with lots of pages this deadlock is more
1025 // severe than occasionally get not the latest revision.
1027 $version = $cache->get_latest_version($pagename);
1028 // getRevision gets the content also!
1029 $revision = $this->getRevision($version, $need_content);
1030 //$backend->unlock();
1036 * Get a specific revision of a WikiDB_Page.
1040 * @param integer $version Which revision to get.
1042 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1043 * false if the requested revision does not exist in the {@link WikiDB}.
1044 * Note that version zero of any page always exists.
1046 function getRevision($version, $need_content=true) {
1047 $cache = &$GLOBALS['request']->_dbi->_cache;
1048 $pagename = &$this->_pagename;
1050 if (! $version ) // 0 or false
1051 return new WikiDB_PageRevision($GLOBALS['request']->_dbi, $pagename, 0);
1053 assert($version > 0);
1054 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1057 return new WikiDB_PageRevision($GLOBALS['request']->_dbi, $pagename, $version,
1062 * Get previous page revision.
1064 * This method find the most recent revision before a specified
1069 * @param integer $version Find most recent revision before this version.
1070 * You can also use a WikiDB_PageRevision object to specify the $version.
1072 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1073 * requested revision does not exist in the {@link WikiDB}. Note that
1074 * unless $version is greater than zero, a revision (perhaps version zero,
1075 * the default revision) will always be found.
1077 function getRevisionBefore($version, $need_content=true) {
1078 $backend = &$GLOBALS['request']->_dbi->_backend;
1079 $pagename = &$this->_pagename;
1081 $version = $this->_coerce_to_version($version);
1086 $previous = $backend->get_previous_version($pagename, $version);
1087 $revision = $this->getRevision($previous, $need_content);
1088 //$backend->unlock();
1094 * Get all revisions of the WikiDB_Page.
1096 * This does not include the version zero (default) revision in the
1097 * returned revision set.
1099 * @return WikiDB_PageRevisionIterator A
1100 * WikiDB_PageRevisionIterator containing all revisions of this
1101 * WikiDB_Page in reverse order by version number.
1103 function getAllRevisions() {
1104 $backend = &$GLOBALS['request']->_dbi->_backend;
1105 $revs = $backend->get_all_revisions($this->_pagename);
1106 return new WikiDB_PageRevisionIterator($GLOBALS['request']->_dbi, $revs);
1110 * Find pages which link to or are linked from a page.
1114 * @param boolean $reversed Which links to find: true for backlinks (default).
1116 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1117 * all matching pages.
1119 function getLinks($reversed = true) {
1120 $backend = &$GLOBALS['request']->_dbi->_backend;
1121 $result = $backend->get_links($this->_pagename, $reversed);
1122 return new WikiDB_PageIterator($GLOBALS['request']->_dbi, $result);
1126 * All Links from other pages to this page.
1128 function getBackLinks() {
1129 return $this->getLinks(true);
1132 * Forward Links: All Links from this page to other pages.
1134 function getPageLinks() {
1135 return $this->getLinks(false);
1139 * Access WikiDB_Page meta-data.
1143 * @param string $key Which meta data to get.
1144 * Some reserved meta-data keys are:
1146 * <dt>'locked'<dd> Is page locked?
1147 * <dt>'hits' <dd> Page hit counter.
1148 * <dt>'pref' <dd> Users preferences, stored in homepages.
1149 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1150 * E.g. "owner.users"
1151 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1152 * page-headers and content.
1153 * <dt>'score' <dd> Page score (not yet implement, do we need?)
1156 * @return scalar The requested value, or false if the requested data
1159 function get($key) {
1160 $cache = &$GLOBALS['request']->_dbi->_cache;
1161 if (!$key || $key[0] == '%')
1163 $data = $cache->get_pagedata($this->_pagename);
1164 return isset($data[$key]) ? $data[$key] : false;
1168 * Get all the page meta-data as a hash.
1170 * @return hash The page meta-data.
1172 function getMetaData() {
1173 $cache = &$GLOBALS['request']->_dbi->_cache;
1174 $data = $cache->get_pagedata($this->_pagename);
1176 foreach ($data as $key => $val) {
1177 if (/*!empty($val) &&*/ $key[0] != '%')
1184 * Set page meta-data.
1189 * @param string $key Meta-data key to set.
1190 * @param string $newval New value.
1192 function set($key, $newval) {
1193 $cache = &$GLOBALS['request']->_dbi->_cache;
1194 $pagename = &$this->_pagename;
1196 assert($key && $key[0] != '%');
1198 $data = $cache->get_pagedata($pagename);
1200 if (!empty($newval)) {
1201 if (!empty($data[$key]) && $data[$key] == $newval)
1202 return; // values identical, skip update.
1205 if (empty($data[$key]))
1206 return; // values identical, skip update.
1209 $cache->update_pagedata($pagename, array($key => $newval));
1213 * Increase page hit count.
1215 * FIXME: IS this needed? Probably not.
1217 * This is a convenience function.
1218 * <pre> $page->increaseHitCount(); </pre>
1219 * is functionally identical to
1220 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1222 * Note that this method may be implemented in more efficient ways
1223 * in certain backends.
1227 function increaseHitCount() {
1228 @$newhits = $this->get('hits') + 1;
1229 $this->set('hits', $newhits);
1233 * Return a string representation of the WikiDB_Page
1235 * This is really only for debugging.
1239 * @return string Printable representation of the WikiDB_Page.
1241 function asString () {
1243 printf("[%s:%s\n", get_class($this), $this->getName());
1244 print_r($this->getMetaData());
1246 $strval = ob_get_contents();
1254 * @param integer_or_object $version_or_pagerevision
1255 * Takes either the version number (and int) or a WikiDB_PageRevision
1257 * @return integer The version number.
1259 function _coerce_to_version($version_or_pagerevision) {
1260 if (method_exists($version_or_pagerevision, "getContent"))
1261 $version = $version_or_pagerevision->getVersion();
1263 $version = (int) $version_or_pagerevision;
1265 assert($version >= 0);
1269 function isUserPage ($include_empty = true) {
1270 if ($include_empty) {
1271 $current = $this->getCurrentRevision(false);
1272 if ($current->hasDefaultContents()) {
1276 return $this->get('pref') ? true : false;
1279 // May be empty. Either the stored owner (/Chown), or the first authorized author
1280 function getOwner() {
1281 if ($owner = $this->get('owner'))
1282 return ($owner == "The PhpWiki programming team") ? ADMIN_USER : $owner;
1283 // check all revisions forwards for the first author_id
1284 $backend = &$GLOBALS['request']->_dbi->_backend;
1285 $pagename = &$this->_pagename;
1286 $latestversion = $backend->get_latest_version($pagename);
1287 for ($v=1; $v <= $latestversion; $v++) {
1288 $rev = $this->getRevision($v,false);
1289 if ($rev and $owner = $rev->get('author_id')) {
1290 return ($owner == "The PhpWiki programming team") ? ADMIN_USER : $owner;
1296 // The authenticated author of the first revision or empty if not authenticated then.
1297 function getCreator() {
1298 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1302 // The authenticated author of the current revision.
1303 function getAuthor() {
1304 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1311 * This class represents a specific revision of a WikiDB_Page within
1314 * A WikiDB_PageRevision has read-only semantics. You may only create
1315 * new revisions (and delete old ones) --- you cannot modify existing
1318 class WikiDB_PageRevision
1320 var $_transformedContent = false; // set by WikiDB_Page::save()
1322 function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1323 $versiondata = false)
1325 $GLOBALS['request']->_dbi = &$wikidb;
1326 $this->_pagename = $pagename;
1327 $this->_version = $version;
1328 $this->_data = $versiondata ? $versiondata : array();
1332 * Get the WikiDB_Page which this revision belongs to.
1336 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1338 function getPage() {
1339 return new WikiDB_Page(/*$GLOBALS['request']->_dbi, */$this->_pagename);
1343 * Get the version number of this revision.
1347 * @return integer The version number of this revision.
1349 function getVersion() {
1350 return $this->_version;
1354 * Determine whether this revision has defaulted content.
1356 * The default revision (version 0) of each page, as well as any
1357 * pages which are created with empty content have their content
1358 * defaulted to something like:
1360 * Describe [ThisPage] here.
1365 * @return boolean Returns true if the page has default content.
1367 function hasDefaultContents() {
1368 $data = &$this->_data;
1369 return empty($data['%content']);
1373 * Get the content as an array of lines.
1377 * @return array An array of lines.
1378 * The lines should contain no trailing white space.
1380 function getContent() {
1381 return explode("\n", $this->getPackedContent());
1385 * Get the pagename of the revision.
1389 * @return string pagename.
1391 function getPageName() {
1392 return $this->_pagename;
1396 * Determine whether revision is the latest.
1400 * @return boolean True iff the revision is the latest (most recent) one.
1402 function isCurrent() {
1403 if (!isset($this->_iscurrent)) {
1404 $page = $this->getPage();
1405 $current = $page->getCurrentRevision(false);
1406 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1408 return $this->_iscurrent;
1412 * Get the transformed content of a page.
1414 * @param string $pagetype Override the page-type of the revision.
1416 * @return object An XmlContent-like object containing the page transformed
1419 function getTransformedContent($pagetype_override=false) {
1420 $backend = &$GLOBALS['request']->_dbi->_backend;
1422 if ($pagetype_override) {
1423 // Figure out the normal page-type for this page.
1424 $type = PageType::GetPageType($this->get('pagetype'));
1425 if ($type->getName() == $pagetype_override)
1426 $pagetype_override = false; // Not really an override...
1429 if ($pagetype_override) {
1430 // Overriden page type, don't cache (or check cache).
1431 return new TransformedText($this->getPage(),
1432 $this->getPackedContent(),
1433 $this->getMetaData(),
1434 $pagetype_override);
1437 $possibly_cache_results = true;
1439 if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1440 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1441 // flush cache for this page.
1442 $page = $this->getPage();
1443 $page->set('_cached_html', false);
1445 $possibly_cache_results = false;
1447 elseif (!$this->_transformedContent) {
1449 if ($this->isCurrent()) {
1450 $page = $this->getPage();
1451 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1454 $possibly_cache_results = false;
1456 //$backend->unlock();
1459 if (!$this->_transformedContent) {
1460 $text = $this->getPackedContent();
1461 $this->_transformedContent
1462 = new TransformedText($this->getPage(),
1464 $this->getMetaData());
1466 if ($possibly_cache_results) {
1467 // If we're still the current version, cache the transfomed page.
1469 if ($this->isCurrent()) {
1470 $page->set('_cached_html', $this->_transformedContent->pack());
1472 //$backend->unlock();
1476 return $this->_transformedContent;
1480 * Get the content as a string.
1484 * @return string The page content.
1485 * Lines are separated by new-lines.
1487 function getPackedContent() {
1488 $data = &$this->_data;
1491 if (empty($data['%content'])) {
1492 include_once('lib/InlineParser.php');
1494 // A feature similar to taglines at http://www.wlug.org.nz/
1495 // Lib from http://www.aasted.org/quote/
1496 if (defined('FORTUNE_DIR')
1497 and is_dir(FORTUNE_DIR)
1498 and in_array($GLOBALS['request']->getArg('action'),
1499 array('create','edit')))
1501 include_once("lib/fortune.php");
1502 $fortune = new Fortune();
1503 $quote = str_replace("\n<br>","\n", $fortune->quoteFromDir(FORTUNE_DIR));
1504 return sprintf("<verbatim>\n%s</verbatim>\n\n"._("Describe %s here."),
1505 $quote, "[" . WikiEscape($this->_pagename) . "]");
1507 // Replace empty content with default value.
1508 return sprintf(_("Describe %s here."),
1509 "[" . WikiEscape($this->_pagename) . "]");
1512 // There is (non-default) content.
1513 assert($this->_version > 0);
1515 if (!is_string($data['%content'])) {
1516 // Content was not provided to us at init time.
1517 // (This is allowed because for some backends, fetching
1518 // the content may be expensive, and often is not wanted
1521 // In any case, now we need to get it.
1522 $data['%content'] = $this->_get_content();
1523 assert(is_string($data['%content']));
1526 return $data['%content'];
1529 function _get_content() {
1530 $cache = &$GLOBALS['request']->_dbi->_cache;
1531 $pagename = $this->_pagename;
1532 $version = $this->_version;
1534 assert($version > 0);
1536 $newdata = $cache->get_versiondata($pagename, $version, true);
1538 assert(is_string($newdata['%content']));
1539 return $newdata['%content'];
1542 // else revision has been deleted... What to do?
1543 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1544 $version, $pagename);
1549 * Get meta-data for this revision.
1554 * @param string $key Which meta-data to access.
1556 * Some reserved revision meta-data keys are:
1558 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1559 * The 'mtime' meta-value is normally set automatically by the database
1560 * backend, but it may be specified explicitly when creating a new revision.
1562 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1563 * of a page must be monotonically increasing. If an attempt is
1564 * made to create a new revision with an mtime less than that of
1565 * the preceeding revision, the new revisions timestamp is force
1566 * to be equal to that of the preceeding revision. In that case,
1567 * the originally requested mtime is preserved in 'orig_mtime'.
1568 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1569 * This meta-value is <em>always</em> automatically maintained by the database
1570 * backend. (It is set from the 'mtime' meta-value of the superceding
1571 * revision.) '_supplanted' has a value of 'false' for the current revision.
1573 * FIXME: this could be refactored:
1575 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1577 * <dd> Authenticated author of a page. This is used to identify
1578 * the distinctness of authors when cleaning old revisions from
1580 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1581 * <dt> 'summary' <dd> Short change summary entered by page author.
1584 * Meta-data keys must be valid C identifers (they have to start with a letter
1585 * or underscore, and can contain only alphanumerics and underscores.)
1587 * @return string The requested value, or false if the requested value
1590 function get($key) {
1591 if (!$key || $key[0] == '%')
1593 $data = &$this->_data;
1594 return isset($data[$key]) ? $data[$key] : false;
1598 * Get all the revision page meta-data as a hash.
1600 * @return hash The revision meta-data.
1602 function getMetaData() {
1604 foreach ($this->_data as $key => $val) {
1605 if (!empty($val) && $key[0] != '%')
1613 * Return a string representation of the revision.
1615 * This is really only for debugging.
1619 * @return string Printable representation of the WikiDB_Page.
1621 function asString () {
1623 printf("[%s:%d\n", get_class($this), $this->get('version'));
1624 print_r($this->_data);
1625 echo $this->getPackedContent() . "\n]\n";
1626 $strval = ob_get_contents();
1634 * Class representing a sequence of WikiDB_Pages.
1635 * TODO: Enhance to php5 iterators
1637 class WikiDB_PageIterator
1639 function WikiDB_PageIterator(&$wikidb, &$pages) {
1640 $this->_pages = $pages;
1641 $GLOBALS['request']->_dbi = &$wikidb;
1645 return $this->_pages->count();
1649 * Get next WikiDB_Page in sequence.
1653 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1656 if ( ! ($next = $this->_pages->next()) )
1659 $pagename = &$next['pagename'];
1661 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1665 // there's always hits, but we cache only if more
1666 // (well not with file, cvs and dba)
1667 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1668 $GLOBALS['request']->_dbi->_cache->cache_data($next);
1671 return new WikiDB_Page(/*$GLOBALS['request']->_dbi,*/ $pagename);
1675 * Release resources held by this iterator.
1677 * The iterator may not be used after free() is called.
1679 * There is no need to call free(), if next() has returned false.
1680 * (I.e. if you iterate through all the pages in the sequence,
1681 * you do not need to call free() --- you only need to call it
1682 * if you stop before the end of the iterator is reached.)
1687 $this->_pages->free();
1690 function asArray() {
1692 while ($page = $this->next())
1702 * A class which represents a sequence of WikiDB_PageRevisions.
1703 * TODO: Enhance to php5 iterators
1705 class WikiDB_PageRevisionIterator
1707 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1708 $this->_revisions = $revisions;
1709 $GLOBALS['request']->_dbi = &$wikidb;
1713 return $this->_revisions->count();
1717 * Get next WikiDB_PageRevision in sequence.
1721 * @return WikiDB_PageRevision
1722 * The next WikiDB_PageRevision in the sequence.
1725 if ( ! ($next = $this->_revisions->next()) )
1728 $GLOBALS['request']->_dbi->_cache->cache_data($next);
1730 $pagename = $next['pagename'];
1731 $version = $next['version'];
1732 $versiondata = $next['versiondata'];
1734 if (!(is_string($pagename) and $pagename != '')) {
1735 trigger_error("empty pagename",E_USER_WARNING);
1738 } else assert(is_string($pagename) and $pagename != '');
1740 if (!is_array($versiondata)) {
1741 trigger_error("empty versiondata",E_USER_WARNING);
1744 } else assert(is_array($versiondata));
1746 if (!($version > 0)) {
1747 trigger_error("invalid version",E_USER_WARNING);
1750 } else assert($version > 0);
1752 return new WikiDB_PageRevision($GLOBALS['request']->_dbi, $pagename, $version,
1757 * Release resources held by this iterator.
1759 * The iterator may not be used after free() is called.
1761 * There is no need to call free(), if next() has returned false.
1762 * (I.e. if you iterate through all the revisions in the sequence,
1763 * you do not need to call free() --- you only need to call it
1764 * if you stop before the end of the iterator is reached.)
1769 $this->_revisions->free();
1772 function asArray() {
1774 while ($rev = $this->next())
1783 class WikiDB_Array_PageIterator
1785 function WikiDB_Array_PageIterator(&$pagenames) {
1787 $this->_dbi = $request->getDbh();
1788 $this->_pages = $pagenames;
1789 reset($this->_pages);
1792 $c =& current($this->_pages);
1793 next($this->_pages);
1794 return $c !== false ? $this->_dbi->getPage($c) : false;
1797 return count($this->_pages);
1800 function asArray() {
1801 reset($this->_pages);
1802 return $this->_pages;
1807 class WikiDB_Array_generic_iter
1809 function WikiDB_Array_generic_iter($result) {
1810 // $result may be either an array or a query result
1811 if (is_array($result)) {
1812 $this->_array = $result;
1813 } elseif (is_object($result)) {
1814 $this->_array = $result->asArray();
1816 $this->_array = array();
1818 if (!empty($this->_array))
1819 reset($this->_array);
1822 $c =& current($this->_array);
1823 next($this->_array);
1824 return $c !== false ? $c : false;
1827 return count($this->_array);
1830 function asArray() {
1831 if (!empty($this->_array))
1832 reset($this->_array);
1833 return $this->_array;
1839 * Data cache used by WikiDB.
1841 * FIXME: Maybe rename this to caching_backend (or some such).
1847 // FIXME: beautify versiondata cache. Cache only limited data?
1849 function WikiDB_cache (&$backend) {
1850 $this->_backend = &$backend;
1852 $this->_pagedata_cache = array();
1853 $this->_versiondata_cache = array();
1854 array_push ($this->_versiondata_cache, array());
1855 $this->_glv_cache = array();
1859 $this->_pagedata_cache = false;
1860 $this->_versiondata_cache = false;
1861 $this->_glv_cache = false;
1864 function get_pagedata($pagename) {
1865 assert(is_string($pagename) && $pagename != '');
1866 if (defined('USECACHE') and USECACHE) {
1867 $cache = &$this->_pagedata_cache;
1868 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1869 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1870 // Never keep a ['%pagedata']['_cached_html'] in cache, other than the current page.
1871 if (isset($cache[$pagename]['_cached_html'])
1872 and $pagename != $GLOBALS['request']->getArg('pagename')) {
1873 unset($cache[$pagename]['_cached_html']);
1875 if (empty($cache[$pagename]))
1876 $cache[$pagename] = array();
1878 return $cache[$pagename];
1880 return $this->_backend->get_pagedata($pagename);
1884 function update_pagedata($pagename, $newdata) {
1885 assert(is_string($pagename) && $pagename != '');
1887 $this->_backend->update_pagedata($pagename, $newdata);
1889 if (defined('USECACHE') and USECACHE
1890 and is_array($this->_pagedata_cache[$pagename]))
1892 $cachedata = &$this->_pagedata_cache[$pagename];
1893 foreach($newdata as $key => $val)
1894 $cachedata[$key] = $val;
1898 function invalidate_cache($pagename) {
1899 unset ($this->_pagedata_cache[$pagename]);
1900 unset ($this->_versiondata_cache[$pagename]);
1901 unset ($this->_glv_cache[$pagename]);
1904 function delete_page($pagename) {
1905 $this->_backend->delete_page($pagename);
1906 unset ($this->_pagedata_cache[$pagename]);
1907 unset ($this->_glv_cache[$pagename]);
1911 function cache_data($data) {
1912 if (isset($data['pagedata']))
1913 $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1916 function get_versiondata($pagename, $version, $need_content = false) {
1917 // FIXME: Seriously ugly hackage
1918 if (defined('USECACHE') and USECACHE) { //temporary - for debugging
1919 assert(is_string($pagename) && $pagename != '');
1920 // there is a bug here somewhere which results in an assertion failure at line 105
1921 // of ArchiveCleaner.php It goes away if we use the next line.
1922 //$need_content = true;
1923 $nc = $need_content ? '1':'0';
1924 $cache = &$this->_versiondata_cache;
1925 if (!isset($cache[$pagename][$version][$nc])||
1926 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1927 $cache[$pagename][$version][$nc] =
1928 $this->_backend->get_versiondata($pagename, $version, $need_content);
1929 // If we have retrieved all data, we may as well set the cache for $need_content = false
1931 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
1934 $vdata = $cache[$pagename][$version][$nc];
1936 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1939 // Rationale: never keep ['%pagedata']['_cached_html'] in cache.
1940 if ($vdata && !empty($vdata['%pagedata'])) {
1941 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1942 // only store _cached_html for the requested page
1943 if (defined('USECACHE') and USECACHE
1944 and isset($vdata['%pagedata']['_cached_html'])
1945 and $pagename != $GLOBALS['request']->getArg('pagename'))
1947 unset($this->_pagedata_cache[$pagename]['_cached_html']);
1948 unset($cache[$pagename][$version][$nc]['%pagedata']['_cached_html']);
1950 unset($cache[$pagename][$version][0]['%pagedata']['_cached_html']);
1956 function set_versiondata($pagename, $version, $data) {
1957 $new = $this->_backend->set_versiondata($pagename, $version, $data);
1959 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1960 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1961 // Is this necessary?
1962 unset($this->_glv_cache[$pagename]);
1965 function update_versiondata($pagename, $version, $data) {
1966 $new = $this->_backend->update_versiondata($pagename, $version, $data);
1968 // FIXME: never keep ['%pagedata']['_cached_html'] in cache.
1969 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1971 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1972 // Is this necessary?
1973 unset($this->_glv_cache[$pagename]);
1976 function delete_versiondata($pagename, $version) {
1977 $new = $this->_backend->delete_versiondata($pagename, $version);
1978 if (isset($this->_versiondata_cache[$pagename][$version]['1']))
1979 unset ($this->_versiondata_cache[$pagename][$version]['1']);
1980 if (isset($this->_versiondata_cache[$pagename][$version]['0']))
1981 unset ($this->_versiondata_cache[$pagename][$version]['0']);
1982 if (isset($this->_glv_cache[$pagename]))
1983 unset ($this->_glv_cache[$pagename]);
1986 function get_latest_version($pagename) {
1987 if (defined('USECACHE') and USECACHE) {
1988 assert (is_string($pagename) && $pagename != '');
1989 $cache = &$this->_glv_cache;
1990 if (!isset($cache[$pagename])) {
1991 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1992 if (empty($cache[$pagename]))
1993 $cache[$pagename] = 0;
1995 return $cache[$pagename];
1997 return $this->_backend->get_latest_version($pagename);
2003 // $Log: not supported by cvs2svn $
2004 // Revision 1.92 2004/10/05 17:00:04 rurban
2005 // support paging for simple lists
2006 // fix RatingDb sql backend.
2007 // remove pages from AllPages (this is ListPages then)
2009 // Revision 1.91 2004/10/04 23:41:19 rurban
2010 // delete notify: fix, @unset syntax error
2012 // Revision 1.90 2004/09/28 12:50:22 rurban
2013 // https://sourceforge.net/forum/forum.php?thread_id=1150924&forum_id=18929
2015 // Revision 1.89 2004/09/26 10:54:42 rurban
2016 // silence deferred check
2018 // Revision 1.88 2004/09/25 18:16:40 rurban
2019 // unset more unneeded _cached_html. (Guess this should fix sf.net now)
2021 // Revision 1.87 2004/09/25 16:25:40 rurban
2022 // notify on rename and remove (to be improved)
2024 // Revision 1.86 2004/09/23 18:52:06 rurban
2025 // only fortune at create
2027 // Revision 1.85 2004/09/16 08:00:51 rurban
2028 // just some comments
2030 // Revision 1.84 2004/09/14 10:34:30 rurban
2031 // fix TransformedText call to use refs
2033 // Revision 1.83 2004/09/08 13:38:00 rurban
2034 // improve loadfile stability by using markup=2 as default for undefined markup-style.
2035 // use more refs for huge objects.
2036 // fix debug=static issue in WikiPluginCached
2038 // Revision 1.82 2004/09/06 12:08:49 rurban
2039 // memory_limit on unix workaround
2040 // VisualWiki: default autosize image
2042 // Revision 1.81 2004/09/06 08:28:00 rurban
2043 // rename genericQuery to genericSqlQuery
2045 // Revision 1.80 2004/07/09 13:05:34 rurban
2048 // Revision 1.79 2004/07/09 10:06:49 rurban
2049 // Use backend specific sortby and sortable_columns method, to be able to
2050 // select between native (Db backend) and custom (PageList) sorting.
2051 // Fixed PageList::AddPageList (missed the first)
2052 // Added the author/creator.. name to AllPagesBy...
2053 // display no pages if none matched.
2054 // Improved dba and file sortby().
2055 // Use &$request reference
2057 // Revision 1.78 2004/07/08 21:32:35 rurban
2058 // Prevent from more warnings, minor db and sort optimizations
2060 // Revision 1.77 2004/07/08 19:04:42 rurban
2061 // more unittest fixes (file backend, metadata RatingsDb)
2063 // Revision 1.76 2004/07/08 17:31:43 rurban
2064 // improve numPages for file (fixing AllPagesTest)
2066 // Revision 1.75 2004/07/05 13:56:22 rurban
2067 // sqlite autoincrement fix
2069 // Revision 1.74 2004/07/03 16:51:05 rurban
2070 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
2071 // added atomic mysql REPLACE for PearDB as in ADODB
2072 // fixed _lock_tables typo links => link
2073 // fixes unserialize ADODB bug in line 180
2075 // Revision 1.73 2004/06/29 08:52:22 rurban
2076 // Use ...version() $need_content argument in WikiDB also:
2077 // To reduce the memory footprint for larger sets of pagelists,
2078 // we don't cache the content (only true or false) and
2079 // we purge the pagedata (_cached_html) also.
2080 // _cached_html is only cached for the current pagename.
2081 // => Vastly improved page existance check, ACL check, ...
2083 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2085 // Revision 1.72 2004/06/25 14:15:08 rurban
2086 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
2088 // Revision 1.71 2004/06/21 16:22:30 rurban
2089 // add DEFAULT_DUMP_DIR and HTML_DUMP_DIR constants, for easier cmdline dumps,
2090 // fixed dumping buttons locally (images/buttons/),
2091 // support pages arg for dumphtml,
2092 // optional directory arg for dumpserial + dumphtml,
2093 // fix a AllPages warning,
2094 // show dump warnings/errors on DEBUG,
2095 // don't warn just ignore on wikilens pagelist columns, if not loaded.
2096 // RateIt pagelist column is called "rating", not "ratingwidget" (Dan?)
2098 // Revision 1.70 2004/06/18 14:39:31 rurban
2099 // actually check USECACHE
2101 // Revision 1.69 2004/06/13 15:33:20 rurban
2102 // new support for arguments owner, author, creator in most relevant
2103 // PageList plugins. in WikiAdmin* via preSelectS()
2105 // Revision 1.68 2004/06/08 21:03:20 rurban
2106 // updated RssParser for XmlParser quirks (store parser object params in globals)
2108 // Revision 1.67 2004/06/07 19:12:49 rurban
2109 // fixed rename version=0, bug #966284
2111 // Revision 1.66 2004/06/07 18:57:27 rurban
2112 // fix rename: Change pagename in all linked pages
2114 // Revision 1.65 2004/06/04 20:32:53 rurban
2115 // Several locale related improvements suggested by Pierrick Meignen
2116 // LDAP fix by John Cole
2117 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2119 // Revision 1.64 2004/06/04 16:50:00 rurban
2120 // add random quotes to empty pages
2122 // Revision 1.63 2004/06/04 11:58:38 rurban
2123 // added USE_TAGLINES
2125 // Revision 1.62 2004/06/03 22:24:41 rurban
2126 // reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after Remove
2128 // Revision 1.61 2004/06/02 17:13:48 rurban
2129 // fix getRevisionBefore assertion
2131 // Revision 1.60 2004/05/28 10:09:58 rurban
2132 // fix bug #962117, incorrect init of auth_dsn
2134 // Revision 1.59 2004/05/27 17:49:05 rurban
2135 // renamed DB_Session to DbSession (in CVS also)
2136 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
2137 // remove leading slash in error message
2138 // added force_unlock parameter to File_Passwd (no return on stale locks)
2139 // fixed adodb session AffectedRows
2140 // added FileFinder helpers to unify local filenames and DATA_PATH names
2141 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
2143 // Revision 1.58 2004/05/18 13:59:14 rurban
2144 // rename simpleQuery to genericQuery
2146 // Revision 1.57 2004/05/16 22:07:35 rurban
2147 // check more config-default and predefined constants
2148 // various PagePerm fixes:
2149 // fix default PagePerms, esp. edit and view for Bogo and Password users
2150 // implemented Creator and Owner
2151 // BOGOUSERS renamed to BOGOUSER
2152 // fixed syntax errors in signin.tmpl
2154 // Revision 1.56 2004/05/15 22:54:49 rurban
2155 // fixed important WikiDB bug with DEBUG > 0: wrong assertion
2156 // improved SetAcl (works) and PagePerms, some WikiGroup helpers.
2158 // Revision 1.55 2004/05/12 19:27:47 rurban
2159 // revert wrong inline optimization.
2161 // Revision 1.54 2004/05/12 10:49:55 rurban
2162 // require_once fix for those libs which are loaded before FileFinder and
2163 // its automatic include_path fix, and where require_once doesn't grok
2164 // dirname(__FILE__) != './lib'
2165 // upgrade fix with PearDB
2166 // navbar.tmpl: remove spaces for IE button alignment
2168 // Revision 1.53 2004/05/08 14:06:12 rurban
2169 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2170 // minor stability and portability fixes
2172 // Revision 1.52 2004/05/06 19:26:16 rurban
2173 // improve stability, trying to find the InlineParser endless loop on sf.net
2175 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2177 // Revision 1.51 2004/05/06 17:30:37 rurban
2178 // CategoryGroup: oops, dos2unix eol
2179 // improved phpwiki_version:
2180 // pre -= .0001 (1.3.10pre: 1030.099)
2181 // -p1 += .001 (1.3.9-p1: 1030.091)
2182 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2183 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2184 // backend->backendType(), backend->database(),
2185 // backend->listOfFields(),
2186 // backend->listOfTables(),
2188 // Revision 1.50 2004/05/04 22:34:25 rurban
2191 // Revision 1.49 2004/05/03 11:16:40 rurban
2192 // fixed sendPageChangeNotification
2193 // subject rewording
2195 // Revision 1.48 2004/04/29 23:03:54 rurban
2196 // fixed sf.net bug #940996
2198 // Revision 1.47 2004/04/29 19:39:44 rurban
2199 // special support for formatted plugins (one-liners)
2200 // like <small><plugin BlaBla ></small>
2201 // iter->asArray() helper for PopularNearby
2202 // db_session for older php's (no &func() allowed)
2204 // Revision 1.46 2004/04/26 20:44:34 rurban
2205 // locking table specific for better databases
2207 // Revision 1.45 2004/04/20 00:06:03 rurban
2208 // themable paging support
2210 // Revision 1.44 2004/04/19 18:27:45 rurban
2211 // Prevent from some PHP5 warnings (ref args, no :: object init)
2212 // php5 runs now through, just one wrong XmlElement object init missing
2213 // Removed unneccesary UpgradeUser lines
2214 // Changed WikiLink to omit version if current (RecentChanges)
2216 // Revision 1.43 2004/04/18 01:34:20 rurban
2217 // protect most_popular from sortby=mtime
2219 // Revision 1.42 2004/04/18 01:11:51 rurban
2220 // more numeric pagename fixes.
2221 // fixed action=upload with merge conflict warnings.
2222 // charset changed from constant to global (dynamic utf-8 switching)
2228 // c-basic-offset: 4
2229 // c-hanging-comment-ender-p: nil
2230 // indent-tabs-mode: nil