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 and empty($meta['is_minor_edit'])) {
1034 require_once("lib/WikiPlugin.php");
1035 $w = new WikiPluginLoader;
1036 $p = $w->getPlugin("RecentChangesCached", false);
1037 $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1039 return $newrevision;
1043 * Get the most recent revision of a page.
1047 * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1049 function getCurrentRevision ($need_content=true) {
1050 $backend = &$this->_wikidb->_backend;
1051 $cache = &$this->_wikidb->_cache;
1052 $pagename = &$this->_pagename;
1054 // Prevent deadlock in case of memory exhausted errors
1055 // Pure selection doesn't really need locking here.
1056 // sf.net bug#927395
1057 // I know it would be better to lock, but with lots of pages this deadlock is more
1058 // severe than occasionally get not the latest revision.
1059 // In spirit to wikiwiki: read fast, edit slower.
1061 $version = $cache->get_latest_version($pagename);
1062 // getRevision gets the content also!
1063 $revision = $this->getRevision($version, $need_content);
1064 //$backend->unlock();
1070 * Get a specific revision of a WikiDB_Page.
1074 * @param integer $version Which revision to get.
1076 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1077 * false if the requested revision does not exist in the {@link WikiDB}.
1078 * Note that version zero of any page always exists.
1080 function getRevision ($version, $need_content=true) {
1081 $cache = &$this->_wikidb->_cache;
1082 $pagename = &$this->_pagename;
1084 if (! $version or $version == -1) // 0 or false
1085 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1087 assert($version > 0);
1088 $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1090 return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1092 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1097 * Get previous page revision.
1099 * This method find the most recent revision before a specified
1104 * @param integer $version Find most recent revision before this version.
1105 * You can also use a WikiDB_PageRevision object to specify the $version.
1107 * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1108 * requested revision does not exist in the {@link WikiDB}. Note that
1109 * unless $version is greater than zero, a revision (perhaps version zero,
1110 * the default revision) will always be found.
1112 function getRevisionBefore ($version=false, $need_content=true) {
1113 $backend = &$this->_wikidb->_backend;
1114 $pagename = &$this->_pagename;
1115 if ($version === false)
1116 $version = $this->_wikidb->_cache->get_latest_version($pagename);
1118 $version = $this->_coerce_to_version($version);
1123 $previous = $backend->get_previous_version($pagename, $version);
1124 $revision = $this->getRevision($previous, $need_content);
1125 //$backend->unlock();
1131 * Get all revisions of the WikiDB_Page.
1133 * This does not include the version zero (default) revision in the
1134 * returned revision set.
1136 * @return WikiDB_PageRevisionIterator A
1137 * WikiDB_PageRevisionIterator containing all revisions of this
1138 * WikiDB_Page in reverse order by version number.
1140 function getAllRevisions() {
1141 $backend = &$this->_wikidb->_backend;
1142 $revs = $backend->get_all_revisions($this->_pagename);
1143 return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1147 * Find pages which link to or are linked from a page.
1148 * relations: $backend->get_links is responsible to add the relation to the pagehash
1149 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1150 * if (isset($next['linkrelation']))
1154 * @param boolean $reversed Which links to find: true for backlinks (default).
1156 * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1157 * all matching pages.
1159 function getLinks ($reversed=true, $include_empty=false, $sortby='',
1160 $limit='', $exclude='', $want_relations=false)
1162 $backend = &$this->_wikidb->_backend;
1163 $result = $backend->get_links($this->_pagename, $reversed,
1164 $include_empty, $sortby, $limit, $exclude,
1166 return new WikiDB_PageIterator($this->_wikidb, $result,
1167 array('include_empty' => $include_empty,
1168 'sortby' => $sortby,
1170 'exclude' => $exclude,
1171 'want_relations'=> $want_relations));
1175 * All Links from other pages to this page.
1177 function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1178 $want_relations=false)
1180 return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1183 * Forward Links: All Links from this page to other pages.
1185 function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1186 $want_relations=false)
1188 return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1191 * Relations: All links from this page to other pages with relation <> 0.
1192 * is_a:=page or population:=number
1194 function getRelations($sortby='', $limit='', $exclude='') {
1195 $backend = &$this->_wikidb->_backend;
1196 $result = $backend->get_links($this->_pagename, false, true,
1197 $sortby, $limit, $exclude,
1199 // we do not care for the linked page versiondata, just the pagename and linkrelation
1200 return new WikiDB_PageIterator($this->_wikidb, $result,
1201 array('include_empty' => true,
1202 'sortby' => $sortby,
1204 'exclude' => $exclude,
1205 'want_relations'=> true));
1209 * possibly faster link existance check. not yet accelerated.
1211 function existLink($link, $reversed=false) {
1212 $backend = &$this->_wikidb->_backend;
1213 if (method_exists($backend,'exists_link'))
1214 return $backend->exists_link($this->_pagename, $link, $reversed);
1215 //$cache = &$this->_wikidb->_cache;
1216 // TODO: check cache if it is possible
1217 $iter = $this->getLinks($reversed, false);
1218 while ($page = $iter->next()) {
1219 if ($page->getName() == $link)
1226 /* Semantic relations are links with the relation pointing to another page,
1227 the so-called "RDF Triple".
1228 [San Diego] is%20a::city
1229 => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1232 /* Semantic attributes for a page.
1233 [San Diego] population:=1,305,736
1234 Attributes are links with the relation pointing to another page.
1238 * Access WikiDB_Page non version-specific meta-data.
1242 * @param string $key Which meta data to get.
1243 * Some reserved meta-data keys are:
1245 * <dt>'date' <dd> Created as unixtime
1246 * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1247 * <dt>'hits' <dd> Page hit counter.
1248 * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1249 * In SQL stored now in an extra column.
1251 * <dt>'pref' <dd> Users preferences, stored only in homepages.
1252 * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1253 * E.g. "owner.users"
1254 * <dt>'perm' <dd> Permission flag to authorize read/write/execution of
1255 * page-headers and content.
1256 + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1257 * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1260 * @return scalar The requested value, or false if the requested data
1263 function get($key) {
1264 $cache = &$this->_wikidb->_cache;
1265 $backend = &$this->_wikidb->_backend;
1266 if (!$key || $key[0] == '%')
1268 // several new SQL backends optimize this.
1269 if (!WIKIDB_NOCACHE_MARKUP
1270 and $key == '_cached_html'
1271 and method_exists($backend, 'get_cached_html'))
1273 return $backend->get_cached_html($this->_pagename);
1275 $data = $cache->get_pagedata($this->_pagename);
1276 return isset($data[$key]) ? $data[$key] : false;
1280 * Get all the page meta-data as a hash.
1282 * @return hash The page meta-data.
1284 function getMetaData() {
1285 $cache = &$this->_wikidb->_cache;
1286 $data = $cache->get_pagedata($this->_pagename);
1288 foreach ($data as $key => $val) {
1289 if (/*!empty($val) &&*/ $key[0] != '%')
1296 * Set page meta-data.
1301 * @param string $key Meta-data key to set.
1302 * @param string $newval New value.
1304 function set($key, $newval) {
1305 $cache = &$this->_wikidb->_cache;
1306 $backend = &$this->_wikidb->_backend;
1307 $pagename = &$this->_pagename;
1309 assert($key && $key[0] != '%');
1311 // several new SQL backends optimize this.
1312 if (!WIKIDB_NOCACHE_MARKUP
1313 and $key == '_cached_html'
1314 and method_exists($backend, 'set_cached_html'))
1316 return $backend->set_cached_html($pagename, $newval);
1319 $data = $cache->get_pagedata($pagename);
1321 if (!empty($newval)) {
1322 if (!empty($data[$key]) && $data[$key] == $newval)
1323 return; // values identical, skip update.
1326 if (empty($data[$key]))
1327 return; // values identical, skip update.
1330 $cache->update_pagedata($pagename, array($key => $newval));
1334 * Increase page hit count.
1336 * FIXME: IS this needed? Probably not.
1338 * This is a convenience function.
1339 * <pre> $page->increaseHitCount(); </pre>
1340 * is functionally identical to
1341 * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1342 * but less expensive (ignores the pagadata string)
1344 * Note that this method may be implemented in more efficient ways
1345 * in certain backends.
1349 function increaseHitCount() {
1350 if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1351 $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1353 @$newhits = $this->get('hits') + 1;
1354 $this->set('hits', $newhits);
1359 * Return a string representation of the WikiDB_Page
1361 * This is really only for debugging.
1365 * @return string Printable representation of the WikiDB_Page.
1367 function asString () {
1369 printf("[%s:%s\n", get_class($this), $this->getName());
1370 print_r($this->getMetaData());
1372 $strval = ob_get_contents();
1380 * @param integer_or_object $version_or_pagerevision
1381 * Takes either the version number (and int) or a WikiDB_PageRevision
1383 * @return integer The version number.
1385 function _coerce_to_version($version_or_pagerevision) {
1386 if (method_exists($version_or_pagerevision, "getContent"))
1387 $version = $version_or_pagerevision->getVersion();
1389 $version = (int) $version_or_pagerevision;
1391 assert($version >= 0);
1395 function isUserPage ($include_empty = true) {
1396 if (!$include_empty and !$this->exists()) return false;
1397 return $this->get('pref') ? true : false;
1400 // May be empty. Either the stored owner (/Chown), or the first authorized author
1401 function getOwner() {
1402 if ($owner = $this->get('owner'))
1404 // check all revisions forwards for the first author_id
1405 $backend = &$this->_wikidb->_backend;
1406 $pagename = &$this->_pagename;
1407 $latestversion = $backend->get_latest_version($pagename);
1408 for ($v=1; $v <= $latestversion; $v++) {
1409 $rev = $this->getRevision($v,false);
1410 if ($rev and $owner = $rev->get('author_id')) {
1417 // The authenticated author of the first revision or empty if not authenticated then.
1418 function getCreator() {
1419 if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1423 // The authenticated author of the current revision.
1424 function getAuthor() {
1425 if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1429 /* Semantic Web value, not stored in the links.
1430 * todo: unify with some unit knowledge
1432 function setAttribute($relation, $value) {
1433 $attr = $this->get('attributes');
1435 $attr = array($relation => $value);
1437 $attr[$relation] = $value;
1438 $this->set('attributes', $attr);
1441 function getAttribute($relation) {
1442 $meta = $this->get('attributes');
1446 return $meta[$relation];
1452 * This class represents a specific revision of a WikiDB_Page within
1455 * A WikiDB_PageRevision has read-only semantics. You may only create
1456 * new revisions (and delete old ones) --- you cannot modify existing
1459 class WikiDB_PageRevision
1461 //var $_transformedContent = false; // set by WikiDB_Page::save()
1463 function WikiDB_PageRevision(&$wikidb, $pagename, $version, $versiondata = false) {
1464 $this->_wikidb = &$wikidb;
1465 $this->_pagename = $pagename;
1466 $this->_version = $version;
1467 $this->_data = $versiondata ? $versiondata : array();
1468 $this->_transformedContent = false; // set by WikiDB_Page::save()
1472 * Get the WikiDB_Page which this revision belongs to.
1476 * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1478 function getPage() {
1479 return new WikiDB_Page($this->_wikidb, $this->_pagename);
1483 * Get the version number of this revision.
1487 * @return integer The version number of this revision.
1489 function getVersion() {
1490 return $this->_version;
1494 * Determine whether this revision has defaulted content.
1496 * The default revision (version 0) of each page, as well as any
1497 * pages which are created with empty content have their content
1498 * defaulted to something like:
1500 * Describe [ThisPage] here.
1505 * @return boolean Returns true if the page has default content.
1507 function hasDefaultContents() {
1508 $data = &$this->_data;
1509 return empty($data['%content']); // FIXME: what if it's the number 0? <>'' or === false
1513 * Get the content as an array of lines.
1517 * @return array An array of lines.
1518 * The lines should contain no trailing white space.
1520 function getContent() {
1521 return explode("\n", $this->getPackedContent());
1525 * Get the pagename of the revision.
1529 * @return string pagename.
1531 function getPageName() {
1532 return $this->_pagename;
1534 function getName() {
1535 return $this->_pagename;
1539 * Determine whether revision is the latest.
1543 * @return boolean True iff the revision is the latest (most recent) one.
1545 function isCurrent() {
1546 if (!isset($this->_iscurrent)) {
1547 $page = $this->getPage();
1548 $current = $page->getCurrentRevision(false);
1549 $this->_iscurrent = $this->getVersion() == $current->getVersion();
1551 return $this->_iscurrent;
1555 * Get the transformed content of a page.
1557 * @param string $pagetype Override the page-type of the revision.
1559 * @return object An XmlContent-like object containing the page transformed
1562 function getTransformedContent($pagetype_override=false) {
1563 $backend = &$this->_wikidb->_backend;
1565 if ($pagetype_override) {
1566 // Figure out the normal page-type for this page.
1567 $type = PageType::GetPageType($this->get('pagetype'));
1568 if ($type->getName() == $pagetype_override)
1569 $pagetype_override = false; // Not really an override...
1572 if ($pagetype_override) {
1573 // Overriden page type, don't cache (or check cache).
1574 return new TransformedText($this->getPage(),
1575 $this->getPackedContent(),
1576 $this->getMetaData(),
1577 $pagetype_override);
1580 $possibly_cache_results = true;
1582 if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1583 if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1584 // flush cache for this page.
1585 $page = $this->getPage();
1586 $page->set('_cached_html', ''); // ignored with !USECACHE
1588 $possibly_cache_results = false;
1590 elseif (USECACHE and !$this->_transformedContent) {
1592 if ($this->isCurrent()) {
1593 $page = $this->getPage();
1594 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1597 $possibly_cache_results = false;
1599 //$backend->unlock();
1602 if (!$this->_transformedContent) {
1603 $this->_transformedContent
1604 = new TransformedText($this->getPage(),
1605 $this->getPackedContent(),
1606 $this->getMetaData());
1608 if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1609 // If we're still the current version, cache the transfomed page.
1611 if ($this->isCurrent()) {
1612 $page->set('_cached_html', $this->_transformedContent->pack());
1614 //$backend->unlock();
1618 return $this->_transformedContent;
1622 * Get the content as a string.
1626 * @return string The page content.
1627 * Lines are separated by new-lines.
1629 function getPackedContent() {
1630 $data = &$this->_data;
1632 if (empty($data['%content'])
1633 || (!$this->_wikidb->isWikiPage($this->_pagename)
1634 && $this->isCurrent())) {
1635 include_once('lib/InlineParser.php');
1637 // A feature similar to taglines at http://www.wlug.org.nz/
1638 // Lib from http://www.aasted.org/quote/
1639 if (defined('FORTUNE_DIR')
1640 and is_dir(FORTUNE_DIR)
1641 and in_array($GLOBALS['request']->getArg('action'),
1642 array('create','edit')))
1644 include_once("lib/fortune.php");
1645 $fortune = new Fortune();
1646 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1648 $quote = "<verbatim>\n"
1649 . str_replace("\n<br>","\n", $quote)
1650 . "</verbatim>\n\n";
1654 . sprintf(_("Describe %s here."),
1655 "[" . WikiEscape($this->_pagename) . "]");
1657 // Replace empty content with default value.
1658 return sprintf(_("Describe %s here."),
1659 "[" . WikiEscape($this->_pagename) . "]");
1662 // There is (non-default) content.
1663 assert($this->_version > 0);
1665 if (!is_string($data['%content'])) {
1666 // Content was not provided to us at init time.
1667 // (This is allowed because for some backends, fetching
1668 // the content may be expensive, and often is not wanted
1671 // In any case, now we need to get it.
1672 $data['%content'] = $this->_get_content();
1673 assert(is_string($data['%content']));
1676 return $data['%content'];
1679 function _get_content() {
1680 $cache = &$this->_wikidb->_cache;
1681 $pagename = $this->_pagename;
1682 $version = $this->_version;
1684 assert($version > 0);
1686 $newdata = $cache->get_versiondata($pagename, $version, true);
1688 assert(is_string($newdata['%content']));
1689 return $newdata['%content'];
1692 // else revision has been deleted... What to do?
1693 return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1694 $version, $pagename);
1699 * Get meta-data for this revision.
1704 * @param string $key Which meta-data to access.
1706 * Some reserved revision meta-data keys are:
1708 * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1709 * The 'mtime' meta-value is normally set automatically by the database
1710 * backend, but it may be specified explicitly when creating a new revision.
1712 * <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1713 * of a page must be monotonically increasing. If an attempt is
1714 * made to create a new revision with an mtime less than that of
1715 * the preceeding revision, the new revisions timestamp is force
1716 * to be equal to that of the preceeding revision. In that case,
1717 * the originally requested mtime is preserved in 'orig_mtime'.
1718 * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1719 * This meta-value is <em>always</em> automatically maintained by the database
1720 * backend. (It is set from the 'mtime' meta-value of the superceding
1721 * revision.) '_supplanted' has a value of 'false' for the current revision.
1723 * FIXME: this could be refactored:
1725 * <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1727 * <dd> Authenticated author of a page. This is used to identify
1728 * the distinctness of authors when cleaning old revisions from
1730 * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1731 * <dt> 'summary' <dd> Short change summary entered by page author.
1734 * Meta-data keys must be valid C identifers (they have to start with a letter
1735 * or underscore, and can contain only alphanumerics and underscores.)
1737 * @return string The requested value, or false if the requested value
1740 function get($key) {
1741 if (!$key || $key[0] == '%')
1743 $data = &$this->_data;
1744 return isset($data[$key]) ? $data[$key] : false;
1748 * Get all the revision page meta-data as a hash.
1750 * @return hash The revision meta-data.
1752 function getMetaData() {
1754 foreach ($this->_data as $key => $val) {
1755 if (!empty($val) && $key[0] != '%')
1763 * Return a string representation of the revision.
1765 * This is really only for debugging.
1769 * @return string Printable representation of the WikiDB_Page.
1771 function asString () {
1773 printf("[%s:%d\n", get_class($this), $this->get('version'));
1774 print_r($this->_data);
1775 echo $this->getPackedContent() . "\n]\n";
1776 $strval = ob_get_contents();
1784 * Class representing a sequence of WikiDB_Pages.
1785 * TODO: Enhance to php5 iterators
1787 * apply filters for options like 'sortby', 'limit', 'exclude'
1788 * for simple queries like titleSearch, where the backend is not ready yet.
1790 class WikiDB_PageIterator
1792 function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1793 $this->_iter = $iter; // a WikiDB_backend_iterator
1794 $this->_wikidb = &$wikidb;
1795 $this->_options = $options;
1799 return $this->_iter->count();
1803 * Get next WikiDB_Page in sequence.
1807 * @return WikiDB_Page The next WikiDB_Page in the sequence.
1810 if ( ! ($next = $this->_iter->next()) )
1813 $pagename = &$next['pagename'];
1814 if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1815 /*if (is_array($pagename) && isset($pagename['linkto'])) {
1816 $pagename = $pagename['linkto'];
1818 $pagename = strval($pagename);*/
1819 trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1822 if (isset($next['linkrelation'])
1823 or isset($next['pagedata']['linkrelation'])) return false;
1824 trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1828 // There's always hits, but we cache only if more
1829 // (well not with file, cvs and dba)
1830 if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1831 $this->_wikidb->_cache->cache_data($next);
1832 // cache existing page id's since we iterate over all links in GleanDescription
1833 // and need them later for LinkExistingWord
1834 } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1835 and !$this->_options['include_empty'] and isset($next['id'])) {
1836 $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1838 $page = new WikiDB_Page($this->_wikidb, $pagename);
1839 if (isset($next['linkrelation']))
1840 $page->set('linkrelation', $next['linkrelation']);
1841 if (isset($next['score']))
1842 $page->score = $next['score'];
1847 * Release resources held by this iterator.
1849 * The iterator may not be used after free() is called.
1851 * There is no need to call free(), if next() has returned false.
1852 * (I.e. if you iterate through all the pages in the sequence,
1853 * you do not need to call free() --- you only need to call it
1854 * if you stop before the end of the iterator is reached.)
1859 $this->_iter->free();
1862 $this->_iter->reset();
1864 function asArray() {
1866 while ($page = $this->next())
1873 * Apply filters for options like 'sortby', 'limit', 'exclude'
1874 * for simple queries like titleSearch, where the backend is not ready yet.
1875 * Since iteration is usually destructive for SQL results,
1876 * we have to generate a copy.
1878 function applyFilters($options = false) {
1879 if (!$options) $options = $this->_options;
1880 if (isset($options['sortby'])) {
1882 /* this is destructive */
1883 while ($page = $this->next())
1884 $result[] = $page->getName();
1885 $this->_doSort($array, $options['sortby']);
1887 /* the rest is not destructive.
1888 * reconstruct a new iterator
1890 $pagenames = array(); $i = 0;
1891 if (isset($options['limit']))
1892 $limit = $options['limit'];
1895 if (isset($options['exclude']))
1896 $exclude = $options['exclude'];
1897 if (is_string($exclude) and !is_array($exclude))
1898 $exclude = PageList::explodePageList($exclude, false, false, $limit);
1899 foreach($array as $pagename) {
1900 if ($limit and $i++ > $limit)
1901 return new WikiDB_Array_PageIterator($pagenames);
1902 if (!empty($exclude) and !in_array($pagename, $exclude))
1903 $pagenames[] = $pagename;
1904 elseif (empty($exclude))
1905 $pagenames[] = $pagename;
1907 return new WikiDB_Array_PageIterator($pagenames);
1911 function _doSort(&$array, $sortby) {
1912 $sortby = PageList::sortby($sortby, 'init');
1913 if ($sortby == '+pagename')
1914 sort($array, SORT_STRING);
1915 elseif ($sortby == '-pagename')
1916 rsort($array, SORT_STRING);
1923 * A class which represents a sequence of WikiDB_PageRevisions.
1924 * TODO: Enhance to php5 iterators
1926 class WikiDB_PageRevisionIterator
1928 function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1929 $this->_revisions = $revisions;
1930 $this->_wikidb = &$wikidb;
1931 $this->_options = $options;
1935 return $this->_revisions->count();
1939 * Get next WikiDB_PageRevision in sequence.
1943 * @return WikiDB_PageRevision
1944 * The next WikiDB_PageRevision in the sequence.
1947 if ( ! ($next = $this->_revisions->next()) )
1950 //$this->_wikidb->_cache->cache_data($next);
1952 $pagename = $next['pagename'];
1953 $version = $next['version'];
1954 $versiondata = $next['versiondata'];
1956 if (!(is_string($pagename) and $pagename != '')) {
1957 trigger_error("empty pagename",E_USER_WARNING);
1960 } else assert(is_string($pagename) and $pagename != '');
1962 if (!is_array($versiondata)) {
1963 trigger_error("empty versiondata",E_USER_WARNING);
1966 } else assert(is_array($versiondata));
1968 if (!($version > 0)) {
1969 trigger_error("invalid version",E_USER_WARNING);
1972 } else assert($version > 0);
1974 return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1979 * Release resources held by this iterator.
1981 * The iterator may not be used after free() is called.
1983 * There is no need to call free(), if next() has returned false.
1984 * (I.e. if you iterate through all the revisions in the sequence,
1985 * you do not need to call free() --- you only need to call it
1986 * if you stop before the end of the iterator is reached.)
1991 $this->_revisions->free();
1994 function asArray() {
1996 while ($rev = $this->next())
2005 class WikiDB_Array_PageIterator
2007 function WikiDB_Array_PageIterator($pagenames) {
2009 $this->_dbi = $request->getDbh();
2010 $this->_pages = $pagenames;
2011 reset($this->_pages);
2014 $c = current($this->_pages);
2015 next($this->_pages);
2016 return $c !== false ? $this->_dbi->getPage($c) : false;
2019 return count($this->_pages);
2022 reset($this->_pages);
2025 function asArray() {
2026 reset($this->_pages);
2027 return $this->_pages;
2031 class WikiDB_Array_generic_iter
2033 function WikiDB_Array_generic_iter($result) {
2034 // $result may be either an array or a query result
2035 if (is_array($result)) {
2036 $this->_array = $result;
2037 } elseif (is_object($result)) {
2038 $this->_array = $result->asArray();
2040 $this->_array = array();
2042 if (!empty($this->_array))
2043 reset($this->_array);
2046 $c = current($this->_array);
2047 next($this->_array);
2048 return $c !== false ? $c : false;
2051 return count($this->_array);
2054 reset($this->_array);
2057 function asArray() {
2058 if (!empty($this->_array))
2059 reset($this->_array);
2060 return $this->_array;
2065 * Data cache used by WikiDB.
2067 * FIXME: Maybe rename this to caching_backend (or some such).
2073 // FIXME: beautify versiondata cache. Cache only limited data?
2075 function WikiDB_cache (&$backend) {
2076 $this->_backend = &$backend;
2078 $this->_pagedata_cache = array();
2079 $this->_versiondata_cache = array();
2080 array_push ($this->_versiondata_cache, array());
2081 $this->_glv_cache = array();
2082 $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2086 $this->_pagedata_cache = array();
2087 $this->_versiondata_cache = array();
2088 $this->_glv_cache = array();
2089 $this->_id_cache = array();
2092 function get_pagedata($pagename) {
2093 assert(is_string($pagename) && $pagename != '');
2095 $cache = &$this->_pagedata_cache;
2096 if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2097 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2098 if (empty($cache[$pagename]))
2099 $cache[$pagename] = array();
2101 return $cache[$pagename];
2103 return $this->_backend->get_pagedata($pagename);
2107 function update_pagedata($pagename, $newdata) {
2108 assert(is_string($pagename) && $pagename != '');
2110 $this->_backend->update_pagedata($pagename, $newdata);
2113 if (!empty($this->_pagedata_cache[$pagename])
2114 and is_array($this->_pagedata_cache[$pagename]))
2116 $cachedata = &$this->_pagedata_cache[$pagename];
2117 foreach($newdata as $key => $val)
2118 $cachedata[$key] = $val;
2120 $this->_pagedata_cache[$pagename] = $newdata;
2124 function invalidate_cache($pagename) {
2125 unset ($this->_pagedata_cache[$pagename]);
2126 unset ($this->_versiondata_cache[$pagename]);
2127 unset ($this->_glv_cache[$pagename]);
2128 unset ($this->_id_cache[$pagename]);
2129 //unset ($this->_backend->_page_data);
2132 function delete_page($pagename) {
2133 $result = $this->_backend->delete_page($pagename);
2134 $this->invalidate_cache($pagename);
2138 function purge_page($pagename) {
2139 $result = $this->_backend->purge_page($pagename);
2140 $this->invalidate_cache($pagename);
2144 // FIXME: ugly and wrong. may overwrite full cache with partial cache
2145 function cache_data($data) {
2147 //if (isset($data['pagedata']))
2148 // $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2151 function get_versiondata($pagename, $version, $need_content = false) {
2152 // FIXME: Seriously ugly hackage
2154 if (USECACHE) { //temporary - for debugging
2155 assert(is_string($pagename) && $pagename != '');
2156 // There is a bug here somewhere which results in an assertion failure at line 105
2157 // of ArchiveCleaner.php It goes away if we use the next line.
2158 //$need_content = true;
2159 $nc = $need_content ? '1':'0';
2160 $cache = &$this->_versiondata_cache;
2161 if (!isset($cache[$pagename][$version][$nc])
2162 || !(is_array ($cache[$pagename]))
2163 || !(is_array ($cache[$pagename][$version])))
2165 $cache[$pagename][$version][$nc] =
2166 $this->_backend->get_versiondata($pagename, $version, $need_content);
2168 // If we have retrieved all data, we may as well set the cache for
2169 // $need_content = false
2171 $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2174 $vdata = $cache[$pagename][$version][$nc];
2176 $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2179 if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2180 if (empty($this->_pagedata_cache))
2181 $this->_pagedata_cache = array();
2182 /* 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 */
2183 $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2188 function set_versiondata($pagename, $version, $data) {
2189 //unset($this->_versiondata_cache[$pagename][$version]);
2191 $new = $this->_backend->set_versiondata($pagename, $version, $data);
2193 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2194 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2195 // Is this necessary?
2196 unset($this->_glv_cache[$pagename]);
2199 function update_versiondata($pagename, $version, $data) {
2200 $new = $this->_backend->update_versiondata($pagename, $version, $data);
2202 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2204 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2205 // Is this necessary?
2206 unset($this->_glv_cache[$pagename]);
2209 function delete_versiondata($pagename, $version) {
2210 $new = $this->_backend->delete_versiondata($pagename, $version);
2211 if (isset($this->_versiondata_cache[$pagename][$version]))
2212 unset ($this->_versiondata_cache[$pagename][$version]);
2213 // dirty latest version cache only if latest version gets deleted
2214 if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2215 unset ($this->_glv_cache[$pagename]);
2218 function get_latest_version($pagename) {
2220 assert (is_string($pagename) && $pagename != '');
2221 $cache = &$this->_glv_cache;
2222 if (!isset($cache[$pagename])) {
2223 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2224 if (empty($cache[$pagename]))
2225 $cache[$pagename] = 0;
2227 return $cache[$pagename];
2229 return $this->_backend->get_latest_version($pagename);
2234 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2238 $stamp = strftime("%y%m%d-%H%M%S");
2239 $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2240 register_shutdown_function("_sql_debuglog_shutdown_function");
2241 } elseif ($shutdown) {
2245 if ($newline) fputs($fp, "[$i++] $msg");
2246 else fwrite($fp, $msg);
2249 function _sql_debuglog_shutdown_function() {
2250 _sql_debuglog('',false,true);
2256 // c-basic-offset: 4
2257 // c-hanging-comment-ender-p: nil
2258 // indent-tabs-mode: nil