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