]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
first rough versions of new plugins:
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.16 2002-09-01 16:33:18 rurban 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      * Blog search. (experimental)
318      *
319      * Search for blog entries related to a certain page.
320      *
321      * FIXME: with pagetype support and perhaps a RegexpSearchQuery
322      * we can make sure we are returning *ONLY* blog pages to the
323      * main routine.  Currently, we just use titleSearch which requires
324      * some furher checking in lib/plugin/WikiBlog.php (BAD).
325      *
326      * @access public
327      *
328      * @param $order   string  'normal' (chronological) or 'reverse'
329      * @param $page    string  Find blog entries related to this page.
330      * @return object A WikiDB_PageIterator containing the relevant pages.
331      */
332     function blogSearch($page, $order) {
333       //FIXME: implement ordering
334
335       require_once('lib/TextSearchQuery.php');
336       $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
337
338       return $this->titleSearch($query);
339     }
340
341 };
342
343
344 /**
345  * An abstract base class which representing a wiki-page within a
346  * WikiDB.
347  *
348  * A WikiDB_Page contains a number (at least one) of
349  * WikiDB_PageRevisions.
350  */
351 class WikiDB_Page 
352 {
353     function WikiDB_Page(&$wikidb, $pagename) {
354         $this->_wikidb = &$wikidb;
355         $this->_pagename = $pagename;
356         assert(!empty($this->_pagename));
357     }
358
359     /**
360      * Get the name of the wiki page.
361      *
362      * @access public
363      *
364      * @return string The page name.
365      */
366     function getName() {
367         return $this->_pagename;
368     }
369
370
371     /**
372      * Delete an old revision of a WikiDB_Page.
373      *
374      * Deletes the specified revision of the page.
375      * It is a fatal error to attempt to delete the current revision.
376      *
377      * @access public
378      *
379      * @param $version integer Which revision to delete.  (You can also
380      *  use a WikiDB_PageRevision object here.)
381      */
382     function deleteRevision($version) {
383         $backend = &$this->_wikidb->_backend;
384         $cache = &$this->_wikidb->_cache;
385         $pagename = &$this->_pagename;
386
387         $version = $this->_coerce_to_version($version);
388         if ($version == 0)
389             return;
390
391         $backend->lock();
392         $latestversion = $cache->get_latest_version($pagename);
393         if ($latestversion && $version == $latestversion) {
394             $backend->unlock();
395             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
396                                   $pagename), E_USER_ERROR);
397             return;
398         }
399
400         $cache->delete_versiondata($pagename, $version);
401                 
402         $backend->unlock();
403     }
404
405     /*
406      * Delete a revision, or possibly merge it with a previous
407      * revision.
408      *
409      * The idea is this:
410      * Suppose an author make a (major) edit to a page.  Shortly
411      * after that the same author makes a minor edit (e.g. to fix
412      * spelling mistakes he just made.)
413      *
414      * Now some time later, where cleaning out old saved revisions,
415      * and would like to delete his minor revision (since there's
416      * really no point in keeping minor revisions around for a long
417      * time.)
418      *
419      * Note that the text after the minor revision probably represents
420      * what the author intended to write better than the text after
421      * the preceding major edit.
422      *
423      * So what we really want to do is merge the minor edit with the
424      * preceding edit.
425      *
426      * We will only do this when:
427      * <ul>
428      * <li>The revision being deleted is a minor one, and
429      * <li>It has the same author as the immediately preceding revision.
430      * </ul>
431      */
432     function mergeRevision($version) {
433         $backend = &$this->_wikidb->_backend;
434         $cache = &$this->_wikidb->_cache;
435         $pagename = &$this->_pagename;
436
437         $version = $this->_coerce_to_version($version);
438         if ($version == 0)
439             return;
440
441         $backend->lock();
442         $latestversion = $backend->get_latest_version($pagename);
443         if ($latestversion && $version == $latestversion) {
444             $backend->unlock();
445             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
446                                   $pagename), E_USER_ERROR);
447             return;
448         }
449
450         $versiondata = $cache->get_versiondata($pagename, $version, true);
451         if (!$versiondata) {
452             // Not there? ... we're done!
453             $backend->unlock();
454             return;
455         }
456
457         if ($versiondata['is_minor_edit']) {
458             $previous = $backend->get_previous_version($pagename, $version);
459             if ($previous) {
460                 $prevdata = $cache->get_versiondata($pagename, $previous);
461                 if ($prevdata['author_id'] == $versiondata['author_id']) {
462                     // This is a minor revision, previous version is
463                     // by the same author. We will merge the
464                     // revisions.
465                     $cache->update_versiondata($pagename, $previous,
466                                                array('%content' => $versiondata['%content'],
467                                                      '_supplanted' => $versiondata['_supplanted']));
468                 }
469             }
470         }
471
472         $cache->delete_versiondata($pagename, $version);
473         $backend->unlock();
474     }
475
476     
477     /**
478      * Create a new revision of a WikiDB_Page.
479      *
480      * @access public
481      *
482      * @param $content string Contents of new revision.
483      *
484      * @param $metadata hash Metadata for new revision.
485      * All values in the hash should be scalars (strings or integers).
486      *
487      *
488      * @param $version int Version number for new revision.  
489      * To ensure proper serialization of edits, $version must be
490      * exactly one higher than the current latest version.
491      * (You can defeat this check by setting $version to
492      * WIKIDB_FORCE_CREATE --- not usually recommended.)
493      *
494      * @param $links array List of pagenames which this page links to.
495      *
496      * @return object Returns the new WikiDB_PageRevision object. If
497      * $version was incorrect, returns false
498      */
499     function createRevision($version, &$content, $metadata, $links) {
500         $backend = &$this->_wikidb->_backend;
501         $cache = &$this->_wikidb->_cache;
502         $pagename = &$this->_pagename;
503                 
504         $backend->lock();
505
506         $latestversion = $backend->get_latest_version($pagename);
507         $newversion = $latestversion + 1;
508         assert($newversion >= 1);
509
510         if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
511             $backend->unlock();
512             return false;
513         }
514
515         $data = $metadata;
516         
517         foreach ($data as $key => $val) {
518             if (empty($val) || $key[0] == '_' || $key[0] == '%')
519                 unset($data[$key]);
520         }
521                         
522         assert(!empty($data['author_id']));
523         if (empty($data['author_id']))
524             @$data['author_id'] = $data['author'];
525                 
526         if (empty($data['mtime']))
527             $data['mtime'] = time();
528
529         if ($latestversion) {
530             // Ensure mtimes are monotonic.
531             $pdata = $cache->get_versiondata($pagename, $latestversion);
532             if ($data['mtime'] < $pdata['mtime']) {
533                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
534                                       $pagename,"'non-monotonic'"),
535                               E_USER_NOTICE);
536                 $data['orig_mtime'] = $data['mtime'];
537                 $data['mtime'] = $pdata['mtime'];
538             }
539             
540             // FIXME: use (possibly user specified) 'mtime' time or
541             // time()?
542             $cache->update_versiondata($pagename, $latestversion,
543                                        array('_supplanted' => $data['mtime']));
544         }
545
546         $data['%content'] = &$content;
547
548         $cache->set_versiondata($pagename, $newversion, $data);
549
550         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
551         //':deleted' => empty($content)));
552         
553         $backend->set_links($pagename, $links);
554
555         $backend->unlock();
556
557         // FIXME: probably should have some global state information
558         // in the backend to control when to optimize.
559         if (time() % 50 == 0) {
560             trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
561             $backend->optimize();
562         }
563
564         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
565                                        $data);
566     }
567
568     /**
569      * Get the most recent revision of a page.
570      *
571      * @access public
572      *
573      * @return object The current WikiDB_PageRevision object. 
574      */
575     function getCurrentRevision() {
576         $backend = &$this->_wikidb->_backend;
577         $cache = &$this->_wikidb->_cache;
578         $pagename = &$this->_pagename;
579
580         $backend->lock();
581         $version = $cache->get_latest_version($pagename);
582         $revision = $this->getRevision($version);
583         $backend->unlock();
584         assert($revision);
585         return $revision;
586     }
587
588     /**
589      * Get a specific revision of a WikiDB_Page.
590      *
591      * @access public
592      *
593      * @param $version integer Which revision to get.
594      *
595      * @return object The requested WikiDB_PageRevision object, or
596      * false if the requested revision does not exist in the WikiDB.
597      * Note that version zero of any page always exists.
598      */
599     function getRevision($version) {
600         $cache = &$this->_wikidb->_cache;
601         $pagename = &$this->_pagename;
602         
603         if ($version == 0)
604             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
605
606         assert($version > 0);
607         $vdata = $cache->get_versiondata($pagename, $version);
608         if (!$vdata)
609             return false;
610         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
611                                        $vdata);
612     }
613
614     /**
615      * Get previous page revision.
616      *
617      * This method find the most recent revision before a specified
618      * version.
619      *
620      * @access public
621      *
622      * @param $version integer Find most recent revision before this version.
623      *  You can also use a WikiDB_PageRevision object to specify the $version.
624      *
625      * @return object The requested WikiDB_PageRevision object, or false if the
626      * requested revision does not exist in the WikiDB.  Note that
627      * unless $version is greater than zero, a revision (perhaps version zero,
628      * the default revision) will always be found.
629      */
630     function getRevisionBefore($version) {
631         $backend = &$this->_wikidb->_backend;
632         $pagename = &$this->_pagename;
633
634         $version = $this->_coerce_to_version($version);
635
636         if ($version == 0)
637             return false;
638         $backend->lock();
639         $previous = $backend->get_previous_version($pagename, $version);
640         $revision = $this->getRevision($previous);
641         $backend->unlock();
642         assert($revision);
643         return $revision;
644     }
645
646     /**
647      * Get all revisions of the WikiDB_Page.
648      *
649      * This does not include the version zero (default) revision in the
650      * returned revision set.
651      *
652      * @return object a WikiDB_PageRevisionIterator containing all
653      * revisions of this WikiDB_Page in reverse order by version
654      * number.
655      */
656     function getAllRevisions() {
657         $backend = &$this->_wikidb->_backend;
658         $revs = $backend->get_all_revisions($this->_pagename);
659         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
660     }
661     
662     /**
663      * Find pages which link to or are linked from a page.
664      *
665      * @access public
666      *
667      * @param $reversed enum Which links to find: true for backlinks (default).
668      *
669      * @return object A WikiDB_PageIterator containing all matching pages.
670      */
671     function getLinks($reversed = true) {
672         $backend = &$this->_wikidb->_backend;
673         $result =  $backend->get_links($this->_pagename, $reversed);
674         return new WikiDB_PageIterator($this->_wikidb, $result);
675     }
676             
677     /**
678      * Access WikiDB_Page meta-data.
679      *
680      * @access public
681      *
682      * @param $key string Which meta data to get.
683      * Some reserved meta-data keys are:
684      * <dl>
685      * <dt>'locked'<dd> Is page locked?
686      * <dt>'hits'  <dd> Page hit counter.
687      * <dt>'pref'  <dd> Users preferences, stored in homepages.
688      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
689      *                  E.g. "owner.users"
690      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
691      *                  page-headers and content.
692      * <dt>'score' <dd> Page score (not yet implement, do we need?)
693      * </dl>
694      *
695      * @return scalar The requested value, or false if the requested data
696      * is not set.
697      */
698     function get($key) {
699         $cache = &$this->_wikidb->_cache;
700         if (!$key || $key[0] == '%')
701             return false;
702         $data = $cache->get_pagedata($this->_pagename);
703         return isset($data[$key]) ? $data[$key] : false;
704     }
705
706     /**
707      * Get all the page meta-data as a hash.
708      *
709      * @return hash The page meta-data.
710      */
711     function getMetaData() {
712         $cache = &$this->_wikidb->_cache;
713         $data = $cache->get_pagedata($this->_pagename);
714         $meta = array();
715         foreach ($data as $key => $val) {
716             if (!empty($val) && $key[0] != '%')
717                 $meta[$key] = $val;
718         }
719         return $meta;
720     }
721
722     /**
723      * Set page meta-data.
724      *
725      * @see get
726      * @access public
727      *
728      * @param $key string Meta-data key to set.
729      * @param $newval string New value.
730      */
731     function set($key, $newval) {
732         $cache = &$this->_wikidb->_cache;
733         $pagename = &$this->_pagename;
734         
735         assert($key && $key[0] != '%');
736
737         $data = $cache->get_pagedata($pagename);
738
739         if (!empty($newval)) {
740             if (!empty($data[$key]) && $data[$key] == $newval)
741                 return;         // values identical, skip update.
742         }
743         else {
744             if (empty($data[$key]))
745                 return;         // values identical, skip update.
746         }
747
748         // special handling of sensitive pref data or upgrades from older versions:
749         if ($key == 'pref') {
750             if (!empty($newval['userid'])) unset($newval['userid']);
751             //if ($GLOBALS['user']->isAdmin()) unset($newval['passwd']);
752         }
753         $cache->update_pagedata($pagename, array($key => $newval));
754     }
755
756     /**
757      * Increase page hit count.
758      *
759      * FIXME: IS this needed?  Probably not.
760      *
761      * This is a convenience function.
762      * <pre> $page->increaseHitCount(); </pre>
763      * is functionally identical to
764      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
765      *
766      * Note that this method may be implemented in more efficient ways
767      * in certain backends.
768      *
769      * @access public
770      */
771     function increaseHitCount() {
772         @$newhits = $this->get('hits') + 1;
773         $this->set('hits', $newhits);
774     }
775
776     /**
777      * Return a string representation of the WikiDB_Page
778      *
779      * This is really only for debugging.
780      *
781      * @access public
782      *
783      * @return string Printable representation of the WikiDB_Page.
784      */
785     function asString () {
786         ob_start();
787         printf("[%s:%s\n", get_class($this), $this->getName());
788         print_r($this->getMetaData());
789         echo "]\n";
790         $strval = ob_get_contents();
791         ob_end_clean();
792         return $strval;
793     }
794
795
796     /**
797      * @access private
798      * @param $version_or_pagerevision int or object
799      * Takes either the version number (and int) or a WikiDB_PageRevision
800      * object.
801      * @return int The version number.
802      */
803     function _coerce_to_version($version_or_pagerevision) {
804         if (method_exists($version_or_pagerevision, "getContent"))
805             $version = $version_or_pagerevision->getVersion();
806         else
807             $version = (int) $version_or_pagerevision;
808
809         assert($version >= 0);
810         return $version;
811     }
812
813     function isUserPage ($include_empty = true) {
814         return $this->get('pref') ? true : false;
815         if ($include_empty)
816             return true;
817         $current = $this->getCurrentRevision();
818         return ! $current->hasDefaultContents();
819     }
820
821 };
822
823 /**
824  * This class represents a specific revision of a WikiDB_Page within
825  * a WikiDB.
826  *
827  * A WikiDB_PageRevision has read-only semantics. You may only create
828  * new revisions (and delete old ones) --- you cannot modify existing
829  * revisions.
830  */
831 class WikiDB_PageRevision
832 {
833     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
834                                  $versiondata = false)
835         {
836             $this->_wikidb = &$wikidb;
837             $this->_pagename = $pagename;
838             $this->_version = $version;
839             $this->_data = $versiondata ? $versiondata : array();
840         }
841     
842     /**
843      * Get the WikiDB_Page which this revision belongs to.
844      *
845      * @access public
846      *
847      * @return object The WikiDB_Page which this revision belongs to.
848      */
849     function getPage() {
850         return new WikiDB_Page($this->_wikidb, $this->_pagename);
851     }
852
853     /**
854      * Get the version number of this revision.
855      *
856      * @access public
857      *
858      * @return int The version number of this revision.
859      */
860     function getVersion() {
861         return $this->_version;
862     }
863     
864     /**
865      * Determine whether this revision has defaulted content.
866      *
867      * The default revision (version 0) of each page, as well as any
868      * pages which are created with empty content have their content
869      * defaulted to something like:
870      * <pre>
871      *   Describe [ThisPage] here.
872      * </pre>
873      *
874      * @access public
875      *
876      * @return boolean Returns true if the page has default content.
877      */
878     function hasDefaultContents() {
879         $data = &$this->_data;
880         return empty($data['%content']);
881     }
882
883     /**
884      * Get the content as an array of lines.
885      *
886      * @access public
887      *
888      * @return array An array of lines.
889      * The lines should contain no trailing white space.
890      */
891     function getContent() {
892         return explode("\n", $this->getPackedContent());
893     }
894         
895         /**
896      * Get the pagename of the revision.
897      *
898      * @access public
899      *
900      * @return string pagename.
901      */
902     function getPageName() {
903         return $this->_pagename;
904     }
905
906     /**
907      * Determine whether revision is the latest.
908      *
909      * @access public
910      *
911      * @return bool True iff the revision is the latest (most recent) one.
912      */
913     function isCurrent() {
914         if (!isset($this->_iscurrent)) {
915             $page = $this->getPage();
916             $current = $page->getCurrentRevision();
917             $this->_iscurrent = $this->getVersion() == $current->getVersion();
918         }
919         return $this->_iscurrent;
920     }
921     
922     /**
923      * Get the content as a string.
924      *
925      * @access public
926      *
927      * @return string The page content.
928      * Lines are separated by new-lines.
929      */
930     function getPackedContent() {
931         $data = &$this->_data;
932
933         
934         if (empty($data['%content'])) {
935             // Replace empty content with default value.
936             return sprintf(_("Describe %s here."),
937                            "[". $this->_pagename ."]");
938         }
939
940         // There is (non-default) content.
941         assert($this->_version > 0);
942         
943         if (!is_string($data['%content'])) {
944             // Content was not provided to us at init time.
945             // (This is allowed because for some backends, fetching
946             // the content may be expensive, and often is not wanted
947             // by the user.)
948             //
949             // In any case, now we need to get it.
950             $data['%content'] = $this->_get_content();
951             assert(is_string($data['%content']));
952         }
953         
954         return $data['%content'];
955     }
956
957     function _get_content() {
958         $cache = &$this->_wikidb->_cache;
959         $pagename = $this->_pagename;
960         $version = $this->_version;
961
962         assert($version > 0);
963         
964         $newdata = $cache->get_versiondata($pagename, $version, true);
965         if ($newdata) {
966             assert(is_string($newdata['%content']));
967             return $newdata['%content'];
968         }
969         else {
970             // else revision has been deleted... What to do?
971             return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
972                              $version, $pagename);
973         }
974     }
975
976     /**
977      * Get meta-data for this revision.
978      *
979      *
980      * @access public
981      *
982      * @param $key string Which meta-data to access.
983      *
984      * Some reserved revision meta-data keys are:
985      * <dl>
986      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
987      *        The 'mtime' meta-value is normally set automatically by the database
988      *        backend, but it may be specified explicitly when creating a new revision.
989      * <dt> orig_mtime
990      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
991      *       of a page must be monotonically increasing.  If an attempt is
992      *       made to create a new revision with an mtime less than that of
993      *       the preceeding revision, the new revisions timestamp is force
994      *       to be equal to that of the preceeding revision.  In that case,
995      *       the originally requested mtime is preserved in 'orig_mtime'.
996      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
997      *        This meta-value is <em>always</em> automatically maintained by the database
998      *        backend.  (It is set from the 'mtime' meta-value of the superceding
999      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1000      *
1001      * FIXME: this could be refactored:
1002      * <dt> author
1003      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1004      * <dt> author_id
1005      *  <dd> Authenticated author of a page.  This is used to identify
1006      *       the distinctness of authors when cleaning old revisions from
1007      *       the database.
1008      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1009      * <dt> 'summary' <dd> Short change summary entered by page author.
1010      * </dl>
1011      *
1012      * Meta-data keys must be valid C identifers (they have to start with a letter
1013      * or underscore, and can contain only alphanumerics and underscores.)
1014      *
1015      * @return string The requested value, or false if the requested value
1016      * is not defined.
1017      */
1018     function get($key) {
1019         if (!$key || $key[0] == '%')
1020             return false;
1021         $data = &$this->_data;
1022         return isset($data[$key]) ? $data[$key] : false;
1023     }
1024
1025     /**
1026      * Get all the revision page meta-data as a hash.
1027      *
1028      * @return hash The revision meta-data.
1029      */
1030     function getMetaData() {
1031         $meta = array();
1032         foreach ($this->_data as $key => $val) {
1033             if (!empty($val) && $key[0] != '%')
1034                 $meta[$key] = $val;
1035         }
1036         return $meta;
1037     }
1038     
1039             
1040     /**
1041      * Return a string representation of the revision.
1042      *
1043      * This is really only for debugging.
1044      *
1045      * @access public
1046      *
1047      * @return string Printable representation of the WikiDB_Page.
1048      */
1049     function asString () {
1050         ob_start();
1051         printf("[%s:%d\n", get_class($this), $this->get('version'));
1052         print_r($this->_data);
1053         echo $this->getPackedContent() . "\n]\n";
1054         $strval = ob_get_contents();
1055         ob_end_clean();
1056         return $strval;
1057     }
1058 };
1059
1060
1061 /**
1062  * A class which represents a sequence of WikiDB_Pages.
1063  */
1064 class WikiDB_PageIterator
1065 {
1066     function WikiDB_PageIterator(&$wikidb, &$pages) {
1067         $this->_pages = $pages;
1068         $this->_wikidb = &$wikidb;
1069     }
1070     
1071     /**
1072      * Get next WikiDB_Page in sequence.
1073      *
1074      * @access public
1075      *
1076      * @return object The next WikiDB_Page in the sequence.
1077      */
1078     function next () {
1079         if ( ! ($next = $this->_pages->next()) )
1080             return false;
1081
1082         $pagename = &$next['pagename'];
1083         if (isset($next['pagedata']))
1084             $this->_wikidb->_cache->cache_data($next);
1085
1086         return new WikiDB_Page($this->_wikidb, $pagename);
1087     }
1088
1089     /**
1090      * Release resources held by this iterator.
1091      *
1092      * The iterator may not be used after free() is called.
1093      *
1094      * There is no need to call free(), if next() has returned false.
1095      * (I.e. if you iterate through all the pages in the sequence,
1096      * you do not need to call free() --- you only need to call it
1097      * if you stop before the end of the iterator is reached.)
1098      *
1099      * @access public
1100      */
1101     function free() {
1102         $this->_pages->free();
1103     }
1104
1105     // Not yet used.
1106     function setSortby ($arg = false) {
1107         if (!$arg) {
1108             $arg = @$_GET['sortby'];
1109             if ($arg) {
1110                 $sortby = substr($arg,1);
1111                 $order  = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1112             }
1113         }
1114         if (is_array($arg)) { // array('mtime' => 'desc')
1115             $sortby = $arg[0];
1116             $order = $arg[1];
1117         } else {
1118             $sortby = $arg;
1119             $order  = 'ASC';
1120         }
1121         // available column types to sort by:
1122         // todo: we must provide access methods for the generic dumb/iterator
1123         $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1124         if (in_array($sortby,$this->_types))
1125             $this->_options['sortby'] = $sortby;
1126         else
1127             trigger_error(fmt("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1128         if (in_array(strtoupper($order),'ASC','DESC')) 
1129             $this->_options['order'] = strtoupper($order);
1130         else
1131             trigger_error(fmt("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1132     }
1133
1134 };
1135
1136 /**
1137  * A class which represents a sequence of WikiDB_PageRevisions.
1138  */
1139 class WikiDB_PageRevisionIterator
1140 {
1141     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1142         $this->_revisions = $revisions;
1143         $this->_wikidb = &$wikidb;
1144     }
1145     
1146     /**
1147      * Get next WikiDB_PageRevision in sequence.
1148      *
1149      * @access public
1150      *
1151      * @return object The next WikiDB_PageRevision in the sequence.
1152      */
1153     function next () {
1154         if ( ! ($next = $this->_revisions->next()) )
1155             return false;
1156
1157         $this->_wikidb->_cache->cache_data($next);
1158
1159         $pagename = $next['pagename'];
1160         $version = $next['version'];
1161         $versiondata = $next['versiondata'];
1162         assert(!empty($pagename));
1163         assert(is_array($versiondata));
1164         assert($version > 0);
1165
1166         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1167                                        $versiondata);
1168     }
1169
1170     /**
1171      * Release resources held by this iterator.
1172      *
1173      * The iterator may not be used after free() is called.
1174      *
1175      * There is no need to call free(), if next() has returned false.
1176      * (I.e. if you iterate through all the revisions in the sequence,
1177      * you do not need to call free() --- you only need to call it
1178      * if you stop before the end of the iterator is reached.)
1179      *
1180      * @access public
1181      */
1182     function free() { 
1183         $this->_revisions->free();
1184     }
1185 };
1186
1187
1188 /**
1189  * Data cache used by WikiDB.
1190  *
1191  * FIXME: Maybe rename this to caching_backend (or some such).
1192  *
1193  * @access protected
1194  */
1195 class WikiDB_cache 
1196 {
1197     // FIXME: beautify versiondata cache.  Cache only limited data?
1198
1199     function WikiDB_cache (&$backend) {
1200         $this->_backend = &$backend;
1201
1202         $this->_pagedata_cache = array();
1203         $this->_versiondata_cache = array();
1204         array_push ($this->_versiondata_cache, array());
1205         $this->_glv_cache = array();
1206     }
1207     
1208     function close() {
1209         $this->_pagedata_cache = false;
1210                 $this->_versiondata_cache = false;
1211                 $this->_glv_cache = false;
1212     }
1213
1214     function get_pagedata($pagename) {
1215         assert(is_string($pagename) && $pagename);
1216         $cache = &$this->_pagedata_cache;
1217
1218         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1219             $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1220             if (empty($cache[$pagename]))
1221                 $cache[$pagename] = array();
1222         }
1223
1224         return $cache[$pagename];
1225     }
1226     
1227     function update_pagedata($pagename, $newdata) {
1228         assert(is_string($pagename) && $pagename);
1229
1230         $this->_backend->update_pagedata($pagename, $newdata);
1231
1232         if (is_array($this->_pagedata_cache[$pagename])) {
1233             $cachedata = &$this->_pagedata_cache[$pagename];
1234             foreach($newdata as $key => $val)
1235                 $cachedata[$key] = $val;
1236         }
1237     }
1238
1239     function invalidate_cache($pagename) {
1240         unset ($this->_pagedata_cache[$pagename]);
1241                 unset ($this->_versiondata_cache[$pagename]);
1242                 unset ($this->_glv_cache[$pagename]);
1243     }
1244     
1245     function delete_page($pagename) {
1246         $this->_backend->delete_page($pagename);
1247         unset ($this->_pagedata_cache[$pagename]);
1248                 unset ($this->_glv_cache[$pagename]);
1249     }
1250
1251     // FIXME: ugly
1252     function cache_data($data) {
1253         if (isset($data['pagedata']))
1254             $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1255     }
1256     
1257     function get_versiondata($pagename, $version, $need_content = false) {
1258                 //  FIXME: Seriously ugly hackage
1259         if (defined ('USECACHE')){   //temporary - for debugging
1260         assert(is_string($pagename) && $pagename);
1261                 // there is a bug here somewhere which results in an assertion failure at line 105
1262                 // of ArchiveCleaner.php  It goes away if we use the next line.
1263                 $need_content = true;
1264                 $nc = $need_content ? '1':'0';
1265         $cache = &$this->_versiondata_cache;
1266         if (!isset($cache[$pagename][$version][$nc])||
1267                                 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1268             $cache[$pagename][$version][$nc] = 
1269                                 $this->_backend->get_versiondata($pagename,$version, $need_content);
1270                         // If we have retrieved all data, we may as well set the cache for $need_content = false
1271                         if($need_content){
1272                                 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1273                         }
1274                 }
1275         $vdata = $cache[$pagename][$version][$nc];
1276         }
1277         else
1278         {
1279     $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1280         }
1281         // FIXME: ugly
1282         if ($vdata && !empty($vdata['%pagedata']))
1283             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1284         return $vdata;
1285     }
1286
1287     function set_versiondata($pagename, $version, $data) {
1288         $new = $this->_backend->
1289              set_versiondata($pagename, $version, $data);
1290                 // Update the cache
1291                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1292                 // FIXME: hack
1293                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1294                 // Is this necessary?
1295                 unset($this->_glv_cache[$pagename]);
1296                 
1297     }
1298
1299     function update_versiondata($pagename, $version, $data) {
1300         $new = $this->_backend->
1301              update_versiondata($pagename, $version, $data);
1302                 // Update the cache
1303                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1304                 // FIXME: hack
1305                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1306                 // Is this necessary?
1307                 unset($this->_glv_cache[$pagename]);
1308
1309     }
1310
1311     function delete_versiondata($pagename, $version) {
1312         $new = $this->_backend->
1313             delete_versiondata($pagename, $version);
1314         unset ($this->_versiondata_cache[$pagename][$version]['1']);
1315         unset ($this->_versiondata_cache[$pagename][$version]['0']);
1316         unset ($this->_glv_cache[$pagename]);
1317     }
1318         
1319     function get_latest_version($pagename)  {
1320         if(defined('USECACHE')){
1321             assert (is_string($pagename) && $pagename);
1322             $cache = &$this->_glv_cache;        
1323             if (!isset($cache[$pagename])) {
1324                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1325                 if (empty($cache[$pagename]))
1326                     $cache[$pagename] = 0;
1327             } 
1328             return $cache[$pagename];}
1329         else {
1330             return $this->_backend->get_latest_version($pagename); 
1331         }
1332     }
1333
1334 };
1335
1336 /**
1337  * FIXME! Class for externally authenticated users.
1338  *
1339  * We might have read-only access to the password and/or group membership,
1340  * or we might even be able to update the entries.
1341  *
1342  * FIXME: This was written before we stored prefs as %pagedata, so 
1343  */
1344 class WikiDB_User
1345 extends WikiUser
1346 {
1347     var $_authdb;
1348
1349     function WikiDB_User($userid, $authlevel = false) {
1350         $this->_authdb = new WikiAuthDB($GLOBALS['DBAuthParams']);
1351         $this->_authmethod = 'AuthDB';
1352         WikiUser::WikiUser($userid, $authlevel);
1353     }
1354
1355     /*
1356     function getPreferences() {
1357         // external prefs override internal ones?
1358         if (! $this->_authdb->getPrefs() )
1359             if ($pref = WikiUser::getPreferences())
1360                 return $prefs;
1361         return false;
1362     }
1363
1364     function setPreferences($prefs) {
1365         if (! $this->_authdb->setPrefs($prefs) )
1366             return WikiUser::setPreferences();
1367     }
1368     */
1369
1370     function exists() {
1371         return $this->_authdb->exists($this->_userid);
1372     }
1373
1374     // create user and default user homepage
1375     function createUser ($pref) {
1376         if ($this->exists()) return;
1377         if (! $this->_authdb->createUser($pref)) {
1378             // external auth doesn't allow this.
1379             // do our policies allow local users instead?
1380             return WikiUser::createUser($pref);
1381         }
1382     }
1383
1384     function checkPassword($passwd) {
1385         return $this->_authdb->pwcheck($this->userid, $passwd);
1386     }
1387
1388     function changePassword($passwd) {
1389         if (! $this->mayChangePassword() ) {
1390             trigger_error(sprintf("Attempt to change an external password for '%s'",
1391                                   $this->_userid), E_USER_ERROR);
1392             return;
1393         }
1394         return $this->_authdb->changePass($this->userid, $passwd);
1395     }
1396
1397     function mayChangePassword() {
1398         return $this->_authdb->auth_update;
1399     }
1400 }
1401
1402 class WikiAuthDB
1403 extends WikiDB
1404 {
1405     var $auth_dsn = false, $auth_check = false;
1406     var $auth_crypt_method = 'crypt', $auth_update = false;
1407     var $group_members = false, $user_groups = false;
1408     var $pref_update = false, $pref_select = false;
1409     var $_dbh;
1410
1411     function WikiAuthDB($DBAuthParams) {
1412         foreach ($DBAuthParams as $key => $value) {
1413             $this->$key = $value;
1414         }
1415         if (!$this->auth_dsn) {
1416             trigger_error(_("no \$DBAuthParams['dsn'] provided"), E_USER_ERROR);
1417             return false;
1418         }
1419         // compare auth DB to the existing page DB. reuse if it's on the same database.
1420         if (isa($this->_backend, 'WikiDB_backend_PearDB') and 
1421             $this->_backend->_dsn == $this->auth_dsn) {
1422             $this->_dbh = &$this->_backend->_dbh;
1423             return $this->_backend;
1424         }
1425         include_once("lib/WikiDB/SQL.php");
1426         return new WikiDB_SQL($DBAuthParams);
1427     }
1428
1429     function param_missing ($param) {
1430         trigger_error(sprintf(_("No \$DBAuthParams['%s'] provided."), $param), E_USER_ERROR);
1431         return;
1432     }
1433
1434     function getPrefs($prefs) {
1435         if ($this->pref_select) {
1436             $statement = $this->_backend->Prepare($this->pref_select);
1437             return unserialize($this->_backend->Execute($statement, 
1438                                                         $prefs->get('userid')));
1439         } else {
1440             param_missing('pref_select');
1441             return false;
1442         }
1443     }
1444
1445     function setPrefs($prefs) {
1446         if ($this->pref_write) {
1447             $statement = $this->_backend->Prepare($this->pref_write);
1448             return $this->_backend->Execute($statement, 
1449                                             $prefs->get('userid'), serialize($prefs->_prefs));
1450         } else {
1451             param_missing('pref_write');
1452             return false;
1453         }
1454     }
1455
1456     function createUser ($pref) {
1457         if ($this->user_create) {
1458             $statement = $this->_backend->Prepare($this->user_create);
1459             return $this->_backend->Execute($statement, 
1460                                         $prefs->get('userid'), serialize($prefs->_prefs));
1461         } else {
1462             param_missing('user_create');
1463             return false;
1464         }
1465     }
1466
1467     function exists($userid) {
1468         if ($this->user_check) {
1469             $statement = $this->_backend->Prepare($this->user_check);
1470             return $this->_backend->Execute($statement, $prefs->get('userid'));
1471         } else {
1472             param_missing('user_check');
1473             return false;
1474         }
1475     }
1476
1477     function pwcheck($userid, $pass) {
1478         if ($this->auth_check) {
1479             $statement = $this->_backend->Prepare($this->auth_check);
1480             return $this->_backend->Execute($statement, $userid, $pass);
1481         } else {
1482             param_missing('auth_check');
1483             return false;
1484         }
1485     }
1486 }
1487
1488 // Local Variables:
1489 // mode: php
1490 // tab-width: 8
1491 // c-basic-offset: 4
1492 // c-hanging-comment-ender-p: nil
1493 // indent-tabs-mode: nil
1494 // End:   
1495 ?>