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