4 require_once('lib/PageType.php');
7 * The classes in the file define the interface to the
11 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
12 * Minor enhancements by Reini Urban
16 * Force the creation of a new revision.
17 * @see WikiDB_Page::createRevision()
19 if (!defined('WIKIDB_FORCE_CREATE'))
20 define('WIKIDB_FORCE_CREATE', -1);
23 * Abstract base class for the database used by PhpWiki.
25 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
26 * turn contain <tt>WikiDB_PageRevision</tt>s.
28 * Conceptually a <tt>WikiDB</tt> contains all possible
29 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
30 * Since all possible pages are already contained in a WikiDB, a call
31 * to WikiDB::getPage() will never fail (barring bugs and
32 * e.g. filesystem or SQL database problems.)
34 * Also each <tt>WikiDB_Page</tt> always contains at least one
35 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
36 * [PageName] here."). This default content has a version number of
39 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
40 * only create new revisions or delete old ones --- one can not modify
41 * an existing revision.
45 * Open a WikiDB database.
47 * This is a static member function. This function inspects its
48 * arguments to determine the proper subclass of WikiDB to
49 * instantiate, and then it instantiates it.
53 * @param hash $dbparams Database configuration parameters.
54 * Some pertinent parameters are:
57 * <dd> The back-end type. Current supported types are:
60 * <dd> Generic SQL backend based on the PEAR/DB database abstraction
61 * library. (More stable and conservative)
63 * <dd> Another generic SQL backend. (More current features are tested here. Much faster)
65 * <dd> Dba based backend. The default and by far the fastest.
73 * <dd> (Used by the SQL and ADODB backends.)
74 * The DSN specifying which database to connect to.
77 * <dd> Prefix to be prepended to database tables (and file names).
80 * <dd> (Used by the dba backend.)
81 * Which directory db files reside in.
84 * <dd> Used only by the dba backend so far.
85 * And: When optimizing mysql it closes timed out mysql processes.
86 * otherwise only used for dba: Timeout in seconds for opening (and
87 * obtaining lock) on the dbm file.
90 * <dd> (Used by the dba backend.)
92 * Which dba handler to use. Good choices are probably either
96 * @return WikiDB A WikiDB object.
98 function open ($dbparams) {
99 $dbtype = $dbparams{'dbtype'};
100 include_once("lib/WikiDB/$dbtype.php");
102 $class = 'WikiDB_' . $dbtype;
103 return new $class ($dbparams);
113 function WikiDB (&$backend, $dbparams) {
114 $this->_backend =& $backend;
115 // don't do the following with the auth_dsn!
116 if (isset($dbparams['auth_dsn'])) return;
118 $this->_cache = new WikiDB_cache($backend);
119 if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
121 // If the database doesn't yet have a timestamp, initialize it now.
122 if ($this->get('_timestamp') === false)
126 if ((int)DEBUG & _DEBUG_SQL) {
127 $this->_backend->check();
132 * Close database connection.
134 * The database may no longer be used after it is closed.
136 * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
137 * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
138 * which have been obtained from it.
143 $this->_backend->close();
144 $this->_cache->close();
148 * Get a WikiDB_Page from a WikiDB.
150 * A {@link WikiDB} consists of the (infinite) set of all possible pages,
151 * therefore this method never fails.
154 * @param string $pagename Which page to get.
155 * @return WikiDB_Page The requested WikiDB_Page.
157 function getPage($pagename) {
158 static $error_displayed = false;
159 $pagename = (string) $pagename;
161 if ($pagename === '') {
162 if ($error_displayed) return false;
163 $error_displayed = true;
164 if (function_exists("xdebug_get_function_stack"))
165 var_dump(xdebug_get_function_stack());
166 trigger_error("empty pagename", E_USER_WARNING);
170 assert($pagename != '');
172 return new WikiDB_Page($this, $pagename);
176 * Determine whether page exists (in non-default form).
179 * $is_page = $dbi->isWikiPage($pagename);
183 * $page = $dbi->getPage($pagename);
184 * $current = $page->getCurrentRevision();
185 * $is_page = ! $current->hasDefaultContents();
187 * however isWikiPage may be implemented in a more efficient
188 * manner in certain back-ends.
191 * @param string $pagename string Which page to check.
192 * @return boolean True if the page actually exists with
193 * non-default contents in the WikiDataBase.
195 function isWikiPage ($pagename) {
196 $page = $this->getPage($pagename);
197 return ($page and $page->exists());
201 * Delete page from the WikiDB.
203 * Deletes the page from the WikiDB with the possibility to revert and diff.
204 * //Also resets all page meta-data to the default values.
206 * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
209 * @param string $pagename Name of page to delete.
212 function deletePage($pagename) {
213 // don't create empty revisions of already purged pages.
214 if ($this->_backend->get_latest_version($pagename))
215 $result = $this->_cache->delete_page($pagename);
219 /* Generate notification emails */
220 if (ENABLE_MAILNOTIFY) {
221 include_once("lib/MailNotify.php");
222 $MailNotify = new MailNotify($pagename);
223 $MailNotify->onDeletePage ($this, $pagename);
226 //How to create a RecentChanges entry with explaining summary? Dynamically
228 $page = $this->getPage($pagename);
229 $current = $page->getCurrentRevision();
230 $meta = $current->_data;
231 $version = $current->getVersion();
232 $meta['summary'] = _("removed");
233 $page->save($current->getPackedContent(), $version + 1, $meta);
239 * Completely remove the page from the WikiDB, without undo possibility.
241 * @param string $pagename Name of page to delete.
244 function purgePage($pagename) {
245 $result = $this->_cache->purge_page($pagename);
246 $this->deletePage($pagename); // just for the notification
251 * Retrieve all pages.
253 * Gets the set of all pages with non-default contents.
257 * @param boolean $include_empty Optional. Normally pages whose most
258 * recent revision has empty content are considered to be
259 * non-existant. Unless $include_defaulted is set to true, those
260 * pages will not be returned.
261 * @param string or false $sortby Optional. "+-column,+-column2".
262 * If false the result is faster in natural order.
263 * @param string or false $limit Optional. Encoded as "$offset,$count".
264 * $offset defaults to 0.
265 * @param string $exclude: Optional comma-seperated list of pagenames.
267 * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
268 * in the WikiDB which have non-default contents.
270 function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
272 // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
274 $mem = ini_get("memory_limit");
275 if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
277 $GLOBALS['request']->setArg('limit', $limit);
278 $GLOBALS['request']->setArg('paging', 'auto');
281 $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
283 if (isa($this->_backend, "WikiDB_backend_dba"))
285 return new WikiDB_PageIterator($this, $result,
286 array('include_empty' => $include_empty,
287 'exclude' => $exclude,
294 * @param boolean $include_empty If true include also empty pages
295 * @param string $exclude: comma-seperated list of pagenames.
296 * TBD: array of pagenames
300 function numPages($include_empty=false, $exclude='') {
301 if (method_exists($this->_backend, 'numPages'))
302 // FIXME: currently are all args ignored.
303 $count = $this->_backend->numPages($include_empty, $exclude);
305 // FIXME: exclude ignored.
306 $iter = $this->getAllPages($include_empty, false, false, $exclude);
307 $count = $iter->count();
316 * Search for pages containing (or not containing) certain words
319 * Pages are returned in alphabetical order whenever it is
320 * practical to do so.
321 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
324 * @param TextSearchQuery $search A TextSearchQuery object
325 * @param string or false $sortby Optional. "+-column,+-column2".
326 * If false the result is faster in natural order.
327 * @param string or false $limit Optional. Encoded as "$offset,$count".
328 * $offset defaults to 0.
329 * @param string $exclude: Optional comma-seperated list of pagenames.
330 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
331 * @see TextSearchQuery
333 function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
334 $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
335 $options = array('exclude' => $exclude,
337 //if (isset($result->_count)) $options['count'] = $result->_count;
338 return new WikiDB_PageIterator($this, $result, $options);
344 * Search for pages containing (or not containing) certain words
345 * in their entire text (this includes the page content and the
348 * Pages are returned in alphabetical order whenever it is
349 * practical to do so.
350 * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
354 * @param TextSearchQuery $search A TextSearchQuery object.
355 * @param string or false $sortby Optional. "+-column,+-column2".
356 * If false the result is faster in natural order.
357 * @param string or false $limit Optional. Encoded as "$offset,$count".
358 * $offset defaults to 0.
359 * @param string $exclude: Optional comma-seperated list of pagenames.
360 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
361 * @see TextSearchQuery
363 function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
364 $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
365 return new WikiDB_PageIterator($this, $result,
366 array('exclude' => $exclude,
368 'stoplisted' => $result->stoplisted
373 * Find the pages with the greatest hit counts.
375 * Pages are returned in reverse order by hit count.
379 * @param integer $limit The maximum number of pages to return.
380 * Set $limit to zero to return all pages. If $limit < 0, pages will
381 * be sorted in decreasing order of popularity.
382 * @param string or false $sortby Optional. "+-column,+-column2".
383 * If false the result is faster in natural order.
385 * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
388 function mostPopular($limit = 20, $sortby = '-hits') {
389 $result = $this->_backend->most_popular($limit, $sortby);
390 return new WikiDB_PageIterator($this, $result);
394 * Find recent page revisions.
396 * Revisions are returned in reverse order by creation time.
400 * @param hash $params This hash is used to specify various optional
404 * <dd> (integer) At most this many revisions will be returned.
406 * <dd> (integer) Only revisions since this time (unix-timestamp)
408 * <dt> include_minor_revisions
409 * <dd> (boolean) Also include minor revisions. (Default is not to.)
410 * <dt> exclude_major_revisions
411 * <dd> (boolean) Don't include non-minor revisions.
412 * (Exclude_major_revisions implies include_minor_revisions.)
413 * <dt> include_all_revisions
414 * <dd> (boolean) Return all matching revisions for each page.
415 * Normally only the most recent matching revision is returned
419 * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
420 * containing the matching revisions.
422 function mostRecent($params = false) {
423 $result = $this->_backend->most_recent($params);
424 return new WikiDB_PageRevisionIterator($this, $result);
430 * @param string or false $sortby Optional. "+-column,+-column2".
431 * If false the result is faster in natural order.
432 * @param string or false $limit Optional. Encoded as "$offset,$count".
433 * $offset defaults to 0.
434 * @return Iterator A generic iterator containing rows of
435 * (duplicate) pagename, wantedfrom.
437 function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
438 return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
439 //return new WikiDB_PageIterator($this, $result);
443 * Generic interface to the link table. Esp. useful to search for rdf triples as in
444 * SemanticSearch and ListRelations.
448 * @param $pages object A TextSearchQuery object.
449 * @param $search object A TextSearchQuery object.
450 * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
451 * linktype parameter:
454 * <dd> search for simple out-links
456 * <dd> in-links, i.e BackLinks
458 * <dd> the first part in a <>::<> link
460 * <dd> the first part in a <>:=<> link
462 * @param $relation object An optional TextSearchQuery to match the
463 * relation name. Ignored on simple in-out links.
465 * @return Iterator A generic iterator containing links to pages or values.
466 * hash of "pagename", "linkname", "linkvalue.
468 function linkSearch($pages, $search, $linktype, $relation=false) {
469 return $this->_backend->link_search($pages, $search, $linktype, $relation);
473 * Return a simple list of all defined relations (and attributes), mainly
474 * for the SemanticSearch autocompletion.
478 * @return array of strings
480 function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
481 if (method_exists($this->_backend, "list_relations"))
482 return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
483 // dumb, slow fallback. no iter, so simply define it here.
484 $relations = array();
485 $iter = $this->getAllPages();
486 while ($page = $iter->next()) {
487 $reliter = $page->getRelations();
489 while ($rel = $reliter->next()) {
490 // if there's no pagename it's an attribute
491 $names[] = $rel->getName();
493 $relations = array_merge($relations, $names);
505 * Call the appropriate backend method.
508 * @param string $from Page to rename
509 * @param string $to New name
510 * @param boolean $updateWikiLinks If the text in all pages should be replaced.
511 * @return boolean true or false
513 function renamePage($from, $to, $updateWikiLinks = false) {
514 assert(is_string($from) && $from != '');
515 assert(is_string($to) && $to != '');
517 if (method_exists($this->_backend, 'rename_page')) {
518 $oldpage = $this->getPage($from);
519 $newpage = $this->getPage($to);
520 //update all WikiLinks in existing pages
521 //non-atomic! i.e. if rename fails the links are not undone
522 if ($updateWikiLinks) {
523 $lookbehind = "/(?<=[\W:])\Q";
524 $lookahead = "\E(?=[\W:])/";
525 if (!check_php_version(4,3,3)) {
526 $lookbehind = "/(?<=[\W:])";
527 $lookahead = "(?=[\W:])/";
528 $from = preg_quote($from, "/");
529 $to = preg_quote($to, "/");
531 require_once('lib/plugin/WikiAdminSearchReplace.php');
532 $links = $oldpage->getBackLinks();
533 while ($linked_page = $links->next()) {
534 WikiPlugin_WikiAdminSearchReplace::replaceHelper
536 $linked_page->getName(),
537 $lookbehind.$from.$lookahead, $to,
540 // FIXME: Disabled to avoid recursive modification when renaming
541 // a page like 'PageFoo to 'PageFooTwo'
543 $links = $newpage->getBackLinks();
544 while ($linked_page = $links->next()) {
545 WikiPlugin_WikiAdminSearchReplace::replaceHelper
547 $linked_page->getName(),
548 $lookbehind.$from.$lookahead, $to,
553 if ($oldpage->exists() and ! $newpage->exists()) {
554 if ($result = $this->_backend->rename_page($from, $to)) {
555 // create a RecentChanges entry with explaining summary
556 $page = $this->getPage($to);
557 $current = $page->getCurrentRevision();
558 $meta = $current->_data;
559 $version = $current->getVersion();
560 $meta['summary'] = sprintf(_("renamed from %s"), $from);
561 unset($meta['mtime']); // force new date
562 $page->save($current->getPackedContent(), $version + 1, $meta);
564 } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
565 // if a version 0 exists try it also.
566 $result = $this->_backend->rename_page($from, $to);
569 trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
572 /* Generate notification emails? */
573 if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
574 $notify = $this->get('notify');
575 if (!empty($notify) and is_array($notify)) {
576 include_once("lib/MailNotify.php");
577 $MailNotify = new MailNotify($from);
578 $MailNotify->onRenamePage ($this, $from, $to);
584 /** Get timestamp when database was last modified.
586 * @return string A string consisting of two integers,
587 * separated by a space. The first is the time in
588 * unix timestamp format, the second is a modification
589 * count for the database.
591 * The idea is that you can cast the return value to an
592 * int to get a timestamp, or you can use the string value
593 * as a good hash for the entire database.
595 function getTimestamp() {
596 $ts = $this->get('_timestamp');
597 return sprintf("%d %d", $ts[0], $ts[1]);
601 * Update the database timestamp.
605 $ts = $this->get('_timestamp');
606 $this->set('_timestamp', array(time(), $ts[1] + 1));
610 * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
612 function get_db_version() {
613 return (float) $this->get('_db_version');
615 function set_db_version($ver) {
616 return $this->set('_db_version', (float)$ver);
620 * Access WikiDB global meta-data.
622 * NOTE: this is currently implemented in a hackish and
623 * not very efficient manner.
627 * @param string $key Which meta data to get.
628 * Some reserved meta-data keys are:
630 * <dt>'_timestamp' <dd> Data used by getTimestamp().
633 * @return scalar The requested value, or false if the requested data
637 if (!$key || $key[0] == '%')
640 * Hack Alert: We can use any page (existing or not) to store
641 * this data (as long as we always use the same one.)
643 $gd = $this->getPage('global_data');
644 $data = $gd->get('__global');
646 if ($data && isset($data[$key]))
653 * Set global meta-data.
655 * NOTE: this is currently implemented in a hackish and
656 * not very efficient manner.
661 * @param string $key Meta-data key to set.
662 * @param string $newval New value.
664 function set($key, $newval) {
665 if (!$key || $key[0] == '%')
668 $gd = $this->getPage('global_data');
669 $data = $gd->get('__global');
676 $data[$key] = $newval;
678 $gd->set('__global', $data);
681 /* TODO: these are really backend methods */
683 // SQL result: for simple select or create/update queries
684 // returns the database specific resource type
685 function genericSqlQuery($sql, $args=false) {
686 if (function_exists('debug_backtrace')) { // >= 4.3.0
687 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
689 trigger_error("no SQL database", E_USER_ERROR);
693 // SQL iter: for simple select or create/update queries
694 // returns the generic iterator object (count,next)
695 function genericSqlIter($sql, $field_list = NULL) {
696 if (function_exists('debug_backtrace')) { // >= 4.3.0
697 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
699 trigger_error("no SQL database", E_USER_ERROR);
703 // see backend upstream methods
704 // ADODB adds surrounding quotes, SQL not yet!
705 function quote ($s) {
711 if (!$request->_dbi) return false;
712 else return false; /* so far only needed for sql so false it.
713 later we have to check dba also */
716 function getParam($param) {
718 if (isset($DBParams[$param])) return $DBParams[$param];
719 elseif ($param == 'prefix') return '';
723 function getAuthParam($param) {
724 global $DBAuthParams;
725 if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
726 elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
727 elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
734 * A base class which representing a wiki-page within a
737 * A WikiDB_Page contains a number (at least one) of
738 * WikiDB_PageRevisions.
742 function WikiDB_Page(&$wikidb, $pagename) {
743 $this->_wikidb = &$wikidb;
744 $this->_pagename = $pagename;
746 if (!(is_string($pagename) and $pagename != '')) {
747 if (function_exists("xdebug_get_function_stack")) {
748 echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
749 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
750 printSimpleTrace(debug_backtrace());
752 trigger_error("empty pagename", E_USER_WARNING);
756 assert(is_string($pagename) and $pagename != '');
761 * Get the name of the wiki page.
765 * @return string The page name.
768 return $this->_pagename;
771 // To reduce the memory footprint for larger sets of pagelists,
772 // we don't cache the content (only true or false) and
773 // we purge the pagedata (_cached_html) also
775 if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
776 $current = $this->getCurrentRevision(false);
777 if (!$current) return false;
778 return ! $current->hasDefaultContents();
782 * Delete an old revision of a WikiDB_Page.
784 * Deletes the specified revision of the page.
785 * It is a fatal error to attempt to delete the current revision.
789 * @param integer $version Which revision to delete. (You can also
790 * use a WikiDB_PageRevision object here.)
792 function deleteRevision($version) {
793 $backend = &$this->_wikidb->_backend;
794 $cache = &$this->_wikidb->_cache;
795 $pagename = &$this->_pagename;
797 $version = $this->_coerce_to_version($version);
801 $backend->lock(array('page','version'));
802 $latestversion = $cache->get_latest_version($pagename);
803 if ($latestversion && ($version == $latestversion)) {
804 $backend->unlock(array('page','version'));
805 trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
806 $pagename), E_USER_ERROR);
810 $cache->delete_versiondata($pagename, $version);
811 $backend->unlock(array('page','version'));
815 * Delete a revision, or possibly merge it with a previous
819 * Suppose an author make a (major) edit to a page. Shortly
820 * after that the same author makes a minor edit (e.g. to fix
821 * spelling mistakes he just made.)
823 * Now some time later, where cleaning out old saved revisions,
824 * and would like to delete his minor revision (since there's
825 * really no point in keeping minor revisions around for a long
828 * Note that the text after the minor revision probably represents
829 * what the author intended to write better than the text after
830 * the preceding major edit.
832 * So what we really want to do is merge the minor edit with the
835 * We will only do this when:
837 * <li>The revision being deleted is a minor one, and
838 * <li>It has the same author as the immediately preceding revision.
841 function mergeRevision($version) {
842 $backend = &$this->_wikidb->_backend;
843 $cache = &$this->_wikidb->_cache;
844 $pagename = &$this->_pagename;
846 $version = $this->_coerce_to_version($version);
850 $backend->lock(array('version'));
851 $latestversion = $cache->get_latest_version($pagename);
852 if ($latestversion && $version == $latestversion) {
853 $backend->unlock(array('version'));
854 trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
855 $pagename), E_USER_ERROR);
859 $versiondata = $cache->get_versiondata($pagename, $version, true);
861 // Not there? ... we're done!
862 $backend->unlock(array('version'));
866 if ($versiondata['is_minor_edit']) {
867 $previous = $backend->get_previous_version($pagename, $version);
869 $prevdata = $cache->get_versiondata($pagename, $previous);
870 if ($prevdata['author_id'] == $versiondata['author_id']) {
871 // This is a minor revision, previous version is
872 // by the same author. We will merge the
874 $cache->update_versiondata($pagename, $previous,
875 array('%content' => $versiondata['%content'],
876 '_supplanted' => $versiondata['_supplanted']));
881 $cache->delete_versiondata($pagename, $version);
882 $backend->unlock(array('version'));
887 * Create a new revision of a {@link WikiDB_Page}.
891 * @param int $version Version number for new revision.
892 * To ensure proper serialization of edits, $version must be
893 * exactly one higher than the current latest version.
894 * (You can defeat this check by setting $version to
895 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
897 * @param string $content Contents of new revision.
899 * @param hash $metadata Metadata for new revision.
900 * All values in the hash should be scalars (strings or integers).
902 * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
904 * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
905 * $version was incorrect, returns false
907 function createRevision($version, &$content, $metadata, $links) {
908 $backend = &$this->_wikidb->_backend;
909 $cache = &$this->_wikidb->_cache;
910 $pagename = &$this->_pagename;
911 $cache->invalidate_cache($pagename);
913 $backend->lock(array('version','page','recent','link','nonempty'));
915 $latestversion = $backend->get_latest_version($pagename);
916 $newversion = ($latestversion ? $latestversion : 0) + 1;
917 assert($newversion >= 1);
919 if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
920 $backend->unlock(array('version','page','recent','link','nonempty'));
926 foreach ($data as $key => $val) {
927 if (empty($val) || $key[0] == '_' || $key[0] == '%')
931 assert(!empty($data['author']));
932 if (empty($data['author_id']))
933 @$data['author_id'] = $data['author'];
935 if (empty($data['mtime']))
936 $data['mtime'] = time();
938 if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
939 // Ensure mtimes are monotonic.
940 $pdata = $cache->get_versiondata($pagename, $latestversion);
941 if ($data['mtime'] < $pdata['mtime']) {
942 trigger_error(sprintf(_("%s: Date of new revision is %s"),
943 $pagename,"'non-monotonic'"),
945 $data['orig_mtime'] = $data['mtime'];
946 $data['mtime'] = $pdata['mtime'];
949 // FIXME: use (possibly user specified) 'mtime' time or
951 $cache->update_versiondata($pagename, $latestversion,
952 array('_supplanted' => $data['mtime']));
955 $data['%content'] = &$content;
957 $cache->set_versiondata($pagename, $newversion, $data);
959 //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
960 //':deleted' => empty($content)));
962 $backend->set_links($pagename, $links);
964 $backend->unlock(array('version','page','recent','link','nonempty'));
966 return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
970 /** A higher-level interface to createRevision.
972 * This takes care of computing the links, and storing
973 * a cached version of the transformed wiki-text.
975 * @param string $wikitext The page content.
977 * @param int $version Version number for new revision.
978 * To ensure proper serialization of edits, $version must be
979 * exactly one higher than the current latest version.
980 * (You can defeat this check by setting $version to
981 * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
983 * @param hash $meta Meta-data for new revision.
985 function save($wikitext, $version, $meta, $formatted = null) {
986 if (is_null($formatted))
987 $formatted = new TransformedText($this, $wikitext, $meta);
988 $type = $formatted->getType();
989 $meta['pagetype'] = $type->getName();
990 $links = $formatted->getWikiPageLinks(); // linkto => relation
991 $attributes = array();
992 foreach ($links as $link) {
993 if ($link['linkto'] === "" and $link['relation']) {
994 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
997 $meta['attribute'] = $attributes;
999 $backend = &$this->_wikidb->_backend;
1000 $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1001 if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1002 $this->set('_cached_html', $formatted->pack());
1004 // FIXME: probably should have some global state information
1005 // in the backend to control when to optimize.
1007 // We're doing this here rather than in createRevision because
1008 // postgresql can't optimize while locked.
1009 if (((int)DEBUG & _DEBUG_SQL)
1010 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1011 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1012 if ($backend->optimize()) {
1014 trigger_error(_("Optimizing database"), E_USER_NOTICE);
1018 /* Generate notification emails? */
1019 if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1020 // Save didn't fail because of concurrent updates.
1021 $notify = $this->_wikidb->get('notify');
1023 and is_array($notify)
1024 and !isa($GLOBALS['request'],'MockRequest'))
1026 include_once("lib/MailNotify.php");
1027 $MailNotify = new MailNotify($newrevision->getName());
1028 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1030 $newrevision->_transformedContent = $formatted;
1032 // more pagechange callbacks: (in a hackish manner for now)
1033 if (ENABLE_RECENTCHANGESBOX
1034 and empty($meta['is_minor_edit'])
1035 and !in_array($GLOBALS['request']->getArg('action'),
1036 array('loadfile','upgrade')))
1038 require_once("lib/WikiPlugin.php");
1039 $w = new WikiPluginLoader;
1040 $p = $w->getPlugin("RecentChangesCached", false);
1041 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1043 return $newrevision;
1047 * Get the most recent revision of a page.
1051 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1053 function getCurrentRevision ($need_content=true) {
1054 $backend = &$this->_wikidb->_backend;
1055 $cache = &$this->_wikidb->_cache;
1056 $pagename = &$this->_pagename;
1058 // Prevent deadlock in case of memory exhausted errors
1059 // Pure selection doesn't really need locking here.
1060 // sf.net bug#927395
1061 // I know it would be better to lock, but with lots of pages this deadlock is more
1062 // severe than occasionally get not the latest revision.
1063 // In spirit to wikiwiki: read fast, edit slower.
1065 $version = $cache->get_latest_version($pagename);
1066 // getRevision gets the content also!
1067 $revision = $this->getRevision($version, $need_content);
1068 //$backend->unlock();
1074 * Get a specific revision of a WikiDB_Page.
1078 * @param integer $version Which revision to get.
1080 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1081 * false if the requested revision does not exist in the {@link WikiDB}.
1082 * Note that version zero of any page always exists.
1084 function getRevision ($version, $need_content=true) {
1085 $cache = &$this->_wikidb->_cache;
1086 $pagename = &$this->_pagename;
1088 if (! $version or $version == -1) // 0 or false
1089 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1091 assert($version > 0);
1092 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1094 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1096 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1101 * Get previous page revision.
1103 * This method find the most recent revision before a specified
1108 * @param integer $version Find most recent revision before this version.
1109 * You can also use a WikiDB_PageRevision object to specify the $version.
1111 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1112 * requested revision does not exist in the {@link WikiDB}. Note that
1113 * unless $version is greater than zero, a revision (perhaps version zero,
1114 * the default revision) will always be found.
1116 function getRevisionBefore ($version=false, $need_content=true) {
1117 $backend = &$this->_wikidb->_backend;
1118 $pagename = &$this->_pagename;
1119 if ($version === false)
1120 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1122 $version = $this->_coerce_to_version($version);
1127 $previous = $backend->get_previous_version($pagename, $version);
1128 $revision = $this->getRevision($previous, $need_content);
1129 //$backend->unlock();
1135 * Get all revisions of the WikiDB_Page.
1137 * This does not include the version zero (default) revision in the
1138 * returned revision set.
1140 * @return WikiDB_PageRevisionIterator A
1141 * WikiDB_PageRevisionIterator containing all revisions of this
1142 * WikiDB_Page in reverse order by version number.
1144 function getAllRevisions() {
1145 $backend = &$this->_wikidb->_backend;
1146 $revs = $backend->get_all_revisions($this->_pagename);
1147 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1151 * Find pages which link to or are linked from a page.
1152 * relations: $backend->get_links is responsible to add the relation to the pagehash
1153 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1154 * if (isset($next['linkrelation']))
1158 * @param boolean $reversed Which links to find: true for backlinks (default).
1160 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1161 * all matching pages.
1163 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1164 $limit='', $exclude='', $want_relations=false)
1166 $backend = &$this->_wikidb->_backend;
1167 $result = $backend->get_links($this->_pagename, $reversed,
1168 $include_empty, $sortby, $limit, $exclude,
1170 return new WikiDB_PageIterator($this->_wikidb, $result,
1171 array('include_empty' => $include_empty,
1172 'sortby' => $sortby,
1174 'exclude' => $exclude,
1175 'want_relations'=> $want_relations));
1179 * All Links from other pages to this page.
1181 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1182 $want_relations=false)
1184 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1187 * Forward Links: All Links from this page to other pages.
1189 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1190 $want_relations=false)
1192 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1195 * Relations: All links from this page to other pages with relation <> 0.
1196 * is_a:=page or population:=number
1198 function getRelations($sortby='', $limit='', $exclude='') {
1199 $backend = &$this->_wikidb->_backend;
1200 $result = $backend->get_links($this->_pagename, false, true,
1201 $sortby, $limit, $exclude,
1203 // we do not care for the linked page versiondata, just the pagename and linkrelation
1204 return new WikiDB_PageIterator($this->_wikidb, $result,
1205 array('include_empty' => true,
1206 'sortby' => $sortby,
1208 'exclude' => $exclude,
1209 'want_relations'=> true));
1213 * possibly faster link existance check. not yet accelerated.
1215 function existLink($link, $reversed=false) {
1216 $backend = &$this->_wikidb->_backend;
1217 if (method_exists($backend,'exists_link'))
1218 return $backend->exists_link($this->_pagename, $link, $reversed);
1219 //$cache = &$this->_wikidb->_cache;
1220 // TODO: check cache if it is possible
1221 $iter = $this->getLinks($reversed, false);
1222 while ($page = $iter->next()) {
1223 if ($page->getName() == $link)
1230 /* Semantic relations are links with the relation pointing to another page,
1231 the so-called "RDF Triple".
1232 [San Diego] is%20a::city
1233 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1236 /* Semantic attributes for a page.
1237 [San Diego] population:=1,305,736
1238 Attributes are links with the relation pointing to another page.
1242 * Access WikiDB_Page non version-specific meta-data.
1246 * @param string $key Which meta data to get.
1247 * Some reserved meta-data keys are:
1249 * <dt>'date' <dd> Created as unixtime
1250 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1251 * <dt>'hits' <dd> Page hit counter.
1252 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1253 * In SQL stored now in an extra column.
1255 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1256 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1257 * E.g. "owner.users"
1258 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1259 * page-headers and content.
1260 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1261 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1264 * @return scalar The requested value, or false if the requested data
1267 function get($key) {
1268 $cache = &$this->_wikidb->_cache;
1269 $backend = &$this->_wikidb->_backend;
1270 if (!$key || $key[0] == '%')
1272 // several new SQL backends optimize this.
1273 if (!WIKIDB_NOCACHE_MARKUP
1274 and $key == '_cached_html'
1275 and method_exists($backend, 'get_cached_html'))
1277 return $backend->get_cached_html($this->_pagename);
1279 $data = $cache->get_pagedata($this->_pagename);
1280 return isset($data[$key]) ? $data[$key] : false;
1284 * Get all the page meta-data as a hash.
1286 * @return hash The page meta-data.
1288 function getMetaData() {
1289 $cache = &$this->_wikidb->_cache;
1290 $data = $cache->get_pagedata($this->_pagename);
1292 foreach ($data as $key => $val) {
1293 if (/*!empty($val) &&*/ $key[0] != '%')
1300 * Set page meta-data.
1305 * @param string $key Meta-data key to set.
1306 * @param string $newval New value.
1308 function set($key, $newval) {
1309 $cache = &$this->_wikidb->_cache;
1310 $backend = &$this->_wikidb->_backend;
1311 $pagename = &$this->_pagename;
1313 assert($key && $key[0] != '%');
1315 // several new SQL backends optimize this.
1316 if (!WIKIDB_NOCACHE_MARKUP
1317 and $key == '_cached_html'
1318 and method_exists($backend, 'set_cached_html'))
1320 return $backend->set_cached_html($pagename, $newval);
1323 $data = $cache->get_pagedata($pagename);
1325 if (!empty($newval)) {
1326 if (!empty($data[$key]) && $data[$key] == $newval)
1327 return; // values identical, skip update.
1330 if (empty($data[$key]))
1331 return; // values identical, skip update.
1334 $cache->update_pagedata($pagename, array($key => $newval));
1338 * Increase page hit count.
1340 * FIXME: IS this needed? Probably not.
1342 * This is a convenience function.
1343 * <pre> $page->increaseHitCount(); </pre>
1344 * is functionally identical to
1345 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1346 * but less expensive (ignores the pagadata string)
1348 * Note that this method may be implemented in more efficient ways
1349 * in certain backends.
1353 function increaseHitCount() {
1354 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1355 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1357 @$newhits = $this->get('hits') + 1;
1358 $this->set('hits', $newhits);
1363 * Return a string representation of the WikiDB_Page
1365 * This is really only for debugging.
1369 * @return string Printable representation of the WikiDB_Page.
1371 function asString () {
1373 printf("[%s:%s\n", get_class($this), $this->getName());
1374 print_r($this->getMetaData());
1376 $strval = ob_get_contents();
1384 * @param integer_or_object $version_or_pagerevision
1385 * Takes either the version number (and int) or a WikiDB_PageRevision
1387 * @return integer The version number.
1389 function _coerce_to_version($version_or_pagerevision) {
1390 if (method_exists($version_or_pagerevision, "getContent"))
1391 $version = $version_or_pagerevision->getVersion();
1393 $version = (int) $version_or_pagerevision;
1395 assert($version >= 0);
1399 function isUserPage ($include_empty = true) {
1400 if (!$include_empty and !$this->exists()) return false;
1401 return $this->get('pref') ? true : false;
1404 // May be empty. Either the stored owner (/Chown), or the first authorized author
1405 function getOwner() {
1406 if ($owner = $this->get('owner'))
1408 // check all revisions forwards for the first author_id
1409 $backend = &$this->_wikidb->_backend;
1410 $pagename = &$this->_pagename;
1411 $latestversion = $backend->get_latest_version($pagename);
1412 for ($v=1; $v <= $latestversion; $v++) {
1413 $rev = $this->getRevision($v,false);
1414 if ($rev and $owner = $rev->get('author_id')) {
1421 // The authenticated author of the first revision or empty if not authenticated then.
1422 function getCreator() {
1423 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1427 // The authenticated author of the current revision.
1428 function getAuthor() {
1429 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1433 /* Semantic Web value, not stored in the links.
1434 * todo: unify with some unit knowledge
1436 function setAttribute($relation, $value) {
1437 $attr = $this->get('attributes');
1439 $attr = array($relation => $value);
1441 $attr[$relation] = $value;
1442 $this->set('attributes', $attr);
1445 function getAttribute($relation) {
1446 $meta = $this->get('attributes');
1450 return $meta[$relation];
1456 * This class represents a specific revision of a WikiDB_Page within
1459 * A WikiDB_PageRevision has read-only semantics. You may only create
1460 * new revisions (and delete old ones) --- you cannot modify existing
1463 class WikiDB_PageRevision
1465 //var $_transformedContent = false; // set by WikiDB_Page::save()
1467 function WikiDB_PageRevision(&$wikidb, $pagename, $version, $versiondata = false) {
1468 $this->_wikidb = &$wikidb;
1469 $this->_pagename = $pagename;
1470 $this->_version = $version;
1471 $this->_data = $versiondata ? $versiondata : array();
1472 $this->_transformedContent = false; // set by WikiDB_Page::save()
1476 * Get the WikiDB_Page which this revision belongs to.
1480 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1482 function getPage() {
1483 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1487 * Get the version number of this revision.
1491 * @return integer The version number of this revision.
1493 function getVersion() {
1494 return $this->_version;
1498 * Determine whether this revision has defaulted content.
1500 * The default revision (version 0) of each page, as well as any
1501 * pages which are created with empty content have their content
1502 * defaulted to something like:
1504 * Describe [ThisPage] here.
1509 * @return boolean Returns true if the page has default content.
1511 function hasDefaultContents() {
1512 $data = &$this->_data;
1513 return empty($data['%content']); // FIXME: what if it's the number 0? <>'' or === false
1517 * Get the content as an array of lines.
1521 * @return array An array of lines.
1522 * The lines should contain no trailing white space.
1524 function getContent() {
1525 return explode("\n", $this->getPackedContent());
1529 * Get the pagename of the revision.
1533 * @return string pagename.
1535 function getPageName() {
1536 return $this->_pagename;
1538 function getName() {
1539 return $this->_pagename;
1543 * Determine whether revision is the latest.
1547 * @return boolean True iff the revision is the latest (most recent) one.
1549 function isCurrent() {
1550 if (!isset($this->_iscurrent)) {
1551 $page = $this->getPage();
1552 $current = $page->getCurrentRevision(false);
1553 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1555 return $this->_iscurrent;
1559 * Get the transformed content of a page.
1561 * @param string $pagetype Override the page-type of the revision.
1563 * @return object An XmlContent-like object containing the page transformed
1566 function getTransformedContent($pagetype_override=false) {
1567 $backend = &$this->_wikidb->_backend;
1569 if ($pagetype_override) {
1570 // Figure out the normal page-type for this page.
1571 $type = PageType::GetPageType($this->get('pagetype'));
1572 if ($type->getName() == $pagetype_override)
1573 $pagetype_override = false; // Not really an override...
1576 if ($pagetype_override) {
1577 // Overriden page type, don't cache (or check cache).
1578 return new TransformedText($this->getPage(),
1579 $this->getPackedContent(),
1580 $this->getMetaData(),
1581 $pagetype_override);
1584 $possibly_cache_results = true;
1586 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1587 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1588 // flush cache for this page.
1589 $page = $this->getPage();
1590 $page->set('_cached_html', ''); // ignored with !USECACHE
1592 $possibly_cache_results = false;
1594 elseif (USECACHE and !$this->_transformedContent) {
1596 if ($this->isCurrent()) {
1597 $page = $this->getPage();
1598 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1601 $possibly_cache_results = false;
1603 //$backend->unlock();
1606 if (!$this->_transformedContent) {
1607 $this->_transformedContent
1608 = new TransformedText($this->getPage(),
1609 $this->getPackedContent(),
1610 $this->getMetaData());
1612 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1613 // If we're still the current version, cache the transfomed page.
1615 if ($this->isCurrent()) {
1616 $page->set('_cached_html', $this->_transformedContent->pack());
1618 //$backend->unlock();
1622 return $this->_transformedContent;
1626 * Get the content as a string.
1630 * @return string The page content.
1631 * Lines are separated by new-lines.
1633 function getPackedContent() {
1634 $data = &$this->_data;
1636 if (empty($data['%content'])
1637 || (!$this->_wikidb->isWikiPage($this->_pagename)
1638 && $this->isCurrent())) {
1639 include_once('lib/InlineParser.php');
1641 // A feature similar to taglines at http://www.wlug.org.nz/
1642 // Lib from http://www.aasted.org/quote/
1643 if (defined('FORTUNE_DIR')
1644 and is_dir(FORTUNE_DIR)
1645 and in_array($GLOBALS['request']->getArg('action'),
1646 array('create','edit')))
1648 include_once("lib/fortune.php");
1649 $fortune = new Fortune();
1650 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1652 $quote = "<verbatim>\n"
1653 . str_replace("\n<br>","\n", $quote)
1654 . "</verbatim>\n\n";
1658 . sprintf(_("Describe %s here."),
1659 "[" . WikiEscape($this->_pagename) . "]");
1661 // Replace empty content with default value.
1662 return sprintf(_("Describe %s here."),
1663 "[" . WikiEscape($this->_pagename) . "]");
1666 // There is (non-default) content.
1667 assert($this->_version > 0);
1669 if (!is_string($data['%content'])) {
1670 // Content was not provided to us at init time.
1671 // (This is allowed because for some backends, fetching
1672 // the content may be expensive, and often is not wanted
1675 // In any case, now we need to get it.
1676 $data['%content'] = $this->_get_content();
1677 assert(is_string($data['%content']));
1680 return $data['%content'];
1683 function _get_content() {
1684 $cache = &$this->_wikidb->_cache;
1685 $pagename = $this->_pagename;
1686 $version = $this->_version;
1688 assert($version > 0);
1690 $newdata = $cache->get_versiondata($pagename, $version, true);
1692 assert(is_string($newdata['%content']));
1693 return $newdata['%content'];
1696 // else revision has been deleted... What to do?
1697 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1698 $version, $pagename);
1703 * Get meta-data for this revision.
1708 * @param string $key Which meta-data to access.
1710 * Some reserved revision meta-data keys are:
1712 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1713 * The 'mtime' meta-value is normally set automatically by the database
1714 * backend, but it may be specified explicitly when creating a new revision.
1716 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1717 * of a page must be monotonically increasing. If an attempt is
1718 * made to create a new revision with an mtime less than that of
1719 * the preceeding revision, the new revisions timestamp is force
1720 * to be equal to that of the preceeding revision. In that case,
1721 * the originally requested mtime is preserved in 'orig_mtime'.
1722 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1723 * This meta-value is <em>always</em> automatically maintained by the database
1724 * backend. (It is set from the 'mtime' meta-value of the superceding
1725 * revision.) '_supplanted' has a value of 'false' for the current revision.
1727 * FIXME: this could be refactored:
1729 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1731 * <dd> Authenticated author of a page. This is used to identify
1732 * the distinctness of authors when cleaning old revisions from
1734 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1735 * <dt> 'summary' <dd> Short change summary entered by page author.
1738 * Meta-data keys must be valid C identifers (they have to start with a letter
1739 * or underscore, and can contain only alphanumerics and underscores.)
1741 * @return string The requested value, or false if the requested value
1744 function get($key) {
1745 if (!$key || $key[0] == '%')
1747 $data = &$this->_data;
1748 return isset($data[$key]) ? $data[$key] : false;
1752 * Get all the revision page meta-data as a hash.
1754 * @return hash The revision meta-data.
1756 function getMetaData() {
1758 foreach ($this->_data as $key => $val) {
1759 if (!empty($val) && $key[0] != '%')
1767 * Return a string representation of the revision.
1769 * This is really only for debugging.
1773 * @return string Printable representation of the WikiDB_Page.
1775 function asString () {
1777 printf("[%s:%d\n", get_class($this), $this->get('version'));
1778 print_r($this->_data);
1779 echo $this->getPackedContent() . "\n]\n";
1780 $strval = ob_get_contents();
1788 * Class representing a sequence of WikiDB_Pages.
1789 * TODO: Enhance to php5 iterators
1791 * apply filters for options like 'sortby', 'limit', 'exclude'
1792 * for simple queries like titleSearch, where the backend is not ready yet.
1794 class WikiDB_PageIterator
1796 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1797 $this->_iter = $iter; // a WikiDB_backend_iterator
1798 $this->_wikidb = &$wikidb;
1799 $this->_options = $options;
1803 return $this->_iter->count();
1807 * Get next WikiDB_Page in sequence.
1811 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1814 if ( ! ($next = $this->_iter->next()) )
1817 $pagename = &$next['pagename'];
1818 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1819 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1820 $pagename = $pagename['linkto'];
1822 $pagename = strval($pagename);*/
1823 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1826 if (isset($next['linkrelation'])
1827 or isset($next['pagedata']['linkrelation'])) return false;
1828 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1832 // There's always hits, but we cache only if more
1833 // (well not with file, cvs and dba)
1834 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1835 $this->_wikidb->_cache->cache_data($next);
1836 // cache existing page id's since we iterate over all links in GleanDescription
1837 // and need them later for LinkExistingWord
1838 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1839 and !$this->_options['include_empty'] and isset($next['id'])) {
1840 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1842 $page = new WikiDB_Page($this->_wikidb, $pagename);
1843 if (isset($next['linkrelation']))
1844 $page->set('linkrelation', $next['linkrelation']);
1845 if (isset($next['score']))
1846 $page->score = $next['score'];
1851 * Release resources held by this iterator.
1853 * The iterator may not be used after free() is called.
1855 * There is no need to call free(), if next() has returned false.
1856 * (I.e. if you iterate through all the pages in the sequence,
1857 * you do not need to call free() --- you only need to call it
1858 * if you stop before the end of the iterator is reached.)
1863 $this->_iter->free();
1866 $this->_iter->reset();
1868 function asArray() {
1870 while ($page = $this->next())
1877 * Apply filters for options like 'sortby', 'limit', 'exclude'
1878 * for simple queries like titleSearch, where the backend is not ready yet.
1879 * Since iteration is usually destructive for SQL results,
1880 * we have to generate a copy.
1882 function applyFilters($options = false) {
1883 if (!$options) $options = $this->_options;
1884 if (isset($options['sortby'])) {
1886 /* this is destructive */
1887 while ($page = $this->next())
1888 $result[] = $page->getName();
1889 $this->_doSort($array, $options['sortby']);
1891 /* the rest is not destructive.
1892 * reconstruct a new iterator
1894 $pagenames = array(); $i = 0;
1895 if (isset($options['limit']))
1896 $limit = $options['limit'];
1899 if (isset($options['exclude']))
1900 $exclude = $options['exclude'];
1901 if (is_string($exclude) and !is_array($exclude))
1902 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1903 foreach($array as $pagename) {
1904 if ($limit and $i++ > $limit)
1905 return new WikiDB_Array_PageIterator($pagenames);
1906 if (!empty($exclude) and !in_array($pagename, $exclude))
1907 $pagenames[] = $pagename;
1908 elseif (empty($exclude))
1909 $pagenames[] = $pagename;
1911 return new WikiDB_Array_PageIterator($pagenames);
1915 function _doSort(&$array, $sortby) {
1916 $sortby = PageList::sortby($sortby, 'init');
1917 if ($sortby == '+pagename')
1918 sort($array, SORT_STRING);
1919 elseif ($sortby == '-pagename')
1920 rsort($array, SORT_STRING);
1927 * A class which represents a sequence of WikiDB_PageRevisions.
1928 * TODO: Enhance to php5 iterators
1930 class WikiDB_PageRevisionIterator
1932 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1933 $this->_revisions = $revisions;
1934 $this->_wikidb = &$wikidb;
1935 $this->_options = $options;
1939 return $this->_revisions->count();
1943 * Get next WikiDB_PageRevision in sequence.
1947 * @return WikiDB_PageRevision
1948 * The next WikiDB_PageRevision in the sequence.
1951 if ( ! ($next = $this->_revisions->next()) )
1954 //$this->_wikidb->_cache->cache_data($next);
1956 $pagename = $next['pagename'];
1957 $version = $next['version'];
1958 $versiondata = $next['versiondata'];
1960 if (!(is_string($pagename) and $pagename != '')) {
1961 trigger_error("empty pagename",E_USER_WARNING);
1964 } else assert(is_string($pagename) and $pagename != '');
1966 if (!is_array($versiondata)) {
1967 trigger_error("empty versiondata",E_USER_WARNING);
1970 } else assert(is_array($versiondata));
1972 if (!($version > 0)) {
1973 trigger_error("invalid version",E_USER_WARNING);
1976 } else assert($version > 0);
1978 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1983 * Release resources held by this iterator.
1985 * The iterator may not be used after free() is called.
1987 * There is no need to call free(), if next() has returned false.
1988 * (I.e. if you iterate through all the revisions in the sequence,
1989 * you do not need to call free() --- you only need to call it
1990 * if you stop before the end of the iterator is reached.)
1995 $this->_revisions->free();
1998 function asArray() {
2000 while ($rev = $this->next())
2009 class WikiDB_Array_PageIterator
2011 function WikiDB_Array_PageIterator($pagenames) {
2013 $this->_dbi = $request->getDbh();
2014 $this->_pages = $pagenames;
2015 reset($this->_pages);
2018 $c = current($this->_pages);
2019 next($this->_pages);
2020 return $c !== false ? $this->_dbi->getPage($c) : false;
2023 return count($this->_pages);
2026 reset($this->_pages);
2029 function asArray() {
2030 reset($this->_pages);
2031 return $this->_pages;
2035 class WikiDB_Array_generic_iter
2037 function WikiDB_Array_generic_iter($result) {
2038 // $result may be either an array or a query result
2039 if (is_array($result)) {
2040 $this->_array = $result;
2041 } elseif (is_object($result)) {
2042 $this->_array = $result->asArray();
2044 $this->_array = array();
2046 if (!empty($this->_array))
2047 reset($this->_array);
2050 $c = current($this->_array);
2051 next($this->_array);
2052 return $c !== false ? $c : false;
2055 return count($this->_array);
2058 reset($this->_array);
2061 function asArray() {
2062 if (!empty($this->_array))
2063 reset($this->_array);
2064 return $this->_array;
2069 * Data cache used by WikiDB.
2071 * FIXME: Maybe rename this to caching_backend (or some such).
2077 // FIXME: beautify versiondata cache. Cache only limited data?
2079 function WikiDB_cache (&$backend) {
2080 $this->_backend = &$backend;
2082 $this->_pagedata_cache = array();
2083 $this->_versiondata_cache = array();
2084 array_push ($this->_versiondata_cache, array());
2085 $this->_glv_cache = array();
2086 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2090 $this->_pagedata_cache = array();
2091 $this->_versiondata_cache = array();
2092 $this->_glv_cache = array();
2093 $this->_id_cache = array();
2096 function get_pagedata($pagename) {
2097 assert(is_string($pagename) && $pagename != '');
2099 $cache = &$this->_pagedata_cache;
2100 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2101 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2102 if (empty($cache[$pagename]))
2103 $cache[$pagename] = array();
2105 return $cache[$pagename];
2107 return $this->_backend->get_pagedata($pagename);
2111 function update_pagedata($pagename, $newdata) {
2112 assert(is_string($pagename) && $pagename != '');
2114 $this->_backend->update_pagedata($pagename, $newdata);
2117 if (!empty($this->_pagedata_cache[$pagename])
2118 and is_array($this->_pagedata_cache[$pagename]))
2120 $cachedata = &$this->_pagedata_cache[$pagename];
2121 foreach($newdata as $key => $val)
2122 $cachedata[$key] = $val;
2124 $this->_pagedata_cache[$pagename] = $newdata;
2128 function invalidate_cache($pagename) {
2129 unset ($this->_pagedata_cache[$pagename]);
2130 unset ($this->_versiondata_cache[$pagename]);
2131 unset ($this->_glv_cache[$pagename]);
2132 unset ($this->_id_cache[$pagename]);
2133 //unset ($this->_backend->_page_data);
2136 function delete_page($pagename) {
2137 $result = $this->_backend->delete_page($pagename);
2138 $this->invalidate_cache($pagename);
2142 function purge_page($pagename) {
2143 $result = $this->_backend->purge_page($pagename);
2144 $this->invalidate_cache($pagename);
2148 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2149 function cache_data($data) {
2151 //if (isset($data['pagedata']))
2152 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2155 function get_versiondata($pagename, $version, $need_content = false) {
2156 // FIXME: Seriously ugly hackage
2158 if (USECACHE) { //temporary - for debugging
2159 assert(is_string($pagename) && $pagename != '');
2160 // There is a bug here somewhere which results in an assertion failure at line 105
2161 // of ArchiveCleaner.php It goes away if we use the next line.
2162 //$need_content = true;
2163 $nc = $need_content ? '1':'0';
2164 $cache = &$this->_versiondata_cache;
2165 if (!isset($cache[$pagename][$version][$nc])
2166 || !(is_array ($cache[$pagename]))
2167 || !(is_array ($cache[$pagename][$version])))
2169 $cache[$pagename][$version][$nc] =
2170 $this->_backend->get_versiondata($pagename, $version, $need_content);
2172 // If we have retrieved all data, we may as well set the cache for
2173 // $need_content = false
2175 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2178 $vdata = $cache[$pagename][$version][$nc];
2180 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2183 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2184 if (empty($this->_pagedata_cache))
2185 $this->_pagedata_cache = array();
2186 /* PHP Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/html/phpwiki/lib/WikiDB.php on line 2180, referer: wiki/TitleSearch?s=and&auto_redirect=1 */
2187 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2192 function set_versiondata($pagename, $version, $data) {
2193 //unset($this->_versiondata_cache[$pagename][$version]);
2195 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2197 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2198 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2199 // Is this necessary?
2200 unset($this->_glv_cache[$pagename]);
2203 function update_versiondata($pagename, $version, $data) {
2204 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2206 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2208 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2209 // Is this necessary?
2210 unset($this->_glv_cache[$pagename]);
2213 function delete_versiondata($pagename, $version) {
2214 $new = $this->_backend->delete_versiondata($pagename, $version);
2215 if (isset($this->_versiondata_cache[$pagename][$version]))
2216 unset ($this->_versiondata_cache[$pagename][$version]);
2217 // dirty latest version cache only if latest version gets deleted
2218 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2219 unset ($this->_glv_cache[$pagename]);
2222 function get_latest_version($pagename) {
2224 assert (is_string($pagename) && $pagename != '');
2225 $cache = &$this->_glv_cache;
2226 if (!isset($cache[$pagename])) {
2227 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2228 if (empty($cache[$pagename]))
2229 $cache[$pagename] = 0;
2231 return $cache[$pagename];
2233 return $this->_backend->get_latest_version($pagename);
2238 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2242 $stamp = strftime("%y%m%d-%H%M%S");
2243 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2244 register_shutdown_function("_sql_debuglog_shutdown_function");
2245 } elseif ($shutdown) {
2249 if ($newline) fputs($fp, "[$i++] $msg");
2250 else fwrite($fp, $msg);
2253 function _sql_debuglog_shutdown_function() {
2254 _sql_debuglog('',false,true);
2260 // c-basic-offset: 4
2261 // c-hanging-comment-ender-p: nil
2262 // indent-tabs-mode: nil