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