]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
Check constants are defined
[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 $version Find most recent revision before this version.
1132      *  You can also use a WikiDB_PageRevision object to specify the $version.
1133      *
1134      * @param bool $need_content
1135      *
1136      * @return WikiDB_PageRevision|bool The requested WikiDB_PageRevision object, or false if the
1137      * requested revision does not exist in the {@link WikiDB}.  Note that
1138      * unless $version is greater than zero, a revision (perhaps version zero,
1139      * the default revision) will always be found.
1140      */
1141     public function getRevisionBefore($version = false, $need_content = true)
1142     {
1143         $backend = &$this->_wikidb->_backend;
1144         $pagename = &$this->_pagename;
1145         if ($version === false)
1146             $version = $this->_wikidb->_cache->get_latest_version($pagename);
1147         else
1148             $version = $this->_coerce_to_version($version);
1149
1150         if ($version == 0)
1151             return false;
1152         //$backend->lock();
1153         $previous = $backend->get_previous_version($pagename, $version);
1154         $revision = $this->getRevision($previous, $need_content);
1155         //$backend->unlock();
1156         assert($revision);
1157         return $revision;
1158     }
1159
1160     /**
1161      * Get all revisions of the WikiDB_Page.
1162      *
1163      * This does not include the version zero (default) revision in the
1164      * returned revision set.
1165      *
1166      * @return WikiDB_PageRevisionIterator A
1167      *   WikiDB_PageRevisionIterator containing all revisions of this
1168      *   WikiDB_Page in reverse order by version number.
1169      */
1170     function getAllRevisions()
1171     {
1172         $backend = &$this->_wikidb->_backend;
1173         $revs = $backend->get_all_revisions($this->_pagename);
1174         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1175     }
1176
1177     /**
1178      * Find pages which link to or are linked from a page.
1179      * relations: $backend->get_links is responsible to add the relation to the pagehash
1180      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1181      *   if (isset($next['linkrelation']))
1182      *
1183      * @param bool $reversed Which links to find: true for backlinks (default).
1184      * @param bool $include_empty
1185      * @param string $sortby
1186      * @param string $limit
1187      * @param string $sortby
1188      * @param string $exclude
1189      * @param bool $want_relations
1190      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1191      * all matching pages.
1192      */
1193     public function getLinks($reversed = true, $include_empty = false, $sortby = '',
1194                       $limit = '', $exclude = '', $want_relations = false)
1195     {
1196         $backend = &$this->_wikidb->_backend;
1197         $result = $backend->get_links($this->_pagename, $reversed,
1198             $include_empty, $sortby, $limit, $exclude,
1199             $want_relations);
1200         return new WikiDB_PageIterator($this->_wikidb, $result,
1201             array('include_empty' => $include_empty,
1202                 'sortby' => $sortby,
1203                 'limit' => $limit,
1204                 'exclude' => $exclude,
1205                 'want_relations' => $want_relations));
1206     }
1207
1208     /**
1209      * All Links from other pages to this page.
1210      */
1211     function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1212     {
1213         return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1214     }
1215
1216     /**
1217      * Forward Links: All Links from this page to other pages.
1218      */
1219     function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '')
1220     {
1221         return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1222     }
1223
1224     /**
1225      * Relations: All links from this page to other pages with relation <> 0.
1226      * is_a:=page or population:=number
1227      */
1228     function getRelations($sortby = '', $limit = '', $exclude = '')
1229     {
1230         $backend = &$this->_wikidb->_backend;
1231         $result = $backend->get_links($this->_pagename, false, true,
1232             $sortby, $limit, $exclude,
1233             true);
1234         // we do not care for the linked page versiondata, just the pagename and linkrelation
1235         return new WikiDB_PageIterator($this->_wikidb, $result,
1236             array('include_empty' => true,
1237                 'sortby' => $sortby,
1238                 'limit' => $limit,
1239                 'exclude' => $exclude,
1240                 'want_relations' => true));
1241     }
1242
1243     /**
1244      * possibly faster link existance check. not yet accelerated.
1245      */
1246     function existLink($link, $reversed = false)
1247     {
1248         $backend = &$this->_wikidb->_backend;
1249         if (method_exists($backend, 'exists_link'))
1250             return $backend->exists_link($this->_pagename, $link, $reversed);
1251         //$cache = &$this->_wikidb->_cache;
1252         // TODO: check cache if it is possible
1253         $iter = $this->getLinks($reversed, false);
1254         while ($page = $iter->next()) {
1255             if ($page->getName() == $link)
1256                 return $page;
1257         }
1258         $iter->free();
1259         return false;
1260     }
1261
1262     /* Semantic relations are links with the relation pointing to another page,
1263        the so-called "RDF Triple".
1264        [San Diego] is%20a::city
1265        => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1266      */
1267
1268     /* Semantic attributes for a page.
1269        [San Diego] population:=1,305,736
1270        Attributes are links with the relation pointing to another page.
1271     */
1272
1273     /**
1274      * Access WikiDB_Page non version-specific meta-data.
1275      *
1276      * @param string $key Which meta data to get.
1277      * Some reserved meta-data keys are:
1278      * <dl>
1279      * <dt>'date'  <dd> Created as unixtime
1280      * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1281      * <dt>'hits'  <dd> Page hit counter.
1282      * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1283      *                         In SQL stored now in an extra column.
1284      * Optional data:
1285      * <dt>'pref'  <dd> Users preferences, stored only in homepages.
1286      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1287      *                  E.g. "owner.users"
1288      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of
1289      *                  page-headers and content.
1290     + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1291      * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1292      * </dl>
1293      *
1294      * @return mixed The requested value, or false if the requested data
1295      * is not set.
1296      */
1297     public function get($key)
1298     {
1299         $cache = &$this->_wikidb->_cache;
1300         $backend = &$this->_wikidb->_backend;
1301         if (!$key || $key[0] == '%')
1302             return false;
1303         // several new SQL backends optimize this.
1304         if (!WIKIDB_NOCACHE_MARKUP
1305             and $key == '_cached_html'
1306                 and method_exists($backend, 'get_cached_html')
1307         ) {
1308             return $backend->get_cached_html($this->_pagename);
1309         }
1310         $data = $cache->get_pagedata($this->_pagename);
1311         return isset($data[$key]) ? $data[$key] : false;
1312     }
1313
1314     /**
1315      * Get all the page meta-data as a hash.
1316      *
1317      * @return array The page meta-data (hash).
1318      */
1319     function getMetaData()
1320     {
1321         $cache = &$this->_wikidb->_cache;
1322         $data = $cache->get_pagedata($this->_pagename);
1323         $meta = array();
1324         foreach ($data as $key => $val) {
1325             if ( /*!empty($val) &&*/
1326                 $key[0] != '%'
1327             )
1328                 $meta[$key] = $val;
1329         }
1330         return $meta;
1331     }
1332
1333     /**
1334      * Set page meta-data.
1335      *
1336      * @see get
1337      *
1338      * @param string $key    Meta-data key to set.
1339      * @param string $newval New value.
1340      */
1341     public function set($key, $newval)
1342     {
1343         $cache = &$this->_wikidb->_cache;
1344         $backend = &$this->_wikidb->_backend;
1345         $pagename = &$this->_pagename;
1346
1347         assert($key && $key[0] != '%');
1348
1349         // several new SQL backends optimize this.
1350         if (!WIKIDB_NOCACHE_MARKUP
1351             and $key == '_cached_html'
1352                 and method_exists($backend, 'set_cached_html')
1353         ) {
1354             if ($this->_wikidb->readonly) {
1355                 trigger_error("readonly database", E_USER_WARNING);
1356                 return;
1357             }
1358             $backend->set_cached_html($pagename, $newval);
1359             return;
1360         }
1361
1362         $data = $cache->get_pagedata($pagename);
1363
1364         if (!empty($newval)) {
1365             if (!empty($data[$key]) && $data[$key] == $newval)
1366                 return; // values identical, skip update.
1367         } else {
1368             if (empty($data[$key]))
1369                 return; // values identical, skip update.
1370         }
1371
1372         if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1373             trigger_error("readonly database", E_USER_WARNING);
1374             return;
1375         }
1376         $cache->update_pagedata($pagename, array($key => $newval));
1377     }
1378
1379     /**
1380      * Increase page hit count.
1381      *
1382      * FIXME: IS this needed?  Probably not.
1383      *
1384      * This is a convenience function.
1385      * <pre> $page->increaseHitCount(); </pre>
1386      * is functionally identical to
1387      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1388      * but less expensive (ignores the pagadata string)
1389      *
1390      * Note that this method may be implemented in more efficient ways
1391      * in certain backends.
1392      */
1393     public function increaseHitCount()
1394     {
1395         if ($this->_wikidb->readonly) {
1396             trigger_error("readonly database", E_USER_NOTICE);
1397             return;
1398         }
1399         if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1400             $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1401         else {
1402             @$newhits = $this->get('hits') + 1;
1403             $this->set('hits', $newhits);
1404         }
1405     }
1406
1407     /**
1408      * Return a string representation of the WikiDB_Page
1409      *
1410      * This is really only for debugging.
1411      *
1412      * @return string Printable representation of the WikiDB_Page.
1413      */
1414     public function asString()
1415     {
1416         ob_start();
1417         printf("[%s:%s\n", get_class($this), $this->getName());
1418         print_r($this->getMetaData());
1419         echo "]\n";
1420         $strval = ob_get_contents();
1421         ob_end_clean();
1422         return $strval;
1423     }
1424
1425     /**
1426      * @param int|object $version_or_pagerevision
1427      * Takes either the version number (and int) or a WikiDB_PageRevision
1428      * object.
1429      * @return integer The version number.
1430      */
1431     private function _coerce_to_version($version_or_pagerevision)
1432     {
1433         if (method_exists($version_or_pagerevision, "getContent"))
1434             $version = $version_or_pagerevision->getVersion();
1435         else
1436             $version = (int)$version_or_pagerevision;
1437
1438         assert($version >= 0);
1439         return $version;
1440     }
1441
1442     function isUserPage($include_empty = true)
1443     {
1444         if (!$include_empty and !$this->exists()) return false;
1445         return $this->get('pref') ? true : false;
1446     }
1447
1448     // May be empty. Either the stored owner (/Chown), or the first authorized author
1449     function getOwner()
1450     {
1451         if ($owner = $this->get('owner'))
1452             return $owner;
1453         // check all revisions forwards for the first author_id
1454         $backend = &$this->_wikidb->_backend;
1455         $pagename = &$this->_pagename;
1456         $latestversion = $backend->get_latest_version($pagename);
1457         for ($v = 1; $v <= $latestversion; $v++) {
1458             $rev = $this->getRevision($v, false);
1459             if ($rev and $owner = $rev->get('author_id')) {
1460                 return $owner;
1461             }
1462         }
1463         return '';
1464     }
1465
1466     // The authenticated author of the first revision or empty if not authenticated then.
1467     function getCreator()
1468     {
1469         if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1470         else return '';
1471     }
1472
1473     // The authenticated author of the current revision.
1474     function getAuthor()
1475     {
1476         if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1477         else return '';
1478     }
1479
1480     /* Semantic Web value, not stored in the links.
1481      * todo: unify with some unit knowledge
1482      */
1483     function setAttribute($relation, $value)
1484     {
1485         $attr = $this->get('attributes');
1486         if (empty($attr))
1487             $attr = array($relation => $value);
1488         else
1489             $attr[$relation] = $value;
1490         $this->set('attributes', $attr);
1491     }
1492
1493     function getAttribute($relation)
1494     {
1495         $meta = $this->get('attributes');
1496         if (empty($meta))
1497             return '';
1498         else
1499             return $meta[$relation];
1500     }
1501
1502 }
1503
1504 /**
1505  * This class represents a specific revision of a WikiDB_Page within
1506  * a WikiDB.
1507  *
1508  * A WikiDB_PageRevision has read-only semantics. You may only create
1509  * new revisions (and delete old ones) --- you cannot modify existing
1510  * revisions.
1511  */
1512 class WikiDB_PageRevision
1513 {
1514     public $_transformedContent = false; // set by WikiDB_Page::save()
1515
1516     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1517                                  $versiondata = false)
1518     {
1519         $this->_wikidb = &$wikidb;
1520         $this->_pagename = $pagename;
1521         $this->_version = $version;
1522         $this->_data = $versiondata ? $versiondata : array();
1523         $this->_transformedContent = false; // set by WikiDB_Page::save()
1524     }
1525
1526     /**
1527      * Get the WikiDB_Page which this revision belongs to.
1528      *
1529      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1530      */
1531     public function getPage()
1532     {
1533         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1534     }
1535
1536     /**
1537      * Get the version number of this revision.
1538      *
1539      * @return integer The version number of this revision.
1540      */
1541     public function getVersion()
1542     {
1543         return $this->_version;
1544     }
1545
1546     /**
1547      * Determine whether this revision has defaulted content.
1548      *
1549      * The default revision (version 0) of each page, as well as any
1550      * pages which are created with empty content have their content
1551      * defaulted to something like:
1552      * <pre>
1553      *   Describe [ThisPage] here.
1554      * </pre>
1555      *
1556      * @return boolean Returns true if the page has default content.
1557      */
1558     public function hasDefaultContents()
1559     {
1560         $data = &$this->_data;
1561         if (!isset($data['%content'])) return true;
1562         if ($data['%content'] === true) return false;
1563         return $data['%content'] === false or $data['%content'] === "";
1564     }
1565
1566     /**
1567      * Get the content as an array of lines.
1568      *
1569      * @return array An array of lines.
1570      * The lines should contain no trailing white space.
1571      */
1572     public function getContent()
1573     {
1574         return explode("\n", $this->getPackedContent());
1575     }
1576
1577     /**
1578      * Get the pagename of the revision.
1579      *
1580      * @return string pagename.
1581      */
1582     public function getPageName()
1583     {
1584         return $this->_pagename;
1585     }
1586
1587     function getName()
1588     {
1589         return $this->_pagename;
1590     }
1591
1592     /**
1593      * Determine whether revision is the latest.
1594      *
1595      * @return boolean True iff the revision is the latest (most recent) one.
1596      */
1597     public function isCurrent()
1598     {
1599         if (!isset($this->_iscurrent)) {
1600             $page = $this->getPage();
1601             $current = $page->getCurrentRevision(false);
1602             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1603         }
1604         return $this->_iscurrent;
1605     }
1606
1607     /**
1608      * Get the transformed content of a page.
1609      *
1610      * @param bool $pagetype_override
1611      * @return object An XmlContent-like object containing the page transformed
1612      * contents.
1613      */
1614     function getTransformedContent($pagetype_override = false)
1615     {
1616         if ($pagetype_override) {
1617             // Figure out the normal page-type for this page.
1618             $type = PageType::GetPageType($this->get('pagetype'));
1619             if ($type->getName() == $pagetype_override)
1620                 $pagetype_override = false; // Not really an override...
1621         }
1622
1623         if ($pagetype_override) {
1624             // Overriden page type, don't cache (or check cache).
1625             return new TransformedText($this->getPage(),
1626                 $this->getPackedContent(),
1627                 $this->getMetaData(),
1628                 $pagetype_override);
1629         }
1630
1631         $possibly_cache_results = true;
1632
1633         if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1634             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1635                 // flush cache for this page.
1636                 $page = $this->getPage();
1637                 $page->set('_cached_html', ''); // ignored with !USECACHE
1638             }
1639             $possibly_cache_results = false;
1640         } elseif (USECACHE and !$this->_transformedContent) {
1641             //$backend->lock();
1642             if ($this->isCurrent()) {
1643                 $page = $this->getPage();
1644                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1645             } else {
1646                 $possibly_cache_results = false;
1647             }
1648             //$backend->unlock();
1649         }
1650
1651         if (!$this->_transformedContent) {
1652             $this->_transformedContent
1653                 = new TransformedText($this->getPage(),
1654                 $this->getPackedContent(),
1655                 $this->getMetaData());
1656
1657             if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1658                 // If we're still the current version, cache the transfomed page.
1659                 //$backend->lock();
1660                 if ($this->isCurrent()) {
1661                     $page->set('_cached_html', $this->_transformedContent->pack());
1662                 }
1663                 //$backend->unlock();
1664             }
1665         }
1666
1667         return $this->_transformedContent;
1668     }
1669
1670     /**
1671      * Get the content as a string.
1672      *
1673      * @return string The page content.
1674      * Lines are separated by new-lines.
1675      */
1676     public function getPackedContent()
1677     {
1678         $data = &$this->_data;
1679
1680         if (empty($data['%content'])
1681             || (!$this->_wikidb->isWikiPage($this->_pagename)
1682                 && $this->isCurrent())
1683         ) {
1684             include_once 'lib/InlineParser.php';
1685
1686             // A feature similar to taglines at http://www.wlug.org.nz/
1687             // Lib from http://www.aasted.org/quote/
1688             if (defined('FORTUNE_DIR')
1689                 and is_dir(FORTUNE_DIR)
1690                     and in_array($GLOBALS['request']->getArg('action'),
1691                         array('create', 'edit'))
1692             ) {
1693                 include_once 'lib/fortune.php';
1694                 $fortune = new Fortune();
1695                 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1696                 if ($quote != -1)
1697                     $quote = "<verbatim>\n"
1698                         . str_replace("\n<br>", "\n", $quote)
1699                         . "</verbatim>\n\n";
1700                 else
1701                     $quote = "";
1702                 return $quote
1703                     . sprintf(_("Describe %s here."),
1704                         "[" . WikiEscape($this->_pagename) . "]");
1705             }
1706             // Replace empty content with default value.
1707             return sprintf(_("Describe %s here."),
1708                 "[" . WikiEscape($this->_pagename) . "]");
1709         }
1710
1711         // There is (non-default) content.
1712         assert($this->_version > 0);
1713
1714         if (!is_string($data['%content'])) {
1715             // Content was not provided to us at init time.
1716             // (This is allowed because for some backends, fetching
1717             // the content may be expensive, and often is not wanted
1718             // by the user.)
1719             //
1720             // In any case, now we need to get it.
1721             $data['%content'] = $this->_get_content();
1722             assert(is_string($data['%content']));
1723         }
1724
1725         return $data['%content'];
1726     }
1727
1728     function _get_content()
1729     {
1730         $cache = &$this->_wikidb->_cache;
1731         $pagename = $this->_pagename;
1732         $version = $this->_version;
1733
1734         assert($version > 0);
1735
1736         $newdata = $cache->get_versiondata($pagename, $version, true);
1737         if ($newdata) {
1738             assert(is_string($newdata['%content']));
1739             return $newdata['%content'];
1740         } else {
1741             // else revision has been deleted... What to do?
1742             return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1743                 $version, $pagename);
1744         }
1745     }
1746
1747     /**
1748      * Get meta-data for this revision.
1749      *
1750      * @param string $key Which meta-data to access.
1751      *
1752      * Some reserved revision meta-data keys are:
1753      * <dl>
1754      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1755      *        The 'mtime' meta-value is normally set automatically by the database
1756      *        backend, but it may be specified explicitly when creating a new revision.
1757      * <dt> orig_mtime
1758      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1759      *       of a page must be monotonically increasing.  If an attempt is
1760      *       made to create a new revision with an mtime less than that of
1761      *       the preceeding revision, the new revisions timestamp is force
1762      *       to be equal to that of the preceeding revision.  In that case,
1763      *       the originally requested mtime is preserved in 'orig_mtime'.
1764      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1765      *        This meta-value is <em>always</em> automatically maintained by the database
1766      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1767      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1768      *
1769      * FIXME: this could be refactored:
1770      * <dt> author
1771      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1772      * <dt> author_id
1773      *  <dd> Authenticated author of a page.  This is used to identify
1774      *       the distinctness of authors when cleaning old revisions from
1775      *       the database.
1776      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1777      * <dt> 'summary' <dd> Short change summary entered by page author.
1778      * </dl>
1779      *
1780      * Meta-data keys must be valid C identifers (they have to start with a letter
1781      * or underscore, and can contain only alphanumerics and underscores.)
1782      *
1783      * @return string The requested value, or false if the requested value
1784      * is not defined.
1785      */
1786     public function get($key)
1787     {
1788         if (!$key || $key[0] == '%')
1789             return false;
1790         $data = &$this->_data;
1791         return isset($data[$key]) ? $data[$key] : false;
1792     }
1793
1794     /**
1795      * Get all the revision page meta-data as a hash.
1796      *
1797      * @return array The revision meta-data.
1798      */
1799     function getMetaData()
1800     {
1801         $meta = array();
1802         foreach ($this->_data as $key => $val) {
1803             if (!empty($val) && $key[0] != '%')
1804                 $meta[$key] = $val;
1805         }
1806         return $meta;
1807     }
1808
1809     /**
1810      * Return a string representation of the revision.
1811      *
1812      * This is really only for debugging.
1813      *
1814      * @return string Printable representation of the WikiDB_Page.
1815      */
1816     public function asString()
1817     {
1818         ob_start();
1819         printf("[%s:%d\n", get_class($this), $this->get('version'));
1820         print_r($this->_data);
1821         echo $this->getPackedContent() . "\n]\n";
1822         $strval = ob_get_contents();
1823         ob_end_clean();
1824         return $strval;
1825     }
1826 }
1827
1828 /**
1829  * Class representing a sequence of WikiDB_Pages.
1830  * TODO: Enhance to php5 iterators
1831  * TODO:
1832  *   apply filters for options like 'sortby', 'limit', 'exclude'
1833  *   for simple queries like titleSearch, where the backend is not ready yet.
1834  */
1835 class WikiDB_PageIterator
1836 {
1837     function WikiDB_PageIterator(&$wikidb, &$iter, $options = false)
1838     {
1839         $this->_iter = $iter; // a WikiDB_backend_iterator
1840         $this->_wikidb = &$wikidb;
1841         $this->_options = $options;
1842     }
1843
1844     function count()
1845     {
1846         return $this->_iter->count();
1847     }
1848
1849     function limit()
1850     {
1851         return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1852     }
1853
1854     /**
1855      * Get next WikiDB_Page in sequence.
1856      *
1857      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1858      */
1859     public function next()
1860     {
1861         if (!($next = $this->_iter->next())) {
1862             return false;
1863         }
1864
1865         $pagename = &$next['pagename'];
1866         if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1867             trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1868         }
1869
1870         if (!$pagename) {
1871             if (isset($next['linkrelation'])
1872                 or isset($next['pagedata']['linkrelation'])
1873             ) {
1874                 return false;
1875             }
1876         }
1877
1878         // There's always hits, but we cache only if more
1879         // (well not with file, cvs and dba)
1880         if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1881             $this->_wikidb->_cache->cache_data($next);
1882             // cache existing page id's since we iterate over all links in GleanDescription
1883             // and need them later for LinkExistingWord
1884         } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1885             and !$this->_options['include_empty'] and isset($next['id'])
1886         ) {
1887             $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1888         }
1889         $page = new WikiDB_Page($this->_wikidb, $pagename);
1890         if (isset($next['linkrelation']))
1891             $page->set('linkrelation', $next['linkrelation']);
1892         if (isset($next['score']))
1893             $page->score = $next['score'];
1894         return $page;
1895     }
1896
1897     /**
1898      * Release resources held by this iterator.
1899      *
1900      * The iterator may not be used after free() is called.
1901      *
1902      * There is no need to call free(), if next() has returned false.
1903      * (I.e. if you iterate through all the pages in the sequence,
1904      * you do not need to call free() --- you only need to call it
1905      * if you stop before the end of the iterator is reached.)
1906      */
1907     public function free()
1908     {
1909         // $this->_iter->free();
1910     }
1911
1912     function reset()
1913     {
1914         $this->_iter->reset();
1915     }
1916
1917     function asArray()
1918     {
1919         $result = array();
1920         while ($page = $this->next())
1921             $result[] = $page;
1922         $this->reset();
1923         return $result;
1924     }
1925
1926     /**
1927      * Apply filters for options like 'sortby', 'limit', 'exclude'
1928      * for simple queries like titleSearch, where the backend is not ready yet.
1929      * Since iteration is usually destructive for SQL results,
1930      * we have to generate a copy.
1931      */
1932     function applyFilters($options = false)
1933     {
1934         if (!$options) $options = $this->_options;
1935         if (isset($options['sortby'])) {
1936             $array = array();
1937             /* this is destructive */
1938             while ($page = $this->next())
1939                 $result[] = $page->getName();
1940             $this->_doSort($array, $options['sortby']);
1941         }
1942         /* the rest is not destructive.
1943          * reconstruct a new iterator
1944          */
1945         $pagenames = array();
1946         $i = 0;
1947         if (isset($options['limit']))
1948             $limit = $options['limit'];
1949         else
1950             $limit = 0;
1951         if (isset($options['exclude']))
1952             $exclude = $options['exclude'];
1953         if (is_string($exclude) and !is_array($exclude))
1954             $exclude = PageList::explodePageList($exclude, false, false, $limit);
1955         foreach ($array as $pagename) {
1956             if ($limit and $i++ > $limit)
1957                 return new WikiDB_Array_PageIterator($pagenames);
1958             if (!empty($exclude) and !in_array($pagename, $exclude))
1959                 $pagenames[] = $pagename;
1960             elseif (empty($exclude))
1961                 $pagenames[] = $pagename;
1962         }
1963         return new WikiDB_Array_PageIterator($pagenames);
1964     }
1965
1966     /* pagename only */
1967     function _doSort(&$array, $sortby)
1968     {
1969         $sortby = PageList::sortby($sortby, 'init');
1970         if ($sortby == '+pagename')
1971             sort($array, SORT_STRING);
1972         elseif ($sortby == '-pagename')
1973             rsort($array, SORT_STRING);
1974         reset($array);
1975     }
1976
1977 }
1978
1979 /**
1980  * A class which represents a sequence of WikiDB_PageRevisions.
1981  * TODO: Enhance to php5 iterators
1982  */
1983 class WikiDB_PageRevisionIterator
1984 {
1985     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
1986     {
1987         $this->_revisions = $revisions;
1988         $this->_wikidb = &$wikidb;
1989         $this->_options = $options;
1990     }
1991
1992     function count()
1993     {
1994         return $this->_revisions->count();
1995     }
1996
1997     /**
1998      * Get next WikiDB_PageRevision in sequence.
1999      *
2000      * @return WikiDB_PageRevision
2001      * The next WikiDB_PageRevision in the sequence.
2002      */
2003     public function next()
2004     {
2005         if (!($next = $this->_revisions->next()))
2006             return false;
2007
2008         //$this->_wikidb->_cache->cache_data($next);
2009
2010         $pagename = $next['pagename'];
2011         $version = $next['version'];
2012         $versiondata = $next['versiondata'];
2013         if ((int)DEBUG) {
2014             if (!(is_string($pagename) and $pagename != '')) {
2015                 trigger_error("empty pagename", E_USER_WARNING);
2016                 return false;
2017             }
2018         } else assert(is_string($pagename) and $pagename != '');
2019         if ((int)DEBUG) {
2020             if (!is_array($versiondata)) {
2021                 trigger_error("empty versiondata", E_USER_WARNING);
2022                 return false;
2023             }
2024         } else assert(is_array($versiondata));
2025         if ((int)DEBUG) {
2026             if (!($version > 0)) {
2027                 trigger_error("invalid version", E_USER_WARNING);
2028                 return false;
2029             }
2030         } else assert($version > 0);
2031
2032         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2033             $versiondata);
2034     }
2035
2036     /**
2037      * Release resources held by this iterator.
2038      *
2039      * The iterator may not be used after free() is called.
2040      *
2041      * There is no need to call free(), if next() has returned false.
2042      * (I.e. if you iterate through all the revisions in the sequence,
2043      * you do not need to call free() --- you only need to call it
2044      * if you stop before the end of the iterator is reached.)
2045      */
2046     public function free()
2047     {
2048         $this->_revisions->free();
2049     }
2050
2051     function asArray()
2052     {
2053         $result = array();
2054         while ($rev = $this->next())
2055             $result[] = $rev;
2056         $this->free();
2057         return $result;
2058     }
2059 }
2060
2061 /** pseudo iterator
2062  */
2063 class WikiDB_Array_PageIterator
2064 {
2065     function WikiDB_Array_PageIterator($pagenames)
2066     {
2067         global $request;
2068         $this->_dbi = $request->getDbh();
2069         $this->_pages = $pagenames;
2070         reset($this->_pages);
2071     }
2072
2073     function next()
2074     {
2075         $c = current($this->_pages);
2076         next($this->_pages);
2077         return $c !== false ? $this->_dbi->getPage($c) : false;
2078     }
2079
2080     function count()
2081     {
2082         return count($this->_pages);
2083     }
2084
2085     function reset()
2086     {
2087         reset($this->_pages);
2088     }
2089
2090     function free()
2091     {
2092     }
2093
2094     function asArray()
2095     {
2096         reset($this->_pages);
2097         return $this->_pages;
2098     }
2099 }
2100
2101 class WikiDB_Array_generic_iter
2102 {
2103     function WikiDB_Array_generic_iter($result)
2104     {
2105         // $result may be either an array or a query result
2106         if (is_array($result)) {
2107             $this->_array = $result;
2108         } elseif (is_object($result)) {
2109             $this->_array = $result->asArray();
2110         } else {
2111             $this->_array = array();
2112         }
2113         if (!empty($this->_array))
2114             reset($this->_array);
2115     }
2116
2117     function next()
2118     {
2119         $c = current($this->_array);
2120         next($this->_array);
2121         return $c !== false ? $c : false;
2122     }
2123
2124     function count()
2125     {
2126         return count($this->_array);
2127     }
2128
2129     function reset()
2130     {
2131         reset($this->_array);
2132     }
2133
2134     function free()
2135     {
2136     }
2137
2138     function asArray()
2139     {
2140         if (!empty($this->_array))
2141             reset($this->_array);
2142         return $this->_array;
2143     }
2144 }
2145
2146 /**
2147  * Data cache used by WikiDB.
2148  *
2149  * FIXME: Maybe rename this to caching_backend (or some such).
2150  *
2151  * @access private
2152  */
2153 class WikiDB_cache
2154 {
2155     // FIXME: beautify versiondata cache.  Cache only limited data?
2156
2157     function WikiDB_cache(&$backend)
2158     {
2159         $this->_backend = &$backend;
2160
2161         $this->_pagedata_cache = array();
2162         $this->_versiondata_cache = array();
2163         array_push($this->_versiondata_cache, array());
2164         $this->_glv_cache = array();
2165         $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2166
2167         if (isset($GLOBALS['request']->_dbi))
2168             $this->readonly = $GLOBALS['request']->_dbi->readonly;
2169     }
2170
2171     function close()
2172     {
2173         $this->_pagedata_cache = array();
2174         $this->_versiondata_cache = array();
2175         $this->_glv_cache = array();
2176         $this->_id_cache = array();
2177     }
2178
2179     function get_pagedata($pagename)
2180     {
2181         assert(is_string($pagename) && $pagename != '');
2182         if (USECACHE) {
2183             $cache = &$this->_pagedata_cache;
2184             if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2185                 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2186                 if (empty($cache[$pagename]))
2187                     $cache[$pagename] = array();
2188             }
2189             return $cache[$pagename];
2190         } else {
2191             return $this->_backend->get_pagedata($pagename);
2192         }
2193     }
2194
2195     function update_pagedata($pagename, $newdata)
2196     {
2197         assert(is_string($pagename) && $pagename != '');
2198         if (!empty($this->readonly)) {
2199             trigger_error("readonly database", E_USER_WARNING);
2200             return;
2201         }
2202
2203         $this->_backend->update_pagedata($pagename, $newdata);
2204
2205         if (USECACHE) {
2206             if (!empty($this->_pagedata_cache[$pagename])
2207                 and is_array($this->_pagedata_cache[$pagename])
2208             ) {
2209                 $cachedata = &$this->_pagedata_cache[$pagename];
2210                 foreach ($newdata as $key => $val)
2211                     $cachedata[$key] = $val;
2212             } else
2213                 $this->_pagedata_cache[$pagename] = $newdata;
2214         }
2215     }
2216
2217     function invalidate_cache($pagename)
2218     {
2219         unset ($this->_pagedata_cache[$pagename]);
2220         unset ($this->_versiondata_cache[$pagename]);
2221         unset ($this->_glv_cache[$pagename]);
2222         unset ($this->_id_cache[$pagename]);
2223         //unset ($this->_backend->_page_data);
2224     }
2225
2226     function delete_page($pagename)
2227     {
2228         if (!empty($this->readonly)) {
2229             trigger_error("readonly database", E_USER_WARNING);
2230             return false;
2231         }
2232         $result = $this->_backend->delete_page($pagename);
2233         $this->invalidate_cache($pagename);
2234         return $result;
2235     }
2236
2237     function purge_page($pagename)
2238     {
2239         if (!empty($this->readonly)) {
2240             trigger_error("readonly database", E_USER_WARNING);
2241             return false;
2242         }
2243         $result = $this->_backend->purge_page($pagename);
2244         $this->invalidate_cache($pagename);
2245         return $result;
2246     }
2247
2248     // FIXME: ugly and wrong. may overwrite full cache with partial cache
2249     function cache_data($data)
2250     {
2251         ;
2252         //if (isset($data['pagedata']))
2253         //    $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2254     }
2255
2256     function get_versiondata($pagename, $version, $need_content = false)
2257     {
2258         //  FIXME: Seriously ugly hackage
2259         $readdata = false;
2260         if (USECACHE) { //temporary - for debugging
2261             assert(is_string($pagename) && $pagename != '');
2262             // There is a bug here somewhere which results in an assertion failure at line 105
2263             // of ArchiveCleaner.php  It goes away if we use the next line.
2264             //$need_content = true;
2265             $nc = $need_content ? '1' : '0';
2266             $cache = &$this->_versiondata_cache;
2267             if (!isset($cache[$pagename][$version][$nc])
2268                 || !(is_array($cache[$pagename]))
2269                 || !(is_array($cache[$pagename][$version]))
2270             ) {
2271                 $cache[$pagename][$version][$nc] =
2272                     $this->_backend->get_versiondata($pagename, $version, $need_content);
2273                 $readdata = true;
2274                 // If we have retrieved all data, we may as well set the cache for
2275                 // $need_content = false
2276                 if ($need_content) {
2277                     $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2278                 }
2279             }
2280             $vdata = $cache[$pagename][$version][$nc];
2281         } else {
2282             $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2283             $readdata = true;
2284         }
2285         if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2286             if (empty($this->_pagedata_cache))
2287                 $this->_pagedata_cache = array();
2288             /* 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 */
2289             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2290         }
2291         return $vdata;
2292     }
2293
2294     function set_versiondata($pagename, $version, $data)
2295     {
2296         //unset($this->_versiondata_cache[$pagename][$version]);
2297
2298         if (!empty($this->readonly)) {
2299             trigger_error("readonly database", E_USER_WARNING);
2300             return;
2301         }
2302         $this->_backend->set_versiondata($pagename, $version, $data);
2303         // Update the cache
2304         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2305         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2306         // Is this necessary?
2307         unset($this->_glv_cache[$pagename]);
2308     }
2309
2310     function update_versiondata($pagename, $version, $data)
2311     {
2312         if (!empty($this->readonly)) {
2313             trigger_error("readonly database", E_USER_WARNING);
2314             return;
2315         }
2316         $this->_backend->update_versiondata($pagename, $version, $data);
2317         // Update the cache
2318         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2319         // FIXME: hack
2320         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2321         // Is this necessary?
2322         unset($this->_glv_cache[$pagename]);
2323     }
2324
2325     function delete_versiondata($pagename, $version)
2326     {
2327         if (!empty($this->readonly)) {
2328             trigger_error("readonly database", E_USER_WARNING);
2329             return;
2330         }
2331         $this->_backend->delete_versiondata($pagename, $version);
2332         if (isset($this->_versiondata_cache[$pagename][$version]))
2333             unset ($this->_versiondata_cache[$pagename][$version]);
2334         // dirty latest version cache only if latest version gets deleted
2335         if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2336             unset ($this->_glv_cache[$pagename]);
2337     }
2338
2339     function get_latest_version($pagename)
2340     {
2341         if (USECACHE) {
2342             assert(is_string($pagename) && $pagename != '');
2343             $cache = &$this->_glv_cache;
2344             if (!isset($cache[$pagename])) {
2345                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2346                 if (empty($cache[$pagename]))
2347                     $cache[$pagename] = 0;
2348             }
2349             return $cache[$pagename];
2350         } else {
2351             return $this->_backend->get_latest_version($pagename);
2352         }
2353     }
2354 }
2355
2356 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2357 {
2358     static $fp = false;
2359     static $i = 0;
2360     if (!$fp) {
2361         $stamp = strftime("%y%m%d-%H%M%S");
2362         $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2363         register_shutdown_function("_sql_debuglog_shutdown_function");
2364     } elseif ($shutdown) {
2365         fclose($fp);
2366         return;
2367     }
2368     if ($newline) fputs($fp, "[$i++] $msg");
2369     else fwrite($fp, $msg);
2370 }
2371
2372 function _sql_debuglog_shutdown_function()
2373 {
2374     _sql_debuglog('', false, true);
2375 }
2376
2377 // Local Variables:
2378 // mode: php
2379 // tab-width: 8
2380 // c-basic-offset: 4
2381 // c-hanging-comment-ender-p: nil
2382 // indent-tabs-mode: nil
2383 // End: