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