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