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