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