]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
printSimpleTrace is void
[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>";
724         printSimpleTrace(debug_backtrace());
725         echo "</pre>\n";
726         trigger_error("no SQL database", E_USER_ERROR);
727         return false;
728     }
729
730     // see backend upstream methods
731     // ADODB adds surrounding quotes, SQL not yet!
732     function quote($s)
733     {
734         return $s;
735     }
736
737     function isOpen()
738     {
739         global $request;
740         if (!$request->_dbi) return false;
741         else return false; /* so far only needed for sql so false it.
742                             later we have to check dba also */
743     }
744
745     function getParam($param)
746     {
747         global $DBParams;
748         if (isset($DBParams[$param])) return $DBParams[$param];
749         elseif ($param == 'prefix') return ''; else return false;
750     }
751
752     function getAuthParam($param)
753     {
754         global $DBAuthParams;
755         if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
756         elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER']; elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY']; else return false;
757     }
758 }
759
760 /**
761  * A base class which representing a wiki-page within a
762  * WikiDB.
763  *
764  * A WikiDB_Page contains a number (at least one) of
765  * WikiDB_PageRevisions.
766  */
767 class WikiDB_Page
768 {
769     function WikiDB_Page(&$wikidb, $pagename)
770     {
771         $this->_wikidb = &$wikidb;
772         $this->_pagename = $pagename;
773         if ((int)DEBUG) {
774             if (!(is_string($pagename) and $pagename != '')) {
775                 if (function_exists("xdebug_get_function_stack")) {
776                     echo "xdebug_get_function_stack(): ";
777                     var_dump(xdebug_get_function_stack());
778                 } else {
779                     printSimpleTrace(debug_backtrace());
780                 }
781                 trigger_error("empty pagename", E_USER_WARNING);
782                 return false;
783             }
784         } else {
785             assert(is_string($pagename) and $pagename != '');
786         }
787     }
788
789     /**
790      * Get the name of the wiki page.
791      *
792      * @access public
793      *
794      * @return string The page name.
795      */
796     function getName()
797     {
798         return $this->_pagename;
799     }
800
801     // To reduce the memory footprint for larger sets of pagelists,
802     // we don't cache the content (only true or false) and
803     // we purge the pagedata (_cached_html) also
804     function exists()
805     {
806         if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
807         $current = $this->getCurrentRevision(false);
808         if (!$current) return false;
809         return !$current->hasDefaultContents();
810     }
811
812     /**
813      * Delete an old revision of a WikiDB_Page.
814      *
815      * Deletes the specified revision of the page.
816      * It is a fatal error to attempt to delete the current revision.
817      *
818      * @access public
819      *
820      * @param integer $version Which revision to delete.  (You can also
821      *  use a WikiDB_PageRevision object here.)
822      */
823     function deleteRevision($version)
824     {
825         if ($this->_wikidb->readonly) {
826             trigger_error("readonly database", E_USER_WARNING);
827             return;
828         }
829         $backend = &$this->_wikidb->_backend;
830         $cache = &$this->_wikidb->_cache;
831         $pagename = &$this->_pagename;
832
833         $version = $this->_coerce_to_version($version);
834         if ($version == 0)
835             return;
836
837         $backend->lock(array('page', 'version'));
838         $latestversion = $cache->get_latest_version($pagename);
839         if ($latestversion && ($version == $latestversion)) {
840             $backend->unlock(array('page', 'version'));
841             trigger_error(sprintf("Attempt to delete most recent revision of “%s”",
842                 $pagename), E_USER_ERROR);
843             return;
844         }
845
846         $cache->delete_versiondata($pagename, $version);
847         $backend->unlock(array('page', 'version'));
848     }
849
850     /*
851      * Delete a revision, or possibly merge it with a previous
852      * revision.
853      *
854      * The idea is this:
855      * Suppose an author make a (major) edit to a page.  Shortly
856      * after that the same author makes a minor edit (e.g. to fix
857      * spelling mistakes he just made.)
858      *
859      * Now some time later, where cleaning out old saved revisions,
860      * and would like to delete his minor revision (since there's
861      * really no point in keeping minor revisions around for a long
862      * time.)
863      *
864      * Note that the text after the minor revision probably represents
865      * what the author intended to write better than the text after
866      * the preceding major edit.
867      *
868      * So what we really want to do is merge the minor edit with the
869      * preceding edit.
870      *
871      * We will only do this when:
872      * <ul>
873      * <li>The revision being deleted is a minor one, and
874      * <li>It has the same author as the immediately preceding revision.
875      * </ul>
876      */
877     function mergeRevision($version)
878     {
879         if ($this->_wikidb->readonly) {
880             trigger_error("readonly database", E_USER_WARNING);
881             return;
882         }
883         $backend = &$this->_wikidb->_backend;
884         $cache = &$this->_wikidb->_cache;
885         $pagename = &$this->_pagename;
886
887         $version = $this->_coerce_to_version($version);
888         if ($version == 0)
889             return;
890
891         $backend->lock(array('version'));
892         $latestversion = $cache->get_latest_version($pagename);
893         if ($latestversion && $version == $latestversion) {
894             $backend->unlock(array('version'));
895             trigger_error(sprintf("Attempt to merge most recent revision of “%s”",
896                 $pagename), E_USER_ERROR);
897             return;
898         }
899
900         $versiondata = $cache->get_versiondata($pagename, $version, true);
901         if (!$versiondata) {
902             // Not there? ... we're done!
903             $backend->unlock(array('version'));
904             return;
905         }
906
907         if ($versiondata['is_minor_edit']) {
908             $previous = $backend->get_previous_version($pagename, $version);
909             if ($previous) {
910                 $prevdata = $cache->get_versiondata($pagename, $previous);
911                 if ($prevdata['author_id'] == $versiondata['author_id']) {
912                     // This is a minor revision, previous version is
913                     // by the same author. We will merge the
914                     // revisions.
915                     $cache->update_versiondata($pagename, $previous,
916                         array('%content' => $versiondata['%content'],
917                             '_supplanted' => $versiondata['_supplanted']));
918                 }
919             }
920         }
921
922         $cache->delete_versiondata($pagename, $version);
923         $backend->unlock(array('version'));
924     }
925
926     /**
927      * Create a new revision of a {@link WikiDB_Page}.
928      *
929      * @access public
930      *
931      * @param int $version Version number for new revision.
932      * To ensure proper serialization of edits, $version must be
933      * exactly one higher than the current latest version.
934      * (You can defeat this check by setting $version to
935      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
936      *
937      * @param string $content Contents of new revision.
938      *
939      * @param hash $metadata Metadata for new revision.
940      * All values in the hash should be scalars (strings or integers).
941      *
942      * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
943      *
944      * @return WikiDB_PageRevision Returns the new WikiDB_PageRevision object. If
945      * $version was incorrect, returns false
946      */
947     function createRevision($version, &$content, $metadata, $links)
948     {
949         if ($this->_wikidb->readonly) {
950             trigger_error("readonly database", E_USER_WARNING);
951             return;
952         }
953         $backend = &$this->_wikidb->_backend;
954         $cache = &$this->_wikidb->_cache;
955         $pagename = &$this->_pagename;
956         $cache->invalidate_cache($pagename);
957
958         $backend->lock(array('version', 'page', 'recent', 'link', 'nonempty'));
959
960         $latestversion = $backend->get_latest_version($pagename);
961         $newversion = ($latestversion ? $latestversion : 0) + 1;
962         assert($newversion >= 1);
963
964         if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
965             $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
966             return false;
967         }
968
969         $data = $metadata;
970
971         foreach ($data as $key => $val) {
972             if (empty($val) || $key[0] == '_' || $key[0] == '%')
973                 unset($data[$key]);
974         }
975
976         assert(!empty($data['author']));
977         if (empty($data['author_id']))
978             @$data['author_id'] = $data['author'];
979
980         if (empty($data['mtime']))
981             $data['mtime'] = time();
982
983         if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
984             // Ensure mtimes are monotonic.
985             $pdata = $cache->get_versiondata($pagename, $latestversion);
986             if ($data['mtime'] < $pdata['mtime']) {
987                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
988                         $pagename, "'non-monotonic'"),
989                     E_USER_NOTICE);
990                 $data['orig_mtime'] = $data['mtime'];
991                 $data['mtime'] = $pdata['mtime'];
992             }
993
994             // FIXME: use (possibly user specified) 'mtime' time or
995             // time()?
996             $cache->update_versiondata($pagename, $latestversion,
997                 array('_supplanted' => $data['mtime']));
998         }
999
1000         $data['%content'] = &$content;
1001
1002         $cache->set_versiondata($pagename, $newversion, $data);
1003
1004         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
1005         //':deleted' => empty($content)));
1006
1007         $backend->set_links($pagename, $links);
1008
1009         $backend->unlock(array('version', 'page', 'recent', 'link', 'nonempty'));
1010
1011         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
1012             $data);
1013     }
1014
1015     /** A higher-level interface to createRevision.
1016      *
1017      * This takes care of computing the links, and storing
1018      * a cached version of the transformed wiki-text.
1019      *
1020      * @param string $wikitext The page content.
1021      *
1022      * @param int $version Version number for new revision.
1023      * To ensure proper serialization of edits, $version must be
1024      * exactly one higher than the current latest version.
1025      * (You can defeat this check by setting $version to
1026      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
1027      *
1028      * @param hash $meta Meta-data for new revision.
1029      */
1030     function save($wikitext, $version, $meta, $formatted = null)
1031     {
1032         if ($this->_wikidb->readonly) {
1033             trigger_error("readonly database", E_USER_WARNING);
1034             return;
1035         }
1036         if (is_null($formatted))
1037             $formatted = new TransformedText($this, $wikitext, $meta);
1038         $type = $formatted->getType();
1039         $meta['pagetype'] = $type->getName();
1040         $links = $formatted->getWikiPageLinks(); // linkto => relation
1041         $attributes = array();
1042         foreach ($links as $link) {
1043             if ($link['linkto'] === "" and !empty($link['relation'])) {
1044                 $attributes[$link['relation']] = $this->getAttribute($link['relation']);
1045             }
1046         }
1047         $meta['attribute'] = $attributes;
1048
1049         $backend = &$this->_wikidb->_backend;
1050         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
1051         if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
1052             $this->set('_cached_html', $formatted->pack());
1053
1054         // FIXME: probably should have some global state information
1055         // in the backend to control when to optimize.
1056         //
1057         // We're doing this here rather than in createRevision because
1058         // postgresql can't optimize while locked.
1059         if (((int)DEBUG & _DEBUG_SQL)
1060             or (DATABASE_OPTIMISE_FREQUENCY > 0 and
1061                 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
1062         ) {
1063             if ($backend->optimize()) {
1064                 if ((int)DEBUG)
1065                     trigger_error(_("Optimizing database"), E_USER_NOTICE);
1066             }
1067         }
1068
1069         /* Generate notification emails? */
1070         if (ENABLE_MAILNOTIFY and isa($newrevision, 'WikiDB_PageRevision')) {
1071             // Save didn't fail because of concurrent updates.
1072             $notify = $this->_wikidb->get('notify');
1073             if (!empty($notify)
1074                 and is_array($notify)
1075                     and !isa($GLOBALS['request'], 'MockRequest')
1076             ) {
1077                 include_once 'lib/MailNotify.php';
1078                 $MailNotify = new MailNotify($newrevision->getName());
1079                 $MailNotify->onChangePage($this->_wikidb, $wikitext, $version, $meta);
1080             }
1081             $newrevision->_transformedContent = $formatted;
1082         }
1083         // more pagechange callbacks: (in a hackish manner for now)
1084         if (ENABLE_RECENTCHANGESBOX
1085             and empty($meta['is_minor_edit'])
1086                 and !in_array($GLOBALS['request']->getArg('action'),
1087                     array('loadfile', 'upgrade'))
1088         ) {
1089             require_once 'lib/WikiPlugin.php';
1090             $w = new WikiPluginLoader;
1091             $p = $w->getPlugin("RecentChangesCached", false);
1092             $p->box_update(false, $GLOBALS['request'], $this->_pagename);
1093         }
1094         return $newrevision;
1095     }
1096
1097     /**
1098      * Get the most recent revision of a page.
1099      *
1100      * @access public
1101      *
1102      * @return WikiDB_PageRevision The current WikiDB_PageRevision object.
1103      */
1104     function getCurrentRevision($need_content = true)
1105     {
1106         $backend = &$this->_wikidb->_backend;
1107         $cache = &$this->_wikidb->_cache;
1108         $pagename = &$this->_pagename;
1109
1110         // Prevent deadlock in case of memory exhausted errors
1111         // Pure selection doesn't really need locking here.
1112         //   sf.net bug#927395
1113         // I know it would be better to lock, but with lots of pages this deadlock is more
1114         // severe than occasionally get not the latest revision.
1115         // In spirit to wikiwiki: read fast, edit slower.
1116         //$backend->lock();
1117         $version = $cache->get_latest_version($pagename);
1118         // getRevision gets the content also!
1119         $revision = $this->getRevision($version, $need_content);
1120         //$backend->unlock();
1121         assert($revision);
1122         return $revision;
1123     }
1124
1125     /**
1126      * Get a specific revision of a WikiDB_Page.
1127      *
1128      * @access public
1129      *
1130      * @param integer $version Which revision to get.
1131      *
1132      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1133      * false if the requested revision does not exist in the {@link WikiDB}.
1134      * Note that version zero of any page always exists.
1135      */
1136     function getRevision($version, $need_content = true)
1137     {
1138         $cache = &$this->_wikidb->_cache;
1139         $pagename = &$this->_pagename;
1140
1141         if ((!$version) or ($version == 0) or ($version == -1)) { // 0 or false
1142             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1143         }
1144
1145         assert($version > 0);
1146         $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1147         if (!$vdata) {
1148             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1149         }
1150         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1151             $vdata);
1152     }
1153
1154     /**
1155      * Get previous page revision.
1156      *
1157      * This method find the most recent revision before a specified
1158      * version.
1159      *
1160      * @access public
1161      *
1162      * @param integer $version Find most recent revision before this version.
1163      *  You can also use a WikiDB_PageRevision object to specify the $version.
1164      *
1165      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1166      * requested revision does not exist in the {@link WikiDB}.  Note that
1167      * unless $version is greater than zero, a revision (perhaps version zero,
1168      * the default revision) will always be found.
1169      */
1170     function getRevisionBefore($version = false, $need_content = true)
1171     {
1172         $backend = &$this->_wikidb->_backend;
1173         $pagename = &$this->_pagename;
1174         if ($version === false)
1175             $version = $this->_wikidb->_cache->get_latest_version($pagename);
1176         else
1177             $version = $this->_coerce_to_version($version);
1178
1179         if ($version == 0)
1180             return false;
1181         //$backend->lock();
1182         $previous = $backend->get_previous_version($pagename, $version);
1183         $revision = $this->getRevision($previous, $need_content);
1184         //$backend->unlock();
1185         assert($revision);
1186         return $revision;
1187     }
1188
1189     /**
1190      * Get all revisions of the WikiDB_Page.
1191      *
1192      * This does not include the version zero (default) revision in the
1193      * returned revision set.
1194      *
1195      * @return WikiDB_PageRevisionIterator A
1196      *   WikiDB_PageRevisionIterator containing all revisions of this
1197      *   WikiDB_Page in reverse order by version number.
1198      */
1199     function getAllRevisions()
1200     {
1201         $backend = &$this->_wikidb->_backend;
1202         $revs = $backend->get_all_revisions($this->_pagename);
1203         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1204     }
1205
1206     /**
1207      * Find pages which link to or are linked from a page.
1208      * relations: $backend->get_links is responsible to add the relation to the pagehash
1209      * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
1210      *   if (isset($next['linkrelation']))
1211      *
1212      * @access public
1213      *
1214      * @param boolean $reversed Which links to find: true for backlinks (default).
1215      *
1216      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1217      * all matching pages.
1218      */
1219     function getLinks($reversed = true, $include_empty = false, $sortby = '',
1220                       $limit = '', $exclude = '', $want_relations = false)
1221     {
1222         $backend = &$this->_wikidb->_backend;
1223         $result = $backend->get_links($this->_pagename, $reversed,
1224             $include_empty, $sortby, $limit, $exclude,
1225             $want_relations);
1226         return new WikiDB_PageIterator($this->_wikidb, $result,
1227             array('include_empty' => $include_empty,
1228                 'sortby' => $sortby,
1229                 'limit' => $limit,
1230                 'exclude' => $exclude,
1231                 'want_relations' => $want_relations));
1232     }
1233
1234     /**
1235      * All Links from other pages to this page.
1236      */
1237     function getBackLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1238                           $want_relations = false)
1239     {
1240         return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1241     }
1242
1243     /**
1244      * Forward Links: All Links from this page to other pages.
1245      */
1246     function getPageLinks($include_empty = false, $sortby = '', $limit = '', $exclude = '',
1247                           $want_relations = false)
1248     {
1249         return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1250     }
1251
1252     /**
1253      * Relations: All links from this page to other pages with relation <> 0.
1254      * is_a:=page or population:=number
1255      */
1256     function getRelations($sortby = '', $limit = '', $exclude = '')
1257     {
1258         $backend = &$this->_wikidb->_backend;
1259         $result = $backend->get_links($this->_pagename, false, true,
1260             $sortby, $limit, $exclude,
1261             true);
1262         // we do not care for the linked page versiondata, just the pagename and linkrelation
1263         return new WikiDB_PageIterator($this->_wikidb, $result,
1264             array('include_empty' => true,
1265                 'sortby' => $sortby,
1266                 'limit' => $limit,
1267                 'exclude' => $exclude,
1268                 'want_relations' => true));
1269     }
1270
1271     /**
1272      * possibly faster link existance check. not yet accelerated.
1273      */
1274     function existLink($link, $reversed = false)
1275     {
1276         $backend = &$this->_wikidb->_backend;
1277         if (method_exists($backend, 'exists_link'))
1278             return $backend->exists_link($this->_pagename, $link, $reversed);
1279         //$cache = &$this->_wikidb->_cache;
1280         // TODO: check cache if it is possible
1281         $iter = $this->getLinks($reversed, false);
1282         while ($page = $iter->next()) {
1283             if ($page->getName() == $link)
1284                 return $page;
1285         }
1286         $iter->free();
1287         return false;
1288     }
1289
1290     /* Semantic relations are links with the relation pointing to another page,
1291        the so-called "RDF Triple".
1292        [San Diego] is%20a::city
1293        => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
1294      */
1295
1296     /* Semantic attributes for a page.
1297        [San Diego] population:=1,305,736
1298        Attributes are links with the relation pointing to another page.
1299     */
1300
1301     /**
1302      * Access WikiDB_Page non version-specific meta-data.
1303      *
1304      * @access public
1305      *
1306      * @param string $key Which meta data to get.
1307      * Some reserved meta-data keys are:
1308      * <dl>
1309      * <dt>'date'  <dd> Created as unixtime
1310      * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1311      * <dt>'hits'  <dd> Page hit counter.
1312      * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1313      *                         In SQL stored now in an extra column.
1314      * Optional data:
1315      * <dt>'pref'  <dd> Users preferences, stored only in homepages.
1316      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1317      *                  E.g. "owner.users"
1318      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of
1319      *                  page-headers and content.
1320     + <dt>'moderation'<dd> ModeratedPage data. Handled by plugin/ModeratedPage
1321      * <dt>'rating' <dd> Page rating. Handled by plugin/RateIt
1322      * </dl>
1323      *
1324      * @return scalar The requested value, or false if the requested data
1325      * is not set.
1326      */
1327     function get($key)
1328     {
1329         $cache = &$this->_wikidb->_cache;
1330         $backend = &$this->_wikidb->_backend;
1331         if (!$key || $key[0] == '%')
1332             return false;
1333         // several new SQL backends optimize this.
1334         if (!WIKIDB_NOCACHE_MARKUP
1335             and $key == '_cached_html'
1336                 and method_exists($backend, 'get_cached_html')
1337         ) {
1338             return $backend->get_cached_html($this->_pagename);
1339         }
1340         $data = $cache->get_pagedata($this->_pagename);
1341         return isset($data[$key]) ? $data[$key] : false;
1342     }
1343
1344     /**
1345      * Get all the page meta-data as a hash.
1346      *
1347      * @return hash The page meta-data.
1348      */
1349     function getMetaData()
1350     {
1351         $cache = &$this->_wikidb->_cache;
1352         $data = $cache->get_pagedata($this->_pagename);
1353         $meta = array();
1354         foreach ($data as $key => $val) {
1355             if ( /*!empty($val) &&*/
1356                 $key[0] != '%'
1357             )
1358                 $meta[$key] = $val;
1359         }
1360         return $meta;
1361     }
1362
1363     /**
1364      * Set page meta-data.
1365      *
1366      * @see get
1367      * @access public
1368      *
1369      * @param string $key    Meta-data key to set.
1370      * @param string $newval New value.
1371      */
1372     function set($key, $newval)
1373     {
1374         $cache = &$this->_wikidb->_cache;
1375         $backend = &$this->_wikidb->_backend;
1376         $pagename = &$this->_pagename;
1377
1378         assert($key && $key[0] != '%');
1379
1380         // several new SQL backends optimize this.
1381         if (!WIKIDB_NOCACHE_MARKUP
1382             and $key == '_cached_html'
1383                 and method_exists($backend, 'set_cached_html')
1384         ) {
1385             if ($this->_wikidb->readonly) {
1386                 trigger_error("readonly database", E_USER_WARNING);
1387                 return;
1388             }
1389             return $backend->set_cached_html($pagename, $newval);
1390         }
1391
1392         $data = $cache->get_pagedata($pagename);
1393
1394         if (!empty($newval)) {
1395             if (!empty($data[$key]) && $data[$key] == $newval)
1396                 return; // values identical, skip update.
1397         } else {
1398             if (empty($data[$key]))
1399                 return; // values identical, skip update.
1400         }
1401
1402         if (isset($this->_wikidb->readonly) and ($this->_wikidb->readonly)) {
1403             trigger_error("readonly database", E_USER_WARNING);
1404             return;
1405         }
1406         $cache->update_pagedata($pagename, array($key => $newval));
1407     }
1408
1409     /**
1410      * Increase page hit count.
1411      *
1412      * FIXME: IS this needed?  Probably not.
1413      *
1414      * This is a convenience function.
1415      * <pre> $page->increaseHitCount(); </pre>
1416      * is functionally identical to
1417      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1418      * but less expensive (ignores the pagadata string)
1419      *
1420      * Note that this method may be implemented in more efficient ways
1421      * in certain backends.
1422      *
1423      * @access public
1424      */
1425     function increaseHitCount()
1426     {
1427         if ($this->_wikidb->readonly) {
1428             trigger_error("readonly database", E_USER_NOTICE);
1429             return;
1430         }
1431         if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1432             $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1433         else {
1434             @$newhits = $this->get('hits') + 1;
1435             $this->set('hits', $newhits);
1436         }
1437     }
1438
1439     /**
1440      * Return a string representation of the WikiDB_Page
1441      *
1442      * This is really only for debugging.
1443      *
1444      * @access public
1445      *
1446      * @return string Printable representation of the WikiDB_Page.
1447      */
1448     function asString()
1449     {
1450         ob_start();
1451         printf("[%s:%s\n", get_class($this), $this->getName());
1452         print_r($this->getMetaData());
1453         echo "]\n";
1454         $strval = ob_get_contents();
1455         ob_end_clean();
1456         return $strval;
1457     }
1458
1459     /**
1460      * @access private
1461      * @param integer_or_object $version_or_pagerevision
1462      * Takes either the version number (and int) or a WikiDB_PageRevision
1463      * object.
1464      * @return integer The version number.
1465      */
1466     function _coerce_to_version($version_or_pagerevision)
1467     {
1468         if (method_exists($version_or_pagerevision, "getContent"))
1469             $version = $version_or_pagerevision->getVersion();
1470         else
1471             $version = (int)$version_or_pagerevision;
1472
1473         assert($version >= 0);
1474         return $version;
1475     }
1476
1477     function isUserPage($include_empty = true)
1478     {
1479         if (!$include_empty and !$this->exists()) return false;
1480         return $this->get('pref') ? true : false;
1481     }
1482
1483     // May be empty. Either the stored owner (/Chown), or the first authorized author
1484     function getOwner()
1485     {
1486         if ($owner = $this->get('owner'))
1487             return $owner;
1488         // check all revisions forwards for the first author_id
1489         $backend = &$this->_wikidb->_backend;
1490         $pagename = &$this->_pagename;
1491         $latestversion = $backend->get_latest_version($pagename);
1492         for ($v = 1; $v <= $latestversion; $v++) {
1493             $rev = $this->getRevision($v, false);
1494             if ($rev and $owner = $rev->get('author_id')) {
1495                 return $owner;
1496             }
1497         }
1498         return '';
1499     }
1500
1501     // The authenticated author of the first revision or empty if not authenticated then.
1502     function getCreator()
1503     {
1504         if ($current = $this->getRevision(1, false)) return $current->get('author_id');
1505         else return '';
1506     }
1507
1508     // The authenticated author of the current revision.
1509     function getAuthor()
1510     {
1511         if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1512         else return '';
1513     }
1514
1515     /* Semantic Web value, not stored in the links.
1516      * todo: unify with some unit knowledge
1517      */
1518     function setAttribute($relation, $value)
1519     {
1520         $attr = $this->get('attributes');
1521         if (empty($attr))
1522             $attr = array($relation => $value);
1523         else
1524             $attr[$relation] = $value;
1525         $this->set('attributes', $attr);
1526     }
1527
1528     function getAttribute($relation)
1529     {
1530         $meta = $this->get('attributes');
1531         if (empty($meta))
1532             return '';
1533         else
1534             return $meta[$relation];
1535     }
1536
1537 }
1538
1539 /**
1540  * This class represents a specific revision of a WikiDB_Page within
1541  * a WikiDB.
1542  *
1543  * A WikiDB_PageRevision has read-only semantics. You may only create
1544  * new revisions (and delete old ones) --- you cannot modify existing
1545  * revisions.
1546  */
1547 class WikiDB_PageRevision
1548 {
1549     //var $_transformedContent = false; // set by WikiDB_Page::save()
1550
1551     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1552                                  $versiondata = false)
1553     {
1554         $this->_wikidb = &$wikidb;
1555         $this->_pagename = $pagename;
1556         $this->_version = $version;
1557         $this->_data = $versiondata ? $versiondata : array();
1558         $this->_transformedContent = false; // set by WikiDB_Page::save()
1559     }
1560
1561     /**
1562      * Get the WikiDB_Page which this revision belongs to.
1563      *
1564      * @access public
1565      *
1566      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1567      */
1568     function getPage()
1569     {
1570         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1571     }
1572
1573     /**
1574      * Get the version number of this revision.
1575      *
1576      * @access public
1577      *
1578      * @return integer The version number of this revision.
1579      */
1580     function getVersion()
1581     {
1582         return $this->_version;
1583     }
1584
1585     /**
1586      * Determine whether this revision has defaulted content.
1587      *
1588      * The default revision (version 0) of each page, as well as any
1589      * pages which are created with empty content have their content
1590      * defaulted to something like:
1591      * <pre>
1592      *   Describe [ThisPage] here.
1593      * </pre>
1594      *
1595      * @access public
1596      *
1597      * @return boolean Returns true if the page has default content.
1598      */
1599     function hasDefaultContents()
1600     {
1601         $data = &$this->_data;
1602         if (!isset($data['%content'])) return true;
1603         if ($data['%content'] === true) return false;
1604         return $data['%content'] === false or $data['%content'] === "";
1605     }
1606
1607     /**
1608      * Get the content as an array of lines.
1609      *
1610      * @access public
1611      *
1612      * @return array An array of lines.
1613      * The lines should contain no trailing white space.
1614      */
1615     function getContent()
1616     {
1617         return explode("\n", $this->getPackedContent());
1618     }
1619
1620     /**
1621      * Get the pagename of the revision.
1622      *
1623      * @access public
1624      *
1625      * @return string pagename.
1626      */
1627     function getPageName()
1628     {
1629         return $this->_pagename;
1630     }
1631
1632     function getName()
1633     {
1634         return $this->_pagename;
1635     }
1636
1637     /**
1638      * Determine whether revision is the latest.
1639      *
1640      * @access public
1641      *
1642      * @return boolean True iff the revision is the latest (most recent) one.
1643      */
1644     function isCurrent()
1645     {
1646         if (!isset($this->_iscurrent)) {
1647             $page = $this->getPage();
1648             $current = $page->getCurrentRevision(false);
1649             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1650         }
1651         return $this->_iscurrent;
1652     }
1653
1654     /**
1655      * Get the transformed content of a page.
1656      *
1657      * @param string $pagetype Override the page-type of the revision.
1658      *
1659      * @return object An XmlContent-like object containing the page transformed
1660      * contents.
1661      */
1662     function getTransformedContent($pagetype_override = false)
1663     {
1664         $backend = &$this->_wikidb->_backend;
1665
1666         if ($pagetype_override) {
1667             // Figure out the normal page-type for this page.
1668             $type = PageType::GetPageType($this->get('pagetype'));
1669             if ($type->getName() == $pagetype_override)
1670                 $pagetype_override = false; // Not really an override...
1671         }
1672
1673         if ($pagetype_override) {
1674             // Overriden page type, don't cache (or check cache).
1675             return new TransformedText($this->getPage(),
1676                 $this->getPackedContent(),
1677                 $this->getMetaData(),
1678                 $pagetype_override);
1679         }
1680
1681         $possibly_cache_results = true;
1682
1683         if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1684             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1685                 // flush cache for this page.
1686                 $page = $this->getPage();
1687                 $page->set('_cached_html', ''); // ignored with !USECACHE
1688             }
1689             $possibly_cache_results = false;
1690         } elseif (USECACHE and !$this->_transformedContent) {
1691             //$backend->lock();
1692             if ($this->isCurrent()) {
1693                 $page = $this->getPage();
1694                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1695             } else {
1696                 $possibly_cache_results = false;
1697             }
1698             //$backend->unlock();
1699         }
1700
1701         if (!$this->_transformedContent) {
1702             $this->_transformedContent
1703                 = new TransformedText($this->getPage(),
1704                 $this->getPackedContent(),
1705                 $this->getMetaData());
1706
1707             if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1708                 // If we're still the current version, cache the transfomed page.
1709                 //$backend->lock();
1710                 if ($this->isCurrent()) {
1711                     $page->set('_cached_html', $this->_transformedContent->pack());
1712                 }
1713                 //$backend->unlock();
1714             }
1715         }
1716
1717         return $this->_transformedContent;
1718     }
1719
1720     /**
1721      * Get the content as a string.
1722      *
1723      * @access public
1724      *
1725      * @return string The page content.
1726      * Lines are separated by new-lines.
1727      */
1728     function getPackedContent()
1729     {
1730         $data = &$this->_data;
1731
1732         if (empty($data['%content'])
1733             || (!$this->_wikidb->isWikiPage($this->_pagename)
1734                 && $this->isCurrent())
1735         ) {
1736             include_once 'lib/InlineParser.php';
1737
1738             // A feature similar to taglines at http://www.wlug.org.nz/
1739             // Lib from http://www.aasted.org/quote/
1740             if (defined('FORTUNE_DIR')
1741                 and is_dir(FORTUNE_DIR)
1742                     and in_array($GLOBALS['request']->getArg('action'),
1743                         array('create', 'edit'))
1744             ) {
1745                 include_once 'lib/fortune.php';
1746                 $fortune = new Fortune();
1747                 $quote = $fortune->quoteFromDir(FORTUNE_DIR);
1748                 if ($quote != -1)
1749                     $quote = "<verbatim>\n"
1750                         . str_replace("\n<br>", "\n", $quote)
1751                         . "</verbatim>\n\n";
1752                 else
1753                     $quote = "";
1754                 return $quote
1755                     . sprintf(_("Describe %s here."),
1756                         "[" . WikiEscape($this->_pagename) . "]");
1757             }
1758             // Replace empty content with default value.
1759             return sprintf(_("Describe %s here."),
1760                 "[" . WikiEscape($this->_pagename) . "]");
1761         }
1762
1763         // There is (non-default) content.
1764         assert($this->_version > 0);
1765
1766         if (!is_string($data['%content'])) {
1767             // Content was not provided to us at init time.
1768             // (This is allowed because for some backends, fetching
1769             // the content may be expensive, and often is not wanted
1770             // by the user.)
1771             //
1772             // In any case, now we need to get it.
1773             $data['%content'] = $this->_get_content();
1774             assert(is_string($data['%content']));
1775         }
1776
1777         return $data['%content'];
1778     }
1779
1780     function _get_content()
1781     {
1782         $cache = &$this->_wikidb->_cache;
1783         $pagename = $this->_pagename;
1784         $version = $this->_version;
1785
1786         assert($version > 0);
1787
1788         $newdata = $cache->get_versiondata($pagename, $version, true);
1789         if ($newdata) {
1790             assert(is_string($newdata['%content']));
1791             return $newdata['%content'];
1792         } else {
1793             // else revision has been deleted... What to do?
1794             return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1795                 $version, $pagename);
1796         }
1797     }
1798
1799     /**
1800      * Get meta-data for this revision.
1801      *
1802      *
1803      * @access public
1804      *
1805      * @param string $key Which meta-data to access.
1806      *
1807      * Some reserved revision meta-data keys are:
1808      * <dl>
1809      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1810      *        The 'mtime' meta-value is normally set automatically by the database
1811      *        backend, but it may be specified explicitly when creating a new revision.
1812      * <dt> orig_mtime
1813      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1814      *       of a page must be monotonically increasing.  If an attempt is
1815      *       made to create a new revision with an mtime less than that of
1816      *       the preceeding revision, the new revisions timestamp is force
1817      *       to be equal to that of the preceeding revision.  In that case,
1818      *       the originally requested mtime is preserved in 'orig_mtime'.
1819      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1820      *        This meta-value is <em>always</em> automatically maintained by the database
1821      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1822      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1823      *
1824      * FIXME: this could be refactored:
1825      * <dt> author
1826      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1827      * <dt> author_id
1828      *  <dd> Authenticated author of a page.  This is used to identify
1829      *       the distinctness of authors when cleaning old revisions from
1830      *       the database.
1831      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1832      * <dt> 'summary' <dd> Short change summary entered by page author.
1833      * </dl>
1834      *
1835      * Meta-data keys must be valid C identifers (they have to start with a letter
1836      * or underscore, and can contain only alphanumerics and underscores.)
1837      *
1838      * @return string The requested value, or false if the requested value
1839      * is not defined.
1840      */
1841     function get($key)
1842     {
1843         if (!$key || $key[0] == '%')
1844             return false;
1845         $data = &$this->_data;
1846         return isset($data[$key]) ? $data[$key] : false;
1847     }
1848
1849     /**
1850      * Get all the revision page meta-data as a hash.
1851      *
1852      * @return hash The revision meta-data.
1853      */
1854     function getMetaData()
1855     {
1856         $meta = array();
1857         foreach ($this->_data as $key => $val) {
1858             if (!empty($val) && $key[0] != '%')
1859                 $meta[$key] = $val;
1860         }
1861         return $meta;
1862     }
1863
1864     /**
1865      * Return a string representation of the revision.
1866      *
1867      * This is really only for debugging.
1868      *
1869      * @access public
1870      *
1871      * @return string Printable representation of the WikiDB_Page.
1872      */
1873     function asString()
1874     {
1875         ob_start();
1876         printf("[%s:%d\n", get_class($this), $this->get('version'));
1877         print_r($this->_data);
1878         echo $this->getPackedContent() . "\n]\n";
1879         $strval = ob_get_contents();
1880         ob_end_clean();
1881         return $strval;
1882     }
1883 }
1884
1885 /**
1886  * Class representing a sequence of WikiDB_Pages.
1887  * TODO: Enhance to php5 iterators
1888  * TODO:
1889  *   apply filters for options like 'sortby', 'limit', 'exclude'
1890  *   for simple queries like titleSearch, where the backend is not ready yet.
1891  */
1892 class WikiDB_PageIterator
1893 {
1894     function WikiDB_PageIterator(&$wikidb, &$iter, $options = false)
1895     {
1896         $this->_iter = $iter; // a WikiDB_backend_iterator
1897         $this->_wikidb = &$wikidb;
1898         $this->_options = $options;
1899     }
1900
1901     function count()
1902     {
1903         return $this->_iter->count();
1904     }
1905
1906     function limit()
1907     {
1908         return empty($this->_options['limit']) ? 0 : $this->_options['limit'];
1909     }
1910
1911     /**
1912      * Get next WikiDB_Page in sequence.
1913      *
1914      * @access public
1915      *
1916      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1917      */
1918     function next()
1919     {
1920         if (!($next = $this->_iter->next())) {
1921             return false;
1922         }
1923
1924         $pagename = &$next['pagename'];
1925         if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
1926             trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
1927         }
1928
1929         if (!$pagename) {
1930             if (isset($next['linkrelation'])
1931                 or isset($next['pagedata']['linkrelation'])
1932             ) {
1933                 return false;
1934             }
1935         }
1936
1937         // There's always hits, but we cache only if more
1938         // (well not with file, cvs and dba)
1939         if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1940             $this->_wikidb->_cache->cache_data($next);
1941             // cache existing page id's since we iterate over all links in GleanDescription
1942             // and need them later for LinkExistingWord
1943         } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1944             and !$this->_options['include_empty'] and isset($next['id'])
1945         ) {
1946             $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1947         }
1948         $page = new WikiDB_Page($this->_wikidb, $pagename);
1949         if (isset($next['linkrelation']))
1950             $page->set('linkrelation', $next['linkrelation']);
1951         if (isset($next['score']))
1952             $page->score = $next['score'];
1953         return $page;
1954     }
1955
1956     /**
1957      * Release resources held by this iterator.
1958      *
1959      * The iterator may not be used after free() is called.
1960      *
1961      * There is no need to call free(), if next() has returned false.
1962      * (I.e. if you iterate through all the pages in the sequence,
1963      * you do not need to call free() --- you only need to call it
1964      * if you stop before the end of the iterator is reached.)
1965      *
1966      * @access public
1967      */
1968     function free()
1969     {
1970         $this->_iter->free();
1971     }
1972
1973     function reset()
1974     {
1975         $this->_iter->reset();
1976     }
1977
1978     function asArray()
1979     {
1980         $result = array();
1981         while ($page = $this->next())
1982             $result[] = $page;
1983         $this->reset();
1984         return $result;
1985     }
1986
1987     /**
1988      * Apply filters for options like 'sortby', 'limit', 'exclude'
1989      * for simple queries like titleSearch, where the backend is not ready yet.
1990      * Since iteration is usually destructive for SQL results,
1991      * we have to generate a copy.
1992      */
1993     function applyFilters($options = false)
1994     {
1995         if (!$options) $options = $this->_options;
1996         if (isset($options['sortby'])) {
1997             $array = array();
1998             /* this is destructive */
1999             while ($page = $this->next())
2000                 $result[] = $page->getName();
2001             $this->_doSort($array, $options['sortby']);
2002         }
2003         /* the rest is not destructive.
2004          * reconstruct a new iterator
2005          */
2006         $pagenames = array();
2007         $i = 0;
2008         if (isset($options['limit']))
2009             $limit = $options['limit'];
2010         else
2011             $limit = 0;
2012         if (isset($options['exclude']))
2013             $exclude = $options['exclude'];
2014         if (is_string($exclude) and !is_array($exclude))
2015             $exclude = PageList::explodePageList($exclude, false, false, $limit);
2016         foreach ($array as $pagename) {
2017             if ($limit and $i++ > $limit)
2018                 return new WikiDB_Array_PageIterator($pagenames);
2019             if (!empty($exclude) and !in_array($pagename, $exclude))
2020                 $pagenames[] = $pagename;
2021             elseif (empty($exclude))
2022                 $pagenames[] = $pagename;
2023         }
2024         return new WikiDB_Array_PageIterator($pagenames);
2025     }
2026
2027     /* pagename only */
2028     function _doSort(&$array, $sortby)
2029     {
2030         $sortby = PageList::sortby($sortby, 'init');
2031         if ($sortby == '+pagename')
2032             sort($array, SORT_STRING);
2033         elseif ($sortby == '-pagename')
2034             rsort($array, SORT_STRING);
2035         reset($array);
2036     }
2037
2038 }
2039
2040 /**
2041  * A class which represents a sequence of WikiDB_PageRevisions.
2042  * TODO: Enhance to php5 iterators
2043  */
2044 class WikiDB_PageRevisionIterator
2045 {
2046     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options = false)
2047     {
2048         $this->_revisions = $revisions;
2049         $this->_wikidb = &$wikidb;
2050         $this->_options = $options;
2051     }
2052
2053     function count()
2054     {
2055         return $this->_revisions->count();
2056     }
2057
2058     /**
2059      * Get next WikiDB_PageRevision in sequence.
2060      *
2061      * @access public
2062      *
2063      * @return WikiDB_PageRevision
2064      * The next WikiDB_PageRevision in the sequence.
2065      */
2066     function next()
2067     {
2068         if (!($next = $this->_revisions->next()))
2069             return false;
2070
2071         //$this->_wikidb->_cache->cache_data($next);
2072
2073         $pagename = $next['pagename'];
2074         $version = $next['version'];
2075         $versiondata = $next['versiondata'];
2076         if ((int)DEBUG) {
2077             if (!(is_string($pagename) and $pagename != '')) {
2078                 trigger_error("empty pagename", E_USER_WARNING);
2079                 return false;
2080             }
2081         } else assert(is_string($pagename) and $pagename != '');
2082         if ((int)DEBUG) {
2083             if (!is_array($versiondata)) {
2084                 trigger_error("empty versiondata", E_USER_WARNING);
2085                 return false;
2086             }
2087         } else assert(is_array($versiondata));
2088         if ((int)DEBUG) {
2089             if (!($version > 0)) {
2090                 trigger_error("invalid version", E_USER_WARNING);
2091                 return false;
2092             }
2093         } else assert($version > 0);
2094
2095         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
2096             $versiondata);
2097     }
2098
2099     /**
2100      * Release resources held by this iterator.
2101      *
2102      * The iterator may not be used after free() is called.
2103      *
2104      * There is no need to call free(), if next() has returned false.
2105      * (I.e. if you iterate through all the revisions in the sequence,
2106      * you do not need to call free() --- you only need to call it
2107      * if you stop before the end of the iterator is reached.)
2108      *
2109      * @access public
2110      */
2111     function free()
2112     {
2113         $this->_revisions->free();
2114     }
2115
2116     function asArray()
2117     {
2118         $result = array();
2119         while ($rev = $this->next())
2120             $result[] = $rev;
2121         $this->free();
2122         return $result;
2123     }
2124 }
2125
2126 /** pseudo iterator
2127  */
2128 class WikiDB_Array_PageIterator
2129 {
2130     function WikiDB_Array_PageIterator($pagenames)
2131     {
2132         global $request;
2133         $this->_dbi = $request->getDbh();
2134         $this->_pages = $pagenames;
2135         reset($this->_pages);
2136     }
2137
2138     function next()
2139     {
2140         $c = current($this->_pages);
2141         next($this->_pages);
2142         return $c !== false ? $this->_dbi->getPage($c) : false;
2143     }
2144
2145     function count()
2146     {
2147         return count($this->_pages);
2148     }
2149
2150     function reset()
2151     {
2152         reset($this->_pages);
2153     }
2154
2155     function free()
2156     {
2157     }
2158
2159     function asArray()
2160     {
2161         reset($this->_pages);
2162         return $this->_pages;
2163     }
2164 }
2165
2166 class WikiDB_Array_generic_iter
2167 {
2168     function WikiDB_Array_generic_iter($result)
2169     {
2170         // $result may be either an array or a query result
2171         if (is_array($result)) {
2172             $this->_array = $result;
2173         } elseif (is_object($result)) {
2174             $this->_array = $result->asArray();
2175         } else {
2176             $this->_array = array();
2177         }
2178         if (!empty($this->_array))
2179             reset($this->_array);
2180     }
2181
2182     function next()
2183     {
2184         $c = current($this->_array);
2185         next($this->_array);
2186         return $c !== false ? $c : false;
2187     }
2188
2189     function count()
2190     {
2191         return count($this->_array);
2192     }
2193
2194     function reset()
2195     {
2196         reset($this->_array);
2197     }
2198
2199     function free()
2200     {
2201     }
2202
2203     function asArray()
2204     {
2205         if (!empty($this->_array))
2206             reset($this->_array);
2207         return $this->_array;
2208     }
2209 }
2210
2211 /**
2212  * Data cache used by WikiDB.
2213  *
2214  * FIXME: Maybe rename this to caching_backend (or some such).
2215  *
2216  * @access private
2217  */
2218 class WikiDB_cache
2219 {
2220     // FIXME: beautify versiondata cache.  Cache only limited data?
2221
2222     function WikiDB_cache(&$backend)
2223     {
2224         $this->_backend = &$backend;
2225
2226         $this->_pagedata_cache = array();
2227         $this->_versiondata_cache = array();
2228         array_push($this->_versiondata_cache, array());
2229         $this->_glv_cache = array();
2230         $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2231
2232         if (isset($GLOBALS['request']->_dbi))
2233             $this->readonly = $GLOBALS['request']->_dbi->readonly;
2234     }
2235
2236     function close()
2237     {
2238         $this->_pagedata_cache = array();
2239         $this->_versiondata_cache = array();
2240         $this->_glv_cache = array();
2241         $this->_id_cache = array();
2242     }
2243
2244     function get_pagedata($pagename)
2245     {
2246         assert(is_string($pagename) && $pagename != '');
2247         if (USECACHE) {
2248             $cache = &$this->_pagedata_cache;
2249             if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2250                 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2251                 if (empty($cache[$pagename]))
2252                     $cache[$pagename] = array();
2253             }
2254             return $cache[$pagename];
2255         } else {
2256             return $this->_backend->get_pagedata($pagename);
2257         }
2258     }
2259
2260     function update_pagedata($pagename, $newdata)
2261     {
2262         assert(is_string($pagename) && $pagename != '');
2263         if (!empty($this->readonly)) {
2264             trigger_error("readonly database", E_USER_WARNING);
2265             return;
2266         }
2267
2268         $this->_backend->update_pagedata($pagename, $newdata);
2269
2270         if (USECACHE) {
2271             if (!empty($this->_pagedata_cache[$pagename])
2272                 and is_array($this->_pagedata_cache[$pagename])
2273             ) {
2274                 $cachedata = &$this->_pagedata_cache[$pagename];
2275                 foreach ($newdata as $key => $val)
2276                     $cachedata[$key] = $val;
2277             } else
2278                 $this->_pagedata_cache[$pagename] = $newdata;
2279         }
2280     }
2281
2282     function invalidate_cache($pagename)
2283     {
2284         unset ($this->_pagedata_cache[$pagename]);
2285         unset ($this->_versiondata_cache[$pagename]);
2286         unset ($this->_glv_cache[$pagename]);
2287         unset ($this->_id_cache[$pagename]);
2288         //unset ($this->_backend->_page_data);
2289     }
2290
2291     function delete_page($pagename)
2292     {
2293         if (!empty($this->readonly)) {
2294             trigger_error("readonly database", E_USER_WARNING);
2295             return;
2296         }
2297         $result = $this->_backend->delete_page($pagename);
2298         $this->invalidate_cache($pagename);
2299         return $result;
2300     }
2301
2302     function purge_page($pagename)
2303     {
2304         if (!empty($this->readonly)) {
2305             trigger_error("readonly database", E_USER_WARNING);
2306             return;
2307         }
2308         $result = $this->_backend->purge_page($pagename);
2309         $this->invalidate_cache($pagename);
2310         return $result;
2311     }
2312
2313     // FIXME: ugly and wrong. may overwrite full cache with partial cache
2314     function cache_data($data)
2315     {
2316         ;
2317         //if (isset($data['pagedata']))
2318         //    $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2319     }
2320
2321     function get_versiondata($pagename, $version, $need_content = false)
2322     {
2323         //  FIXME: Seriously ugly hackage
2324         $readdata = false;
2325         if (USECACHE) { //temporary - for debugging
2326             assert(is_string($pagename) && $pagename != '');
2327             // There is a bug here somewhere which results in an assertion failure at line 105
2328             // of ArchiveCleaner.php  It goes away if we use the next line.
2329             //$need_content = true;
2330             $nc = $need_content ? '1' : '0';
2331             $cache = &$this->_versiondata_cache;
2332             if (!isset($cache[$pagename][$version][$nc])
2333                 || !(is_array($cache[$pagename]))
2334                 || !(is_array($cache[$pagename][$version]))
2335             ) {
2336                 $cache[$pagename][$version][$nc] =
2337                     $this->_backend->get_versiondata($pagename, $version, $need_content);
2338                 $readdata = true;
2339                 // If we have retrieved all data, we may as well set the cache for
2340                 // $need_content = false
2341                 if ($need_content) {
2342                     $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2343                 }
2344             }
2345             $vdata = $cache[$pagename][$version][$nc];
2346         } else {
2347             $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2348             $readdata = true;
2349         }
2350         if ($readdata && is_array($vdata) && !empty($vdata['%pagedata'])) {
2351             if (empty($this->_pagedata_cache))
2352                 $this->_pagedata_cache = array();
2353             /* 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 */
2354             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
2355         }
2356         return $vdata;
2357     }
2358
2359     function set_versiondata($pagename, $version, $data)
2360     {
2361         //unset($this->_versiondata_cache[$pagename][$version]);
2362
2363         if (!empty($this->readonly)) {
2364             trigger_error("readonly database", E_USER_WARNING);
2365             return;
2366         }
2367         $new = $this->_backend->set_versiondata($pagename, $version, $data);
2368         // Update the cache
2369         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2370         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2371         // Is this necessary?
2372         unset($this->_glv_cache[$pagename]);
2373     }
2374
2375     function update_versiondata($pagename, $version, $data)
2376     {
2377         if (!empty($this->readonly)) {
2378             trigger_error("readonly database", E_USER_WARNING);
2379             return;
2380         }
2381         $new = $this->_backend->update_versiondata($pagename, $version, $data);
2382         // Update the cache
2383         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2384         // FIXME: hack
2385         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2386         // Is this necessary?
2387         unset($this->_glv_cache[$pagename]);
2388     }
2389
2390     function delete_versiondata($pagename, $version)
2391     {
2392         if (!empty($this->readonly)) {
2393             trigger_error("readonly database", E_USER_WARNING);
2394             return;
2395         }
2396         $new = $this->_backend->delete_versiondata($pagename, $version);
2397         if (isset($this->_versiondata_cache[$pagename][$version]))
2398             unset ($this->_versiondata_cache[$pagename][$version]);
2399         // dirty latest version cache only if latest version gets deleted
2400         if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2401             unset ($this->_glv_cache[$pagename]);
2402     }
2403
2404     function get_latest_version($pagename)
2405     {
2406         if (USECACHE) {
2407             assert(is_string($pagename) && $pagename != '');
2408             $cache = &$this->_glv_cache;
2409             if (!isset($cache[$pagename])) {
2410                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2411                 if (empty($cache[$pagename]))
2412                     $cache[$pagename] = 0;
2413             }
2414             return $cache[$pagename];
2415         } else {
2416             return $this->_backend->get_latest_version($pagename);
2417         }
2418     }
2419 }
2420
2421 function _sql_debuglog($msg, $newline = true, $shutdown = false)
2422 {
2423     static $fp = false;
2424     static $i = 0;
2425     if (!$fp) {
2426         $stamp = strftime("%y%m%d-%H%M%S");
2427         $fp = fopen(TEMP_DIR . "/sql-$stamp.log", "a");
2428         register_shutdown_function("_sql_debuglog_shutdown_function");
2429     } elseif ($shutdown) {
2430         fclose($fp);
2431         return;
2432     }
2433     if ($newline) fputs($fp, "[$i++] $msg");
2434     else fwrite($fp, $msg);
2435 }
2436
2437 function _sql_debuglog_shutdown_function()
2438 {
2439     _sql_debuglog('', false, true);
2440 }
2441
2442 // Local Variables:
2443 // mode: php
2444 // tab-width: 8
2445 // c-basic-offset: 4
2446 // c-hanging-comment-ender-p: nil
2447 // indent-tabs-mode: nil
2448 // End: