]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
Hack so that (when using the IncludePage plugin) the including page shows
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.26 2003-03-04 02:08:08 dairiki Exp $');
3
4 require_once('lib/stdlib.php');
5 require_once('lib/PageType.php');
6
7 //FIXME: arg on get*Revision to hint that content is wanted.
8
9 /**
10  * The classes in the file define the interface to the
11  * page database.
12  *
13  * @package WikiDB
14  * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
15  */
16
17 /**
18  * Force the creation of a new revision.
19  * @see WikiDB_Page::createRevision()
20  */
21 define('WIKIDB_FORCE_CREATE', -1);
22
23 // FIXME:  used for debugging only.  Comment out if cache does not work
24 define('USECACHE', 1);
25
26 /** 
27  * Abstract base class for the database used by PhpWiki.
28  *
29  * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
30  * turn contain <tt>WikiDB_PageRevision</tt>s.
31  *
32  * Conceptually a <tt>WikiDB</tt> contains all possible
33  * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
34  * Since all possible pages are already contained in a WikiDB, a call
35  * to WikiDB::getPage() will never fail (barring bugs and
36  * e.g. filesystem or SQL database problems.)
37  *
38  * Also each <tt>WikiDB_Page</tt> always contains at least one
39  * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
40  * [PageName] here.").  This default content has a version number of
41  * zero.
42  *
43  * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
44  * only create new revisions or delete old ones --- one can not modify
45  * an existing revision.
46  */
47 class WikiDB {
48     /**
49      * Open a WikiDB database.
50      *
51      * This is a static member function. This function inspects its
52      * arguments to determine the proper subclass of WikiDB to
53      * instantiate, and then it instantiates it.
54      *
55      * @access public
56      *
57      * @param hash $dbparams Database configuration parameters.
58      * Some pertinent paramters are:
59      * <dl>
60      * <dt> dbtype
61      * <dd> The back-end type.  Current supported types are:
62      *   <dl>
63      *   <dt> SQL
64      *   <dd> Generic SQL backend based on the PEAR/DB database abstraction
65      *       library.
66      *   <dt> dba
67      *   <dd> Dba based backend.
68      *   </dl>
69      *
70      * <dt> dsn
71      * <dd> (Used by the SQL backend.)
72      *      The DSN specifying which database to connect to.
73      *
74      * <dt> prefix
75      * <dd> Prefix to be prepended to database table (and file names).
76      *
77      * <dt> directory
78      * <dd> (Used by the dba backend.)
79      *      Which directory db files reside in.
80      *
81      * <dt> timeout
82      * <dd> (Used by the dba backend.)
83      *      Timeout in seconds for opening (and obtaining lock) on the
84      *      db files.
85      *
86      * <dt> dba_handler
87      * <dd> (Used by the dba backend.)
88      *
89      *      Which dba handler to use. Good choices are probably either
90      *      'gdbm' or 'db2'.
91      * </dl>
92      *
93      * @return WikiDB A WikiDB object.
94      **/
95     function open ($dbparams) {
96         $dbtype = $dbparams{'dbtype'};
97         include_once("lib/WikiDB/$dbtype.php");
98                                 
99         $class = 'WikiDB_' . $dbtype;
100         return new $class ($dbparams);
101     }
102
103
104     /**
105      * Constructor.
106      *
107      * @access private
108      * @see open()
109      */
110     function WikiDB (&$backend, $dbparams) {
111         $this->_backend = &$backend;
112         $this->_cache = new WikiDB_cache($backend);
113
114         // If the database doesn't yet have a timestamp, initialize it now.
115         if ($this->get('_timestamp') === false)
116             $this->touch();
117         
118         //FIXME: devel checking.
119         //$this->_backend->check();
120     }
121     
122     /**
123      * Get any user-level warnings about this WikiDB.
124      *
125      * Some back-ends, e.g. by default create there data files in the
126      * global /tmp directory. We would like to warn the user when this
127      * happens (since /tmp files tend to get wiped periodically.)
128      * Warnings such as these may be communicated from specific
129      * back-ends through this method.
130      *
131      * @access public
132      *
133      * @return string A warning message (or <tt>false</tt> if there is
134      * none.)
135      */
136     function genericWarnings() {
137         return false;
138     }
139      
140     /**
141      * Close database connection.
142      *
143      * The database may no longer be used after it is closed.
144      *
145      * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
146      * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
147      * which have been obtained from it.
148      *
149      * @access public
150      */
151     function close () {
152         $this->_backend->close();
153         $this->_cache->close();
154     }
155     
156     /**
157      * Get a WikiDB_Page from a WikiDB.
158      *
159      * A {@link WikiDB} consists of the (infinite) set of all possible pages,
160      * therefore this method never fails.
161      *
162      * @access public
163      * @param string $pagename Which page to get.
164      * @return WikiDB_Page The requested WikiDB_Page.
165      */
166     function getPage($pagename) {
167         assert(is_string($pagename) && $pagename);
168         return new WikiDB_Page($this, $pagename);
169     }
170
171         
172     // Do we need this?
173     //function nPages() { 
174     //}
175
176
177     /**
178      * Determine whether page exists (in non-default form).
179      *
180      * <pre>
181      *   $is_page = $dbi->isWikiPage($pagename);
182      * </pre>
183      * is equivalent to
184      * <pre>
185      *   $page = $dbi->getPage($pagename);
186      *   $current = $page->getCurrentRevision();
187      *   $is_page = ! $current->hasDefaultContents();
188      * </pre>
189      * however isWikiPage may be implemented in a more efficient
190      * manner in certain back-ends.
191      *
192      * @access public
193      *
194      * @param string $pagename string Which page to check.
195      *
196      * @return boolean True if the page actually exists with
197      * non-default contents in the WikiDataBase.
198      */
199     function isWikiPage ($pagename) {
200         $page = $this->getPage($pagename);
201         $current = $page->getCurrentRevision();
202         return ! $current->hasDefaultContents();
203     }
204
205     /**
206      * Delete page from the WikiDB. 
207      *
208      * Deletes all revisions of the page from the WikiDB. Also resets
209      * all page meta-data to the default values.
210      *
211      * @access public
212      *
213      * @param string $pagename Name of page to delete.
214      */
215     function deletePage($pagename) {
216         $this->_cache->delete_page($pagename);
217     }
218
219     /**
220      * Retrieve all pages.
221      *
222      * Gets the set of all pages with non-default contents.
223      *
224      * FIXME: do we need this?  I think so.  The simple searches
225      *        need this stuff.
226      *
227      * @access public
228      *
229      * @param boolean $include_defaulted Normally pages whose most
230      * recent revision has empty content are considered to be
231      * non-existant. Unless $include_defaulted is set to true, those
232      * pages will not be returned.
233      *
234      * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
235      *     in the WikiDB which have non-default contents.
236      */
237     function getAllPages($include_defaulted = false) {
238         $result = $this->_backend->get_all_pages($include_defaulted);
239         return new WikiDB_PageIterator($this, $result);
240     }
241
242     /**
243      * Title search.
244      *
245      * Search for pages containing (or not containing) certain words
246      * in their names.
247      *
248      * Pages are returned in alphabetical order whenever it is
249      * practical to do so.
250      *
251      * FIXME: should titleSearch and fullSearch be combined?  I think so.
252      *
253      * @access public
254      * @param TextSearchQuery $search A TextSearchQuery object
255      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
256      * @see TextSearchQuery
257      */
258     function titleSearch($search) {
259         $result = $this->_backend->text_search($search);
260         return new WikiDB_PageIterator($this, $result);
261     }
262
263     /**
264      * Full text search.
265      *
266      * Search for pages containing (or not containing) certain words
267      * in their entire text (this includes the page content and the
268      * page name).
269      *
270      * Pages are returned in alphabetical order whenever it is
271      * practical to do so.
272      *
273      * @access public
274      *
275      * @param TextSearchQuery $search A TextSearchQuery object.
276      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
277      * @see TextSearchQuery
278      */
279     function fullSearch($search) {
280         $result = $this->_backend->text_search($search, 'full_text');
281         return new WikiDB_PageIterator($this, $result);
282     }
283
284     /**
285      * Find the pages with the greatest hit counts.
286      *
287      * Pages are returned in reverse order by hit count.
288      *
289      * @access public
290      *
291      * @param integer $limit The maximum number of pages to return.
292      * Set $limit to zero to return all pages.  If $limit < 0, pages will
293      * be sorted in decreasing order of popularity.
294      *
295      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
296      * pages.
297      */
298     function mostPopular($limit = 20) {
299         $result = $this->_backend->most_popular($limit);
300         return new WikiDB_PageIterator($this, $result);
301     }
302
303     /**
304      * Find recent page revisions.
305      *
306      * Revisions are returned in reverse order by creation time.
307      *
308      * @access public
309      *
310      * @param hash $params This hash is used to specify various optional
311      *   parameters:
312      * <dl>
313      * <dt> limit 
314      *    <dd> (integer) At most this many revisions will be returned.
315      * <dt> since
316      *    <dd> (integer) Only revisions since this time (unix-timestamp) will be returned. 
317      * <dt> include_minor_revisions
318      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
319      * <dt> exclude_major_revisions
320      *    <dd> (boolean) Don't include non-minor revisions.
321      *         (Exclude_major_revisions implies include_minor_revisions.)
322      * <dt> include_all_revisions
323      *    <dd> (boolean) Return all matching revisions for each page.
324      *         Normally only the most recent matching revision is returned
325      *         for each page.
326      * </dl>
327      *
328      * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
329      * matching revisions.
330      */
331     function mostRecent($params = false) {
332         $result = $this->_backend->most_recent($params);
333         return new WikiDB_PageRevisionIterator($this, $result);
334     }
335
336    /**
337      * Blog search. (experimental)
338      *
339      * Search for blog entries related to a certain page.
340      *
341      * FIXME: with pagetype support and perhaps a RegexpSearchQuery
342      * we can make sure we are returning *ONLY* blog pages to the
343      * main routine.  Currently, we just use titleSearch which requires
344      * some furher checking in lib/plugin/WikiBlog.php (BAD).
345      *
346      * @access public
347      *
348      * @param string $order  'normal' (chronological) or 'reverse'
349      * @param string $page   Find blog entries related to this page.
350      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the relevant pages.
351      */
352     // Deleting until such time as this is properly implemented...
353     // (As long as it's just a title search, just use titleSearch.)
354     //function blogSearch($page, $order) {
355     //  //FIXME: implement ordering
356     //
357     //  require_once('lib/TextSearchQuery.php');
358     //  $query = new TextSearchQuery ($page . SUBPAGE_SEPARATOR);
359     //
360     //  return $this->titleSearch($query);
361     //}
362
363     /** Get timestamp when database was last modified.
364      *
365      * @return string A string consisting of two integers,
366      * separated by a space.  The first is the time in
367      * unix timestamp format, the second is a modification
368      * count for the database.
369      *
370      * The idea is that you can cast the return value to an
371      * int to get a timestamp, or you can use the string value
372      * as a good hash for the entire database.
373      */
374     function getTimestamp() {
375         $ts = $this->get('_timestamp');
376         return sprintf("%d %d", $ts[0], $ts[1]);
377     }
378     
379     /**
380      * Update the database timestamp.
381      *
382      */
383     function touch() {
384         $ts = $this->get('_timestamp');
385         $this->set('_timestamp', array(time(), $ts[1] + 1));
386     }
387
388         
389     /**
390      * Access WikiDB global meta-data.
391      *
392      * NOTE: this is currently implemented in a hackish and
393      * not very efficient manner.
394      *
395      * @access public
396      *
397      * @param string $key Which meta data to get.
398      * Some reserved meta-data keys are:
399      * <dl>
400      * <dt>'_timestamp' <dd> Data used by getTimestamp().
401      * </dl>
402      *
403      * @return scalar The requested value, or false if the requested data
404      * is not set.
405      */
406     function get($key) {
407         if (!$key || $key[0] == '%')
408             return false;
409         /*
410          * Hack Alert: We can use any page (existing or not) to store
411          * this data (as long as we always use the same one.)
412          */
413         $gd = $this->getPage('global_data');
414         $data = $gd->get('__global');
415
416         if ($data && isset($data[$key]))
417             return $data[$key];
418         else
419             return false;
420     }
421
422     /**
423      * Set global meta-data.
424      *
425      * NOTE: this is currently implemented in a hackish and
426      * not very efficient manner.
427      *
428      * @see get
429      * @access public
430      *
431      * @param string $key  Meta-data key to set.
432      * @param string $newval  New value.
433      */
434     function set($key, $newval) {
435         if (!$key || $key[0] == '%')
436             return;
437         
438         $gd = $this->getPage('global_data');
439         
440         $data = $gd->get('__global');
441         if ($data === false)
442             $data = array();
443
444         if (empty($newval))
445             unset($data[$key]);
446         else
447             $data[$key] = $newval;
448
449         $gd->set('__global', $data);
450     }
451 };
452
453
454 /**
455  * An abstract base class which representing a wiki-page within a
456  * WikiDB.
457  *
458  * A WikiDB_Page contains a number (at least one) of
459  * WikiDB_PageRevisions.
460  */
461 class WikiDB_Page 
462 {
463     function WikiDB_Page(&$wikidb, $pagename) {
464         $this->_wikidb = &$wikidb;
465         $this->_pagename = $pagename;
466         assert(!empty($this->_pagename));
467     }
468
469     /**
470      * Get the name of the wiki page.
471      *
472      * @access public
473      *
474      * @return string The page name.
475      */
476     function getName() {
477         return $this->_pagename;
478     }
479
480
481     /**
482      * Delete an old revision of a WikiDB_Page.
483      *
484      * Deletes the specified revision of the page.
485      * It is a fatal error to attempt to delete the current revision.
486      *
487      * @access public
488      *
489      * @param integer $version Which revision to delete.  (You can also
490      *  use a WikiDB_PageRevision object here.)
491      */
492     function deleteRevision($version) {
493         $backend = &$this->_wikidb->_backend;
494         $cache = &$this->_wikidb->_cache;
495         $pagename = &$this->_pagename;
496
497         $version = $this->_coerce_to_version($version);
498         if ($version == 0)
499             return;
500
501         $backend->lock();
502         $latestversion = $cache->get_latest_version($pagename);
503         if ($latestversion && $version == $latestversion) {
504             $backend->unlock();
505             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
506                                   $pagename), E_USER_ERROR);
507             return;
508         }
509
510         $cache->delete_versiondata($pagename, $version);
511                 
512         $backend->unlock();
513     }
514
515     /*
516      * Delete a revision, or possibly merge it with a previous
517      * revision.
518      *
519      * The idea is this:
520      * Suppose an author make a (major) edit to a page.  Shortly
521      * after that the same author makes a minor edit (e.g. to fix
522      * spelling mistakes he just made.)
523      *
524      * Now some time later, where cleaning out old saved revisions,
525      * and would like to delete his minor revision (since there's
526      * really no point in keeping minor revisions around for a long
527      * time.)
528      *
529      * Note that the text after the minor revision probably represents
530      * what the author intended to write better than the text after
531      * the preceding major edit.
532      *
533      * So what we really want to do is merge the minor edit with the
534      * preceding edit.
535      *
536      * We will only do this when:
537      * <ul>
538      * <li>The revision being deleted is a minor one, and
539      * <li>It has the same author as the immediately preceding revision.
540      * </ul>
541      */
542     function mergeRevision($version) {
543         $backend = &$this->_wikidb->_backend;
544         $cache = &$this->_wikidb->_cache;
545         $pagename = &$this->_pagename;
546
547         $version = $this->_coerce_to_version($version);
548         if ($version == 0)
549             return;
550
551         $backend->lock();
552         $latestversion = $backend->get_latest_version($pagename);
553         if ($latestversion && $version == $latestversion) {
554             $backend->unlock();
555             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
556                                   $pagename), E_USER_ERROR);
557             return;
558         }
559
560         $versiondata = $cache->get_versiondata($pagename, $version, true);
561         if (!$versiondata) {
562             // Not there? ... we're done!
563             $backend->unlock();
564             return;
565         }
566
567         if ($versiondata['is_minor_edit']) {
568             $previous = $backend->get_previous_version($pagename, $version);
569             if ($previous) {
570                 $prevdata = $cache->get_versiondata($pagename, $previous);
571                 if ($prevdata['author_id'] == $versiondata['author_id']) {
572                     // This is a minor revision, previous version is
573                     // by the same author. We will merge the
574                     // revisions.
575                     $cache->update_versiondata($pagename, $previous,
576                                                array('%content' => $versiondata['%content'],
577                                                      '_supplanted' => $versiondata['_supplanted']));
578                 }
579             }
580         }
581
582         $cache->delete_versiondata($pagename, $version);
583         $backend->unlock();
584     }
585
586     
587     /**
588      * Create a new revision of a {@link WikiDB_Page}.
589      *
590      * @access public
591      *
592      * @param int $version Version number for new revision.  
593      * To ensure proper serialization of edits, $version must be
594      * exactly one higher than the current latest version.
595      * (You can defeat this check by setting $version to
596      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
597      *
598      * @param string $content Contents of new revision.
599      *
600      * @param hash $metadata Metadata for new revision.
601      * All values in the hash should be scalars (strings or integers).
602      *
603      * @param array $links List of pagenames which this page links to.
604      *
605      * @return WikiDB_PageRevision  Returns the new WikiDB_PageRevision object. If
606      * $version was incorrect, returns false
607      */
608     function createRevision($version, &$content, $metadata, $links) {
609         $backend = &$this->_wikidb->_backend;
610         $cache = &$this->_wikidb->_cache;
611         $pagename = &$this->_pagename;
612                 
613         $backend->lock();
614
615         $latestversion = $backend->get_latest_version($pagename);
616         $newversion = $latestversion + 1;
617         assert($newversion >= 1);
618
619         if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
620             $backend->unlock();
621             return false;
622         }
623
624         $data = $metadata;
625         
626         foreach ($data as $key => $val) {
627             if (empty($val) || $key[0] == '_' || $key[0] == '%')
628                 unset($data[$key]);
629         }
630                         
631         assert(!empty($data['author_id']));
632         if (empty($data['author_id']))
633             @$data['author_id'] = $data['author'];
634                 
635         if (empty($data['mtime']))
636             $data['mtime'] = time();
637
638         if ($latestversion) {
639             // Ensure mtimes are monotonic.
640             $pdata = $cache->get_versiondata($pagename, $latestversion);
641             if ($data['mtime'] < $pdata['mtime']) {
642                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
643                                       $pagename,"'non-monotonic'"),
644                               E_USER_NOTICE);
645                 $data['orig_mtime'] = $data['mtime'];
646                 $data['mtime'] = $pdata['mtime'];
647             }
648             
649             // FIXME: use (possibly user specified) 'mtime' time or
650             // time()?
651             $cache->update_versiondata($pagename, $latestversion,
652                                        array('_supplanted' => $data['mtime']));
653         }
654
655         $data['%content'] = &$content;
656
657         $cache->set_versiondata($pagename, $newversion, $data);
658
659         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
660         //':deleted' => empty($content)));
661         
662         $backend->set_links($pagename, $links);
663
664         $backend->unlock();
665
666         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
667                                        $data);
668     }
669
670     /** A higher-level interface to createRevision.
671      *
672      * This takes care of computing the links, and storing
673      * a cached version of the transformed wiki-text.
674      *
675      * @param string $wikitext  The page content.
676      *
677      * @param int $version Version number for new revision.  
678      * To ensure proper serialization of edits, $version must be
679      * exactly one higher than the current latest version.
680      * (You can defeat this check by setting $version to
681      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
682      *
683      * @param hash $meta  Meta-data for new revision.
684      */
685     function save($wikitext, $version, $meta) {
686         $formatted = new TransformedText($this, $wikitext, $meta);
687         $type = $formatted->getType();
688         $meta['pagetype'] = $type->getName();
689         $links = $formatted->getWikiPageLinks();
690
691         $backend = &$this->_wikidb->_backend;
692         $backend->lock();
693         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
694         if ($newrevision)
695             if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
696                 $this->set('_cached_html', $formatted->pack());
697         $backend->unlock();
698
699         // FIXME: probably should have some global state information
700         // in the backend to control when to optimize.
701         //
702         // We're doing this here rather than in createRevision because
703         // postgres can't optimize while locked.
704         if (time() % 50 == 0) {
705             trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
706             $backend->optimize();
707         }
708
709         $newrevision->_transformedContent = $formatted;
710         return $newrevision;
711     }
712
713     /**
714      * Get the most recent revision of a page.
715      *
716      * @access public
717      *
718      * @return WikiDB_PageRevision The current WikiDB_PageRevision object. 
719      */
720     function getCurrentRevision() {
721         $backend = &$this->_wikidb->_backend;
722         $cache = &$this->_wikidb->_cache;
723         $pagename = &$this->_pagename;
724
725         $backend->lock();
726         $version = $cache->get_latest_version($pagename);
727         $revision = $this->getRevision($version);
728         $backend->unlock();
729         assert($revision);
730         return $revision;
731     }
732
733     /**
734      * Get a specific revision of a WikiDB_Page.
735      *
736      * @access public
737      *
738      * @param integer $version  Which revision to get.
739      *
740      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
741      * false if the requested revision does not exist in the {@link WikiDB}.
742      * Note that version zero of any page always exists.
743      */
744     function getRevision($version) {
745         $cache = &$this->_wikidb->_cache;
746         $pagename = &$this->_pagename;
747         
748         if ($version == 0)
749             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
750
751         assert($version > 0);
752         $vdata = $cache->get_versiondata($pagename, $version);
753         if (!$vdata)
754             return false;
755         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
756                                        $vdata);
757     }
758
759     /**
760      * Get previous page revision.
761      *
762      * This method find the most recent revision before a specified
763      * version.
764      *
765      * @access public
766      *
767      * @param integer $version  Find most recent revision before this version.
768      *  You can also use a WikiDB_PageRevision object to specify the $version.
769      *
770      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
771      * requested revision does not exist in the {@link WikiDB}.  Note that
772      * unless $version is greater than zero, a revision (perhaps version zero,
773      * the default revision) will always be found.
774      */
775     function getRevisionBefore($version) {
776         $backend = &$this->_wikidb->_backend;
777         $pagename = &$this->_pagename;
778
779         $version = $this->_coerce_to_version($version);
780
781         if ($version == 0)
782             return false;
783         $backend->lock();
784         $previous = $backend->get_previous_version($pagename, $version);
785         $revision = $this->getRevision($previous);
786         $backend->unlock();
787         assert($revision);
788         return $revision;
789     }
790
791     /**
792      * Get all revisions of the WikiDB_Page.
793      *
794      * This does not include the version zero (default) revision in the
795      * returned revision set.
796      *
797      * @return WikiDB_PageRevisionIterator A
798      * WikiDB_PageRevisionIterator containing all revisions of this
799      * WikiDB_Page in reverse order by version number.
800      */
801     function getAllRevisions() {
802         $backend = &$this->_wikidb->_backend;
803         $revs = $backend->get_all_revisions($this->_pagename);
804         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
805     }
806     
807     /**
808      * Find pages which link to or are linked from a page.
809      *
810      * @access public
811      *
812      * @param boolean $reversed Which links to find: true for backlinks (default).
813      *
814      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
815      * all matching pages.
816      */
817     function getLinks($reversed = true) {
818         $backend = &$this->_wikidb->_backend;
819         $result =  $backend->get_links($this->_pagename, $reversed);
820         return new WikiDB_PageIterator($this->_wikidb, $result);
821     }
822             
823     /**
824      * Access WikiDB_Page meta-data.
825      *
826      * @access public
827      *
828      * @param string $key Which meta data to get.
829      * Some reserved meta-data keys are:
830      * <dl>
831      * <dt>'locked'<dd> Is page locked?
832      * <dt>'hits'  <dd> Page hit counter.
833      * <dt>'pref'  <dd> Users preferences, stored in homepages.
834      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
835      *                  E.g. "owner.users"
836      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
837      *                  page-headers and content.
838      * <dt>'score' <dd> Page score (not yet implement, do we need?)
839      * </dl>
840      *
841      * @return scalar The requested value, or false if the requested data
842      * is not set.
843      */
844     function get($key) {
845         $cache = &$this->_wikidb->_cache;
846         if (!$key || $key[0] == '%')
847             return false;
848         $data = $cache->get_pagedata($this->_pagename);
849         return isset($data[$key]) ? $data[$key] : false;
850     }
851
852     /**
853      * Get all the page meta-data as a hash.
854      *
855      * @return hash The page meta-data.
856      */
857     function getMetaData() {
858         $cache = &$this->_wikidb->_cache;
859         $data = $cache->get_pagedata($this->_pagename);
860         $meta = array();
861         foreach ($data as $key => $val) {
862             if (!empty($val) && $key[0] != '%')
863                 $meta[$key] = $val;
864         }
865         return $meta;
866     }
867
868     /**
869      * Set page meta-data.
870      *
871      * @see get
872      * @access public
873      *
874      * @param string $key  Meta-data key to set.
875      * @param string $newval  New value.
876      */
877     function set($key, $newval) {
878         $cache = &$this->_wikidb->_cache;
879         $pagename = &$this->_pagename;
880         
881         assert($key && $key[0] != '%');
882
883         $data = $cache->get_pagedata($pagename);
884
885         if (!empty($newval)) {
886             if (!empty($data[$key]) && $data[$key] == $newval)
887                 return;         // values identical, skip update.
888         }
889         else {
890             if (empty($data[$key]))
891                 return;         // values identical, skip update.
892         }
893
894         $cache->update_pagedata($pagename, array($key => $newval));
895     }
896
897     /**
898      * Increase page hit count.
899      *
900      * FIXME: IS this needed?  Probably not.
901      *
902      * This is a convenience function.
903      * <pre> $page->increaseHitCount(); </pre>
904      * is functionally identical to
905      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
906      *
907      * Note that this method may be implemented in more efficient ways
908      * in certain backends.
909      *
910      * @access public
911      */
912     function increaseHitCount() {
913         @$newhits = $this->get('hits') + 1;
914         $this->set('hits', $newhits);
915     }
916
917     /**
918      * Return a string representation of the WikiDB_Page
919      *
920      * This is really only for debugging.
921      *
922      * @access public
923      *
924      * @return string Printable representation of the WikiDB_Page.
925      */
926     function asString () {
927         ob_start();
928         printf("[%s:%s\n", get_class($this), $this->getName());
929         print_r($this->getMetaData());
930         echo "]\n";
931         $strval = ob_get_contents();
932         ob_end_clean();
933         return $strval;
934     }
935
936
937     /**
938      * @access private
939      * @param integer_or_object $version_or_pagerevision
940      * Takes either the version number (and int) or a WikiDB_PageRevision
941      * object.
942      * @return integer The version number.
943      */
944     function _coerce_to_version($version_or_pagerevision) {
945         if (method_exists($version_or_pagerevision, "getContent"))
946             $version = $version_or_pagerevision->getVersion();
947         else
948             $version = (int) $version_or_pagerevision;
949
950         assert($version >= 0);
951         return $version;
952     }
953
954     function isUserPage ($include_empty = true) {
955         return $this->get('pref') ? true : false;
956         if ($include_empty)
957             return true;
958         $current = $this->getCurrentRevision();
959         return ! $current->hasDefaultContents();
960     }
961
962 };
963
964 /**
965  * This class represents a specific revision of a WikiDB_Page within
966  * a WikiDB.
967  *
968  * A WikiDB_PageRevision has read-only semantics. You may only create
969  * new revisions (and delete old ones) --- you cannot modify existing
970  * revisions.
971  */
972 class WikiDB_PageRevision
973 {
974     var $_transformedContent = false; // set by WikiDB_Page::save()
975     
976     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
977                                  $versiondata = false)
978         {
979             $this->_wikidb = &$wikidb;
980             $this->_pagename = $pagename;
981             $this->_version = $version;
982             $this->_data = $versiondata ? $versiondata : array();
983         }
984     
985     /**
986      * Get the WikiDB_Page which this revision belongs to.
987      *
988      * @access public
989      *
990      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
991      */
992     function getPage() {
993         return new WikiDB_Page($this->_wikidb, $this->_pagename);
994     }
995
996     /**
997      * Get the version number of this revision.
998      *
999      * @access public
1000      *
1001      * @return integer The version number of this revision.
1002      */
1003     function getVersion() {
1004         return $this->_version;
1005     }
1006     
1007     /**
1008      * Determine whether this revision has defaulted content.
1009      *
1010      * The default revision (version 0) of each page, as well as any
1011      * pages which are created with empty content have their content
1012      * defaulted to something like:
1013      * <pre>
1014      *   Describe [ThisPage] here.
1015      * </pre>
1016      *
1017      * @access public
1018      *
1019      * @return boolean Returns true if the page has default content.
1020      */
1021     function hasDefaultContents() {
1022         $data = &$this->_data;
1023         return empty($data['%content']);
1024     }
1025
1026     /**
1027      * Get the content as an array of lines.
1028      *
1029      * @access public
1030      *
1031      * @return array An array of lines.
1032      * The lines should contain no trailing white space.
1033      */
1034     function getContent() {
1035         return explode("\n", $this->getPackedContent());
1036     }
1037         
1038         /**
1039      * Get the pagename of the revision.
1040      *
1041      * @access public
1042      *
1043      * @return string pagename.
1044      */
1045     function getPageName() {
1046         return $this->_pagename;
1047     }
1048
1049     /**
1050      * Determine whether revision is the latest.
1051      *
1052      * @access public
1053      *
1054      * @return boolean True iff the revision is the latest (most recent) one.
1055      */
1056     function isCurrent() {
1057         if (!isset($this->_iscurrent)) {
1058             $page = $this->getPage();
1059             $current = $page->getCurrentRevision();
1060             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1061         }
1062         return $this->_iscurrent;
1063     }
1064
1065     /**
1066      * Get the transformed content of a page.
1067      *
1068      * @param string $pagetype  Override the page-type of the revision.
1069      *
1070      * @return object An XmlContent-like object containing the page transformed
1071      * contents.
1072      */
1073     function getTransformedContent($pagetype_override=false) {
1074         $backend = &$this->_wikidb->_backend;
1075         
1076         if ($pagetype_override) {
1077             // Figure out the normal page-type for this page.
1078             $type = PageType::GetPageType($this->get('pagetype'));
1079             if ($type->getName() == $pagetype_override)
1080                 $pagetype_override = false; // Not really an override...
1081         }
1082
1083         if ($pagetype_override) {
1084             // Overriden page type, don't cache (or check cache).
1085             return new TransformedText($this->getPage(),
1086                                        $this->getPackedContent(),
1087                                        $this->getMetaData(),
1088                                        $pagetype_override);
1089         }
1090
1091         $possibly_cache_results = true;
1092
1093         if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1094             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1095                 // flush cache for this page.
1096                 $page = $this->getPage();
1097                 $page->set('_cached_html', false);
1098             }
1099             $possibly_cache_results = false;
1100         }
1101         elseif (!$this->_transformedContent) {
1102             $backend->lock();
1103             if ($this->isCurrent()) {
1104                 $page = $this->getPage();
1105                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1106             }
1107             else {
1108                 $possibly_cache_results = false;
1109             }
1110             $backend->unlock();
1111         }
1112         
1113         if (!$this->_transformedContent) {
1114             $this->_transformedContent
1115                 = new TransformedText($this->getPage(),
1116                                       $this->getPackedContent(),
1117                                       $this->getMetaData());
1118             
1119             if ($possibly_cache_results) {
1120                 // If we're still the current version, cache the transfomed page.
1121                 $backend->lock();
1122                 if ($this->isCurrent()) {
1123                     $page->set('_cached_html', $this->_transformedContent->pack());
1124                 }
1125                 $backend->unlock();
1126             }
1127         }
1128
1129         return $this->_transformedContent;
1130     }
1131
1132     /**
1133      * Get the content as a string.
1134      *
1135      * @access public
1136      *
1137      * @return string The page content.
1138      * Lines are separated by new-lines.
1139      */
1140     function getPackedContent() {
1141         $data = &$this->_data;
1142
1143         
1144         if (empty($data['%content'])) {
1145             include_once('lib/InlineParser.php');
1146             // Replace empty content with default value.
1147             return sprintf(_("Describe %s here."), 
1148                            "[" . WikiEscape($this->_pagename) . "]");
1149         }
1150
1151         // There is (non-default) content.
1152         assert($this->_version > 0);
1153         
1154         if (!is_string($data['%content'])) {
1155             // Content was not provided to us at init time.
1156             // (This is allowed because for some backends, fetching
1157             // the content may be expensive, and often is not wanted
1158             // by the user.)
1159             //
1160             // In any case, now we need to get it.
1161             $data['%content'] = $this->_get_content();
1162             assert(is_string($data['%content']));
1163         }
1164         
1165         return $data['%content'];
1166     }
1167
1168     function _get_content() {
1169         $cache = &$this->_wikidb->_cache;
1170         $pagename = $this->_pagename;
1171         $version = $this->_version;
1172
1173         assert($version > 0);
1174         
1175         $newdata = $cache->get_versiondata($pagename, $version, true);
1176         if ($newdata) {
1177             assert(is_string($newdata['%content']));
1178             return $newdata['%content'];
1179         }
1180         else {
1181             // else revision has been deleted... What to do?
1182             return __sprintf("Acck! Revision %s of %s seems to have been deleted!",
1183                              $version, $pagename);
1184         }
1185     }
1186
1187     /**
1188      * Get meta-data for this revision.
1189      *
1190      *
1191      * @access public
1192      *
1193      * @param string $key Which meta-data to access.
1194      *
1195      * Some reserved revision meta-data keys are:
1196      * <dl>
1197      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1198      *        The 'mtime' meta-value is normally set automatically by the database
1199      *        backend, but it may be specified explicitly when creating a new revision.
1200      * <dt> orig_mtime
1201      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1202      *       of a page must be monotonically increasing.  If an attempt is
1203      *       made to create a new revision with an mtime less than that of
1204      *       the preceeding revision, the new revisions timestamp is force
1205      *       to be equal to that of the preceeding revision.  In that case,
1206      *       the originally requested mtime is preserved in 'orig_mtime'.
1207      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1208      *        This meta-value is <em>always</em> automatically maintained by the database
1209      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1210      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1211      *
1212      * FIXME: this could be refactored:
1213      * <dt> author
1214      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1215      * <dt> author_id
1216      *  <dd> Authenticated author of a page.  This is used to identify
1217      *       the distinctness of authors when cleaning old revisions from
1218      *       the database.
1219      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1220      * <dt> 'summary' <dd> Short change summary entered by page author.
1221      * </dl>
1222      *
1223      * Meta-data keys must be valid C identifers (they have to start with a letter
1224      * or underscore, and can contain only alphanumerics and underscores.)
1225      *
1226      * @return string The requested value, or false if the requested value
1227      * is not defined.
1228      */
1229     function get($key) {
1230         if (!$key || $key[0] == '%')
1231             return false;
1232         $data = &$this->_data;
1233         return isset($data[$key]) ? $data[$key] : false;
1234     }
1235
1236     /**
1237      * Get all the revision page meta-data as a hash.
1238      *
1239      * @return hash The revision meta-data.
1240      */
1241     function getMetaData() {
1242         $meta = array();
1243         foreach ($this->_data as $key => $val) {
1244             if (!empty($val) && $key[0] != '%')
1245                 $meta[$key] = $val;
1246         }
1247         return $meta;
1248     }
1249     
1250             
1251     /**
1252      * Return a string representation of the revision.
1253      *
1254      * This is really only for debugging.
1255      *
1256      * @access public
1257      *
1258      * @return string Printable representation of the WikiDB_Page.
1259      */
1260     function asString () {
1261         ob_start();
1262         printf("[%s:%d\n", get_class($this), $this->get('version'));
1263         print_r($this->_data);
1264         echo $this->getPackedContent() . "\n]\n";
1265         $strval = ob_get_contents();
1266         ob_end_clean();
1267         return $strval;
1268     }
1269 };
1270
1271
1272 /**
1273  * A class which represents a sequence of WikiDB_Pages.
1274  */
1275 class WikiDB_PageIterator
1276 {
1277     function WikiDB_PageIterator(&$wikidb, &$pages) {
1278         $this->_pages = $pages;
1279         $this->_wikidb = &$wikidb;
1280     }
1281     
1282     /**
1283      * Get next WikiDB_Page in sequence.
1284      *
1285      * @access public
1286      *
1287      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1288      */
1289     function next () {
1290         if ( ! ($next = $this->_pages->next()) )
1291             return false;
1292
1293         $pagename = &$next['pagename'];
1294         if (isset($next['pagedata']))
1295             $this->_wikidb->_cache->cache_data($next);
1296
1297         return new WikiDB_Page($this->_wikidb, $pagename);
1298     }
1299
1300     /**
1301      * Release resources held by this iterator.
1302      *
1303      * The iterator may not be used after free() is called.
1304      *
1305      * There is no need to call free(), if next() has returned false.
1306      * (I.e. if you iterate through all the pages in the sequence,
1307      * you do not need to call free() --- you only need to call it
1308      * if you stop before the end of the iterator is reached.)
1309      *
1310      * @access public
1311      */
1312     function free() {
1313         $this->_pages->free();
1314     }
1315
1316     // Not yet used.
1317     function setSortby ($arg = false) {
1318         if (!$arg) {
1319             $arg = @$_GET['sortby'];
1320             if ($arg) {
1321                 $sortby = substr($arg,1);
1322                 $order  = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1323             }
1324         }
1325         if (is_array($arg)) { // array('mtime' => 'desc')
1326             $sortby = $arg[0];
1327             $order = $arg[1];
1328         } else {
1329             $sortby = $arg;
1330             $order  = 'ASC';
1331         }
1332         // available column types to sort by:
1333         // todo: we must provide access methods for the generic dumb/iterator
1334         $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1335         if (in_array($sortby,$this->_types))
1336             $this->_options['sortby'] = $sortby;
1337         else
1338             trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1339         if (in_array(strtoupper($order),'ASC','DESC')) 
1340             $this->_options['order'] = strtoupper($order);
1341         else
1342             trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1343     }
1344
1345 };
1346
1347 /**
1348  * A class which represents a sequence of WikiDB_PageRevisions.
1349  */
1350 class WikiDB_PageRevisionIterator
1351 {
1352     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1353         $this->_revisions = $revisions;
1354         $this->_wikidb = &$wikidb;
1355     }
1356     
1357     /**
1358      * Get next WikiDB_PageRevision in sequence.
1359      *
1360      * @access public
1361      *
1362      * @return WikiDB_PageRevision
1363      * The next WikiDB_PageRevision in the sequence.
1364      */
1365     function next () {
1366         if ( ! ($next = $this->_revisions->next()) )
1367             return false;
1368
1369         $this->_wikidb->_cache->cache_data($next);
1370
1371         $pagename = $next['pagename'];
1372         $version = $next['version'];
1373         $versiondata = $next['versiondata'];
1374         assert(!empty($pagename));
1375         assert(is_array($versiondata));
1376         assert($version > 0);
1377
1378         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1379                                        $versiondata);
1380     }
1381
1382     /**
1383      * Release resources held by this iterator.
1384      *
1385      * The iterator may not be used after free() is called.
1386      *
1387      * There is no need to call free(), if next() has returned false.
1388      * (I.e. if you iterate through all the revisions in the sequence,
1389      * you do not need to call free() --- you only need to call it
1390      * if you stop before the end of the iterator is reached.)
1391      *
1392      * @access public
1393      */
1394     function free() { 
1395         $this->_revisions->free();
1396     }
1397 };
1398
1399
1400 /**
1401  * Data cache used by WikiDB.
1402  *
1403  * FIXME: Maybe rename this to caching_backend (or some such).
1404  *
1405  * @access private
1406  */
1407 class WikiDB_cache 
1408 {
1409     // FIXME: beautify versiondata cache.  Cache only limited data?
1410
1411     function WikiDB_cache (&$backend) {
1412         $this->_backend = &$backend;
1413
1414         $this->_pagedata_cache = array();
1415         $this->_versiondata_cache = array();
1416         array_push ($this->_versiondata_cache, array());
1417         $this->_glv_cache = array();
1418     }
1419     
1420     function close() {
1421         $this->_pagedata_cache = false;
1422                 $this->_versiondata_cache = false;
1423                 $this->_glv_cache = false;
1424     }
1425
1426     function get_pagedata($pagename) {
1427         assert(is_string($pagename) && $pagename);
1428         $cache = &$this->_pagedata_cache;
1429
1430         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1431             $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1432             if (empty($cache[$pagename]))
1433                 $cache[$pagename] = array();
1434         }
1435
1436         return $cache[$pagename];
1437     }
1438     
1439     function update_pagedata($pagename, $newdata) {
1440         assert(is_string($pagename) && $pagename);
1441
1442         $this->_backend->update_pagedata($pagename, $newdata);
1443
1444         if (is_array($this->_pagedata_cache[$pagename])) {
1445             $cachedata = &$this->_pagedata_cache[$pagename];
1446             foreach($newdata as $key => $val)
1447                 $cachedata[$key] = $val;
1448         }
1449     }
1450
1451     function invalidate_cache($pagename) {
1452         unset ($this->_pagedata_cache[$pagename]);
1453                 unset ($this->_versiondata_cache[$pagename]);
1454                 unset ($this->_glv_cache[$pagename]);
1455     }
1456     
1457     function delete_page($pagename) {
1458         $this->_backend->delete_page($pagename);
1459         unset ($this->_pagedata_cache[$pagename]);
1460                 unset ($this->_glv_cache[$pagename]);
1461     }
1462
1463     // FIXME: ugly
1464     function cache_data($data) {
1465         if (isset($data['pagedata']))
1466             $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1467     }
1468     
1469     function get_versiondata($pagename, $version, $need_content = false) {
1470                 //  FIXME: Seriously ugly hackage
1471         if (defined ('USECACHE')){   //temporary - for debugging
1472         assert(is_string($pagename) && $pagename);
1473                 // there is a bug here somewhere which results in an assertion failure at line 105
1474                 // of ArchiveCleaner.php  It goes away if we use the next line.
1475                 $need_content = true;
1476                 $nc = $need_content ? '1':'0';
1477         $cache = &$this->_versiondata_cache;
1478         if (!isset($cache[$pagename][$version][$nc])||
1479                                 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1480             $cache[$pagename][$version][$nc] = 
1481                                 $this->_backend->get_versiondata($pagename,$version, $need_content);
1482                         // If we have retrieved all data, we may as well set the cache for $need_content = false
1483                         if($need_content){
1484                                 $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1485                         }
1486                 }
1487         $vdata = $cache[$pagename][$version][$nc];
1488         }
1489         else
1490         {
1491     $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1492         }
1493         // FIXME: ugly
1494         if ($vdata && !empty($vdata['%pagedata']))
1495             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1496         return $vdata;
1497     }
1498
1499     function set_versiondata($pagename, $version, $data) {
1500         $new = $this->_backend->
1501              set_versiondata($pagename, $version, $data);
1502                 // Update the cache
1503                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1504                 // FIXME: hack
1505                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1506                 // Is this necessary?
1507                 unset($this->_glv_cache[$pagename]);
1508                 
1509     }
1510
1511     function update_versiondata($pagename, $version, $data) {
1512         $new = $this->_backend->
1513              update_versiondata($pagename, $version, $data);
1514                 // Update the cache
1515                 $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1516                 // FIXME: hack
1517                 $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1518                 // Is this necessary?
1519                 unset($this->_glv_cache[$pagename]);
1520
1521     }
1522
1523     function delete_versiondata($pagename, $version) {
1524         $new = $this->_backend->
1525             delete_versiondata($pagename, $version);
1526         unset ($this->_versiondata_cache[$pagename][$version]['1']);
1527         unset ($this->_versiondata_cache[$pagename][$version]['0']);
1528         unset ($this->_glv_cache[$pagename]);
1529     }
1530         
1531     function get_latest_version($pagename)  {
1532         if(defined('USECACHE')){
1533             assert (is_string($pagename) && $pagename);
1534             $cache = &$this->_glv_cache;        
1535             if (!isset($cache[$pagename])) {
1536                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1537                 if (empty($cache[$pagename]))
1538                     $cache[$pagename] = 0;
1539             } 
1540             return $cache[$pagename];}
1541         else {
1542             return $this->_backend->get_latest_version($pagename); 
1543         }
1544     }
1545
1546 };
1547
1548 /**
1549  * FIXME! Class for externally authenticated users.
1550  *
1551  * We might have read-only access to the password and/or group membership,
1552  * or we might even be able to update the entries.
1553  *
1554  * FIXME: This was written before we stored prefs as %pagedata, so
1555  *
1556  * FIXME: I believe this is not currently used.
1557  */
1558 //  class WikiDB_User
1559 //  extends WikiUser
1560 //  {
1561 //      var $_authdb;
1562
1563 //      function WikiDB_User($userid, $authlevel = false) {
1564 //          global $request;
1565 //          $this->_authdb = new WikiAuthDB($GLOBALS['DBAuthParams']);
1566 //          $this->_authmethod = 'AuthDB';
1567 //          WikiUser::WikiUser($request, $userid, $authlevel);
1568 //      }
1569
1570 //      /*
1571 //      function getPreferences() {
1572 //          // external prefs override internal ones?
1573 //          if (! $this->_authdb->getPrefs() )
1574 //              if ($pref = WikiUser::getPreferences())
1575 //                  return $prefs;
1576 //          return false;
1577 //      }
1578
1579 //      function setPreferences($prefs) {
1580 //          if (! $this->_authdb->setPrefs($prefs) )
1581 //              return WikiUser::setPreferences();
1582 //      }
1583 //      */
1584
1585 //      function exists() {
1586 //          return $this->_authdb->exists($this->_userid);
1587 //      }
1588
1589 //      // create user and default user homepage
1590 //      function createUser ($pref) {
1591 //          if ($this->exists()) return;
1592 //          if (! $this->_authdb->createUser($pref)) {
1593 //              // external auth doesn't allow this.
1594 //              // do our policies allow local users instead?
1595 //              return WikiUser::createUser($pref);
1596 //          }
1597 //      }
1598
1599 //      function checkPassword($passwd) {
1600 //          return $this->_authdb->pwcheck($this->userid, $passwd);
1601 //      }
1602
1603 //      function changePassword($passwd) {
1604 //          if (! $this->mayChangePassword() ) {
1605 //              trigger_error(sprintf("Attempt to change an external password for '%s'",
1606 //                                    $this->_userid), E_USER_ERROR);
1607 //              return;
1608 //          }
1609 //          return $this->_authdb->changePass($this->userid, $passwd);
1610 //      }
1611
1612 //      function mayChangePassword() {
1613 //          return $this->_authdb->auth_update;
1614 //      }
1615 //  }
1616
1617 /*
1618  * FIXME: I believe this is not currently used.
1619  */
1620 //  class WikiAuthDB
1621 //  extends WikiDB
1622 //  {
1623 //      var $auth_dsn = false, $auth_check = false;
1624 //      var $auth_crypt_method = 'crypt', $auth_update = false;
1625 //      var $group_members = false, $user_groups = false;
1626 //      var $pref_update = false, $pref_select = false;
1627 //      var $_dbh;
1628
1629 //      function WikiAuthDB($DBAuthParams) {
1630 //          foreach ($DBAuthParams as $key => $value) {
1631 //              $this->$key = $value;
1632 //          }
1633 //          if (!$this->auth_dsn) {
1634 //              trigger_error(_("no \$DBAuthParams['dsn'] provided"), E_USER_ERROR);
1635 //              return false;
1636 //          }
1637 //          // compare auth DB to the existing page DB. reuse if it's on the same database.
1638 //          if (isa($this->_backend, 'WikiDB_backend_PearDB') and 
1639 //              $this->_backend->_dsn == $this->auth_dsn) {
1640 //              $this->_dbh = &$this->_backend->_dbh;
1641 //              return $this->_backend;
1642 //          }
1643 //          include_once("lib/WikiDB/SQL.php");
1644 //          return new WikiDB_SQL($DBAuthParams);
1645 //      }
1646
1647 //      function param_missing ($param) {
1648 //          trigger_error(sprintf(_("No \$DBAuthParams['%s'] provided."), $param), E_USER_ERROR);
1649 //          return;
1650 //      }
1651
1652 //      function getPrefs($prefs) {
1653 //          if ($this->pref_select) {
1654 //              $statement = $this->_backend->Prepare($this->pref_select);
1655 //              return unserialize($this->_backend->Execute($statement, 
1656 //                                                          $prefs->get('userid')));
1657 //          } else {
1658 //              param_missing('pref_select');
1659 //              return false;
1660 //          }
1661 //      }
1662
1663 //      function setPrefs($prefs) {
1664 //          if ($this->pref_write) {
1665 //              $statement = $this->_backend->Prepare($this->pref_write);
1666 //              return $this->_backend->Execute($statement, 
1667 //                                              $prefs->get('userid'), serialize($prefs->_prefs));
1668 //          } else {
1669 //              param_missing('pref_write');
1670 //              return false;
1671 //          }
1672 //      }
1673
1674 //      function createUser ($pref) {
1675 //          if ($this->user_create) {
1676 //              $statement = $this->_backend->Prepare($this->user_create);
1677 //              return $this->_backend->Execute($statement, 
1678 //                                          $prefs->get('userid'), serialize($prefs->_prefs));
1679 //          } else {
1680 //              param_missing('user_create');
1681 //              return false;
1682 //          }
1683 //      }
1684
1685 //      function exists($userid) {
1686 //          if ($this->user_check) {
1687 //              $statement = $this->_backend->Prepare($this->user_check);
1688 //              return $this->_backend->Execute($statement, $prefs->get('userid'));
1689 //          } else {
1690 //              param_missing('user_check');
1691 //              return false;
1692 //          }
1693 //      }
1694
1695 //      function pwcheck($userid, $pass) {
1696 //          if ($this->auth_check) {
1697 //              $statement = $this->_backend->Prepare($this->auth_check);
1698 //              return $this->_backend->Execute($statement, $userid, $pass);
1699 //          } else {
1700 //              param_missing('auth_check');
1701 //              return false;
1702 //          }
1703 //      }
1704 //  }
1705
1706 // Local Variables:
1707 // mode: php
1708 // tab-width: 8
1709 // c-basic-offset: 4
1710 // c-hanging-comment-ender-p: nil
1711 // indent-tabs-mode: nil
1712 // End:   
1713 ?>