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