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