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