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