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