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