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