]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
More cacheing hacks. Currently doesn't
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.8 2002-02-07 17:07:58 lakka Exp $');
3
4 //FIXME: arg on get*Revision to hint that content is wanted.
5
6 define('WIKIDB_FORCE_CREATE', -1);
7
8 //FIXME:  Use this to use new cache.  Remove refs to it before release
9 //define('USECACHE', 1);
10
11 /** 
12  * Abstract base class for the database used by PhpWiki.
13  *
14  * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
15  * turn contain <tt>WikiDB_PageRevision</tt>s.
16  *
17  * Conceptually a <tt>WikiDB</tt> contains all possible
18  * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
19  * Since all possible pages are already contained in a WikiDB, a call
20  * to WikiDB::getPage() will never fail (barring bugs and
21  * e.g. filesystem or SQL database problems.)
22  *
23  * Also each <tt>WikiDB_Page</tt> always contains at least one
24  * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
25  * [PageName] here.").  This default content has a version number of
26  * zero.
27  *
28  * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
29  * only create new revisions or delete old ones --- one can not modify
30  * an existing revision.
31  */
32 class WikiDB {
33     /**
34      * Open a WikiDB database.
35      *
36      * This is a static member function. This function inspects its
37      * arguments to determine the proper subclass of WikiDB to
38      * instantiate, and then it instantiates it.
39      *
40      * @access public
41      *
42      * @param $dbparams hash Database configuration parameters.
43      * Some pertinent paramters are:
44      * <dl>
45      * <dt> dbtype
46      * <dd> The back-end type.  Current supported types are:
47      *   <dl>
48      *   <dt> SQL
49      *   <dd> Generic SQL backend based on the PEAR/DB database abstraction
50      *       library.
51      *   <dt> dba
52      *   <dd> Dba based backend.
53      *   </dl>
54      *
55      * <dt> dsn
56      * <dd> (Used by the SQL backend.)
57      *      The DSN specifying which database to connect to.
58      *
59      * <dt> prefix
60      * <dd> Prefix to be prepended to database table (and file names).
61      *
62      * <dt> directory
63      * <dd> (Used by the dba backend.)
64      *      Which directory db files reside in.
65      *
66      * <dt> timeout
67      * <dd> (Used by the dba backend.)
68      *      Timeout in seconds for opening (and obtaining lock) on the
69      *      db files.
70      *
71      * <dt> dba_handler
72      * <dd> (Used by the dba backend.)
73      *
74      *      Which dba handler to use. Good choices are probably either
75      *      'gdbm' or 'db2'.
76      * </dl>
77      *
78      * @return object A WikiDB object.
79      **/
80     function open ($dbparams) {
81         $dbtype = $dbparams{'dbtype'};
82         include_once("lib/WikiDB/$dbtype.php");
83         $class = 'WikiDB_' . $dbtype;
84         return new $class ($dbparams);
85     }
86
87
88     /**
89      * Constructor
90      * @access protected
91      */
92     function WikiDB ($backend, $dbparams) {
93         $this->_backend = &$backend;
94         $this->_cache = new WikiDB_cache($backend);
95
96         //FIXME: devel checking.
97         //$this->_backend->check();
98     }
99     
100     /**
101      * Get any user-level warnings about this WikiDB.
102      *
103      * Some back-ends, e.g. by default create there data files in the
104      * global /tmp directory. We would like to warn the user when this
105      * happens (since /tmp files tend to get wiped periodically.)
106      * Warnings such as these may be communicated from specific
107      * back-ends through this method.
108      *
109      * @access public
110      *
111      * @return string A warning message (or <tt>false</tt> if there is
112      * none.)
113      */
114     function genericWarnings() {
115         return false;
116     }
117      
118     /**
119      * Close database connection.
120      *
121      * The database may no longer be used after it is closed.
122      *
123      * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
124      * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
125      * which have been obtained from it.
126      *
127      * @access public
128      */
129     function close () {
130         $this->_backend->close();
131         $this->_cache->close();
132     }
133     
134     /**
135      * Get a WikiDB_Page from a WikiDB.
136      *
137      * A WikiDB consists of the (infinite) set of all possible pages,
138      * therefore this method never fails.
139      *
140      * @access public
141      * @param $pagename string Which page to get.
142      * @return object The requested WikiDB_Page.
143      */
144     function getPage($pagename) {
145         assert(is_string($pagename) && $pagename);
146         return new WikiDB_Page($this, $pagename);
147     }
148
149         
150     // Do we need this?
151     //function nPages() { 
152     //}
153
154
155     /**
156      * Determine whether page exists (in non-default form).
157      *
158      * <pre>
159      *   $is_page = $dbi->isWikiPage($pagename);
160      * </pre>
161      * is equivalent to
162      * <pre>
163      *   $page = $dbi->getPage($pagename);
164      *   $current = $page->getCurrentRevision();
165      *   $is_page = ! $current->hasDefaultContents();
166      * </pre>
167      * however isWikiPage may be implemented in a more efficient
168      * manner in certain back-ends.
169      *
170      * @access public
171      *
172      * @param $pagename string Which page to check.
173      *
174      * @return boolean True if the page actually exists with
175      * non-default contents in the WikiDataBase.
176      */
177     function isWikiPage ($pagename) {
178         $page = $this->getPage($pagename);
179         $current = $page->getCurrentRevision();
180         return ! $current->hasDefaultContents();
181     }
182
183     /**
184      * Delete page from the WikiDB. 
185      *
186      * Deletes all revisions of the page from the WikiDB. Also resets
187      * all page meta-data to the default values.
188      *
189      * @access public
190      *
191      * @param $pagename string Name of page to delete.
192      */
193     function deletePage($pagename) {
194         $this->_cache->delete_page($pagename);
195         $this->_backend->set_links($pagename, false);
196     }
197
198     /**
199      * Retrieve all pages.
200      *
201      * Gets the set of all pages with non-default contents.
202      *
203      * FIXME: do we need this?  I think so.  The simple searches
204      *        need this stuff.
205      *
206      * @access public
207      *
208      * @param $include_defaulted boolean Normally pages whose most
209      * recent revision has empty content are considered to be
210      * non-existant. Unless $include_defaulted is set to true, those
211      * pages will not be returned.
212      *
213      * @return object A WikiDB_PageIterator which contains all pages
214      *     in the WikiDB which have non-default contents.
215      */
216     function getAllPages($include_defaulted = false) {
217         $result = $this->_backend->get_all_pages($include_defaulted);
218         return new WikiDB_PageIterator($this, $result);
219     }
220
221     /**
222      * Title search.
223      *
224      * Search for pages containing (or not containing) certain words
225      * in their names.
226      *
227      * Pages are returned in alphabetical order whenever it is
228      * practical to do so.
229      *
230      * FIXME: should titleSearch and fullSearch be combined?  I think so.
231      *
232      * @access public
233      * @param $search object A TextSearchQuery
234      * @return object A WikiDB_PageIterator containing the matching pages.
235      * @see TextSearchQuery
236      */
237     function titleSearch($search) {
238         $result = $this->_backend->text_search($search);
239         return new WikiDB_PageIterator($this, $result);
240     }
241
242     /**
243      * Full text search.
244      *
245      * Search for pages containing (or not containing) certain words
246      * in their entire text (this includes the page content and the
247      * page name).
248      *
249      * Pages are returned in alphabetical order whenever it is
250      * practical to do so.
251      *
252      * @access public
253      *
254      * @param $search object A TextSearchQuery object.
255      * @return object A WikiDB_PageIterator containing the matching pages.
256      * @see TextSearchQuery
257      */
258     function fullSearch($search) {
259         $result = $this->_backend->text_search($search, 'full_text');
260         return new WikiDB_PageIterator($this, $result);
261     }
262
263     /**
264      * Find the pages with the greatest hit counts.
265      *
266      * Pages are returned in reverse order by hit count.
267      *
268      * @access public
269      *
270      * @param $limit unsigned The maximum number of pages to return.
271      * Set $limit to zero to return all pages.
272      *
273      * @return object A WikiDB_PageIterator containing the matching
274      * pages.
275      */
276     function mostPopular($limit = 20) {
277         $result = $this->_backend->most_popular($limit);
278         return new WikiDB_PageIterator($this, $result);
279     }
280
281     /**
282      * Find recent page revisions.
283      *
284      * Revisions are returned in reverse order by creation time.
285      *
286      * @access public
287      *
288      * @param $params hash This hash is used to specify various optional
289      *   parameters:
290      * <dl>
291      * <dt> limit 
292      *    <dd> (integer) At most this many revisions will be returned.
293      * <dt> since
294      *    <dd> (integer) Only revisions since this time (unix-timestamp) will be returned. 
295      * <dt> include_minor_revisions
296      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
297      * <dt> exclude_major_revisions
298      *    <dd> (boolean) Don't include non-minor revisions.
299      *         (Exclude_major_revisions implies include_minor_revisions.)
300      * <dt> include_all_revisions
301      *    <dd> (boolean) Return all matching revisions for each page.
302      *         Normally only the most recent matching revision is returned
303      *         for each page.
304      * </dl>
305      *
306      * @return object A WikiDB_PageRevisionIterator containing the
307      * matching revisions.
308      */
309     function mostRecent($params = false) {
310         $result = $this->_backend->most_recent($params);
311         return new WikiDB_PageRevisionIterator($this, $result);
312     }
313 };
314
315
316 /**
317  * An abstract base class which representing a wiki-page within a
318  * WikiDB.
319  *
320  * A WikiDB_Page contains a number (at least one) of
321  * WikiDB_PageRevisions.
322  */
323 class WikiDB_Page 
324 {
325     function WikiDB_Page(&$wikidb, $pagename) {
326         $this->_wikidb = &$wikidb;
327         $this->_pagename = $pagename;
328         assert(!empty($this->_pagename));
329     }
330
331     /**
332      * Get the name of the wiki page.
333      *
334      * @access public
335      *
336      * @return string The page name.
337      */
338     function getName() {
339         return $this->_pagename;
340     }
341
342
343     /**
344      * Delete an old revision of a WikiDB_Page.
345      *
346      * Deletes the specified revision of the page.
347      * It is a fatal error to attempt to delete the current revision.
348      *
349      * @access public
350      *
351      * @param $version integer Which revision to delete.  (You can also
352      *  use a WikiDB_PageRevision object here.)
353      */
354     function deleteRevision($version) {
355         $backend = &$this->_wikidb->_backend;
356         $cache = &$this->_wikidb->_cache;
357         $pagename = &$this->_pagename;
358
359         $version = $this->_coerce_to_version($version);
360         if ($version == 0)
361             return;
362
363         $backend->lock();
364         $latestversion = $cache->get_latest_version($pagename);
365         if ($latestversion && $version == $latestversion) {
366             $backend->unlock();
367             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
368                                   $pagename), E_USER_ERROR);
369             return;
370         }
371
372         $cache->delete_versiondata($pagename, $version);
373                 
374         $backend->unlock();
375     }
376
377     /*
378      * Delete a revision, or possibly merge it with a previous
379      * revision.
380      *
381      * The idea is this:
382      * Suppose an author make a (major) edit to a page.  Shortly
383      * after that the same author makes a minor edit (e.g. to fix
384      * spelling mistakes he just made.)
385      *
386      * Now some time later, where cleaning out old saved revisions,
387      * and would like to delete his minor revision (since there's
388      * really no point in keeping minor revisions around for a long
389      * time.)
390      *
391      * Note that the text after the minor revision probably represents
392      * what the author intended to write better than the text after
393      * the preceding major edit.
394      *
395      * So what we really want to do is merge the minor edit with the
396      * preceding edit.
397      *
398      * We will only do this when:
399      * <ul>
400      * <li>The revision being deleted is a minor one, and
401      * <li>It has the same author as the immediately preceding revision.
402      * </ul>
403      */
404     function mergeRevision($version) {
405         $backend = &$this->_wikidb->_backend;
406         $cache = &$this->_wikidb->_cache;
407         $pagename = &$this->_pagename;
408
409         $version = $this->_coerce_to_version($version);
410         if ($version == 0)
411             return;
412
413         $backend->lock();
414         $latestversion = $backend->get_latest_version($pagename);
415         if ($latestversion && $version == $latestversion) {
416             $backend->unlock();
417             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
418                                   $pagename), E_USER_ERROR);
419             return;
420         }
421
422         $versiondata = $cache->get_versiondata($pagename, $version, true);
423         if (!$versiondata) {
424             // Not there? ... we're done!
425             $backend->unlock();
426             return;
427         }
428
429         if ($versiondata['is_minor_edit']) {
430             $previous = $backend->get_previous_version($pagename, $version);
431             if ($previous) {
432                 $prevdata = $cache->get_versiondata($pagename, $previous);
433                 if ($prevdata['author_id'] == $versiondata['author_id']) {
434                     // This is a minor revision, previous version is
435                     // by the same author. We will merge the
436                     // revisions.
437                     $cache->update_versiondata($pagename, $previous,
438                                                array('%content' => $versiondata['%content'],
439                                                      '_supplanted' => $versiondata['_supplanted']));
440                 }
441             }
442         }
443
444         $cache->delete_versiondata($pagename, $version);
445         $backend->unlock();
446     }
447
448     
449     /**
450      * Create a new revision of a WikiDB_Page.
451      *
452      * @access public
453      *
454      * @param $content string Contents of new revision.
455      *
456      * @param $metadata hash Metadata for new revision.
457      * All values in the hash should be scalars (strings or integers).
458      *
459      *
460      * @param $version int Version number for new revision.  
461      * To ensure proper serialization of edits, $version must be
462      * exactly one higher than the current latest version.
463      * (You can defeat this check by setting $version to
464      * WIKIDB_FORCE_CREATE --- not usually recommended.)
465      *
466      * @param $links array List of pagenames which this page links to.
467      *
468      * @return object Returns the new WikiDB_PageRevision object. If
469      * $version was incorrect, returns false
470      */
471     function createRevision($version, &$content, $metadata, $links) {
472         $backend = &$this->_wikidb->_backend;
473         $cache = &$this->_wikidb->_cache;
474         $pagename = &$this->_pagename;
475                 
476         $backend->lock();
477
478         $latestversion = $backend->get_latest_version($pagename);
479         $newversion = $latestversion + 1;
480         assert($newversion >= 1);
481
482         if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
483             $backend->unlock();
484             return false;
485         }
486
487         $data = $metadata;
488         
489         foreach ($data as $key => $val) {
490             if (empty($val) || $key[0] == '_' || $key[0] == '%')
491                 unset($data[$key]);
492         }
493                         
494         assert(!empty($data['author_id']));
495         if (empty($data['author_id']))
496             @$data['author_id'] = $data['author'];
497                 
498         if (empty($data['mtime']))
499             $data['mtime'] = time();
500
501         if ($latestversion) {
502             // Ensure mtimes are monotonic.
503             $pdata = $cache->get_versiondata($pagename, $latestversion);
504             if ($data['mtime'] < $pdata['mtime']) {
505                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
506                                       $pagename,"'non-monotonic'"),
507                               E_USER_NOTICE);
508                 $data['orig_mtime'] = $data['mtime'];
509                 $data['mtime'] = $pdata['mtime'];
510             }
511             
512             // FIXME: use (possibly user specified) 'mtime' time or
513             // time()?
514             $cache->update_versiondata($pagename, $latestversion,
515                                        array('_supplanted' => $data['mtime']));
516         }
517
518         $data['%content'] = &$content;
519
520         $cache->set_versiondata($pagename, $newversion, $data);
521
522         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
523         //':deleted' => empty($content)));
524         
525         $backend->set_links($pagename, $links);
526
527         $backend->unlock();
528
529         // FIXME: probably should have some global state information
530         // in the backend to control when to optimize.
531         if (time() % 50 == 0) {
532             trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
533             $backend->optimize();
534         }
535
536         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
537                                        $data);
538     }
539
540     /**
541      * Get the most recent revision of a page.
542      *
543      * @access public
544      *
545      * @return object The current WikiDB_PageRevision object. 
546      */
547     function getCurrentRevision() {
548         $backend = &$this->_wikidb->_backend;
549         $cache = &$this->_wikidb->_cache;
550         $pagename = &$this->_pagename;
551
552         $backend->lock();
553         $version = $cache->get_latest_version($pagename);
554         $revision = $this->getRevision($version);
555         $backend->unlock();
556         assert($revision);
557         return $revision;
558     }
559
560     /**
561      * Get a specific revision of a WikiDB_Page.
562      *
563      * @access public
564      *
565      * @param $version integer Which revision to get.
566      *
567      * @return object The requested WikiDB_PageRevision object, or
568      * false if the requested revision does not exist in the WikiDB.
569      * Note that version zero of any page always exists.
570      */
571     function getRevision($version) {
572         $cache = &$this->_wikidb->_cache;
573         $pagename = &$this->_pagename;
574         
575         if ($version == 0)
576             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
577
578         assert($version > 0);
579         $vdata = $cache->get_versiondata($pagename, $version);
580         if (!$vdata)
581             return false;
582         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
583                                        $vdata);
584     }
585
586     /**
587      * Get previous page revision.
588      *
589      * This method find the most recent revision before a specified
590      * version.
591      *
592      * @access public
593      *
594      * @param $version integer Find most recent revision before this version.
595      *  You can also use a WikiDB_PageRevision object to specify the $version.
596      *
597      * @return object The requested WikiDB_PageRevision object, or false if the
598      * requested revision does not exist in the WikiDB.  Note that
599      * unless $version is greater than zero, a revision (perhaps version zero,
600      * the default revision) will always be found.
601      */
602     function getRevisionBefore($version) {
603         $backend = &$this->_wikidb->_backend;
604         $pagename = &$this->_pagename;
605
606         $version = $this->_coerce_to_version($version);
607
608         if ($version == 0)
609             return false;
610         $backend->lock();
611         $previous = $backend->get_previous_version($pagename, $version);
612         $revision = $this->getRevision($previous);
613         $backend->unlock();
614         assert($revision);
615         return $revision;
616     }
617
618     /**
619      * Get all revisions of the WikiDB_Page.
620      *
621      * This does not include the version zero (default) revision in the
622      * returned revision set.
623      *
624      * @return object a WikiDB_PageRevisionIterator containing all
625      * revisions of this WikiDB_Page in reverse order by version
626      * number.
627      */
628     function getAllRevisions() {
629         $backend = &$this->_wikidb->_backend;
630         $revs = $backend->get_all_revisions($this->_pagename);
631         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
632     }
633     
634     /**
635      * Find pages which link to or are linked from a page.
636      *
637      * @access public
638      *
639      * @param $reversed enum Which links to find: true for backlinks (default).
640      *
641      * @return object A WikiDB_PageIterator containing all matching pages.
642      */
643     function getLinks($reversed = true) {
644         $backend = &$this->_wikidb->_backend;
645         $result =  $backend->get_links($this->_pagename, $reversed);
646         return new WikiDB_PageIterator($this->_wikidb, $result);
647     }
648             
649     /**
650      * Access WikiDB_Page meta-data.
651      *
652      * @access public
653      *
654      * @param $key string Which meta data to get.
655      * Some reserved meta-data keys are:
656      * <dl>
657      * <dt>'locked'<dd> Is page locked?
658      * <dt>'hits'  <dd> Page hit counter.
659      * <dt>'score  <dd> Page score (not yet implement, do we need?)
660      * </dl>
661      *
662      * @return scalar The requested value, or false if the requested data
663      * is not set.
664      */
665     function get($key) {
666         $cache = &$this->_wikidb->_cache;
667         if (!$key || $key[0] == '%')
668             return false;
669         $data = $cache->get_pagedata($this->_pagename);
670         return isset($data[$key]) ? $data[$key] : false;
671     }
672
673     /**
674      * Get all the page meta-data as a hash.
675      *
676      * @return hash The page meta-data.
677      */
678     function getMetaData() {
679         $cache = &$this->_wikidb->_cache;
680         $data = $cache->get_pagedata($this->_pagename);
681         $meta = array();
682         foreach ($data as $key => $val) {
683             if (!empty($val) && $key[0] != '%')
684                 $meta[$key] = $val;
685         }
686         return $meta;
687     }
688
689     /**
690      * Set page meta-data.
691      *
692      * @see get
693      * @access public
694      *
695      * @param $key string Meta-data key to set.
696      * @param $newval string New value.
697      */
698     function set($key, $newval) {
699         $cache = &$this->_wikidb->_cache;
700         $pagename = &$this->_pagename;
701         
702         assert($key && $key[0] != '%');
703
704         $data = $cache->get_pagedata($pagename);
705
706         if (!empty($newval)) {
707             if (!empty($data[$key]) && $data[$key] == $newval)
708                 return;         // values identical, skip update.
709         }
710         else {
711             if (empty($data[$key]))
712                 return;         // values identical, skip update.
713         }
714
715         $cache->update_pagedata($pagename, array($key => $newval));
716     }
717
718     /**
719      * Increase page hit count.
720      *
721      * FIXME: IS this needed?  Probably not.
722      *
723      * This is a convenience function.
724      * <pre> $page->increaseHitCount(); </pre>
725      * is functionally identical to
726      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
727      *
728      * Note that this method may be implemented in more efficient ways
729      * in certain backends.
730      *
731      * @access public
732      */
733     function increaseHitCount() {
734         @$newhits = $this->get('hits') + 1;
735         $this->set('hits', $newhits);
736     }
737
738     /**
739      * Return a string representation of the WikiDB_Page
740      *
741      * This is really only for debugging.
742      *
743      * @access public
744      *
745      * @return string Printable representation of the WikiDB_Page.
746      */
747     function asString () {
748         ob_start();
749         printf("[%s:%s\n", get_class($this), $this->getName());
750         print_r($this->getMetaData());
751         echo "]\n";
752         $strval = ob_get_contents();
753         ob_end_clean();
754         return $strval;
755     }
756
757
758     /**
759      * @access private
760      * @param $version_or_pagerevision int or object
761      * Takes either the version number (and int) or a WikiDB_PageRevision
762      * object.
763      * @return int The version number.
764      */
765     function _coerce_to_version($version_or_pagerevision) {
766         if (method_exists($version_or_pagerevision, "getContent"))
767             $version = $version_or_pagerevision->getVersion();
768         else
769             $version = (int) $version_or_pagerevision;
770
771         assert($version >= 0);
772         return $version;
773     }
774 };
775
776 /**
777  * This class represents a specific revision of a WikiDB_Page within
778  * a WikiDB.
779  *
780  * A WikiDB_PageRevision has read-only semantics. You may only create
781  * new revisions (and delete old ones) --- you cannot modify existing
782  * revisions.
783  */
784 class WikiDB_PageRevision
785 {
786     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
787                                  $versiondata = false)
788         {
789             $this->_wikidb = &$wikidb;
790             $this->_pagename = $pagename;
791             $this->_version = $version;
792             $this->_data = $versiondata ? $versiondata : array();
793         }
794     
795     /**
796      * Get the WikiDB_Page which this revision belongs to.
797      *
798      * @access public
799      *
800      * @return object The WikiDB_Page which this revision belongs to.
801      */
802     function getPage() {
803         return new WikiDB_Page($this->_wikidb, $this->_pagename);
804     }
805
806     /**
807      * Get the version number of this revision.
808      *
809      * @access public
810      *
811      * @return int The version number of this revision.
812      */
813     function getVersion() {
814         return $this->_version;
815     }
816     
817     /**
818      * Determine whether this revision has defaulted content.
819      *
820      * The default revision (version 0) of each page, as well as any
821      * pages which are created with empty content have their content
822      * defaulted to something like:
823      * <pre>
824      *   Describe [ThisPage] here.
825      * </pre>
826      *
827      * @access public
828      *
829      * @return boolean Returns true if the page has default content.
830      */
831     function hasDefaultContents() {
832         $data = &$this->_data;
833         return empty($data['%content']);
834     }
835
836     /**
837      * Get the content as an array of lines.
838      *
839      * @access public
840      *
841      * @return array An array of lines.
842      * The lines should contain no trailing white space.
843      */
844     function getContent() {
845         return explode("\n", $this->getPackedContent());
846     }
847
848     /**
849      * Determine whether revision is the latest.
850      *
851      * @access public
852      *
853      * @return bool True iff the revision is the latest (most recent) one.
854      */
855     function isCurrent() {
856         if (!isset($this->_iscurrent)) {
857             $page = $this->getPage();
858             $current = $page->getCurrentRevision();
859             $this->_iscurrent = $this->getVersion() == $current->getVersion();
860         }
861         return $this->_iscurrent;
862     }
863     
864     /**
865      * Get the content as a string.
866      *
867      * @access public
868      *
869      * @return string The page content.
870      * Lines are separated by new-lines.
871      */
872     function getPackedContent() {
873         $data = &$this->_data;
874
875         
876         if (empty($data['%content'])) {
877             // Replace empty content with default value.
878             return sprintf(_("Describe %s here."),
879                            "[". $this->_pagename ."]");
880         }
881
882         // There is (non-default) content.
883         assert($this->_version > 0);
884         
885         if (!is_string($data['%content'])) {
886             // Content was not provided to us at init time.
887             // (This is allowed because for some backends, fetching
888             // the content may be expensive, and often is not wanted
889             // by the user.)
890             //
891             // In any case, now we need to get it.
892             $data['%content'] = $this->_get_content();
893             assert(is_string($data['%content']));
894         }
895         
896         return $data['%content'];
897     }
898
899     function _get_content() {
900         $cache = &$this->_wikidb->_cache;
901         $pagename = $this->_pagename;
902         $version = $this->_version;
903
904         assert($version > 0);
905         
906         $newdata = $cache->get_versiondata($pagename, $version, true);
907         if ($newdata) {
908             assert(is_string($newdata['%content']));
909             return $newdata['%content'];
910         }
911         else {
912             // else revision has been deleted... What to do?
913             return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
914                              $version, $pagename);
915         }
916     }
917
918     /**
919      * Get meta-data for this revision.
920      *
921      *
922      * @access public
923      *
924      * @param $key string Which meta-data to access.
925      *
926      * Some reserved revision meta-data keys are:
927      * <dl>
928      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
929      *        The 'mtime' meta-value is normally set automatically by the database
930      *        backend, but it may be specified explicitly when creating a new revision.
931      * <dt> orig_mtime
932      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
933      *       of a page must be monotonically increasing.  If an attempt is
934      *       made to create a new revision with an mtime less than that of
935      *       the preceeding revision, the new revisions timestamp is force
936      *       to be equal to that of the preceeding revision.  In that case,
937      *       the originally requested mtime is preserved in 'orig_mtime'.
938      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
939      *        This meta-value is <em>always</em> automatically maintained by the database
940      *        backend.  (It is set from the 'mtime' meta-value of the superceding
941      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
942      *
943      * FIXME: this could be refactored:
944      * <dt> author
945      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
946      * <dt> author_id
947      *  <dd> Authenticated author of a page.  This is used to identify
948      *       the distinctness of authors when cleaning old revisions from
949      *       the database.
950      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
951      * <dt> 'summary' <dd> Short change summary entered by page author.
952      * </dl>
953      *
954      * Meta-data keys must be valid C identifers (they have to start with a letter
955      * or underscore, and can contain only alphanumerics and underscores.)
956      *
957      * @return string The requested value, or false if the requested value
958      * is not defined.
959      */
960     function get($key) {
961         if (!$key || $key[0] == '%')
962             return false;
963         $data = &$this->_data;
964         return isset($data[$key]) ? $data[$key] : false;
965     }
966
967     /**
968      * Get all the revision page meta-data as a hash.
969      *
970      * @return hash The revision meta-data.
971      */
972     function getMetaData() {
973         $meta = array();
974         foreach ($this->_data as $key => $val) {
975             if (!empty($val) && $key[0] != '%')
976                 $meta[$key] = $val;
977         }
978         return $meta;
979     }
980     
981             
982     /**
983      * Return a string representation of the revision.
984      *
985      * This is really only for debugging.
986      *
987      * @access public
988      *
989      * @return string Printable representation of the WikiDB_Page.
990      */
991     function asString () {
992         ob_start();
993         printf("[%s:%d\n", get_class($this), $this->get('version'));
994         print_r($this->_data);
995         echo $this->getPackedContent() . "\n]\n";
996         $strval = ob_get_contents();
997         ob_end_clean();
998         return $strval;
999     }
1000 };
1001
1002
1003 /**
1004  * A class which represents a sequence of WikiDB_Pages.
1005  */
1006 class WikiDB_PageIterator
1007 {
1008     function WikiDB_PageIterator(&$wikidb, &$pages) {
1009         $this->_pages = $pages;
1010         $this->_wikidb = &$wikidb;
1011     }
1012     
1013     /**
1014      * Get next WikiDB_Page in sequence.
1015      *
1016      * @access public
1017      *
1018      * @return object The next WikiDB_Page in the sequence.
1019      */
1020     function next () {
1021         if ( ! ($next = $this->_pages->next()) )
1022             return false;
1023
1024         $pagename = &$next['pagename'];
1025         if (isset($next['pagedata']))
1026             $this->_wikidb->_cache->cache_data($next);
1027
1028         return new WikiDB_Page($this->_wikidb, $pagename);
1029     }
1030
1031     /**
1032      * Release resources held by this iterator.
1033      *
1034      * The iterator may not be used after free() is called.
1035      *
1036      * There is no need to call free(), if next() has returned false.
1037      * (I.e. if you iterate through all the pages in the sequence,
1038      * you do not need to call free() --- you only need to call it
1039      * if you stop before the end of the iterator is reached.)
1040      *
1041      * @access public
1042      */
1043     function free() {
1044         $this->_pages->free();
1045     }
1046 };
1047
1048 /**
1049  * A class which represents a sequence of WikiDB_PageRevisions.
1050  */
1051 class WikiDB_PageRevisionIterator
1052 {
1053     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1054         $this->_revisions = $revisions;
1055         $this->_wikidb = &$wikidb;
1056     }
1057     
1058     /**
1059      * Get next WikiDB_PageRevision in sequence.
1060      *
1061      * @access public
1062      *
1063      * @return object The next WikiDB_PageRevision in the sequence.
1064      */
1065     function next () {
1066         if ( ! ($next = $this->_revisions->next()) )
1067             return false;
1068
1069         $this->_wikidb->_cache->cache_data($next);
1070
1071         $pagename = $next['pagename'];
1072         $version = $next['version'];
1073         $versiondata = $next['versiondata'];
1074         assert(!empty($pagename));
1075         assert(is_array($versiondata));
1076         assert($version > 0);
1077
1078         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1079                                        $versiondata);
1080     }
1081
1082     /**
1083      * Release resources held by this iterator.
1084      *
1085      * The iterator may not be used after free() is called.
1086      *
1087      * There is no need to call free(), if next() has returned false.
1088      * (I.e. if you iterate through all the revisions in the sequence,
1089      * you do not need to call free() --- you only need to call it
1090      * if you stop before the end of the iterator is reached.)
1091      *
1092      * @access public
1093      */
1094     function free() { 
1095         $this->_revisions->free();
1096     }
1097 };
1098
1099
1100 /**
1101  * Data cache used by WikiDB.
1102  *
1103  * FIXME: Maybe rename this to caching_backend (or some such).
1104  *
1105  * @access protected
1106  */
1107 class WikiDB_cache 
1108 {
1109     // FIXME: beautify versiondata cache.  Cache only limited data?
1110
1111     function WikiDB_cache (&$backend) {
1112         $this->_backend = &$backend;
1113
1114         $this->_pagedata_cache = array();
1115                 $this->_versiondata_cache = array();
1116                 array_push ($this->_versiondata_cache, array());
1117                 $this->_glv_cache = array();
1118     }
1119     
1120     function close() {
1121         $this->_pagedata_cache = false;
1122                 $this->_versiondata_cache = false;
1123                 $this->_glv_cache = false;
1124     }
1125
1126     function get_pagedata($pagename) {
1127         assert(is_string($pagename) && $pagename);
1128         $cache = &$this->_pagedata_cache;
1129
1130         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1131             $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1132             if (empty($cache[$pagename]))
1133                 $cache[$pagename] = array();
1134         }
1135
1136         return $cache[$pagename];
1137     }
1138     
1139     function update_pagedata($pagename, $newdata) {
1140         assert(is_string($pagename) && $pagename);
1141
1142         $this->_backend->update_pagedata($pagename, $newdata);
1143
1144         if (is_array($this->_pagedata_cache[$pagename])) {
1145             $cachedata = &$this->_pagedata_cache[$pagename];
1146             foreach($newdata as $key => $val)
1147                 $cachedata[$key] = $val;
1148         }
1149     }
1150
1151     function invalidate_cache($pagename) {
1152         $this->_pagedata_cache[$pagename] = false;
1153                 $this->_versiondata_cache[$pagename] = false;
1154                 $this->_glv_cache[$pagename] = false;
1155     }
1156     
1157     function delete_page($pagename) {
1158         $this->_backend->delete_page($pagename);
1159         $this->_pagedata_cache[$pagename] = false;
1160                 $this->_glv_cache[$pagename] = false;
1161     }
1162
1163     // FIXME: ugly
1164     function cache_data($data) {
1165         if (isset($data['pagedata']))
1166             $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1167     }
1168     
1169     function get_versiondata($pagename, $version, $need_content = false) {
1170                 //  FIXME: Seriously ugly hackage
1171         if (defined ('USECACHE')){   //temporary - for debugging
1172         assert(is_string($pagename) && $pagename);
1173                 $nc = $need_content ? '1':'0';
1174         $cache = &$this->_versiondata_cache;
1175         if (!isset($cache[$pagename][$version][$nc])||
1176                                 !(is_array ($cache[$pagename])) && is_array ($cache[$pagename][$version])) {
1177             $cache[$pagename][$version][$nc] = 
1178                                 $this->_backend->get_versiondata($pagename,$version, $need_content);
1179                         }
1180                 
1181         $vdata = $cache[$pagename][$version][$nc];
1182         }
1183         else
1184         {
1185     $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1186         }
1187         // FIXME: ugly
1188         if ($vdata && !empty($vdata['%pagedata']))
1189             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1190         return $vdata;
1191     }
1192
1193     function set_versiondata($pagename, $version, $data) {
1194         $new = $this->_backend->
1195              set_versiondata($pagename, $version, $data);
1196                 // Update the cache
1197                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1198                 
1199     }
1200
1201     function update_versiondata($pagename, $version, $data) {
1202         $new = $this->_backend->
1203              update_versiondata($pagename, $version, $data);
1204                 // Update the cache
1205                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1206     }
1207
1208     function delete_versiondata($pagename, $version) {
1209         $new = $this->_backend->
1210              delete_versiondata($pagename, $version);
1211                 $this->_versiondata_cache[$pagename][(string)$version] = false;
1212                 // No need to delete entry from _glv_cache because most recent version is not deleted
1213     }
1214         
1215         function get_latest_version($pagename)  {
1216         if(defined('USECACHE')){
1217                 assert (is_string($pagename) && $pagename);
1218         $cache = &$this->_glv_cache;    
1219         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1220             $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1221             if (empty($cache[$pagename]))
1222                 $cache[$pagename] = 0;
1223         }
1224
1225         return $cache[$pagename];}
1226         else {
1227                 return $this->_backend->get_latest_version($pagename); 
1228                 }
1229         }
1230         
1231 };
1232
1233 // Local Variables:
1234 // mode: php
1235 // tab-width: 8
1236 // c-basic-offset: 4
1237 // c-hanging-comment-ender-p: nil
1238 // indent-tabs-mode: nil
1239 // End:   
1240 ?>