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