]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
phpdoc_params
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //$Id$
2 require_once('lib/PageType.php');
3
4 /**
5  * The classes in the file define the interface to the
6  * page database.
7  *
8  * @package WikiDB
9  * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
10  * Minor enhancements by Reini Urban
11  */
12
13 /**
14  * Force the creation of a new revision.
15  * @see WikiDB_Page::createRevision()
16  */
17 if (!defined('WIKIDB_FORCE_CREATE'))
18     define('WIKIDB_FORCE_CREATE', -1);
19
20 /**
21  * Abstract base class for the database used by PhpWiki.
22  *
23  * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
24  * turn contain <tt>WikiDB_PageRevision</tt>s.
25  *
26  * Conceptually a <tt>WikiDB</tt> contains all possible
27  * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
28  * Since all possible pages are already contained in a WikiDB, a call
29  * to WikiDB::getPage() will never fail (barring bugs and
30  * e.g. filesystem or SQL database problems.)
31  *
32  * Also each <tt>WikiDB_Page</tt> always contains at least one
33  * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
34  * [PageName] here.").  This default content has a version number of
35  * zero.
36  *
37  * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
38  * only create new revisions or delete old ones --- one can not modify
39  * an existing revision.
40  */
41 class WikiDB {
42     /**
43      * Open a WikiDB database.
44      *
45      * This is a static member function. This function inspects its
46      * arguments to determine the proper subclass of WikiDB to
47      * instantiate, and then it instantiates it.
48      *
49      * @access public
50      *
51      * @param hash $dbparams Database configuration parameters.
52      * Some pertinent parameters are:
53      * <dl>
54      * <dt> dbtype
55      * <dd> The back-end type.  Current supported types are:
56      *   <dl>
57      *   <dt> SQL
58      *     <dd> Generic SQL backend based on the PEAR/DB database abstraction
59      *       library. (More stable and conservative)
60      *   <dt> ADODB
61      *     <dd> Another generic SQL backend. (More current features are tested here. Much faster)
62      *   <dt> dba
63      *     <dd> Dba based backend. The default and by far the fastest.
64      *   <dt> cvs
65      *     <dd>
66      *   <dt> file
67      *     <dd> flat files
68      *   </dl>
69      *
70      * <dt> dsn
71      * <dd> (Used by the SQL and ADODB backends.)
72      *      The DSN specifying which database to connect to.
73      *
74      * <dt> prefix
75      * <dd> Prefix to be prepended to database tables (and file names).
76      *
77      * <dt> directory
78      * <dd> (Used by the dba backend.)
79      *      Which directory db files reside in.
80      *
81      * <dt> timeout
82      * <dd> Used only by the dba backend so far.
83      *      And: When optimizing mysql it closes timed out mysql processes.
84      *      otherwise only used for dba: Timeout in seconds for opening (and
85      *      obtaining lock) on the dbm file.
86      *
87      * <dt> dba_handler
88      * <dd> (Used by the dba backend.)
89      *
90      *      Which dba handler to use. Good choices are probably either
91      *      'gdbm' or 'db2'.
92      *
93      * <dt> readonly
94      * <dd> Either set by config.ini: READONLY = true or detected automatically
95      *      when a database can be read but cannot be updated.
96      * </dl>
97      *
98      * @return WikiDB A WikiDB object.
99      **/
100     function open ($dbparams) {
101         $dbtype = $dbparams{'dbtype'};
102         include_once("lib/WikiDB/$dbtype.php");
103
104         $class = 'WikiDB_' . $dbtype;
105         return new $class ($dbparams);
106     }
107
108
109     /**
110      * Constructor.
111      *
112      * @access private
113      * @see open()
114      */
115     function WikiDB (&$backend, $dbparams) {
116         $this->_backend =& $backend;
117         // don't do the following with the auth_dsn!
118         if (isset($dbparams['auth_dsn'])) return;
119
120         $this->_cache = new WikiDB_cache($backend);
121         if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
122
123         // If the database doesn't yet have a timestamp, initialize it now.
124         if ($this->get('_timestamp') === false)
125             $this->touch();
126
127         // devel checking.
128         if ((int)DEBUG & _DEBUG_SQL) {
129             $this->_backend->check();
130         }
131         // might be changed when opening the database fails
132         $this->readonly = defined("READONLY") ? READONLY : false;
133     }
134
135     /**
136      * Close database connection.
137      *
138      * The database may no longer be used after it is closed.
139      *
140      * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
141      * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
142      * which have been obtained from it.
143      *
144      * @access public
145      */
146     function close () {
147         $this->_backend->close();
148         $this->_cache->close();
149     }
150
151     /**
152      * Get a WikiDB_Page from a WikiDB.
153      *
154      * A {@link WikiDB} consists of the (infinite) set of all possible pages,
155      * therefore this method never fails.
156      *
157      * @access public
158      * @param  string      $pagename Which page to get.
159      * @return WikiDB_Page The requested WikiDB_Page.
160      */
161     function getPage($pagename) {
162         static $error_displayed = false;
163         $pagename = (string) $pagename;
164         if ((int)DEBUG) {
165             if ($pagename === '') {
166                 if ($error_displayed) return false;
167                 $error_displayed = true;
168                 if (function_exists("xdebug_get_function_stack"))
169                     var_dump(xdebug_get_function_stack());
170                 trigger_error("empty pagename", E_USER_WARNING);
171                 return false;
172             }
173         } else {
174             assert($pagename != '');
175         }
176         return new WikiDB_Page($this, $pagename);
177     }
178
179     /**
180      * Determine whether page exists (in non-default form).
181      *
182      * <pre>
183      *   $is_page = $dbi->isWikiPage($pagename);
184      * </pre>
185      * is equivalent to
186      * <pre>
187      *   $page = $dbi->getPage($pagename);
188      *   $current = $page->getCurrentRevision();
189      *   $is_page = ! $current->hasDefaultContents();
190      * </pre>
191      * however isWikiPage may be implemented in a more efficient
192      * manner in certain back-ends.
193      *
194      * @access public
195      * @param  string  $pagename string Which page to check.
196      * @return boolean True if the page actually exists with
197      * non-default contents in the WikiDataBase.
198      */
199     function isWikiPage ($pagename) {
200         $page = $this->getPage($pagename);
201         return ($page and $page->exists());
202     }
203
204     /**
205      * Delete page from the WikiDB.
206      *
207      * Deletes the page from the WikiDB with the possibility to revert and diff.
208      * //Also resets all page meta-data to the default values.
209      *
210      * Note: purgePage() effectively destroys all revisions of the page from the WikiDB.
211      *
212      * @access public
213      * @param string $pagename Name of page to delete.
214      * @see purgePage
215      */
216     function deletePage($pagename) {
217         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
218         // don't create empty revisions of already purged pages.
219         if ($this->_backend->get_latest_version($pagename))
220             $result = $this->_cache->delete_page($pagename);
221         else
222             $result = -1;
223
224         /* Generate notification emails */
225         if (ENABLE_MAILNOTIFY) {
226             include_once("lib/MailNotify.php");
227             $MailNotify = new MailNotify($pagename);
228             $MailNotify->onDeletePage ($this, $pagename);
229         }
230
231         //How to create a RecentChanges entry with explaining summary? Dynamically
232         /*
233         $page = $this->getPage($pagename);
234         $current = $page->getCurrentRevision();
235         $meta = $current->_data;
236         $version = $current->getVersion();
237         $meta['summary'] = _("removed");
238         $page->save($current->getPackedContent(), $version + 1, $meta);
239         */
240         return $result;
241     }
242
243     /**
244      * Completely remove the page from the WikiDB, without undo possibility.
245      * @access public
246      * @param string $pagename Name of page to delete.
247      * @see deletePage
248      */
249     function purgePage($pagename) {
250         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
251         $result = $this->_cache->purge_page($pagename);
252         $this->deletePage($pagename); // just for the notification
253         return $result;
254     }
255
256     /**
257      * Retrieve all pages.
258      *
259      * Gets the set of all pages with non-default contents.
260      *
261      * @access public
262      *
263      * @param boolean $include_empty Optional. Normally pages whose most
264      * recent revision has empty content are considered to be
265      * non-existant. Unless $include_defaulted is set to true, those
266      * pages will not be returned.
267      * @param string or false $sortby Optional. "+-column,+-column2".
268      *        If false the result is faster in natural order.
269      * @param string or false $limit Optional. Encoded as "$offset,$count".
270      *         $offset defaults to 0.
271      * @param string $exclude: Optional comma-seperated list of pagenames.
272      *
273      * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
274      *     in the WikiDB which have non-default contents.
275      */
276     function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='')
277     {
278         $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit,
279                                                  $exclude);
280         return new WikiDB_PageIterator($this, $result,
281                                        array('include_empty' => $include_empty,
282                                              'exclude' => $exclude,
283                                              'limit_by_db' => $result->_options['limit_by_db'],
284                                              'limit' => $result->limit()));
285     }
286
287     /**
288      * @access public
289      *
290      * @param boolean $include_empty If true include also empty pages
291      * @param string  $exclude:      comma-seperated list of pagenames.
292      *             TBD: array of pagenames
293      * @return integer
294      *
295      */
296     function numPages($include_empty=false, $exclude='') {
297         if (method_exists($this->_backend, 'numPages'))
298             // FIXME: currently are all args ignored.
299             $count = $this->_backend->numPages($include_empty, $exclude);
300         else {
301             // FIXME: exclude ignored.
302             $iter = $this->getAllPages($include_empty, false, false, $exclude);
303             $count = $iter->count();
304             $iter->free();
305         }
306         return (int)$count;
307     }
308
309     /**
310      * Title search.
311      *
312      * Search for pages containing (or not containing) certain words
313      * in their names.
314      *
315      * Pages are returned in alphabetical order whenever it is
316      * practical to do so.
317      * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
318      *
319      * @access public
320      * @param TextSearchQuery $search A TextSearchQuery object
321      * @param string or false $sortby Optional. "+-column,+-column2".
322      *        If false the result is faster in natural order.
323      * @param string or false $limit Optional. Encoded as "$offset,$count".
324      *         $offset defaults to 0.
325      * @param  string              $exclude: Optional comma-seperated list of pagenames.
326      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
327      * @see TextSearchQuery
328      */
329     function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
330         $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
331         $options = array('exclude' => $exclude,
332                          'limit'   => $limit);
333         //if (isset($result->_count)) $options['count'] = $result->_count;
334         return new WikiDB_PageIterator($this, $result, $options);
335     }
336
337     /**
338      * Full text search.
339      *
340      * Search for pages containing (or not containing) certain words
341      * in their entire text (this includes the page content and the
342      * page name).
343      *
344      * Pages are returned in alphabetical order whenever it is
345      * practical to do so.
346      * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
347      *
348      * @access public
349      *
350      * @param TextSearchQuery $search A TextSearchQuery object.
351      * @param string or false $sortby Optional. "+-column,+-column2".
352      *        If false the result is faster in natural order.
353      * @param string or false $limit Optional. Encoded as "$offset,$count".
354      *         $offset defaults to 0.
355      * @param  string              $exclude: Optional comma-seperated list of pagenames.
356      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
357      * @see TextSearchQuery
358      */
359     function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
360         $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
361         return new WikiDB_PageIterator($this, $result,
362                                        array('exclude' => $exclude,
363                                              'limit'   => $limit,
364                                              'stoplisted' => $result->stoplisted
365                                              ));
366     }
367
368     /**
369      * Find the pages with the greatest hit counts.
370      *
371      * Pages are returned in reverse order by hit count.
372      *
373      * @access public
374      *
375      * @param integer $limit The maximum number of pages to return.
376      * Set $limit to zero to return all pages.  If $limit < 0, pages will
377      * be sorted in decreasing order of popularity.
378      * @param string or false $sortby Optional. "+-column,+-column2".
379      *        If false the result is faster in natural order.
380      *
381      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
382      * pages.
383      */
384     function mostPopular($limit = 20, $sortby = '-hits') {
385         $result = $this->_backend->most_popular($limit, $sortby);
386         return new WikiDB_PageIterator($this, $result);
387     }
388
389     /**
390      * Find recent page revisions.
391      *
392      * Revisions are returned in reverse order by creation time.
393      *
394      * @access public
395      *
396      * @param hash $params This hash is used to specify various optional
397      *   parameters:
398      * <dl>
399      * <dt> limit
400      *    <dd> (integer) At most this many revisions will be returned.
401      * <dt> since
402      *    <dd> (integer) Only revisions since this time (unix-timestamp)
403      *        will be returned.
404      * <dt> include_minor_revisions
405      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
406      * <dt> exclude_major_revisions
407      *    <dd> (boolean) Don't include non-minor revisions.
408      *         (Exclude_major_revisions implies include_minor_revisions.)
409      * <dt> include_all_revisions
410      *    <dd> (boolean) Return all matching revisions for each page.
411      *         Normally only the most recent matching revision is returned
412      *         for each page.
413      * </dl>
414      *
415      * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator
416      * containing the matching revisions.
417      */
418     function mostRecent($params = false) {
419         $result = $this->_backend->most_recent($params);
420         return new WikiDB_PageRevisionIterator($this, $result);
421     }
422
423     /**
424      * @access public
425      *
426      * @param string or false $sortby Optional. "+-column,+-column2".
427      *        If false the result is faster in natural order.
428      * @param string or false $limit Optional. Encoded as "$offset,$count".
429      *         $offset defaults to 0.
430      * @return Iterator A generic iterator containing rows of
431      *         (duplicate) pagename, wantedfrom.
432      */
433     function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
434         return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
435         //return new WikiDB_PageIterator($this, $result);
436     }
437
438     /**
439      * Generic interface to the link table. Esp. useful to search for rdf triples as in
440      * SemanticSearch and ListRelations.
441      *
442      * @access public
443      *
444      * @param $pages  object A TextSearchQuery object.
445      * @param $search object A TextSearchQuery object.
446      * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
447      *   linktype parameter:
448      * <dl>
449      * <dt> "linkto"
450      *    <dd> search for simple out-links
451      * <dt> "linkfrom"
452      *    <dd> in-links, i.e BackLinks
453      * <dt> "relation"
454      *    <dd> the first part in a <>::<> link
455      * <dt> "attribute"
456      *    <dd> the first part in a <>:=<> link
457      * </dl>
458      * @param $relation object An optional TextSearchQuery to match the
459      * relation name. Ignored on simple in-out links.
460      *
461      * @return Iterator A generic iterator containing links to pages or values.
462      *                  hash of "pagename", "linkname", "linkvalue.
463      */
464     function linkSearch($pages, $search, $linktype, $relation=false) {
465         return $this->_backend->link_search($pages, $search, $linktype, $relation);
466     }
467
468     /**
469      * Return a simple list of all defined relations (and attributes), mainly
470      * for the SemanticSearch autocompletion.
471      *
472      * @access public
473      *
474      * @return array of strings
475      */
476     function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
477         if (method_exists($this->_backend, "list_relations"))
478             return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
479         // dumb, slow fallback. no iter, so simply define it here.
480         $relations = array();
481         $iter = $this->getAllPages();
482         while ($page = $iter->next()) {
483             $reliter = $page->getRelations();
484             $names = array();
485             while ($rel = $reliter->next()) {
486             // if there's no pagename it's an attribute
487                 $names[] = $rel->getName();
488             }
489             $relations = array_merge($relations, $names);
490             $reliter->free();
491         }
492         $iter->free();
493         if ($sorted) {
494             sort($relations);
495             reset($relations);
496         }
497         return $relations;
498     }
499
500     /**
501      * Call the appropriate backend method.
502      *
503      * @access public
504      * @param  string  $from            Page to rename
505      * @param  string  $to              New name
506      * @param  boolean $updateWikiLinks If the text in all pages should be replaced.
507      * @return boolean true or false
508      */
509     function renamePage($from, $to, $updateWikiLinks = false) {
510         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
511         assert(is_string($from) && $from != '');
512         assert(is_string($to) && $to != '');
513         $result = false;
514         if (method_exists($this->_backend, 'rename_page')) {
515             $oldpage = $this->getPage($from);
516             $newpage = $this->getPage($to);
517             //update all WikiLinks in existing pages
518             //non-atomic! i.e. if rename fails the links are not undone
519             if ($updateWikiLinks) {
520                 $lookbehind = "/(?<=[\W:])\Q";
521                 $lookahead = "\E(?=[\W:])/";
522                 require_once('lib/plugin/WikiAdminSearchReplace.php');
523                 $links = $oldpage->getBackLinks();
524                 while ($linked_page = $links->next()) {
525                     WikiPlugin_WikiAdminSearchReplace::replaceHelper
526                         ($this,
527                          $linked_page->getName(),
528                          $lookbehind.$from.$lookahead, $to,
529                          true, true);
530                 }
531                 // FIXME: Disabled to avoid recursive modification when renaming
532                 // a page like 'PageFoo to 'PageFooTwo'
533                 if (0) {
534                   $links = $newpage->getBackLinks();
535                   while ($linked_page = $links->next()) {
536                     WikiPlugin_WikiAdminSearchReplace::replaceHelper
537             ($this,
538              $linked_page->getName(),
539              $lookbehind.$from.$lookahead, $to,
540              true, true);
541                   }
542                 }
543             }
544             if ($oldpage->exists() and ! $newpage->exists()) {
545                 if ($result = $this->_backend->rename_page($from, $to)) {
546                     // create a RecentChanges entry with explaining summary
547                     $page = $this->getPage($to);
548                     $current = $page->getCurrentRevision();
549                     $meta = $current->_data;
550                     $version = $current->getVersion();
551                     $meta['summary'] = sprintf(_("renamed from %s"), $from);
552                     unset($meta['mtime']); // force new date
553                     $page->save($current->getPackedContent(), $version + 1, $meta);
554                 }
555             } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
556                 // if a version 0 exists try it also.
557                 $result = $this->_backend->rename_page($from, $to);
558             }
559         } else {
560             trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
561                           E_USER_WARNING);
562         }
563         /* Generate notification emails? */
564         if ($result and ENABLE_MAILNOTIFY and !isa($GLOBALS['request'], 'MockRequest')) {
565             $notify = $this->get('notify');
566             if (!empty($notify) and is_array($notify)) {
567                 include_once("lib/MailNotify.php");
568                 $MailNotify = new MailNotify($from);
569                 $MailNotify->onRenamePage ($this, $from, $to);
570             }
571         }
572         return $result;
573     }
574
575     /** Get timestamp when database was last modified.
576      *
577      * @return string A string consisting of two integers,
578      * separated by a space.  The first is the time in
579      * unix timestamp format, the second is a modification
580      * count for the database.
581      *
582      * The idea is that you can cast the return value to an
583      * int to get a timestamp, or you can use the string value
584      * as a good hash for the entire database.
585      */
586     function getTimestamp() {
587         $ts = $this->get('_timestamp');
588         return sprintf("%d %d", $ts[0], $ts[1]);
589     }
590
591     /**
592      * Update the database timestamp.
593      *
594      */
595     function touch() {
596         $ts = $this->get('_timestamp');
597         $this->set('_timestamp', array(time(), $ts[1] + 1));
598     }
599
600     /**
601      * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
602      */
603     function get_db_version() {
604         return (float) $this->get('_db_version');
605     }
606     function set_db_version($ver) {
607         return $this->set('_db_version', (float)$ver);
608     }
609
610     /**
611      * Access WikiDB global meta-data.
612      *
613      * NOTE: this is currently implemented in a hackish and
614      * not very efficient manner.
615      *
616      * @access public
617      *
618      * @param string $key Which meta data to get.
619      * Some reserved meta-data keys are:
620      * <dl>
621      * <dt>'_timestamp' <dd> Data used by getTimestamp().
622      * </dl>
623      *
624      * @return scalar The requested value, or false if the requested data
625      * is not set.
626      */
627     function get($key) {
628         if (!$key || $key[0] == '%')
629             return false;
630         /*
631          * Hack Alert: We can use any page (existing or not) to store
632          * this data (as long as we always use the same one.)
633          */
634         $gd = $this->getPage('global_data');
635         $data = $gd->get('__global');
636
637         if ($data && isset($data[$key]))
638             return $data[$key];
639         else
640             return false;
641     }
642
643     /**
644      * Set global meta-data.
645      *
646      * NOTE: this is currently implemented in a hackish and
647      * not very efficient manner.
648      *
649      * @see get
650      * @access public
651      *
652      * @param string $key    Meta-data key to set.
653      * @param string $newval New value.
654      */
655     function set($key, $newval) {
656         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
657         if (!$key || $key[0] == '%')
658             return;
659
660         $gd = $this->getPage('global_data');
661         $data = $gd->get('__global');
662         if ($data === false)
663             $data = array();
664
665         if (empty($newval))
666             unset($data[$key]);
667         else
668             $data[$key] = $newval;
669
670         $gd->set('__global', $data);
671     }
672
673     /* TODO: these are really backend methods */
674
675     // SQL result: for simple select or create/update queries
676     // returns the database specific resource type
677     function genericSqlQuery($sql, $args=false) {
678         echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
679         trigger_error("no SQL database", E_USER_ERROR);
680         return false;
681     }
682
683     // SQL iter: for simple select or create/update queries
684     // returns the generic iterator object (count,next)
685     function genericSqlIter($sql, $field_list = NULL) {
686         echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
687         trigger_error("no SQL database", E_USER_ERROR);
688         return false;
689     }
690
691     // see backend upstream methods
692     // ADODB adds surrounding quotes, SQL not yet!
693     function quote ($s) {
694         return $s;
695     }
696
697     function isOpen () {
698         global $request;
699         if (!$request->_dbi) return false;
700         else return false; /* so far only needed for sql so false it.
701                             later we have to check dba also */
702     }
703
704     function getParam($param) {
705         global $DBParams;
706         if (isset($DBParams[$param])) return $DBParams[$param];
707         elseif ($param == 'prefix') return '';
708         else return false;
709     }
710
711     function getAuthParam($param) {
712         global $DBAuthParams;
713         if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
714         elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
715         elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
716         else return false;
717     }
718 };
719
720
721 /**
722  * A base class which representing a wiki-page within a
723  * WikiDB.
724  *
725  * A WikiDB_Page contains a number (at least one) of
726  * WikiDB_PageRevisions.
727  */
728 class WikiDB_Page
729 {
730     function WikiDB_Page(&$wikidb, $pagename) {
731         $this->_wikidb = &$wikidb;
732         $this->_pagename = $pagename;
733         if ((int)DEBUG) {
734             if (!(is_string($pagename) and $pagename != '')) {
735                 if (function_exists("xdebug_get_function_stack")) {
736                     echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
737                 } else {
738                     printSimpleTrace(debug_backtrace());
739                 }
740                 trigger_error("empty pagename", E_USER_WARNING);
741                 return false;
742             }
743         } else {
744             assert(is_string($pagename) and $pagename != '');
745         }
746     }
747
748     /**
749      * Get the name of the wiki page.
750      *
751      * @access public
752      *
753      * @return string The page name.
754      */
755     function getName() {
756         return $this->_pagename;
757     }
758
759     // To reduce the memory footprint for larger sets of pagelists,
760     // we don't cache the content (only true or false) and
761     // we purge the pagedata (_cached_html) also
762     function exists() {
763         if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
764         $current = $this->getCurrentRevision(false);
765         if (!$current) return false;
766         return ! $current->hasDefaultContents();
767     }
768
769     /**
770      * Delete an old revision of a WikiDB_Page.
771      *
772      * Deletes the specified revision of the page.
773      * It is a fatal error to attempt to delete the current revision.
774      *
775      * @access public
776      *
777      * @param integer $version Which revision to delete.  (You can also
778      *  use a WikiDB_PageRevision object here.)
779      */
780     function deleteRevision($version) {
781         if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
782         $backend = &$this->_wikidb->_backend;
783         $cache = &$this->_wikidb->_cache;
784         $pagename = &$this->_pagename;
785
786         $version = $this->_coerce_to_version($version);
787         if ($version == 0)
788             return;
789
790         $backend->lock(array('page','version'));
791         $latestversion = $cache->get_latest_version($pagename);
792         if ($latestversion && ($version == $latestversion)) {
793             $backend->unlock(array('page','version'));
794             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
795                                   $pagename), E_USER_ERROR);
796             return;
797         }
798
799         $cache->delete_versiondata($pagename, $version);
800         $backend->unlock(array('page','version'));
801     }
802
803     /*
804      * Delete a revision, or possibly merge it with a previous
805      * revision.
806      *
807      * The idea is this:
808      * Suppose an author make a (major) edit to a page.  Shortly
809      * after that the same author makes a minor edit (e.g. to fix
810      * spelling mistakes he just made.)
811      *
812      * Now some time later, where cleaning out old saved revisions,
813      * and would like to delete his minor revision (since there's
814      * really no point in keeping minor revisions around for a long
815      * time.)
816      *
817      * Note that the text after the minor revision probably represents
818      * what the author intended to write better than the text after
819      * the preceding major edit.
820      *
821      * So what we really want to do is merge the minor edit with the
822      * preceding edit.
823      *
824      * We will only do this when:
825      * <ul>
826      * <li>The revision being deleted is a minor one, and
827      * <li>It has the same author as the immediately preceding revision.
828      * </ul>
829      */
830     function mergeRevision($version) {
831         if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
832         $backend = &$this->_wikidb->_backend;
833         $cache = &$this->_wikidb->_cache;
834         $pagename = &$this->_pagename;
835
836         $version = $this->_coerce_to_version($version);
837         if ($version == 0)
838             return;
839
840         $backend->lock(array('version'));
841         $latestversion = $cache->get_latest_version($pagename);
842         if ($latestversion && $version == $latestversion) {
843             $backend->unlock(array('version'));
844             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
845                                   $pagename), E_USER_ERROR);
846             return;
847         }
848
849         $versiondata = $cache->get_versiondata($pagename, $version, true);
850         if (!$versiondata) {
851             // Not there? ... we're done!
852             $backend->unlock(array('version'));
853             return;
854         }
855
856         if ($versiondata['is_minor_edit']) {
857             $previous = $backend->get_previous_version($pagename, $version);
858             if ($previous) {
859                 $prevdata = $cache->get_versiondata($pagename, $previous);
860                 if ($prevdata['author_id'] == $versiondata['author_id']) {
861                     // This is a minor revision, previous version is
862                     // by the same author. We will merge the
863                     // revisions.
864                     $cache->update_versiondata($pagename, $previous,
865                                                array('%content' => $versiondata['%content'],
866                                                      '_supplanted' => $versiondata['_supplanted']));
867                 }
868             }
869         }
870
871         $cache->delete_versiondata($pagename, $version);
872         $backend->unlock(array('version'));
873     }
874
875
876     /**
877      * Create a new revision of a {@link WikiDB_Page}.
878      *
879      * @access public
880      *
881      * @param int $version Version number for new revision.
882      * To ensure proper serialization of edits, $version must be
883      * exactly one higher than the current latest version.
884      * (You can defeat this check by setting $version to
885      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
886      *
887      * @param string $content Contents of new revision.
888      *
889      * @param hash $metadata Metadata for new revision.
890      * All values in the hash should be scalars (strings or integers).
891      *
892      * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
893      *
894      * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
895      * $version was incorrect, returns false
896      */
897     function createRevision($version, &$content, $metadata, $links) {
898         if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
899         $backend = &$this->_wikidb->_backend;
900         $cache = &$this->_wikidb->_cache;
901         $pagename = &$this->_pagename;
902         $cache->invalidate_cache($pagename);
903
904         $backend->lock(array('version','page','recent','link','nonempty'));
905
906         $latestversion = $backend->get_latest_version($pagename);
907         $newversion = ($latestversion ? $latestversion : 0) + 1;
908         assert($newversion >= 1);
909
910         if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
911             $backend->unlock(array('version','page','recent','link','nonempty'));
912             return false;
913         }
914
915         $data = $metadata;
916
917         foreach ($data as $key => $val) {
918             if (empty($val) || $key[0] == '_' || $key[0] == '%')
919                 unset($data[$key]);
920         }
921
922         assert(!empty($data['author']));
923         if (empty($data['author_id']))
924             @$data['author_id'] = $data['author'];
925
926         if (empty($data['mtime']))
927             $data['mtime'] = time();
928
929         if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
930             // Ensure mtimes are monotonic.
931             $pdata = $cache->get_versiondata($pagename, $latestversion);
932             if ($data['mtime'] < $pdata['mtime']) {
933                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
934                                       $pagename,"'non-monotonic'"),
935                               E_USER_NOTICE);
936                 $data['orig_mtime'] = $data['mtime'];
937                 $data['mtime'] = $pdata['mtime'];
938             }
939
940             // FIXME: use (possibly user specified) 'mtime' time or
941             // time()?
942             $cache->update_versiondata($pagename, $latestversion,
943                                        array('_supplanted' => $data['mtime']));
944         }
945
946         $data['%content'] = &$content;
947
948         $cache->set_versiondata($pagename, $newversion, $data);
949
950         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
951         //':deleted' => empty($content)));
952
953         $backend->set_links($pagename, $links);
954
955         $backend->unlock(array('version','page','recent','link','nonempty'));
956
957         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
958                                        $data);
959     }
960
961     /** A higher-level interface to createRevision.
962      *
963      * This takes care of computing the links, and storing
964      * a cached version of the transformed wiki-text.
965      *
966      * @param string $wikitext The page content.
967      *
968      * @param int $version Version number for new revision.
969      * To ensure proper serialization of edits, $version must be
970      * exactly one higher than the current latest version.
971      * (You can defeat this check by setting $version to
972      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
973      *
974      * @param hash $meta Meta-data for new revision.
975      */
976     function save($wikitext, $version, $meta, $formatted = null) {
977         if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
978         if (is_null($formatted))
979             $formatted = new TransformedText($this, $wikitext, $meta);
980         $type = $formatted->getType();
981         $meta['pagetype'] = $type->getName();
982         $links = $formatted->getWikiPageLinks(); // linkto => relation
983         $attributes = array();
984         foreach ($links as $link) {
985             if ($link['linkto'] === "" and !empty($link['relation'])) {
986                 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
987             }
988         }
989         $meta['attribute'] = $attributes;
990
991         $backend = &$this->_wikidb->_backend;
992         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
993         if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
994             $this->set('_cached_html', $formatted->pack());
995
996         // FIXME: probably should have some global state information
997         // in the backend to control when to optimize.
998         //
999         // We're doing this here rather than in createRevision because
1000         // postgresql can't optimize while locked.
1001         if (((int)DEBUG & _DEBUG_SQL)
1002         or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1003                 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
1004             if ($backend->optimize()) {
1005                 if ((int)DEBUG)
1006                     trigger_error(_("Optimizing database"), E_USER_NOTICE);
1007             }
1008         }
1009
1010         /* Generate notification emails? */
1011         if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1012             // Save didn't fail because of concurrent updates.
1013             $notify = $this->_wikidb->get('notify');
1014             if (!empty($notify)
1015                 and is_array($notify)
1016                 and !isa($GLOBALS['request'],'MockRequest'))
1017             {
1018                 include_once("lib/MailNotify.php");
1019                 $MailNotify = new MailNotify($newrevision->getName());
1020                 $MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
1021             }
1022             $newrevision->_transformedContent = $formatted;
1023         }
1024         // more pagechange callbacks: (in a hackish manner for now)
1025         if (ENABLE_RECENTCHANGESBOX
1026             and empty($meta['is_minor_edit'])
1027             and !in_array($GLOBALS['request']->getArg('action'),
1028                           array('loadfile','upgrade')))
1029         {
1030             require_once("lib/WikiPlugin.php");
1031             $w = new WikiPluginLoader;
1032             $p = $w->getPlugin("RecentChangesCached", false);
1033             $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1034         }
1035         return $newrevision;
1036     }
1037
1038     /**
1039      * Get the most recent revision of a page.
1040      *
1041      * @access public
1042      *
1043      * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1044      */
1045     function getCurrentRevision ($need_content=true) {
1046         $backend = &$this->_wikidb->_backend;
1047         $cache = &$this->_wikidb->_cache;
1048         $pagename = &$this->_pagename;
1049
1050         // Prevent deadlock in case of memory exhausted errors
1051         // Pure selection doesn't really need locking here.
1052         //   sf.net bug#927395
1053         // I know it would be better to lock, but with lots of pages this deadlock is more
1054         // severe than occasionally get not the latest revision.
1055         // In spirit to wikiwiki: read fast, edit slower.
1056         //$backend->lock();
1057         $version = $cache->get_latest_version($pagename);
1058         // getRevision gets the content also!
1059         $revision = $this->getRevision($version, $need_content);
1060         //$backend->unlock();
1061         assert($revision);
1062         return $revision;
1063     }
1064
1065     /**
1066      * Get a specific revision of a WikiDB_Page.
1067      *
1068      * @access public
1069      *
1070      * @param integer $version Which revision to get.
1071      *
1072      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1073      * false if the requested revision does not exist in the {@link WikiDB}.
1074      * Note that version zero of any page always exists.
1075      */
1076     function getRevision ($version, $need_content=true) {
1077         $cache = &$this->_wikidb->_cache;
1078         $pagename = &$this->_pagename;
1079
1080         if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1081             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1082         }
1083
1084         assert($version > 0);
1085         $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1086         if (!$vdata) {
1087             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1088         }
1089         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1090                                        $vdata);
1091     }
1092
1093     /**
1094      * Get previous page revision.
1095      *
1096      * This method find the most recent revision before a specified
1097      * version.
1098      *
1099      * @access public
1100      *
1101      * @param integer $version Find most recent revision before this version.
1102      *  You can also use a WikiDB_PageRevision object to specify the $version.
1103      *
1104      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1105      * requested revision does not exist in the {@link WikiDB}.  Note that
1106      * unless $version is greater than zero, a revision (perhaps version zero,
1107      * the default revision) will always be found.
1108      */
1109     function getRevisionBefore ($version=false, $need_content=true) {
1110         $backend = &$this->_wikidb->_backend;
1111         $pagename = &$this->_pagename;
1112         if ($version === false)
1113             $version = $this->_wikidb->_cache->get_latest_version($pagename);
1114         else
1115             $version = $this->_coerce_to_version($version);
1116
1117         if ($version == 0)
1118             return false;
1119         //$backend->lock();
1120         $previous = $backend->get_previous_version($pagename, $version);
1121         $revision = $this->getRevision($previous, $need_content);
1122         //$backend->unlock();
1123         assert($revision);
1124         return $revision;
1125     }
1126
1127     /**
1128      * Get all revisions of the WikiDB_Page.
1129      *
1130      * This does not include the version zero (default) revision in the
1131      * returned revision set.
1132      *
1133      * @return WikiDB_PageRevisionIterator A
1134      *   WikiDB_PageRevisionIterator containing all revisions of this
1135      *   WikiDB_Page in reverse order by version number.
1136      */
1137     function getAllRevisions() {
1138         $backend = &$this->_wikidb->_backend;
1139         $revs = $backend->get_all_revisions($this->_pagename);
1140         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1141     }
1142
1143     /**
1144      * Find pages which link to or are linked from a page.
1145      * relations: $backend->get_links is responsible to add the relation to the pagehash
1146      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1147      *   if (isset($next['linkrelation']))
1148      *
1149      * @access public
1150      *
1151      * @param boolean $reversed Which links to find: true for backlinks (default).
1152      *
1153      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1154      * all matching pages.
1155      */
1156     function getLinks ($reversed=true, $include_empty=false, $sortby='',
1157                        $limit='', $exclude='', $want_relations=false)
1158     {
1159         $backend = &$this->_wikidb->_backend;
1160         $result =  $backend->get_links($this->_pagename, $reversed,
1161                                        $include_empty, $sortby, $limit, $exclude,
1162                                        $want_relations);
1163         return new WikiDB_PageIterator($this->_wikidb, $result,
1164                                        array('include_empty' => $include_empty,
1165                                              'sortby'        => $sortby,
1166                                              'limit'         => $limit,
1167                                              'exclude'       => $exclude,
1168                                              'want_relations'=> $want_relations));
1169     }
1170
1171     /**
1172      * All Links from other pages to this page.
1173      */
1174     function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1175                           $want_relations=false)
1176     {
1177         return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1178     }
1179     /**
1180      * Forward Links: All Links from this page to other pages.
1181      */
1182     function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='',
1183                           $want_relations=false)
1184     {
1185         return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1186     }
1187     /**
1188      * Relations: All links from this page to other pages with relation <> 0.
1189      * is_a:=page or population:=number
1190      */
1191     function getRelations($sortby='', $limit='', $exclude='') {
1192         $backend = &$this->_wikidb->_backend;
1193         $result =  $backend->get_links($this->_pagename, false, true,
1194                                        $sortby, $limit, $exclude,
1195                                        true);
1196         // we do not care for the linked page versiondata, just the pagename and linkrelation
1197         return new WikiDB_PageIterator($this->_wikidb, $result,
1198                                        array('include_empty' => true,
1199                                              'sortby'        => $sortby,
1200                                              'limit'         => $limit,
1201                                              'exclude'       => $exclude,
1202                                              'want_relations'=> true));
1203     }
1204
1205     /**
1206      * possibly faster link existance check. not yet accelerated.
1207      */
1208     function existLink($link, $reversed=false) {
1209         $backend = &$this->_wikidb->_backend;
1210         if (method_exists($backend,'exists_link'))
1211             return $backend->exists_link($this->_pagename, $link, $reversed);
1212         //$cache = &$this->_wikidb->_cache;
1213         // TODO: check cache if it is possible
1214         $iter = $this->getLinks($reversed, false);
1215         while ($page = $iter->next()) {
1216             if ($page->getName() == $link)
1217                 return $page;
1218         }
1219         $iter->free();
1220         return false;
1221     }
1222
1223     /* Semantic relations are links with the relation pointing to another page,
1224        the so-called "RDF Triple".
1225        [San Diego] is%20a::city
1226        => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1227      */
1228
1229     /* Semantic attributes for a page.
1230        [San Diego] population:=1,305,736
1231        Attributes are links with the relation pointing to another page.
1232     */
1233
1234     /**
1235      * Access WikiDB_Page non version-specific meta-data.
1236      *
1237      * @access public
1238      *
1239      * @param string $key Which meta data to get.
1240      * Some reserved meta-data keys are:
1241      * <dl>
1242      * <dt>'date'  <dd> Created as unixtime
1243      * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1244      * <dt>'hits'  <dd> Page hit counter.
1245      * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1246      *                         In SQL stored now in an extra column.
1247      * Optional data:
1248      * <dt>'pref'  <dd> Users preferences, stored only in homepages.
1249      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1250      *                  E.g. "owner.users"
1251      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of
1252      *                  page-headers and content.
1253      + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1254      * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1255      * </dl>
1256      *
1257      * @return scalar The requested value, or false if the requested data
1258      * is not set.
1259      */
1260     function get($key) {
1261         $cache = &$this->_wikidb->_cache;
1262         $backend = &$this->_wikidb->_backend;
1263         if (!$key || $key[0] == '%')
1264             return false;
1265         // several new SQL backends optimize this.
1266         if (!WIKIDB_NOCACHE_MARKUP
1267             and $key == '_cached_html'
1268             and method_exists($backend, 'get_cached_html'))
1269         {
1270             return $backend->get_cached_html($this->_pagename);
1271         }
1272         $data = $cache->get_pagedata($this->_pagename);
1273         return isset($data[$key]) ? $data[$key] : false;
1274     }
1275
1276     /**
1277      * Get all the page meta-data as a hash.
1278      *
1279      * @return hash The page meta-data.
1280      */
1281     function getMetaData() {
1282         $cache = &$this->_wikidb->_cache;
1283         $data = $cache->get_pagedata($this->_pagename);
1284         $meta = array();
1285         foreach ($data as $key => $val) {
1286             if (/*!empty($val) &&*/ $key[0] != '%')
1287                 $meta[$key] = $val;
1288         }
1289         return $meta;
1290     }
1291
1292     /**
1293      * Set page meta-data.
1294      *
1295      * @see get
1296      * @access public
1297      *
1298      * @param string $key    Meta-data key to set.
1299      * @param string $newval New value.
1300      */
1301     function set($key, $newval) {
1302         $cache = &$this->_wikidb->_cache;
1303         $backend = &$this->_wikidb->_backend;
1304         $pagename = &$this->_pagename;
1305
1306         assert($key && $key[0] != '%');
1307
1308         // several new SQL backends optimize this.
1309         if (!WIKIDB_NOCACHE_MARKUP
1310             and $key == '_cached_html'
1311             and method_exists($backend, 'set_cached_html'))
1312         {
1313             if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_WARNING); return; }
1314             return $backend->set_cached_html($pagename, $newval);
1315         }
1316
1317         $data = $cache->get_pagedata($pagename);
1318
1319         if (!empty($newval)) {
1320             if (!empty($data[$key]) && $data[$key] == $newval)
1321                 return;         // values identical, skip update.
1322         }
1323         else {
1324             if (empty($data[$key]))
1325                 return;         // values identical, skip update.
1326         }
1327
1328         if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1329             trigger_error("readonly database", E_USER_WARNING);
1330             return;
1331         }
1332         $cache->update_pagedata($pagename, array($key => $newval));
1333     }
1334
1335     /**
1336      * Increase page hit count.
1337      *
1338      * FIXME: IS this needed?  Probably not.
1339      *
1340      * This is a convenience function.
1341      * <pre> $page->increaseHitCount(); </pre>
1342      * is functionally identical to
1343      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1344      * but less expensive (ignores the pagadata string)
1345      *
1346      * Note that this method may be implemented in more efficient ways
1347      * in certain backends.
1348      *
1349      * @access public
1350      */
1351     function increaseHitCount() {
1352         if ($this->_wikidb->readonly) { trigger_error("readonly database", E_USER_NOTICE); return; }
1353         if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1354             $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1355         else {
1356             @$newhits = $this->get('hits') + 1;
1357             $this->set('hits', $newhits);
1358         }
1359     }
1360
1361     /**
1362      * Return a string representation of the WikiDB_Page
1363      *
1364      * This is really only for debugging.
1365      *
1366      * @access public
1367      *
1368      * @return string Printable representation of the WikiDB_Page.
1369      */
1370     function asString () {
1371         ob_start();
1372         printf("[%s:%s\n", get_class($this), $this->getName());
1373         print_r($this->getMetaData());
1374         echo "]\n";
1375         $strval = ob_get_contents();
1376         ob_end_clean();
1377         return $strval;
1378     }
1379
1380
1381     /**
1382      * @access private
1383      * @param integer_or_object $version_or_pagerevision
1384      * Takes either the version number (and int) or a WikiDB_PageRevision
1385      * object.
1386      * @return integer The version number.
1387      */
1388     function _coerce_to_version($version_or_pagerevision) {
1389         if (method_exists($version_or_pagerevision, "getContent"))
1390             $version = $version_or_pagerevision->getVersion();
1391         else
1392             $version = (int) $version_or_pagerevision;
1393
1394         assert($version >= 0);
1395         return $version;
1396     }
1397
1398     function isUserPage ($include_empty = true) {
1399         if (!$include_empty and !$this->exists()) return false;
1400         return $this->get('pref') ? true : false;
1401     }
1402
1403     // May be empty. Either the stored owner (/Chown), or the first authorized author
1404     function getOwner() {
1405         if ($owner = $this->get('owner'))
1406             return $owner;
1407         // check all revisions forwards for the first author_id
1408         $backend = &$this->_wikidb->_backend;
1409         $pagename = &$this->_pagename;
1410         $latestversion = $backend->get_latest_version($pagename);
1411         for ($v=1; $v <= $latestversion; $v++) {
1412             $rev = $this->getRevision($v,false);
1413             if ($rev and $owner = $rev->get('author_id')) {
1414                 return $owner;
1415             }
1416         }
1417         return '';
1418     }
1419
1420     // The authenticated author of the first revision or empty if not authenticated then.
1421     function getCreator() {
1422         if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1423         else return '';
1424     }
1425
1426     // The authenticated author of the current revision.
1427     function getAuthor() {
1428         if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1429         else return '';
1430     }
1431
1432     /* Semantic Web value, not stored in the links.
1433      * todo: unify with some unit knowledge
1434      */
1435     function setAttribute($relation, $value) {
1436         $attr = $this->get('attributes');
1437         if (empty($attr))
1438             $attr = array($relation => $value);
1439         else
1440             $attr[$relation] = $value;
1441         $this->set('attributes', $attr);
1442     }
1443
1444     function getAttribute($relation) {
1445         $meta = $this->get('attributes');
1446         if (empty($meta))
1447             return '';
1448         else
1449             return $meta[$relation];
1450     }
1451
1452 };
1453
1454 /**
1455  * This class represents a specific revision of a WikiDB_Page within
1456  * a WikiDB.
1457  *
1458  * A WikiDB_PageRevision has read-only semantics. You may only create
1459  * new revisions (and delete old ones) --- you cannot modify existing
1460  * revisions.
1461  */
1462 class WikiDB_PageRevision
1463 {
1464     //var $_transformedContent = false; // set by WikiDB_Page::save()
1465
1466     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1467                                  $versiondata = false)
1468     {
1469         $this->_wikidb = &$wikidb;
1470         $this->_pagename = $pagename;
1471         $this->_version = $version;
1472         $this->_data = $versiondata ? $versiondata : array();
1473         $this->_transformedContent = false; // set by WikiDB_Page::save()
1474     }
1475
1476     /**
1477      * Get the WikiDB_Page which this revision belongs to.
1478      *
1479      * @access public
1480      *
1481      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1482      */
1483     function getPage() {
1484         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1485     }
1486
1487     /**
1488      * Get the version number of this revision.
1489      *
1490      * @access public
1491      *
1492      * @return integer The version number of this revision.
1493      */
1494     function getVersion() {
1495         return $this->_version;
1496     }
1497
1498     /**
1499      * Determine whether this revision has defaulted content.
1500      *
1501      * The default revision (version 0) of each page, as well as any
1502      * pages which are created with empty content have their content
1503      * defaulted to something like:
1504      * <pre>
1505      *   Describe [ThisPage] here.
1506      * </pre>
1507      *
1508      * @access public
1509      *
1510      * @return boolean Returns true if the page has default content.
1511      */
1512     function hasDefaultContents() {
1513         $data = &$this->_data;
1514         if (!isset($data['%content'])) return true;
1515         if ($data['%content'] === true) return false;
1516         return $data['%content'] === false or $data['%content'] === "";
1517     }
1518
1519     /**
1520      * Get the content as an array of lines.
1521      *
1522      * @access public
1523      *
1524      * @return array An array of lines.
1525      * The lines should contain no trailing white space.
1526      */
1527     function getContent() {
1528         return explode("\n", $this->getPackedContent());
1529     }
1530
1531    /**
1532      * Get the pagename of the revision.
1533      *
1534      * @access public
1535      *
1536      * @return string pagename.
1537      */
1538     function getPageName() {
1539         return $this->_pagename;
1540     }
1541     function getName() {
1542         return $this->_pagename;
1543     }
1544
1545     /**
1546      * Determine whether revision is the latest.
1547      *
1548      * @access public
1549      *
1550      * @return boolean True iff the revision is the latest (most recent) one.
1551      */
1552     function isCurrent() {
1553         if (!isset($this->_iscurrent)) {
1554             $page = $this->getPage();
1555             $current = $page->getCurrentRevision(false);
1556             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1557         }
1558         return $this->_iscurrent;
1559     }
1560
1561     /**
1562      * Get the transformed content of a page.
1563      *
1564      * @param string $pagetype Override the page-type of the revision.
1565      *
1566      * @return object An XmlContent-like object containing the page transformed
1567      * contents.
1568      */
1569     function getTransformedContent($pagetype_override=false) {
1570         $backend = &$this->_wikidb->_backend;
1571
1572         if ($pagetype_override) {
1573             // Figure out the normal page-type for this page.
1574             $type = PageType::GetPageType($this->get('pagetype'));
1575             if ($type->getName() == $pagetype_override)
1576                 $pagetype_override = false; // Not really an override...
1577         }
1578
1579         if ($pagetype_override) {
1580             // Overriden page type, don't cache (or check cache).
1581             return new TransformedText($this->getPage(),
1582                                        $this->getPackedContent(),
1583                                        $this->getMetaData(),
1584                                        $pagetype_override);
1585         }
1586
1587         $possibly_cache_results = true;
1588
1589         if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1590             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1591                 // flush cache for this page.
1592                 $page = $this->getPage();
1593                 $page->set('_cached_html', ''); // ignored with !USECACHE
1594             }
1595             $possibly_cache_results = false;
1596         }
1597         elseif (USECACHE and !$this->_transformedContent) {
1598             //$backend->lock();
1599             if ($this->isCurrent()) {
1600                 $page = $this->getPage();
1601                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1602             }
1603             else {
1604                 $possibly_cache_results = false;
1605             }
1606             //$backend->unlock();
1607         }
1608
1609         if (!$this->_transformedContent) {
1610             $this->_transformedContent
1611                 = new TransformedText($this->getPage(),
1612                                       $this->getPackedContent(),
1613                                       $this->getMetaData());
1614
1615             if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1616                 // If we're still the current version, cache the transfomed page.
1617                 //$backend->lock();
1618                 if ($this->isCurrent()) {
1619                     $page->set('_cached_html', $this->_transformedContent->pack());
1620                 }
1621                 //$backend->unlock();
1622             }
1623         }
1624
1625         return $this->_transformedContent;
1626     }
1627
1628     /**
1629      * Get the content as a string.
1630      *
1631      * @access public
1632      *
1633      * @return string The page content.
1634      * Lines are separated by new-lines.
1635      */
1636     function getPackedContent() {
1637         $data = &$this->_data;
1638
1639         if (empty($data['%content'])
1640             || (!$this->_wikidb->isWikiPage($this->_pagename)
1641                 && $this->isCurrent())) {
1642             include_once('lib/InlineParser.php');
1643
1644             // A feature similar to taglines at http://www.wlug.org.nz/
1645             // Lib from http://www.aasted.org/quote/
1646             if (defined('FORTUNE_DIR')
1647                 and is_dir(FORTUNE_DIR)
1648                 and in_array($GLOBALS['request']->getArg('action'),
1649                              array('create','edit')))
1650             {
1651                 include_once("lib/fortune.php");
1652                 $fortune = new Fortune();
1653                 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1654                 if ($quote != -1)
1655                     $quote = "<verbatim>\n"
1656                     . str_replace("\n<br>","\n", $quote)
1657                     . "</verbatim>\n\n";
1658                 else
1659                     $quote = "";
1660                 return $quote
1661                     . sprintf(_("Describe %s here."),
1662                   "[" . WikiEscape($this->_pagename) . "]");
1663             }
1664             // Replace empty content with default value.
1665             return sprintf(_("Describe %s here."),
1666                            "[" . WikiEscape($this->_pagename) . "]");
1667         }
1668
1669         // There is (non-default) content.
1670         assert($this->_version > 0);
1671
1672         if (!is_string($data['%content'])) {
1673             // Content was not provided to us at init time.
1674             // (This is allowed because for some backends, fetching
1675             // the content may be expensive, and often is not wanted
1676             // by the user.)
1677             //
1678             // In any case, now we need to get it.
1679             $data['%content'] = $this->_get_content();
1680             assert(is_string($data['%content']));
1681         }
1682
1683         return $data['%content'];
1684     }
1685
1686     function _get_content() {
1687         $cache = &$this->_wikidb->_cache;
1688         $pagename = $this->_pagename;
1689         $version = $this->_version;
1690
1691         assert($version > 0);
1692
1693         $newdata = $cache->get_versiondata($pagename, $version, true);
1694         if ($newdata) {
1695             assert(is_string($newdata['%content']));
1696             return $newdata['%content'];
1697         }
1698         else {
1699             // else revision has been deleted... What to do?
1700             return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1701                              $version, $pagename);
1702         }
1703     }
1704
1705     /**
1706      * Get meta-data for this revision.
1707      *
1708      *
1709      * @access public
1710      *
1711      * @param string $key Which meta-data to access.
1712      *
1713      * Some reserved revision meta-data keys are:
1714      * <dl>
1715      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1716      *        The 'mtime' meta-value is normally set automatically by the database
1717      *        backend, but it may be specified explicitly when creating a new revision.
1718      * <dt> orig_mtime
1719      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1720      *       of a page must be monotonically increasing.  If an attempt is
1721      *       made to create a new revision with an mtime less than that of
1722      *       the preceeding revision, the new revisions timestamp is force
1723      *       to be equal to that of the preceeding revision.  In that case,
1724      *       the originally requested mtime is preserved in 'orig_mtime'.
1725      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1726      *        This meta-value is <em>always</em> automatically maintained by the database
1727      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1728      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1729      *
1730      * FIXME: this could be refactored:
1731      * <dt> author
1732      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1733      * <dt> author_id
1734      *  <dd> Authenticated author of a page.  This is used to identify
1735      *       the distinctness of authors when cleaning old revisions from
1736      *       the database.
1737      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1738      * <dt> 'summary' <dd> Short change summary entered by page author.
1739      * </dl>
1740      *
1741      * Meta-data keys must be valid C identifers (they have to start with a letter
1742      * or underscore, and can contain only alphanumerics and underscores.)
1743      *
1744      * @return string The requested value, or false if the requested value
1745      * is not defined.
1746      */
1747     function get($key) {
1748         if (!$key || $key[0] == '%')
1749             return false;
1750         $data = &$this->_data;
1751         return isset($data[$key]) ? $data[$key] : false;
1752     }
1753
1754     /**
1755      * Get all the revision page meta-data as a hash.
1756      *
1757      * @return hash The revision meta-data.
1758      */
1759     function getMetaData() {
1760         $meta = array();
1761         foreach ($this->_data as $key => $val) {
1762             if (!empty($val) && $key[0] != '%')
1763                 $meta[$key] = $val;
1764         }
1765         return $meta;
1766     }
1767
1768
1769     /**
1770      * Return a string representation of the revision.
1771      *
1772      * This is really only for debugging.
1773      *
1774      * @access public
1775      *
1776      * @return string Printable representation of the WikiDB_Page.
1777      */
1778     function asString () {
1779         ob_start();
1780         printf("[%s:%d\n", get_class($this), $this->get('version'));
1781         print_r($this->_data);
1782         echo $this->getPackedContent() . "\n]\n";
1783         $strval = ob_get_contents();
1784         ob_end_clean();
1785         return $strval;
1786     }
1787 };
1788
1789
1790 /**
1791  * Class representing a sequence of WikiDB_Pages.
1792  * TODO: Enhance to php5 iterators
1793  * TODO:
1794  *   apply filters for options like 'sortby', 'limit', 'exclude'
1795  *   for simple queries like titleSearch, where the backend is not ready yet.
1796  */
1797 class WikiDB_PageIterator
1798 {
1799     function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1800         $this->_iter = $iter; // a WikiDB_backend_iterator
1801         $this->_wikidb = &$wikidb;
1802         $this->_options = $options;
1803      }
1804
1805     function count () {
1806         return $this->_iter->count();
1807     }
1808     function limit () {
1809         return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1810     }
1811
1812     /**
1813      * Get next WikiDB_Page in sequence.
1814      *
1815      * @access public
1816      *
1817      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1818      */
1819     function next () {
1820         if ( ! ($next = $this->_iter->next()) ) {
1821             return false;
1822         }
1823
1824         $pagename = &$next['pagename'];
1825         if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1826             trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1827         }
1828
1829         if (!$pagename) {
1830             if (isset($next['linkrelation'])
1831               or isset($next['pagedata']['linkrelation'])) {
1832                 return false;
1833             }
1834         }
1835
1836         // There's always hits, but we cache only if more
1837         // (well not with file, cvs and dba)
1838         if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1839             $this->_wikidb->_cache->cache_data($next);
1840         // cache existing page id's since we iterate over all links in GleanDescription
1841         // and need them later for LinkExistingWord
1842         } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1843                   and !$this->_options['include_empty'] and isset($next['id'])) {
1844             $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1845         }
1846         $page = new WikiDB_Page($this->_wikidb, $pagename);
1847         if (isset($next['linkrelation']))
1848             $page->set('linkrelation', $next['linkrelation']);
1849         if (isset($next['score']))
1850             $page->score = $next['score'];
1851         return $page;
1852     }
1853
1854     /**
1855      * Release resources held by this iterator.
1856      *
1857      * The iterator may not be used after free() is called.
1858      *
1859      * There is no need to call free(), if next() has returned false.
1860      * (I.e. if you iterate through all the pages in the sequence,
1861      * you do not need to call free() --- you only need to call it
1862      * if you stop before the end of the iterator is reached.)
1863      *
1864      * @access public
1865      */
1866     function free() {
1867         $this->_iter->free();
1868     }
1869     function reset() {
1870         $this->_iter->reset();
1871     }
1872     function asArray() {
1873         $result = array();
1874         while ($page = $this->next())
1875             $result[] = $page;
1876         $this->reset();
1877         return $result;
1878     }
1879
1880     /**
1881      * Apply filters for options like 'sortby', 'limit', 'exclude'
1882      * for simple queries like titleSearch, where the backend is not ready yet.
1883      * Since iteration is usually destructive for SQL results,
1884      * we have to generate a copy.
1885      */
1886     function applyFilters($options = false) {
1887         if (!$options) $options = $this->_options;
1888         if (isset($options['sortby'])) {
1889             $array = array();
1890             /* this is destructive */
1891             while ($page = $this->next())
1892                 $result[] = $page->getName();
1893             $this->_doSort($array, $options['sortby']);
1894         }
1895         /* the rest is not destructive.
1896          * reconstruct a new iterator
1897          */
1898         $pagenames = array(); $i = 0;
1899         if (isset($options['limit']))
1900             $limit = $options['limit'];
1901         else
1902             $limit = 0;
1903         if (isset($options['exclude']))
1904             $exclude = $options['exclude'];
1905         if (is_string($exclude) and !is_array($exclude))
1906             $exclude = PageList::explodePageList($exclude, false, false, $limit);
1907         foreach($array as $pagename) {
1908             if ($limit and $i++ > $limit)
1909                 return new WikiDB_Array_PageIterator($pagenames);
1910             if (!empty($exclude) and !in_array($pagename, $exclude))
1911                 $pagenames[] = $pagename;
1912             elseif (empty($exclude))
1913                 $pagenames[] = $pagename;
1914         }
1915         return new WikiDB_Array_PageIterator($pagenames);
1916     }
1917
1918     /* pagename only */
1919     function _doSort(&$array, $sortby) {
1920         $sortby = PageList::sortby($sortby, 'init');
1921         if ($sortby == '+pagename')
1922             sort($array, SORT_STRING);
1923         elseif ($sortby == '-pagename')
1924             rsort($array, SORT_STRING);
1925         reset($array);
1926     }
1927
1928 };
1929
1930 /**
1931  * A class which represents a sequence of WikiDB_PageRevisions.
1932  * TODO: Enhance to php5 iterators
1933  */
1934 class WikiDB_PageRevisionIterator
1935 {
1936     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1937         $this->_revisions = $revisions;
1938         $this->_wikidb = &$wikidb;
1939         $this->_options = $options;
1940     }
1941
1942     function count () {
1943         return $this->_revisions->count();
1944     }
1945
1946     /**
1947      * Get next WikiDB_PageRevision in sequence.
1948      *
1949      * @access public
1950      *
1951      * @return WikiDB_PageRevision
1952      * The next WikiDB_PageRevision in the sequence.
1953      */
1954     function next () {
1955         if ( ! ($next = $this->_revisions->next()) )
1956             return false;
1957
1958         //$this->_wikidb->_cache->cache_data($next);
1959
1960         $pagename = $next['pagename'];
1961         $version = $next['version'];
1962         $versiondata = $next['versiondata'];
1963         if ((int)DEBUG) {
1964             if (!(is_string($pagename) and $pagename != '')) {
1965                 trigger_error("empty pagename",E_USER_WARNING);
1966                 return false;
1967             }
1968         } else assert(is_string($pagename) and $pagename != '');
1969         if ((int)DEBUG) {
1970             if (!is_array($versiondata)) {
1971                 trigger_error("empty versiondata",E_USER_WARNING);
1972                 return false;
1973             }
1974         } else assert(is_array($versiondata));
1975         if ((int)DEBUG) {
1976             if (!($version > 0)) {
1977                 trigger_error("invalid version",E_USER_WARNING);
1978                 return false;
1979             }
1980         } else assert($version > 0);
1981
1982         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1983                                        $versiondata);
1984     }
1985
1986     /**
1987      * Release resources held by this iterator.
1988      *
1989      * The iterator may not be used after free() is called.
1990      *
1991      * There is no need to call free(), if next() has returned false.
1992      * (I.e. if you iterate through all the revisions in the sequence,
1993      * you do not need to call free() --- you only need to call it
1994      * if you stop before the end of the iterator is reached.)
1995      *
1996      * @access public
1997      */
1998     function free() {
1999         $this->_revisions->free();
2000     }
2001
2002     function asArray() {
2003         $result = array();
2004         while ($rev = $this->next())
2005             $result[] = $rev;
2006         $this->free();
2007         return $result;
2008     }
2009 };
2010
2011 /** pseudo iterator
2012  */
2013 class WikiDB_Array_PageIterator
2014 {
2015     function WikiDB_Array_PageIterator($pagenames) {
2016         global $request;
2017         $this->_dbi = $request->getDbh();
2018         $this->_pages = $pagenames;
2019         reset($this->_pages);
2020     }
2021     function next() {
2022         $c = current($this->_pages);
2023         next($this->_pages);
2024         return $c !== false ? $this->_dbi->getPage($c) : false;
2025     }
2026     function count() {
2027         return count($this->_pages);
2028     }
2029     function reset() {
2030         reset($this->_pages);
2031     }
2032     function free() {}
2033     function asArray() {
2034         reset($this->_pages);
2035         return $this->_pages;
2036     }
2037 }
2038
2039 class WikiDB_Array_generic_iter
2040 {
2041     function WikiDB_Array_generic_iter($result) {
2042         // $result may be either an array or a query result
2043         if (is_array($result)) {
2044             $this->_array = $result;
2045         } elseif (is_object($result)) {
2046             $this->_array = $result->asArray();
2047         } else {
2048             $this->_array = array();
2049         }
2050         if (!empty($this->_array))
2051             reset($this->_array);
2052     }
2053     function next() {
2054         $c = current($this->_array);
2055         next($this->_array);
2056         return $c !== false ? $c : false;
2057     }
2058     function count() {
2059         return count($this->_array);
2060     }
2061     function reset() {
2062         reset($this->_array);
2063     }
2064     function free() {}
2065     function asArray() {
2066         if (!empty($this->_array))
2067             reset($this->_array);
2068         return $this->_array;
2069     }
2070 }
2071
2072 /**
2073  * Data cache used by WikiDB.
2074  *
2075  * FIXME: Maybe rename this to caching_backend (or some such).
2076  *
2077  * @access private
2078  */
2079 class WikiDB_cache
2080 {
2081     // FIXME: beautify versiondata cache.  Cache only limited data?
2082
2083     function WikiDB_cache (&$backend) {
2084         $this->_backend = &$backend;
2085
2086         $this->_pagedata_cache = array();
2087         $this->_versiondata_cache = array();
2088         array_push ($this->_versiondata_cache, array());
2089         $this->_glv_cache = array();
2090         $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2091
2092         if (isset($GLOBALS['request']->_dbi))
2093             $this->readonly = $GLOBALS['request']->_dbi->readonly;
2094     }
2095
2096     function close() {
2097         $this->_pagedata_cache = array();
2098         $this->_versiondata_cache = array();
2099         $this->_glv_cache = array();
2100         $this->_id_cache = array();
2101     }
2102
2103     function get_pagedata($pagename) {
2104         assert(is_string($pagename) && $pagename != '');
2105         if (USECACHE) {
2106             $cache = &$this->_pagedata_cache;
2107             if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2108                 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2109                 if (empty($cache[$pagename]))
2110                     $cache[$pagename] = array();
2111             }
2112             return $cache[$pagename];
2113         } else {
2114             return $this->_backend->get_pagedata($pagename);
2115         }
2116     }
2117
2118     function update_pagedata($pagename, $newdata) {
2119         assert(is_string($pagename) && $pagename != '');
2120         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2121
2122         $this->_backend->update_pagedata($pagename, $newdata);
2123
2124         if (USECACHE) {
2125             if (!empty($this->_pagedata_cache[$pagename])
2126                 and is_array($this->_pagedata_cache[$pagename]))
2127             {
2128                 $cachedata = &$this->_pagedata_cache[$pagename];
2129                 foreach($newdata as $key => $val)
2130                     $cachedata[$key] = $val;
2131             } else
2132                 $this->_pagedata_cache[$pagename] = $newdata;
2133         }
2134     }
2135
2136     function invalidate_cache($pagename) {
2137         unset ($this->_pagedata_cache[$pagename]);
2138         unset ($this->_versiondata_cache[$pagename]);
2139         unset ($this->_glv_cache[$pagename]);
2140         unset ($this->_id_cache[$pagename]);
2141         //unset ($this->_backend->_page_data);
2142     }
2143
2144     function delete_page($pagename) {
2145         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2146         $result = $this->_backend->delete_page($pagename);
2147         $this->invalidate_cache($pagename);
2148         return $result;
2149     }
2150
2151     function purge_page($pagename) {
2152         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2153         $result = $this->_backend->purge_page($pagename);
2154         $this->invalidate_cache($pagename);
2155         return $result;
2156     }
2157
2158     // FIXME: ugly and wrong. may overwrite full cache with partial cache
2159     function cache_data($data) {
2160         ;
2161         //if (isset($data['pagedata']))
2162         //    $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2163     }
2164
2165     function get_versiondata($pagename, $version, $need_content = false) {
2166         //  FIXME: Seriously ugly hackage
2167         $readdata = false;
2168         if (USECACHE) {   //temporary - for debugging
2169             assert(is_string($pagename) && $pagename != '');
2170             // There is a bug here somewhere which results in an assertion failure at line 105
2171             // of ArchiveCleaner.php  It goes away if we use the next line.
2172             //$need_content = true;
2173             $nc = $need_content ? '1':'0';
2174             $cache = &$this->_versiondata_cache;
2175             if (!isset($cache[$pagename][$version][$nc])
2176                 || !(is_array ($cache[$pagename]))
2177                 || !(is_array ($cache[$pagename][$version])))
2178             {
2179                 $cache[$pagename][$version][$nc] =
2180                     $this->_backend->get_versiondata($pagename, $version, $need_content);
2181                 $readdata = true;
2182                 // If we have retrieved all data, we may as well set the cache for
2183                 // $need_content = false
2184                 if ($need_content){
2185                     $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2186                 }
2187             }
2188             $vdata = $cache[$pagename][$version][$nc];
2189         } else {
2190             $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2191             $readdata = true;
2192         }
2193         if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2194             if (empty($this->_pagedata_cache))
2195                 $this->_pagedata_cache = array();
2196             /* 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 */
2197             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2198         }
2199         return $vdata;
2200     }
2201
2202     function set_versiondata($pagename, $version, $data) {
2203         //unset($this->_versiondata_cache[$pagename][$version]);
2204
2205         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2206         $new = $this->_backend->set_versiondata($pagename, $version, $data);
2207         // Update the cache
2208         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2209         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2210         // Is this necessary?
2211         unset($this->_glv_cache[$pagename]);
2212     }
2213
2214     function update_versiondata($pagename, $version, $data) {
2215         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2216         $new = $this->_backend->update_versiondata($pagename, $version, $data);
2217         // Update the cache
2218         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2219         // FIXME: hack
2220         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2221         // Is this necessary?
2222         unset($this->_glv_cache[$pagename]);
2223     }
2224
2225     function delete_versiondata($pagename, $version) {
2226         if (!empty($this->readonly)) { trigger_error("readonly database", E_USER_WARNING); return; }
2227         $new = $this->_backend->delete_versiondata($pagename, $version);
2228         if (isset($this->_versiondata_cache[$pagename][$version]))
2229             unset ($this->_versiondata_cache[$pagename][$version]);
2230         // dirty latest version cache only if latest version gets deleted
2231         if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2232             unset ($this->_glv_cache[$pagename]);
2233     }
2234
2235     function get_latest_version($pagename)  {
2236         if (USECACHE) {
2237             assert (is_string($pagename) && $pagename != '');
2238             $cache = &$this->_glv_cache;
2239             if (!isset($cache[$pagename])) {
2240                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2241                 if (empty($cache[$pagename]))
2242                     $cache[$pagename] = 0;
2243             }
2244             return $cache[$pagename];
2245         } else {
2246             return $this->_backend->get_latest_version($pagename);
2247         }
2248     }
2249 };
2250
2251 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2252     static $fp = false;
2253     static $i = 0;
2254     if (!$fp) {
2255         $stamp = strftime("%y%m%d-%H%M%S");
2256         $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
2257         register_shutdown_function("_sql_debuglog_shutdown_function");
2258     } elseif ($shutdown) {
2259         fclose($fp);
2260         return;
2261     }
2262     if ($newline) fputs($fp, "[$i++] $msg");
2263     else fwrite($fp, $msg);
2264 }
2265
2266 function _sql_debuglog_shutdown_function() {
2267     _sql_debuglog('',false,true);
2268 }
2269
2270 // Local Variables:
2271 // mode: php
2272 // tab-width: 8
2273 // c-basic-offset: 4
2274 // c-hanging-comment-ender-p: nil
2275 // indent-tabs-mode: nil
2276 // End:
2277 ?>