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