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