]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
fixed DumpHtmlToDir,
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.36 2004-02-22 23:20:31 rurban Exp $');
3
4 require_once('lib/stdlib.php');
5 require_once('lib/PageType.php');
6
7 //FIXME: arg on get*Revision to hint that content is wanted.
8
9 /**
10  * The classes in the file define the interface to the
11  * page database.
12  *
13  * @package WikiDB
14  * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
15  */
16
17 /**
18  * Force the creation of a new revision.
19  * @see WikiDB_Page::createRevision()
20  */
21 define('WIKIDB_FORCE_CREATE', -1);
22
23 // FIXME:  used for debugging only.  Comment out if cache does not work
24 define('USECACHE', 1);
25
26 /** 
27  * Abstract base class for the database used by PhpWiki.
28  *
29  * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
30  * turn contain <tt>WikiDB_PageRevision</tt>s.
31  *
32  * Conceptually a <tt>WikiDB</tt> contains all possible
33  * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
34  * Since all possible pages are already contained in a WikiDB, a call
35  * to WikiDB::getPage() will never fail (barring bugs and
36  * e.g. filesystem or SQL database problems.)
37  *
38  * Also each <tt>WikiDB_Page</tt> always contains at least one
39  * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
40  * [PageName] here.").  This default content has a version number of
41  * zero.
42  *
43  * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
44  * only create new revisions or delete old ones --- one can not modify
45  * an existing revision.
46  */
47 class WikiDB {
48     /**
49      * Open a WikiDB database.
50      *
51      * This is a static member function. This function inspects its
52      * arguments to determine the proper subclass of WikiDB to
53      * instantiate, and then it instantiates it.
54      *
55      * @access public
56      *
57      * @param hash $dbparams Database configuration parameters.
58      * Some pertinent paramters are:
59      * <dl>
60      * <dt> dbtype
61      * <dd> The back-end type.  Current supported types are:
62      *   <dl>
63      *   <dt> SQL
64      *   <dd> Generic SQL backend based on the PEAR/DB database abstraction
65      *       library.
66      *   <dt> dba
67      *   <dd> Dba based backend.
68      *   </dl>
69      *
70      * <dt> dsn
71      * <dd> (Used by the SQL backend.)
72      *      The DSN specifying which database to connect to.
73      *
74      * <dt> prefix
75      * <dd> Prefix to be prepended to database table (and file names).
76      *
77      * <dt> directory
78      * <dd> (Used by the dba backend.)
79      *      Which directory db files reside in.
80      *
81      * <dt> timeout
82      * <dd> (Used by the dba backend.)
83      *      Timeout in seconds for opening (and obtaining lock) on the
84      *      db files.
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      * </dl>
92      *
93      * @return WikiDB A WikiDB object.
94      **/
95     function open ($dbparams) {
96         $dbtype = $dbparams{'dbtype'};
97         include_once("lib/WikiDB/$dbtype.php");
98                                 
99         $class = 'WikiDB_' . $dbtype;
100         return new $class ($dbparams);
101     }
102
103
104     /**
105      * Constructor.
106      *
107      * @access private
108      * @see open()
109      */
110     function WikiDB (&$backend, $dbparams) {
111         $this->_backend = &$backend;
112         $this->_cache = new WikiDB_cache($backend);
113
114         // If the database doesn't yet have a timestamp, initialize it now.
115         if ($this->get('_timestamp') === false)
116             $this->touch();
117         
118         //FIXME: devel checking.
119         //$this->_backend->check();
120     }
121     
122     /**
123      * Get any user-level warnings about this WikiDB.
124      *
125      * Some back-ends, e.g. by default create there data files in the
126      * global /tmp directory. We would like to warn the user when this
127      * happens (since /tmp files tend to get wiped periodically.)
128      * Warnings such as these may be communicated from specific
129      * back-ends through this method.
130      *
131      * @access public
132      *
133      * @return string A warning message (or <tt>false</tt> if there is
134      * none.)
135      */
136     function genericWarnings() {
137         return false;
138     }
139      
140     /**
141      * Close database connection.
142      *
143      * The database may no longer be used after it is closed.
144      *
145      * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
146      * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
147      * which have been obtained from it.
148      *
149      * @access public
150      */
151     function close () {
152         $this->_backend->close();
153         $this->_cache->close();
154     }
155     
156     /**
157      * Get a WikiDB_Page from a WikiDB.
158      *
159      * A {@link WikiDB} consists of the (infinite) set of all possible pages,
160      * therefore this method never fails.
161      *
162      * @access public
163      * @param string $pagename Which page to get.
164      * @return WikiDB_Page The requested WikiDB_Page.
165      */
166     function getPage($pagename) {
167         assert(is_string($pagename) && $pagename);
168         return new WikiDB_Page($this, $pagename);
169     }
170
171         
172     // Do we need this?
173     //function nPages() { 
174     //}
175
176
177     /**
178      * Determine whether page exists (in non-default form).
179      *
180      * <pre>
181      *   $is_page = $dbi->isWikiPage($pagename);
182      * </pre>
183      * is equivalent to
184      * <pre>
185      *   $page = $dbi->getPage($pagename);
186      *   $current = $page->getCurrentRevision();
187      *   $is_page = ! $current->hasDefaultContents();
188      * </pre>
189      * however isWikiPage may be implemented in a more efficient
190      * manner in certain back-ends.
191      *
192      * @access public
193      *
194      * @param string $pagename string Which page to check.
195      *
196      * @return boolean True if the page actually exists with
197      * non-default contents in the WikiDataBase.
198      */
199     function isWikiPage ($pagename) {
200         $page = $this->getPage($pagename);
201         $current = $page->getCurrentRevision();
202         return ! $current->hasDefaultContents();
203     }
204
205     /**
206      * Delete page from the WikiDB. 
207      *
208      * Deletes all revisions of the page from the WikiDB. Also resets
209      * all page meta-data to the default values.
210      *
211      * @access public
212      *
213      * @param string $pagename Name of page to delete.
214      */
215     function deletePage($pagename) {
216         $this->_cache->delete_page($pagename);
217
218         //How to create a RecentChanges entry with explaining summary?
219         /*
220         $page = $this->getPage($pagename);
221         $current = $page->getCurrentRevision();
222         $meta = $current->_data;
223         $version = $current->getVersion();
224         $meta['summary'] = sprintf(_("renamed from %s"),$from);
225         $page->save($current->getPackedContent(), $version + 1, $meta);
226         */
227     }
228
229     /**
230      * Retrieve all pages.
231      *
232      * Gets the set of all pages with non-default contents.
233      *
234      * FIXME: do we need this?  I think so.  The simple searches
235      *        need this stuff.
236      *
237      * @access public
238      *
239      * @param boolean $include_defaulted Normally pages whose most
240      * recent revision has empty content are considered to be
241      * non-existant. Unless $include_defaulted is set to true, those
242      * pages will not be returned.
243      *
244      * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
245      *     in the WikiDB which have non-default contents.
246      */
247     function getAllPages($include_defaulted=false, $sortby=false, $limit=false) {
248         $result = $this->_backend->get_all_pages($include_defaulted,$sortby,$limit);
249         return new WikiDB_PageIterator($this, $result);
250     }
251
252     /**
253      * Title search.
254      *
255      * Search for pages containing (or not containing) certain words
256      * in their names.
257      *
258      * Pages are returned in alphabetical order whenever it is
259      * practical to do so.
260      *
261      * FIXME: should titleSearch and fullSearch be combined?  I think so.
262      *
263      * @access public
264      * @param TextSearchQuery $search A TextSearchQuery object
265      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
266      * @see TextSearchQuery
267      */
268     function titleSearch($search) {
269         $result = $this->_backend->text_search($search);
270         return new WikiDB_PageIterator($this, $result);
271     }
272
273     /**
274      * Full text search.
275      *
276      * Search for pages containing (or not containing) certain words
277      * in their entire text (this includes the page content and the
278      * page name).
279      *
280      * Pages are returned in alphabetical order whenever it is
281      * practical to do so.
282      *
283      * @access public
284      *
285      * @param TextSearchQuery $search A TextSearchQuery object.
286      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
287      * @see TextSearchQuery
288      */
289     function fullSearch($search) {
290         $result = $this->_backend->text_search($search, 'full_text');
291         return new WikiDB_PageIterator($this, $result);
292     }
293
294     /**
295      * Find the pages with the greatest hit counts.
296      *
297      * Pages are returned in reverse order by hit count.
298      *
299      * @access public
300      *
301      * @param integer $limit The maximum number of pages to return.
302      * Set $limit to zero to return all pages.  If $limit < 0, pages will
303      * be sorted in decreasing order of popularity.
304      *
305      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
306      * pages.
307      */
308     function mostPopular($limit = 20) {
309         $result = $this->_backend->most_popular($limit);
310         return new WikiDB_PageIterator($this, $result);
311     }
312
313     /**
314      * Find recent page revisions.
315      *
316      * Revisions are returned in reverse order by creation time.
317      *
318      * @access public
319      *
320      * @param hash $params This hash is used to specify various optional
321      *   parameters:
322      * <dl>
323      * <dt> limit 
324      *    <dd> (integer) At most this many revisions will be returned.
325      * <dt> since
326      *    <dd> (integer) Only revisions since this time (unix-timestamp) will be returned. 
327      * <dt> include_minor_revisions
328      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
329      * <dt> exclude_major_revisions
330      *    <dd> (boolean) Don't include non-minor revisions.
331      *         (Exclude_major_revisions implies include_minor_revisions.)
332      * <dt> include_all_revisions
333      *    <dd> (boolean) Return all matching revisions for each page.
334      *         Normally only the most recent matching revision is returned
335      *         for each page.
336      * </dl>
337      *
338      * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
339      * matching revisions.
340      */
341     function mostRecent($params = false) {
342         $result = $this->_backend->most_recent($params);
343         return new WikiDB_PageRevisionIterator($this, $result);
344     }
345
346    /**
347      * Blog search. (experimental)
348      *
349      * Search for blog entries related to a certain page.
350      *
351      * FIXME: with pagetype support and perhaps a RegexpSearchQuery
352      * we can make sure we are returning *ONLY* blog pages to the
353      * main routine.  Currently, we just use titleSearch which requires
354      * some further checking in lib/plugin/WikiBlog.php (BAD).
355      *
356      * @access public
357      *
358      * @param string $order  'normal' (chronological) or 'reverse'
359      * @param string $page   Find blog entries related to this page.
360      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
361      */
362     // Deleting until such time as this is properly implemented...
363     // (As long as it's just a title search, just use titleSearch.)
364     //function blogSearch($page, $order) {
365     //  //FIXME: implement ordering
366     //
367     //  require_once('lib/TextSearchQuery.php');
368     //  $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
369     //
370     //  return $this->titleSearch($query);
371     //}
372
373     /**
374      * Call the appropriate backend method
375      *
376      * A {@link WikiDB} consists of the (infinite) set of all possible pages,
377      * therefore this method never fails.
378      *
379      * @access public
380      * @param string $from Page to rename
381      * @param string $to   New name
382      * @param boolean $updateWikiLinks If the text in all pages should be replaced.
383      * @return boolean     true or false
384      */
385     function renamePage($from, $to, $updateWikiLinks = false) {
386         assert(is_string($from) && $from);
387         assert(is_string($to) && $to);
388         $result = false;
389         if (method_exists($this->_backend,'rename_page')) {
390             $oldpage = $this->getPage($from);
391             if ($oldpage->exists()) {
392                 if ($result = $this->_backend->rename_page($from, $to)) {
393                     //update all WikiLinks in existing pages
394                     if ($updateWikiLinks) {
395                         //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
396                         require_once('lib/plugin/WikiAdminSearchReplace.php');
397                         $links = $page->getLinks();
398                         while ($linked_page = $links->next()) {
399                             WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
400                         }
401                     }
402                     //create a RecentChanges entry with explaining summary
403                     $page = $this->getPage($to);
404                     $current = $page->getCurrentRevision();
405                     $meta = $current->_data;
406                     $version = $current->getVersion();
407                     $meta['summary'] = sprintf(_("renamed from %s"),$from);
408                     $page->save($current->getPackedContent(), $version + 1, $meta);
409                 }
410             }
411         } else {
412             trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
413         }
414         return $result;
415     }
416
417     /** Get timestamp when database was last modified.
418      *
419      * @return string A string consisting of two integers,
420      * separated by a space.  The first is the time in
421      * unix timestamp format, the second is a modification
422      * count for the database.
423      *
424      * The idea is that you can cast the return value to an
425      * int to get a timestamp, or you can use the string value
426      * as a good hash for the entire database.
427      */
428     function getTimestamp() {
429         $ts = $this->get('_timestamp');
430         return sprintf("%d %d", $ts[0], $ts[1]);
431     }
432     
433     /**
434      * Update the database timestamp.
435      *
436      */
437     function touch() {
438         $ts = $this->get('_timestamp');
439         $this->set('_timestamp', array(time(), $ts[1] + 1));
440     }
441
442         
443     /**
444      * Access WikiDB global meta-data.
445      *
446      * NOTE: this is currently implemented in a hackish and
447      * not very efficient manner.
448      *
449      * @access public
450      *
451      * @param string $key Which meta data to get.
452      * Some reserved meta-data keys are:
453      * <dl>
454      * <dt>'_timestamp' <dd> Data used by getTimestamp().
455      * </dl>
456      *
457      * @return scalar The requested value, or false if the requested data
458      * is not set.
459      */
460     function get($key) {
461         if (!$key || $key[0] == '%')
462             return false;
463         /*
464          * Hack Alert: We can use any page (existing or not) to store
465          * this data (as long as we always use the same one.)
466          */
467         $gd = $this->getPage('global_data');
468         $data = $gd->get('__global');
469
470         if ($data && isset($data[$key]))
471             return $data[$key];
472         else
473             return false;
474     }
475
476     /**
477      * Set global meta-data.
478      *
479      * NOTE: this is currently implemented in a hackish and
480      * not very efficient manner.
481      *
482      * @see get
483      * @access public
484      *
485      * @param string $key  Meta-data key to set.
486      * @param string $newval  New value.
487      */
488     function set($key, $newval) {
489         if (!$key || $key[0] == '%')
490             return;
491         
492         $gd = $this->getPage('global_data');
493         
494         $data = $gd->get('__global');
495         if ($data === false)
496             $data = array();
497
498         if (empty($newval))
499             unset($data[$key]);
500         else
501             $data[$key] = $newval;
502
503         $gd->set('__global', $data);
504     }
505 };
506
507
508 /**
509  * An abstract base class which representing a wiki-page within a
510  * WikiDB.
511  *
512  * A WikiDB_Page contains a number (at least one) of
513  * WikiDB_PageRevisions.
514  */
515 class WikiDB_Page 
516 {
517     function WikiDB_Page(&$wikidb, $pagename) {
518         $this->_wikidb = &$wikidb;
519         $this->_pagename = $pagename;
520         assert(!empty($this->_pagename));
521     }
522
523     /**
524      * Get the name of the wiki page.
525      *
526      * @access public
527      *
528      * @return string The page name.
529      */
530     function getName() {
531         return $this->_pagename;
532     }
533
534     function exists() {
535         $current = $this->getCurrentRevision();
536         return ! $current->hasDefaultContents();
537     }
538
539     /**
540      * Delete an old revision of a WikiDB_Page.
541      *
542      * Deletes the specified revision of the page.
543      * It is a fatal error to attempt to delete the current revision.
544      *
545      * @access public
546      *
547      * @param integer $version Which revision to delete.  (You can also
548      *  use a WikiDB_PageRevision object here.)
549      */
550     function deleteRevision($version) {
551         $backend = &$this->_wikidb->_backend;
552         $cache = &$this->_wikidb->_cache;
553         $pagename = &$this->_pagename;
554
555         $version = $this->_coerce_to_version($version);
556         if ($version == 0)
557             return;
558
559         $backend->lock();
560         $latestversion = $cache->get_latest_version($pagename);
561         if ($latestversion && $version == $latestversion) {
562             $backend->unlock();
563             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
564                                   $pagename), E_USER_ERROR);
565             return;
566         }
567
568         $cache->delete_versiondata($pagename, $version);
569                 
570         $backend->unlock();
571     }
572
573     /*
574      * Delete a revision, or possibly merge it with a previous
575      * revision.
576      *
577      * The idea is this:
578      * Suppose an author make a (major) edit to a page.  Shortly
579      * after that the same author makes a minor edit (e.g. to fix
580      * spelling mistakes he just made.)
581      *
582      * Now some time later, where cleaning out old saved revisions,
583      * and would like to delete his minor revision (since there's
584      * really no point in keeping minor revisions around for a long
585      * time.)
586      *
587      * Note that the text after the minor revision probably represents
588      * what the author intended to write better than the text after
589      * the preceding major edit.
590      *
591      * So what we really want to do is merge the minor edit with the
592      * preceding edit.
593      *
594      * We will only do this when:
595      * <ul>
596      * <li>The revision being deleted is a minor one, and
597      * <li>It has the same author as the immediately preceding revision.
598      * </ul>
599      */
600     function mergeRevision($version) {
601         $backend = &$this->_wikidb->_backend;
602         $cache = &$this->_wikidb->_cache;
603         $pagename = &$this->_pagename;
604
605         $version = $this->_coerce_to_version($version);
606         if ($version == 0)
607             return;
608
609         $backend->lock();
610         $latestversion = $backend->get_latest_version($pagename);
611         if ($latestversion && $version == $latestversion) {
612             $backend->unlock();
613             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
614                                   $pagename), E_USER_ERROR);
615             return;
616         }
617
618         $versiondata = $cache->get_versiondata($pagename, $version, true);
619         if (!$versiondata) {
620             // Not there? ... we're done!
621             $backend->unlock();
622             return;
623         }
624
625         if ($versiondata['is_minor_edit']) {
626             $previous = $backend->get_previous_version($pagename, $version);
627             if ($previous) {
628                 $prevdata = $cache->get_versiondata($pagename, $previous);
629                 if ($prevdata['author_id'] == $versiondata['author_id']) {
630                     // This is a minor revision, previous version is
631                     // by the same author. We will merge the
632                     // revisions.
633                     $cache->update_versiondata($pagename, $previous,
634                                                array('%content' => $versiondata['%content'],
635                                                      '_supplanted' => $versiondata['_supplanted']));
636                 }
637             }
638         }
639
640         $cache->delete_versiondata($pagename, $version);
641         $backend->unlock();
642     }
643
644     
645     /**
646      * Create a new revision of a {@link WikiDB_Page}.
647      *
648      * @access public
649      *
650      * @param int $version Version number for new revision.  
651      * To ensure proper serialization of edits, $version must be
652      * exactly one higher than the current latest version.
653      * (You can defeat this check by setting $version to
654      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
655      *
656      * @param string $content Contents of new revision.
657      *
658      * @param hash $metadata Metadata for new revision.
659      * All values in the hash should be scalars (strings or integers).
660      *
661      * @param array $links List of pagenames which this page links to.
662      *
663      * @return WikiDB_PageRevision  Returns the new WikiDB_PageRevision object. If
664      * $version was incorrect, returns false
665      */
666     function createRevision($version, &$content, $metadata, $links) {
667         $backend = &$this->_wikidb->_backend;
668         $cache = &$this->_wikidb->_cache;
669         $pagename = &$this->_pagename;
670                 
671         $backend->lock();
672
673         $latestversion = $backend->get_latest_version($pagename);
674         $newversion = $latestversion + 1;
675         assert($newversion >= 1);
676
677         if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
678             $backend->unlock();
679             return false;
680         }
681
682         $data = $metadata;
683         
684         foreach ($data as $key => $val) {
685             if (empty($val) || $key[0] == '_' || $key[0] == '%')
686                 unset($data[$key]);
687         }
688                         
689         assert(!empty($data['author']));
690         if (empty($data['author_id']))
691             @$data['author_id'] = $data['author'];
692                 
693         if (empty($data['mtime']))
694             $data['mtime'] = time();
695
696         if ($latestversion) {
697             // Ensure mtimes are monotonic.
698             $pdata = $cache->get_versiondata($pagename, $latestversion);
699             if ($data['mtime'] < $pdata['mtime']) {
700                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
701                                       $pagename,"'non-monotonic'"),
702                               E_USER_NOTICE);
703                 $data['orig_mtime'] = $data['mtime'];
704                 $data['mtime'] = $pdata['mtime'];
705             }
706             
707             // FIXME: use (possibly user specified) 'mtime' time or
708             // time()?
709             $cache->update_versiondata($pagename, $latestversion,
710                                        array('_supplanted' => $data['mtime']));
711         }
712
713         $data['%content'] = &$content;
714
715         $cache->set_versiondata($pagename, $newversion, $data);
716
717         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
718         //':deleted' => empty($content)));
719         
720         $backend->set_links($pagename, $links);
721
722         $backend->unlock();
723
724         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
725                                        $data);
726     }
727
728     /** A higher-level interface to createRevision.
729      *
730      * This takes care of computing the links, and storing
731      * a cached version of the transformed wiki-text.
732      *
733      * @param string $wikitext  The page content.
734      *
735      * @param int $version Version number for new revision.  
736      * To ensure proper serialization of edits, $version must be
737      * exactly one higher than the current latest version.
738      * (You can defeat this check by setting $version to
739      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
740      *
741      * @param hash $meta  Meta-data for new revision.
742      */
743     function save($wikitext, $version, $meta) {
744         $formatted = new TransformedText($this, $wikitext, $meta);
745         $type = $formatted->getType();
746         $meta['pagetype'] = $type->getName();
747         $links = $formatted->getWikiPageLinks();
748
749         $backend = &$this->_wikidb->_backend;
750         $backend->lock();
751         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
752         if ($newrevision)
753             if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
754                 $this->set('_cached_html', $formatted->pack());
755         $backend->unlock();
756
757         // FIXME: probably should have some global state information
758         // in the backend to control when to optimize.
759         //
760         // We're doing this here rather than in createRevision because
761         // postgres can't optimize while locked.
762         if (time() % 50 == 0) {
763             trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
764             $backend->optimize();
765         }
766
767         $newrevision->_transformedContent = $formatted;
768         return $newrevision;
769     }
770
771     /**
772      * Get the most recent revision of a page.
773      *
774      * @access public
775      *
776      * @return WikiDB_PageRevision The current WikiDB_PageRevision object. 
777      */
778     function getCurrentRevision() {
779         $backend = &$this->_wikidb->_backend;
780         $cache = &$this->_wikidb->_cache;
781         $pagename = &$this->_pagename;
782
783         $backend->lock();
784         $version = $cache->get_latest_version($pagename);
785         $revision = $this->getRevision($version);
786         $backend->unlock();
787         assert($revision);
788         return $revision;
789     }
790
791     /**
792      * Get a specific revision of a WikiDB_Page.
793      *
794      * @access public
795      *
796      * @param integer $version  Which revision to get.
797      *
798      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
799      * false if the requested revision does not exist in the {@link WikiDB}.
800      * Note that version zero of any page always exists.
801      */
802     function getRevision($version) {
803         $cache = &$this->_wikidb->_cache;
804         $pagename = &$this->_pagename;
805         
806         if ($version == 0)
807             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
808
809         assert($version > 0);
810         $vdata = $cache->get_versiondata($pagename, $version);
811         if (!$vdata)
812             return false;
813         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
814                                        $vdata);
815     }
816
817     /**
818      * Get previous page revision.
819      *
820      * This method find the most recent revision before a specified
821      * version.
822      *
823      * @access public
824      *
825      * @param integer $version  Find most recent revision before this version.
826      *  You can also use a WikiDB_PageRevision object to specify the $version.
827      *
828      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
829      * requested revision does not exist in the {@link WikiDB}.  Note that
830      * unless $version is greater than zero, a revision (perhaps version zero,
831      * the default revision) will always be found.
832      */
833     function getRevisionBefore($version) {
834         $backend = &$this->_wikidb->_backend;
835         $pagename = &$this->_pagename;
836
837         $version = $this->_coerce_to_version($version);
838
839         if ($version == 0)
840             return false;
841         $backend->lock();
842         $previous = $backend->get_previous_version($pagename, $version);
843         $revision = $this->getRevision($previous);
844         $backend->unlock();
845         assert($revision);
846         return $revision;
847     }
848
849     /**
850      * Get all revisions of the WikiDB_Page.
851      *
852      * This does not include the version zero (default) revision in the
853      * returned revision set.
854      *
855      * @return WikiDB_PageRevisionIterator A
856      * WikiDB_PageRevisionIterator containing all revisions of this
857      * WikiDB_Page in reverse order by version number.
858      */
859     function getAllRevisions() {
860         $backend = &$this->_wikidb->_backend;
861         $revs = $backend->get_all_revisions($this->_pagename);
862         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
863     }
864     
865     /**
866      * Find pages which link to or are linked from a page.
867      *
868      * @access public
869      *
870      * @param boolean $reversed Which links to find: true for backlinks (default).
871      *
872      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
873      * all matching pages.
874      */
875     function getLinks($reversed = true) {
876         $backend = &$this->_wikidb->_backend;
877         $result =  $backend->get_links($this->_pagename, $reversed);
878         return new WikiDB_PageIterator($this->_wikidb, $result);
879     }
880             
881     /**
882      * Access WikiDB_Page meta-data.
883      *
884      * @access public
885      *
886      * @param string $key Which meta data to get.
887      * Some reserved meta-data keys are:
888      * <dl>
889      * <dt>'locked'<dd> Is page locked?
890      * <dt>'hits'  <dd> Page hit counter.
891      * <dt>'pref'  <dd> Users preferences, stored in homepages.
892      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
893      *                  E.g. "owner.users"
894      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
895      *                  page-headers and content.
896      * <dt>'score' <dd> Page score (not yet implement, do we need?)
897      * </dl>
898      *
899      * @return scalar The requested value, or false if the requested data
900      * is not set.
901      */
902     function get($key) {
903         $cache = &$this->_wikidb->_cache;
904         if (!$key || $key[0] == '%')
905             return false;
906         $data = $cache->get_pagedata($this->_pagename);
907         return isset($data[$key]) ? $data[$key] : false;
908     }
909
910     /**
911      * Get all the page meta-data as a hash.
912      *
913      * @return hash The page meta-data.
914      */
915     function getMetaData() {
916         $cache = &$this->_wikidb->_cache;
917         $data = $cache->get_pagedata($this->_pagename);
918         $meta = array();
919         foreach ($data as $key => $val) {
920             if (/*!empty($val) &&*/ $key[0] != '%')
921                 $meta[$key] = $val;
922         }
923         return $meta;
924     }
925
926     /**
927      * Set page meta-data.
928      *
929      * @see get
930      * @access public
931      *
932      * @param string $key  Meta-data key to set.
933      * @param string $newval  New value.
934      */
935     function set($key, $newval) {
936         $cache = &$this->_wikidb->_cache;
937         $pagename = &$this->_pagename;
938         
939         assert($key && $key[0] != '%');
940
941         $data = $cache->get_pagedata($pagename);
942
943         if (!empty($newval)) {
944             if (!empty($data[$key]) && $data[$key] == $newval)
945                 return;         // values identical, skip update.
946         }
947         else {
948             if (empty($data[$key]))
949                 return;         // values identical, skip update.
950         }
951
952         $cache->update_pagedata($pagename, array($key => $newval));
953     }
954
955     /**
956      * Increase page hit count.
957      *
958      * FIXME: IS this needed?  Probably not.
959      *
960      * This is a convenience function.
961      * <pre> $page->increaseHitCount(); </pre>
962      * is functionally identical to
963      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
964      *
965      * Note that this method may be implemented in more efficient ways
966      * in certain backends.
967      *
968      * @access public
969      */
970     function increaseHitCount() {
971         @$newhits = $this->get('hits') + 1;
972         $this->set('hits', $newhits);
973     }
974
975     /**
976      * Return a string representation of the WikiDB_Page
977      *
978      * This is really only for debugging.
979      *
980      * @access public
981      *
982      * @return string Printable representation of the WikiDB_Page.
983      */
984     function asString () {
985         ob_start();
986         printf("[%s:%s\n", get_class($this), $this->getName());
987         print_r($this->getMetaData());
988         echo "]\n";
989         $strval = ob_get_contents();
990         ob_end_clean();
991         return $strval;
992     }
993
994
995     /**
996      * @access private
997      * @param integer_or_object $version_or_pagerevision
998      * Takes either the version number (and int) or a WikiDB_PageRevision
999      * object.
1000      * @return integer The version number.
1001      */
1002     function _coerce_to_version($version_or_pagerevision) {
1003         if (method_exists($version_or_pagerevision, "getContent"))
1004             $version = $version_or_pagerevision->getVersion();
1005         else
1006             $version = (int) $version_or_pagerevision;
1007
1008         assert($version >= 0);
1009         return $version;
1010     }
1011
1012     function isUserPage ($include_empty = true) {
1013         if ($include_empty) {
1014             $current = $this->getCurrentRevision();
1015             if ($current->hasDefaultContents()) {
1016                 return false;
1017             }
1018         }
1019         return $this->get('pref') ? true : false;
1020     }
1021
1022 };
1023
1024 /**
1025  * This class represents a specific revision of a WikiDB_Page within
1026  * a WikiDB.
1027  *
1028  * A WikiDB_PageRevision has read-only semantics. You may only create
1029  * new revisions (and delete old ones) --- you cannot modify existing
1030  * revisions.
1031  */
1032 class WikiDB_PageRevision
1033 {
1034     var $_transformedContent = false; // set by WikiDB_Page::save()
1035     
1036     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1037                                  $versiondata = false)
1038         {
1039             $this->_wikidb = &$wikidb;
1040             $this->_pagename = $pagename;
1041             $this->_version = $version;
1042             $this->_data = $versiondata ? $versiondata : array();
1043         }
1044     
1045     /**
1046      * Get the WikiDB_Page which this revision belongs to.
1047      *
1048      * @access public
1049      *
1050      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1051      */
1052     function getPage() {
1053         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1054     }
1055
1056     /**
1057      * Get the version number of this revision.
1058      *
1059      * @access public
1060      *
1061      * @return integer The version number of this revision.
1062      */
1063     function getVersion() {
1064         return $this->_version;
1065     }
1066     
1067     /**
1068      * Determine whether this revision has defaulted content.
1069      *
1070      * The default revision (version 0) of each page, as well as any
1071      * pages which are created with empty content have their content
1072      * defaulted to something like:
1073      * <pre>
1074      *   Describe [ThisPage] here.
1075      * </pre>
1076      *
1077      * @access public
1078      *
1079      * @return boolean Returns true if the page has default content.
1080      */
1081     function hasDefaultContents() {
1082         $data = &$this->_data;
1083         return empty($data['%content']);
1084     }
1085
1086     /**
1087      * Get the content as an array of lines.
1088      *
1089      * @access public
1090      *
1091      * @return array An array of lines.
1092      * The lines should contain no trailing white space.
1093      */
1094     function getContent() {
1095         return explode("\n", $this->getPackedContent());
1096     }
1097         
1098         /**
1099      * Get the pagename of the revision.
1100      *
1101      * @access public
1102      *
1103      * @return string pagename.
1104      */
1105     function getPageName() {
1106         return $this->_pagename;
1107     }
1108
1109     /**
1110      * Determine whether revision is the latest.
1111      *
1112      * @access public
1113      *
1114      * @return boolean True iff the revision is the latest (most recent) one.
1115      */
1116     function isCurrent() {
1117         if (!isset($this->_iscurrent)) {
1118             $page = $this->getPage();
1119             $current = $page->getCurrentRevision();
1120             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1121         }
1122         return $this->_iscurrent;
1123     }
1124
1125     /**
1126      * Get the transformed content of a page.
1127      *
1128      * @param string $pagetype  Override the page-type of the revision.
1129      *
1130      * @return object An XmlContent-like object containing the page transformed
1131      * contents.
1132      */
1133     function getTransformedContent($pagetype_override=false) {
1134         $backend = &$this->_wikidb->_backend;
1135         
1136         if ($pagetype_override) {
1137             // Figure out the normal page-type for this page.
1138             $type = PageType::GetPageType($this->get('pagetype'));
1139             if ($type->getName() == $pagetype_override)
1140                 $pagetype_override = false; // Not really an override...
1141         }
1142
1143         if ($pagetype_override) {
1144             // Overriden page type, don't cache (or check cache).
1145             return new TransformedText($this->getPage(),
1146                                        $this->getPackedContent(),
1147                                        $this->getMetaData(),
1148                                        $pagetype_override);
1149         }
1150
1151         $possibly_cache_results = true;
1152
1153         if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1154             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1155                 // flush cache for this page.
1156                 $page = $this->getPage();
1157                 $page->set('_cached_html', false);
1158             }
1159             $possibly_cache_results = false;
1160         }
1161         elseif (!$this->_transformedContent) {
1162             $backend->lock();
1163             if ($this->isCurrent()) {
1164                 $page = $this->getPage();
1165                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1166             }
1167             else {
1168                 $possibly_cache_results = false;
1169             }
1170             $backend->unlock();
1171         }
1172         
1173         if (!$this->_transformedContent) {
1174             $this->_transformedContent
1175                 = new TransformedText($this->getPage(),
1176                                       $this->getPackedContent(),
1177                                       $this->getMetaData());
1178             
1179             if ($possibly_cache_results) {
1180                 // If we're still the current version, cache the transfomed page.
1181                 $backend->lock();
1182                 if ($this->isCurrent()) {
1183                     $page->set('_cached_html', $this->_transformedContent->pack());
1184                 }
1185                 $backend->unlock();
1186             }
1187         }
1188
1189         return $this->_transformedContent;
1190     }
1191
1192     /**
1193      * Get the content as a string.
1194      *
1195      * @access public
1196      *
1197      * @return string The page content.
1198      * Lines are separated by new-lines.
1199      */
1200     function getPackedContent() {
1201         $data = &$this->_data;
1202
1203         
1204         if (empty($data['%content'])) {
1205             include_once('lib/InlineParser.php');
1206             // Replace empty content with default value.
1207             return sprintf(_("Describe %s here."), 
1208                            "[" . WikiEscape($this->_pagename) . "]");
1209         }
1210
1211         // There is (non-default) content.
1212         assert($this->_version > 0);
1213         
1214         if (!is_string($data['%content'])) {
1215             // Content was not provided to us at init time.
1216             // (This is allowed because for some backends, fetching
1217             // the content may be expensive, and often is not wanted
1218             // by the user.)
1219             //
1220             // In any case, now we need to get it.
1221             $data['%content'] = $this->_get_content();
1222             assert(is_string($data['%content']));
1223         }
1224         
1225         return $data['%content'];
1226     }
1227
1228     function _get_content() {
1229         $cache = &$this->_wikidb->_cache;
1230         $pagename = $this->_pagename;
1231         $version = $this->_version;
1232
1233         assert($version > 0);
1234         
1235         $newdata = $cache->get_versiondata($pagename, $version, true);
1236         if ($newdata) {
1237             assert(is_string($newdata['%content']));
1238             return $newdata['%content'];
1239         }
1240         else {
1241             // else revision has been deleted... What to do?
1242             return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
1243                              $version, $pagename);
1244         }
1245     }
1246
1247     /**
1248      * Get meta-data for this revision.
1249      *
1250      *
1251      * @access public
1252      *
1253      * @param string $key Which meta-data to access.
1254      *
1255      * Some reserved revision meta-data keys are:
1256      * <dl>
1257      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1258      *        The 'mtime' meta-value is normally set automatically by the database
1259      *        backend, but it may be specified explicitly when creating a new revision.
1260      * <dt> orig_mtime
1261      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1262      *       of a page must be monotonically increasing.  If an attempt is
1263      *       made to create a new revision with an mtime less than that of
1264      *       the preceeding revision, the new revisions timestamp is force
1265      *       to be equal to that of the preceeding revision.  In that case,
1266      *       the originally requested mtime is preserved in 'orig_mtime'.
1267      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1268      *        This meta-value is <em>always</em> automatically maintained by the database
1269      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1270      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1271      *
1272      * FIXME: this could be refactored:
1273      * <dt> author
1274      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1275      * <dt> author_id
1276      *  <dd> Authenticated author of a page.  This is used to identify
1277      *       the distinctness of authors when cleaning old revisions from
1278      *       the database.
1279      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1280      * <dt> 'summary' <dd> Short change summary entered by page author.
1281      * </dl>
1282      *
1283      * Meta-data keys must be valid C identifers (they have to start with a letter
1284      * or underscore, and can contain only alphanumerics and underscores.)
1285      *
1286      * @return string The requested value, or false if the requested value
1287      * is not defined.
1288      */
1289     function get($key) {
1290         if (!$key || $key[0] == '%')
1291             return false;
1292         $data = &$this->_data;
1293         return isset($data[$key]) ? $data[$key] : false;
1294     }
1295
1296     /**
1297      * Get all the revision page meta-data as a hash.
1298      *
1299      * @return hash The revision meta-data.
1300      */
1301     function getMetaData() {
1302         $meta = array();
1303         foreach ($this->_data as $key => $val) {
1304             if (!empty($val) && $key[0] != '%')
1305                 $meta[$key] = $val;
1306         }
1307         return $meta;
1308     }
1309     
1310             
1311     /**
1312      * Return a string representation of the revision.
1313      *
1314      * This is really only for debugging.
1315      *
1316      * @access public
1317      *
1318      * @return string Printable representation of the WikiDB_Page.
1319      */
1320     function asString () {
1321         ob_start();
1322         printf("[%s:%d\n", get_class($this), $this->get('version'));
1323         print_r($this->_data);
1324         echo $this->getPackedContent() . "\n]\n";
1325         $strval = ob_get_contents();
1326         ob_end_clean();
1327         return $strval;
1328     }
1329 };
1330
1331
1332 /**
1333  * A class which represents a sequence of WikiDB_Pages.
1334  */
1335 class WikiDB_PageIterator
1336 {
1337     function WikiDB_PageIterator(&$wikidb, &$pages) {
1338         $this->_pages = $pages;
1339         $this->_wikidb = &$wikidb;
1340     }
1341     
1342     /**
1343      * Get next WikiDB_Page in sequence.
1344      *
1345      * @access public
1346      *
1347      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1348      */
1349     function next () {
1350         if ( ! ($next = $this->_pages->next()) )
1351             return false;
1352
1353         $pagename = &$next['pagename'];
1354         if (isset($next['pagedata']))
1355             $this->_wikidb->_cache->cache_data($next);
1356
1357         return new WikiDB_Page($this->_wikidb, $pagename);
1358     }
1359
1360     /**
1361      * Release resources held by this iterator.
1362      *
1363      * The iterator may not be used after free() is called.
1364      *
1365      * There is no need to call free(), if next() has returned false.
1366      * (I.e. if you iterate through all the pages in the sequence,
1367      * you do not need to call free() --- you only need to call it
1368      * if you stop before the end of the iterator is reached.)
1369      *
1370      * @access public
1371      */
1372     function free() {
1373         $this->_pages->free();
1374     }
1375
1376     // Not yet used.
1377     function setSortby ($arg = false) {
1378         if (!$arg) {
1379             $arg = @$_GET['sortby'];
1380             if ($arg) {
1381                 $sortby = substr($arg,1);
1382                 $order  = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1383             }
1384         }
1385         if (is_array($arg)) { // array('mtime' => 'desc')
1386             $sortby = $arg[0];
1387             $order = $arg[1];
1388         } else {
1389             $sortby = $arg;
1390             $order  = 'ASC';
1391         }
1392         // available column types to sort by:
1393         // todo: we must provide access methods for the generic dumb/iterator
1394         $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1395         if (in_array($sortby,$this->_types))
1396             $this->_options['sortby'] = $sortby;
1397         else
1398             trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1399         if (in_array(strtoupper($order),'ASC','DESC')) 
1400             $this->_options['order'] = strtoupper($order);
1401         else
1402             trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1403     }
1404
1405 };
1406
1407 /**
1408  * A class which represents a sequence of WikiDB_PageRevisions.
1409  */
1410 class WikiDB_PageRevisionIterator
1411 {
1412     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1413         $this->_revisions = $revisions;
1414         $this->_wikidb = &$wikidb;
1415     }
1416     
1417     /**
1418      * Get next WikiDB_PageRevision in sequence.
1419      *
1420      * @access public
1421      *
1422      * @return WikiDB_PageRevision
1423      * The next WikiDB_PageRevision in the sequence.
1424      */
1425     function next () {
1426         if ( ! ($next = $this->_revisions->next()) )
1427             return false;
1428
1429         $this->_wikidb->_cache->cache_data($next);
1430
1431         $pagename = $next['pagename'];
1432         $version = $next['version'];
1433         $versiondata = $next['versiondata'];
1434         assert(!empty($pagename));
1435         assert(is_array($versiondata));
1436         assert($version > 0);
1437
1438         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1439                                        $versiondata);
1440     }
1441
1442     /**
1443      * Release resources held by this iterator.
1444      *
1445      * The iterator may not be used after free() is called.
1446      *
1447      * There is no need to call free(), if next() has returned false.
1448      * (I.e. if you iterate through all the revisions in the sequence,
1449      * you do not need to call free() --- you only need to call it
1450      * if you stop before the end of the iterator is reached.)
1451      *
1452      * @access public
1453      */
1454     function free() { 
1455         $this->_revisions->free();
1456     }
1457 };
1458
1459
1460 /**
1461  * Data cache used by WikiDB.
1462  *
1463  * FIXME: Maybe rename this to caching_backend (or some such).
1464  *
1465  * @access private
1466  */
1467 class WikiDB_cache 
1468 {
1469     // FIXME: beautify versiondata cache.  Cache only limited data?
1470
1471     function WikiDB_cache (&$backend) {
1472         $this->_backend = &$backend;
1473
1474         $this->_pagedata_cache = array();
1475         $this->_versiondata_cache = array();
1476         array_push ($this->_versiondata_cache, array());
1477         $this->_glv_cache = array();
1478     }
1479     
1480     function close() {
1481         $this->_pagedata_cache = false;
1482                 $this->_versiondata_cache = false;
1483                 $this->_glv_cache = false;
1484     }
1485
1486     function get_pagedata($pagename) {
1487         assert(is_string($pagename) && $pagename);
1488         $cache = &$this->_pagedata_cache;
1489
1490         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1491             $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1492             if (empty($cache[$pagename]))
1493                 $cache[$pagename] = array();
1494         }
1495
1496         return $cache[$pagename];
1497     }
1498     
1499     function update_pagedata($pagename, $newdata) {
1500         assert(is_string($pagename) && $pagename);
1501
1502         $this->_backend->update_pagedata($pagename, $newdata);
1503
1504         if (is_array($this->_pagedata_cache[$pagename])) {
1505             $cachedata = &$this->_pagedata_cache[$pagename];
1506             foreach($newdata as $key => $val)
1507                 $cachedata[$key] = $val;
1508         }
1509     }
1510
1511     function invalidate_cache($pagename) {
1512         unset ($this->_pagedata_cache[$pagename]);
1513                 unset ($this->_versiondata_cache[$pagename]);
1514                 unset ($this->_glv_cache[$pagename]);
1515     }
1516     
1517     function delete_page($pagename) {
1518         $this->_backend->delete_page($pagename);
1519         unset ($this->_pagedata_cache[$pagename]);
1520                 unset ($this->_glv_cache[$pagename]);
1521     }
1522
1523     // FIXME: ugly
1524     function cache_data($data) {
1525         if (isset($data['pagedata']))
1526             $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1527     }
1528     
1529     function get_versiondata($pagename, $version, $need_content = false) {
1530                 //  FIXME: Seriously ugly hackage
1531         if (defined ('USECACHE')){   //temporary - for debugging
1532         assert(is_string($pagename) && $pagename);
1533                 // there is a bug here somewhere which results in an assertion failure at line 105
1534                 // of ArchiveCleaner.php  It goes away if we use the next line.
1535                 $need_content = true;
1536                 $nc = $need_content ? '1':'0';
1537         $cache = &$this->_versiondata_cache;
1538         if (!isset($cache[$pagename][$version][$nc])||
1539                                 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1540             $cache[$pagename][$version][$nc] = 
1541                                 $this->_backend->get_versiondata($pagename,$version, $need_content);
1542                         // If we have retrieved all data, we may as well set the cache for $need_content = false
1543                         if($need_content){
1544                                 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1545                         }
1546                 }
1547         $vdata = $cache[$pagename][$version][$nc];
1548         }
1549         else
1550         {
1551     $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1552         }
1553         // FIXME: ugly
1554         if ($vdata && !empty($vdata['%pagedata']))
1555             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1556         return $vdata;
1557     }
1558
1559     function set_versiondata($pagename, $version, $data) {
1560         $new = $this->_backend->
1561              set_versiondata($pagename, $version, $data);
1562                 // Update the cache
1563                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1564                 // FIXME: hack
1565                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1566                 // Is this necessary?
1567                 unset($this->_glv_cache[$pagename]);
1568                 
1569     }
1570
1571     function update_versiondata($pagename, $version, $data) {
1572         $new = $this->_backend->
1573              update_versiondata($pagename, $version, $data);
1574                 // Update the cache
1575                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1576                 // FIXME: hack
1577                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1578                 // Is this necessary?
1579                 unset($this->_glv_cache[$pagename]);
1580
1581     }
1582
1583     function delete_versiondata($pagename, $version) {
1584         $new = $this->_backend->
1585             delete_versiondata($pagename, $version);
1586         unset ($this->_versiondata_cache[$pagename][$version]['1']);
1587         unset ($this->_versiondata_cache[$pagename][$version]['0']);
1588         unset ($this->_glv_cache[$pagename]);
1589     }
1590         
1591     function get_latest_version($pagename)  {
1592         if(defined('USECACHE')){
1593             assert (is_string($pagename) && $pagename);
1594             $cache = &$this->_glv_cache;        
1595             if (!isset($cache[$pagename])) {
1596                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1597                 if (empty($cache[$pagename]))
1598                     $cache[$pagename] = 0;
1599             } 
1600             return $cache[$pagename];}
1601         else {
1602             return $this->_backend->get_latest_version($pagename); 
1603         }
1604     }
1605
1606 };
1607
1608 // Local Variables:
1609 // mode: php
1610 // tab-width: 8
1611 // c-basic-offset: 4
1612 // c-hanging-comment-ender-p: nil
1613 // indent-tabs-mode: nil
1614 // End:   
1615 ?>