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