]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
revert wrong inline optimization.
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.55 2004-05-12 19:27:47 rurban 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         static $error_displayed = false;
168         if (DEBUG) {
169             if (!(is_string($pagename) and $pagename != '')) {
170                 if ($error_displayed) return false;
171                 $error_displayed = true;
172                 if (function_exists("xdebug_get_function_stack"))
173                     var_dump(xdebug_get_function_stack());
174                 trigger_error("empty pagename",E_USER_WARNING);
175                 return false;
176             }
177         } else 
178             assert(is_string($pagename) and $pagename != '');
179         return new WikiDB_Page($this, $pagename);
180     }
181
182     /**
183      * Determine whether page exists (in non-default form).
184      *
185      * <pre>
186      *   $is_page = $dbi->isWikiPage($pagename);
187      * </pre>
188      * is equivalent to
189      * <pre>
190      *   $page = $dbi->getPage($pagename);
191      *   $current = $page->getCurrentRevision();
192      *   $is_page = ! $current->hasDefaultContents();
193      * </pre>
194      * however isWikiPage may be implemented in a more efficient
195      * manner in certain back-ends.
196      *
197      * @access public
198      *
199      * @param string $pagename string Which page to check.
200      *
201      * @return boolean True if the page actually exists with
202      * non-default contents in the WikiDataBase.
203      */
204     function isWikiPage ($pagename) {
205         $page = $this->getPage($pagename);
206         $current = $page->getCurrentRevision();
207         return ! $current->hasDefaultContents();
208     }
209
210     /**
211      * Delete page from the WikiDB. 
212      *
213      * Deletes all revisions of the page from the WikiDB. Also resets
214      * all page meta-data to the default values.
215      *
216      * @access public
217      *
218      * @param string $pagename Name of page to delete.
219      */
220     function deletePage($pagename) {
221         $this->_cache->delete_page($pagename);
222
223         //How to create a RecentChanges entry with explaining summary?
224         /*
225         $page = $this->getPage($pagename);
226         $current = $page->getCurrentRevision();
227         $meta = $current->_data;
228         $version = $current->getVersion();
229         $meta['summary'] = _("removed");
230         $page->save($current->getPackedContent(), $version + 1, $meta);
231         */
232     }
233
234     /**
235      * Retrieve all pages.
236      *
237      * Gets the set of all pages with non-default contents.
238      *
239      * FIXME: do we need this?  I think so.  The simple searches
240      *        need this stuff.
241      *
242      * @access public
243      *
244      * @param boolean $include_defaulted Normally pages whose most
245      * recent revision has empty content are considered to be
246      * non-existant. Unless $include_defaulted is set to true, those
247      * pages will not be returned.
248      *
249      * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
250      *     in the WikiDB which have non-default contents.
251      */
252     function getAllPages($include_defaulted=false, $sortby=false, $limit=false) {
253         $result = $this->_backend->get_all_pages($include_defaulted,$sortby,$limit);
254         return new WikiDB_PageIterator($this, $result);
255     }
256
257     // Do we need this?
258     //function nPages() { 
259     //}
260     // Yes, for paging. Renamed.
261     function numPages($filter=false, $exclude='') {
262         if (method_exists($this->_backend,'numPages'))
263             $count = $this->_backend->numPages($filter,$exclude);
264         else {
265             $iter = $this->getAllPages();
266             $count = $iter->count();
267         }
268         return (int)$count;
269     }
270     
271     /**
272      * Title search.
273      *
274      * Search for pages containing (or not containing) certain words
275      * in their names.
276      *
277      * Pages are returned in alphabetical order whenever it is
278      * practical to do so.
279      *
280      * FIXME: should titleSearch and fullSearch be combined?  I think so.
281      *
282      * @access public
283      * @param TextSearchQuery $search A TextSearchQuery object
284      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
285      * @see TextSearchQuery
286      */
287     function titleSearch($search) {
288         $result = $this->_backend->text_search($search);
289         return new WikiDB_PageIterator($this, $result);
290     }
291
292     /**
293      * Full text search.
294      *
295      * Search for pages containing (or not containing) certain words
296      * in their entire text (this includes the page content and the
297      * page name).
298      *
299      * Pages are returned in alphabetical order whenever it is
300      * practical to do so.
301      *
302      * @access public
303      *
304      * @param TextSearchQuery $search A TextSearchQuery object.
305      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
306      * @see TextSearchQuery
307      */
308     function fullSearch($search) {
309         $result = $this->_backend->text_search($search, 'full_text');
310         return new WikiDB_PageIterator($this, $result);
311     }
312
313     /**
314      * Find the pages with the greatest hit counts.
315      *
316      * Pages are returned in reverse order by hit count.
317      *
318      * @access public
319      *
320      * @param integer $limit The maximum number of pages to return.
321      * Set $limit to zero to return all pages.  If $limit < 0, pages will
322      * be sorted in decreasing order of popularity.
323      *
324      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
325      * pages.
326      */
327     function mostPopular($limit = 20, $sortby = '') {
328         // we don't support sortby=mtime here
329         if (strstr($sortby,'mtime'))
330             $sortby = '';
331         $result = $this->_backend->most_popular($limit, $sortby);
332         return new WikiDB_PageIterator($this, $result);
333     }
334
335     /**
336      * Find recent page revisions.
337      *
338      * Revisions are returned in reverse order by creation time.
339      *
340      * @access public
341      *
342      * @param hash $params This hash is used to specify various optional
343      *   parameters:
344      * <dl>
345      * <dt> limit 
346      *    <dd> (integer) At most this many revisions will be returned.
347      * <dt> since
348      *    <dd> (integer) Only revisions since this time (unix-timestamp) will be returned. 
349      * <dt> include_minor_revisions
350      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
351      * <dt> exclude_major_revisions
352      *    <dd> (boolean) Don't include non-minor revisions.
353      *         (Exclude_major_revisions implies include_minor_revisions.)
354      * <dt> include_all_revisions
355      *    <dd> (boolean) Return all matching revisions for each page.
356      *         Normally only the most recent matching revision is returned
357      *         for each page.
358      * </dl>
359      *
360      * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
361      * matching revisions.
362      */
363     function mostRecent($params = false) {
364         $result = $this->_backend->most_recent($params);
365         return new WikiDB_PageRevisionIterator($this, $result);
366     }
367
368     /**
369      * Call the appropriate backend method.
370      *
371      * @access public
372      * @param string $from Page to rename
373      * @param string $to   New name
374      * @param boolean $updateWikiLinks If the text in all pages should be replaced.
375      * @return boolean     true or false
376      */
377     function renamePage($from, $to, $updateWikiLinks = false) {
378         assert(is_string($from) && $from != '');
379         assert(is_string($to) && $to != '');
380         $result = false;
381         if (method_exists($this->_backend,'rename_page')) {
382             $oldpage = $this->getPage($from);
383             $newpage = $this->getPage($to);
384             if ($oldpage->exists() and ! $newpage->exists()) {
385                 if ($result = $this->_backend->rename_page($from, $to)) {
386                     //update all WikiLinks in existing pages
387                     if ($updateWikiLinks) {
388                         //trigger_error(_("WikiDB::renamePage(..,..,updateWikiLinks) not yet implemented"),E_USER_WARNING);
389                         require_once('lib/plugin/WikiAdminSearchReplace.php');
390                         $links = $oldpage->getLinks();
391                         while ($linked_page = $links->next()) {
392                             WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
393                         }
394                         $links = $newpage->getLinks();
395                         while ($linked_page = $links->next()) {
396                             WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,$linked_page->getName(),$from,$to);
397                         }
398                     }
399                     //create a RecentChanges entry with explaining summary
400                     $page = $this->getPage($to);
401                     $current = $page->getCurrentRevision();
402                     $meta = $current->_data;
403                     $version = $current->getVersion();
404                     $meta['summary'] = sprintf(_("renamed from %s"),$from);
405                     $page->save($current->getPackedContent(), $version + 1, $meta);
406                 }
407             }
408         } else {
409             trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),E_USER_WARNING);
410         }
411         return $result;
412     }
413
414     /** Get timestamp when database was last modified.
415      *
416      * @return string A string consisting of two integers,
417      * separated by a space.  The first is the time in
418      * unix timestamp format, the second is a modification
419      * count for the database.
420      *
421      * The idea is that you can cast the return value to an
422      * int to get a timestamp, or you can use the string value
423      * as a good hash for the entire database.
424      */
425     function getTimestamp() {
426         $ts = $this->get('_timestamp');
427         return sprintf("%d %d", $ts[0], $ts[1]);
428     }
429     
430     /**
431      * Update the database timestamp.
432      *
433      */
434     function touch() {
435         $ts = $this->get('_timestamp');
436         $this->set('_timestamp', array(time(), $ts[1] + 1));
437     }
438
439         
440     /**
441      * Access WikiDB global meta-data.
442      *
443      * NOTE: this is currently implemented in a hackish and
444      * not very efficient manner.
445      *
446      * @access public
447      *
448      * @param string $key Which meta data to get.
449      * Some reserved meta-data keys are:
450      * <dl>
451      * <dt>'_timestamp' <dd> Data used by getTimestamp().
452      * </dl>
453      *
454      * @return scalar The requested value, or false if the requested data
455      * is not set.
456      */
457     function get($key) {
458         if (!$key || $key[0] == '%')
459             return false;
460         /*
461          * Hack Alert: We can use any page (existing or not) to store
462          * this data (as long as we always use the same one.)
463          */
464         $gd = $this->getPage('global_data');
465         $data = $gd->get('__global');
466
467         if ($data && isset($data[$key]))
468             return $data[$key];
469         else
470             return false;
471     }
472
473     /**
474      * Set global meta-data.
475      *
476      * NOTE: this is currently implemented in a hackish and
477      * not very efficient manner.
478      *
479      * @see get
480      * @access public
481      *
482      * @param string $key  Meta-data key to set.
483      * @param string $newval  New value.
484      */
485     function set($key, $newval) {
486         if (!$key || $key[0] == '%')
487             return;
488         
489         $gd = $this->getPage('global_data');
490         
491         $data = $gd->get('__global');
492         if ($data === false)
493             $data = array();
494
495         if (empty($newval))
496             unset($data[$key]);
497         else
498             $data[$key] = $newval;
499
500         $gd->set('__global', $data);
501     }
502
503     // simple select or create/update queries which do trigger_error
504     function simpleQuery($sql) {
505         global $DBParams;
506         if ($DBParams['dbtype'] == 'SQL') {
507             $result = $this->_backend->_dbh->query($sql);
508             if (DB::isError($result)) {
509                 $msg = $result->getMessage();
510                 trigger_error("SQL Error: ".DB::errorMessage($result),E_USER_WARNING);
511                 return false;
512             } else {
513                 return $result;
514             }
515         } elseif ($DBParams['dbtype'] == 'ADODB') {
516             if (!($result = $this->_backend->_dbh->Execute($sql))) {
517                 trigger_error("SQL Error: ".$this->_backend->_dbh->ErrorMsg(),E_USER_WARNING);
518                 return false;
519             } else {
520                 return $result;
521             }
522         }
523     }
524
525 };
526
527
528 /**
529  * An abstract base class which representing a wiki-page within a
530  * WikiDB.
531  *
532  * A WikiDB_Page contains a number (at least one) of
533  * WikiDB_PageRevisions.
534  */
535 class WikiDB_Page 
536 {
537     function WikiDB_Page(&$wikidb, $pagename) {
538         $this->_wikidb = &$wikidb;
539         $this->_pagename = $pagename;
540         if (DEBUG) {
541             if (!(is_string($pagename) and $pagename != '')) {
542                 if (function_exists("xdebug_get_function_stack")) {
543                     echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
544
545                 }
546                 trigger_error("empty pagename",E_USER_WARNING);
547                 return false;
548             }
549         } else assert(is_string($pagename) and $pagename != '');
550     }
551
552     /**
553      * Get the name of the wiki page.
554      *
555      * @access public
556      *
557      * @return string The page name.
558      */
559     function getName() {
560         return $this->_pagename;
561     }
562
563     function exists() {
564         $current = $this->getCurrentRevision();
565         return ! $current->hasDefaultContents();
566     }
567
568     /**
569      * Delete an old revision of a WikiDB_Page.
570      *
571      * Deletes the specified revision of the page.
572      * It is a fatal error to attempt to delete the current revision.
573      *
574      * @access public
575      *
576      * @param integer $version Which revision to delete.  (You can also
577      *  use a WikiDB_PageRevision object here.)
578      */
579     function deleteRevision($version) {
580         $backend = &$this->_wikidb->_backend;
581         $cache = &$this->_wikidb->_cache;
582         $pagename = &$this->_pagename;
583
584         $version = $this->_coerce_to_version($version);
585         if ($version == 0)
586             return;
587
588         $backend->lock(array('page','version'));
589         $latestversion = $cache->get_latest_version($pagename);
590         if ($latestversion && $version == $latestversion) {
591             $backend->unlock(array('page','version'));
592             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
593                                   $pagename), E_USER_ERROR);
594             return;
595         }
596
597         $cache->delete_versiondata($pagename, $version);
598         $backend->unlock(array('page','version'));
599     }
600
601     /*
602      * Delete a revision, or possibly merge it with a previous
603      * revision.
604      *
605      * The idea is this:
606      * Suppose an author make a (major) edit to a page.  Shortly
607      * after that the same author makes a minor edit (e.g. to fix
608      * spelling mistakes he just made.)
609      *
610      * Now some time later, where cleaning out old saved revisions,
611      * and would like to delete his minor revision (since there's
612      * really no point in keeping minor revisions around for a long
613      * time.)
614      *
615      * Note that the text after the minor revision probably represents
616      * what the author intended to write better than the text after
617      * the preceding major edit.
618      *
619      * So what we really want to do is merge the minor edit with the
620      * preceding edit.
621      *
622      * We will only do this when:
623      * <ul>
624      * <li>The revision being deleted is a minor one, and
625      * <li>It has the same author as the immediately preceding revision.
626      * </ul>
627      */
628     function mergeRevision($version) {
629         $backend = &$this->_wikidb->_backend;
630         $cache = &$this->_wikidb->_cache;
631         $pagename = &$this->_pagename;
632
633         $version = $this->_coerce_to_version($version);
634         if ($version == 0)
635             return;
636
637         $backend->lock(array('version'));
638         $latestversion = $backend->get_latest_version($pagename);
639         if ($latestversion && $version == $latestversion) {
640             $backend->unlock(array('version'));
641             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
642                                   $pagename), E_USER_ERROR);
643             return;
644         }
645
646         $versiondata = $cache->get_versiondata($pagename, $version, true);
647         if (!$versiondata) {
648             // Not there? ... we're done!
649             $backend->unlock(array('version'));
650             return;
651         }
652
653         if ($versiondata['is_minor_edit']) {
654             $previous = $backend->get_previous_version($pagename, $version);
655             if ($previous) {
656                 $prevdata = $cache->get_versiondata($pagename, $previous);
657                 if ($prevdata['author_id'] == $versiondata['author_id']) {
658                     // This is a minor revision, previous version is
659                     // by the same author. We will merge the
660                     // revisions.
661                     $cache->update_versiondata($pagename, $previous,
662                                                array('%content' => $versiondata['%content'],
663                                                      '_supplanted' => $versiondata['_supplanted']));
664                 }
665             }
666         }
667
668         $cache->delete_versiondata($pagename, $version);
669         $backend->unlock(array('version'));
670     }
671
672     
673     /**
674      * Create a new revision of a {@link WikiDB_Page}.
675      *
676      * @access public
677      *
678      * @param int $version Version number for new revision.  
679      * To ensure proper serialization of edits, $version must be
680      * exactly one higher than the current latest version.
681      * (You can defeat this check by setting $version to
682      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
683      *
684      * @param string $content Contents of new revision.
685      *
686      * @param hash $metadata Metadata for new revision.
687      * All values in the hash should be scalars (strings or integers).
688      *
689      * @param array $links List of pagenames which this page links to.
690      *
691      * @return WikiDB_PageRevision  Returns the new WikiDB_PageRevision object. If
692      * $version was incorrect, returns false
693      */
694     function createRevision($version, &$content, $metadata, $links) {
695         $backend = &$this->_wikidb->_backend;
696         $cache = &$this->_wikidb->_cache;
697         $pagename = &$this->_pagename;
698                 
699         $backend->lock(array('version','page','recent','links','nonempty'));
700
701         $latestversion = $backend->get_latest_version($pagename);
702         $newversion = $latestversion + 1;
703         assert($newversion >= 1);
704
705         if ($version != WIKIDB_FORCE_CREATE && $version != $newversion) {
706             $backend->unlock(array('version','page','recent','links'));
707             return false;
708         }
709
710         $data = $metadata;
711         
712         foreach ($data as $key => $val) {
713             if (empty($val) || $key[0] == '_' || $key[0] == '%')
714                 unset($data[$key]);
715         }
716                         
717         assert(!empty($data['author']));
718         if (empty($data['author_id']))
719             @$data['author_id'] = $data['author'];
720                 
721         if (empty($data['mtime']))
722             $data['mtime'] = time();
723
724         if ($latestversion) {
725             // Ensure mtimes are monotonic.
726             $pdata = $cache->get_versiondata($pagename, $latestversion);
727             if ($data['mtime'] < $pdata['mtime']) {
728                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
729                                       $pagename,"'non-monotonic'"),
730                               E_USER_NOTICE);
731                 $data['orig_mtime'] = $data['mtime'];
732                 $data['mtime'] = $pdata['mtime'];
733             }
734             
735             // FIXME: use (possibly user specified) 'mtime' time or
736             // time()?
737             $cache->update_versiondata($pagename, $latestversion,
738                                        array('_supplanted' => $data['mtime']));
739         }
740
741         $data['%content'] = &$content;
742
743         $cache->set_versiondata($pagename, $newversion, $data);
744
745         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
746         //':deleted' => empty($content)));
747         
748         $backend->set_links($pagename, $links);
749
750         $backend->unlock(array('version','page','recent','links','nonempty'));
751
752         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
753                                        $data);
754     }
755
756     /** A higher-level interface to createRevision.
757      *
758      * This takes care of computing the links, and storing
759      * a cached version of the transformed wiki-text.
760      *
761      * @param string $wikitext  The page content.
762      *
763      * @param int $version Version number for new revision.  
764      * To ensure proper serialization of edits, $version must be
765      * exactly one higher than the current latest version.
766      * (You can defeat this check by setting $version to
767      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
768      *
769      * @param hash $meta  Meta-data for new revision.
770      */
771     function save($wikitext, $version, $meta) {
772         $formatted = new TransformedText($this, $wikitext, $meta);
773         $type = $formatted->getType();
774         $meta['pagetype'] = $type->getName();
775         $links = $formatted->getWikiPageLinks();
776
777         $backend = &$this->_wikidb->_backend;
778         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
779         if ($newrevision)
780             if (!defined('WIKIDB_NOCACHE_MARKUP') or !WIKIDB_NOCACHE_MARKUP)
781                 $this->set('_cached_html', $formatted->pack());
782
783         // FIXME: probably should have some global state information
784         // in the backend to control when to optimize.
785         //
786         // We're doing this here rather than in createRevision because
787         // postgres can't optimize while locked.
788         if (time() % 50 == 0) {
789             if ($backend->optimize())
790                 trigger_error(sprintf(_("Optimizing %s"),'backend'), E_USER_NOTICE);
791         }
792
793         /* Generate notification emails? */
794         if (isa($newrevision, 'wikidb_pagerevision')) {
795             // Save didn't fail because of concurrent updates.
796             $notify = $this->_wikidb->get('notify');
797             if (!empty($notify) and is_array($notify)) {
798                 list($emails,$userids) = $this->getPageChangeEmails($notify);
799                 if (!empty($emails))
800                     $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
801             }
802         }
803
804         $newrevision->_transformedContent = $formatted;
805         return $newrevision;
806     }
807
808     function getPageChangeEmails($notify) {
809         $emails = array(); $userids = array();
810         foreach ($notify as $page => $users) {
811             if (glob_match($page,$this->_pagename)) {
812                 foreach ($users as $userid => $user) {
813                     if (!empty($user['verified']) and !empty($user['email'])) {
814                         $emails[]  = $user['email'];
815                         $userids[] = $userid;
816                     } elseif (!empty($user['email'])) {
817                         global $request;
818                         // do a dynamic emailVerified check update
819                         $u = $request->getUser();
820                         if ($u->UserName() == $userid) {
821                             if ($request->_prefs->get('emailVerified')) {
822                                 $emails[] = $user['email'];
823                                 $userids[] = $userid;
824                                 $notify[$page][$userid]['verified'] = 1;
825                                 $request->_dbi->set('notify',$notify);
826                             }
827                         } else {
828                             $u = WikiUser($userid);
829                             if ($u->_prefs->get('emailVerified')) {
830                                 $emails[] = $user['email'];
831                                 $userids[] = $userid;
832                                 $notify[$page][$userid]['verified'] = 1;
833                                 $request->_dbi->set('notify',$notify);
834                             }
835                         }
836                         // ignore verification
837                         /*
838                         if (DEBUG) {
839                             if (!in_array($user['email'],$emails))
840                                 $emails[] = $user['email'];
841                         }
842                         */
843                     }
844                 }
845             }
846         }
847         $emails = array_unique($emails);
848         $userids = array_unique($userids);
849         return array($emails,$userids);
850     }
851
852     function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
853         $backend = &$this->_wikidb->_backend;
854         $subject = _("Page change").' '.$this->_pagename;
855         $previous = $backend->get_previous_version($this->_pagename, $version);
856         if (!isset($meta['mtime'])) $meta['mtime'] = time();
857         if ($previous) {
858             $difflink = WikiURL($this->_pagename,array('action'=>'diff'),true);
859             $cache = &$this->_wikidb->_cache;
860             $this_content = explode("\n", $wikitext);
861             $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
862             if (empty($prevdata['%content']))
863                 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
864             $other_content = explode("\n", $prevdata['%content']);
865             
866             include_once("lib/diff.php");
867             $diff2 = new Diff($other_content, $this_content);
868             $context_lines = max(4, count($other_content) + 1,
869                                  count($this_content) + 1);
870             $fmt = new UnifiedDiffFormatter($context_lines);
871             $content  = $this->_pagename . " " . $previous . " " . Iso8601DateTime($prevdata['mtime']) . "\n";
872             $content .= $this->_pagename . " " . $version . " " .  Iso8601DateTime($meta['mtime']) . "\n";
873             $content .= $fmt->format($diff2);
874             
875         } else {
876             $difflink = WikiURL($this->_pagename,array(),true);
877             $content = $this->_pagename . " " . $version . " " .  Iso8601DateTime($meta['mtime']) . "\n";
878             $content .= _("New Page");
879         }
880         $editedby = sprintf(_("Edited by: %s"), $meta['author']);
881         $emails = join(',',$emails);
882         if (mail($emails,"[".WIKI_NAME."] ".$subject, 
883                  $subject."\n".
884                  $editedby."\n".
885                  $difflink."\n\n".
886                  $content))
887             trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
888                                   $this->_pagename, join(',',$userids)), E_USER_NOTICE);
889         else
890             trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
891                                   $this->_pagename, join(',',$userids)), E_USER_WARNING);
892     }
893
894     /**
895      * Get the most recent revision of a page.
896      *
897      * @access public
898      *
899      * @return WikiDB_PageRevision The current WikiDB_PageRevision object. 
900      */
901     function getCurrentRevision() {
902         $backend = &$this->_wikidb->_backend;
903         $cache = &$this->_wikidb->_cache;
904         $pagename = &$this->_pagename;
905         
906         // Prevent deadlock in case of memory exhausted errors
907         // Pure selection doesn't really need locking here.
908         //   sf.net bug#927395
909         // I know it would be better, but with lots of pages this deadlock is more 
910         // severe than occasionally get not the latest revision.
911         //$backend->lock();
912         $version = $cache->get_latest_version($pagename);
913         $revision = $this->getRevision($version);
914         //$backend->unlock();
915         assert($revision);
916         return $revision;
917     }
918
919     /**
920      * Get a specific revision of a WikiDB_Page.
921      *
922      * @access public
923      *
924      * @param integer $version  Which revision to get.
925      *
926      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
927      * false if the requested revision does not exist in the {@link WikiDB}.
928      * Note that version zero of any page always exists.
929      */
930     function getRevision($version) {
931         $cache = &$this->_wikidb->_cache;
932         $pagename = &$this->_pagename;
933         
934         if ($version == 0)
935             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
936
937         assert($version > 0);
938         $vdata = $cache->get_versiondata($pagename, $version);
939         if (!$vdata)
940             return false;
941         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
942                                        $vdata);
943     }
944
945     /**
946      * Get previous page revision.
947      *
948      * This method find the most recent revision before a specified
949      * version.
950      *
951      * @access public
952      *
953      * @param integer $version  Find most recent revision before this version.
954      *  You can also use a WikiDB_PageRevision object to specify the $version.
955      *
956      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
957      * requested revision does not exist in the {@link WikiDB}.  Note that
958      * unless $version is greater than zero, a revision (perhaps version zero,
959      * the default revision) will always be found.
960      */
961     function getRevisionBefore($version) {
962         $backend = &$this->_wikidb->_backend;
963         $pagename = &$this->_pagename;
964
965         $version = $this->_coerce_to_version($version);
966
967         if ($version == 0)
968             return false;
969         //$backend->lock();
970         $previous = $backend->get_previous_version($pagename, $version);
971         $revision = $this->getRevision($previous);
972         //$backend->unlock();
973         assert($revision);
974         return $revision;
975     }
976
977     /**
978      * Get all revisions of the WikiDB_Page.
979      *
980      * This does not include the version zero (default) revision in the
981      * returned revision set.
982      *
983      * @return WikiDB_PageRevisionIterator A
984      * WikiDB_PageRevisionIterator containing all revisions of this
985      * WikiDB_Page in reverse order by version number.
986      */
987     function getAllRevisions() {
988         $backend = &$this->_wikidb->_backend;
989         $revs = $backend->get_all_revisions($this->_pagename);
990         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
991     }
992     
993     /**
994      * Find pages which link to or are linked from a page.
995      *
996      * @access public
997      *
998      * @param boolean $reversed Which links to find: true for backlinks (default).
999      *
1000      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1001      * all matching pages.
1002      */
1003     function getLinks($reversed = true) {
1004         $backend = &$this->_wikidb->_backend;
1005         $result =  $backend->get_links($this->_pagename, $reversed);
1006         return new WikiDB_PageIterator($this->_wikidb, $result);
1007     }
1008             
1009     /**
1010      * Access WikiDB_Page meta-data.
1011      *
1012      * @access public
1013      *
1014      * @param string $key Which meta data to get.
1015      * Some reserved meta-data keys are:
1016      * <dl>
1017      * <dt>'locked'<dd> Is page locked?
1018      * <dt>'hits'  <dd> Page hit counter.
1019      * <dt>'pref'  <dd> Users preferences, stored in homepages.
1020      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1021      *                  E.g. "owner.users"
1022      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
1023      *                  page-headers and content.
1024      * <dt>'score' <dd> Page score (not yet implement, do we need?)
1025      * </dl>
1026      *
1027      * @return scalar The requested value, or false if the requested data
1028      * is not set.
1029      */
1030     function get($key) {
1031         $cache = &$this->_wikidb->_cache;
1032         if (!$key || $key[0] == '%')
1033             return false;
1034         $data = $cache->get_pagedata($this->_pagename);
1035         return isset($data[$key]) ? $data[$key] : false;
1036     }
1037
1038     /**
1039      * Get all the page meta-data as a hash.
1040      *
1041      * @return hash The page meta-data.
1042      */
1043     function getMetaData() {
1044         $cache = &$this->_wikidb->_cache;
1045         $data = $cache->get_pagedata($this->_pagename);
1046         $meta = array();
1047         foreach ($data as $key => $val) {
1048             if (/*!empty($val) &&*/ $key[0] != '%')
1049                 $meta[$key] = $val;
1050         }
1051         return $meta;
1052     }
1053
1054     /**
1055      * Set page meta-data.
1056      *
1057      * @see get
1058      * @access public
1059      *
1060      * @param string $key  Meta-data key to set.
1061      * @param string $newval  New value.
1062      */
1063     function set($key, $newval) {
1064         $cache = &$this->_wikidb->_cache;
1065         $pagename = &$this->_pagename;
1066         
1067         assert($key && $key[0] != '%');
1068
1069         $data = $cache->get_pagedata($pagename);
1070
1071         if (!empty($newval)) {
1072             if (!empty($data[$key]) && $data[$key] == $newval)
1073                 return;         // values identical, skip update.
1074         }
1075         else {
1076             if (empty($data[$key]))
1077                 return;         // values identical, skip update.
1078         }
1079
1080         $cache->update_pagedata($pagename, array($key => $newval));
1081     }
1082
1083     /**
1084      * Increase page hit count.
1085      *
1086      * FIXME: IS this needed?  Probably not.
1087      *
1088      * This is a convenience function.
1089      * <pre> $page->increaseHitCount(); </pre>
1090      * is functionally identical to
1091      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1092      *
1093      * Note that this method may be implemented in more efficient ways
1094      * in certain backends.
1095      *
1096      * @access public
1097      */
1098     function increaseHitCount() {
1099         @$newhits = $this->get('hits') + 1;
1100         $this->set('hits', $newhits);
1101     }
1102
1103     /**
1104      * Return a string representation of the WikiDB_Page
1105      *
1106      * This is really only for debugging.
1107      *
1108      * @access public
1109      *
1110      * @return string Printable representation of the WikiDB_Page.
1111      */
1112     function asString () {
1113         ob_start();
1114         printf("[%s:%s\n", get_class($this), $this->getName());
1115         print_r($this->getMetaData());
1116         echo "]\n";
1117         $strval = ob_get_contents();
1118         ob_end_clean();
1119         return $strval;
1120     }
1121
1122
1123     /**
1124      * @access private
1125      * @param integer_or_object $version_or_pagerevision
1126      * Takes either the version number (and int) or a WikiDB_PageRevision
1127      * object.
1128      * @return integer The version number.
1129      */
1130     function _coerce_to_version($version_or_pagerevision) {
1131         if (method_exists($version_or_pagerevision, "getContent"))
1132             $version = $version_or_pagerevision->getVersion();
1133         else
1134             $version = (int) $version_or_pagerevision;
1135
1136         assert($version >= 0);
1137         return $version;
1138     }
1139
1140     function isUserPage ($include_empty = true) {
1141         if ($include_empty) {
1142             $current = $this->getCurrentRevision();
1143             if ($current->hasDefaultContents()) {
1144                 return false;
1145             }
1146         }
1147         return $this->get('pref') ? true : false;
1148     }
1149
1150 };
1151
1152 /**
1153  * This class represents a specific revision of a WikiDB_Page within
1154  * a WikiDB.
1155  *
1156  * A WikiDB_PageRevision has read-only semantics. You may only create
1157  * new revisions (and delete old ones) --- you cannot modify existing
1158  * revisions.
1159  */
1160 class WikiDB_PageRevision
1161 {
1162     var $_transformedContent = false; // set by WikiDB_Page::save()
1163     
1164     function WikiDB_PageRevision(&$wikidb, $pagename, $version,
1165                                  $versiondata = false)
1166         {
1167             $this->_wikidb = &$wikidb;
1168             $this->_pagename = $pagename;
1169             $this->_version = $version;
1170             $this->_data = $versiondata ? $versiondata : array();
1171         }
1172     
1173     /**
1174      * Get the WikiDB_Page which this revision belongs to.
1175      *
1176      * @access public
1177      *
1178      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1179      */
1180     function getPage() {
1181         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1182     }
1183
1184     /**
1185      * Get the version number of this revision.
1186      *
1187      * @access public
1188      *
1189      * @return integer The version number of this revision.
1190      */
1191     function getVersion() {
1192         return $this->_version;
1193     }
1194     
1195     /**
1196      * Determine whether this revision has defaulted content.
1197      *
1198      * The default revision (version 0) of each page, as well as any
1199      * pages which are created with empty content have their content
1200      * defaulted to something like:
1201      * <pre>
1202      *   Describe [ThisPage] here.
1203      * </pre>
1204      *
1205      * @access public
1206      *
1207      * @return boolean Returns true if the page has default content.
1208      */
1209     function hasDefaultContents() {
1210         $data = &$this->_data;
1211         return empty($data['%content']);
1212     }
1213
1214     /**
1215      * Get the content as an array of lines.
1216      *
1217      * @access public
1218      *
1219      * @return array An array of lines.
1220      * The lines should contain no trailing white space.
1221      */
1222     function getContent() {
1223         return explode("\n", $this->getPackedContent());
1224     }
1225         
1226         /**
1227      * Get the pagename of the revision.
1228      *
1229      * @access public
1230      *
1231      * @return string pagename.
1232      */
1233     function getPageName() {
1234         return $this->_pagename;
1235     }
1236
1237     /**
1238      * Determine whether revision is the latest.
1239      *
1240      * @access public
1241      *
1242      * @return boolean True iff the revision is the latest (most recent) one.
1243      */
1244     function isCurrent() {
1245         if (!isset($this->_iscurrent)) {
1246             $page = $this->getPage();
1247             $current = $page->getCurrentRevision();
1248             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1249         }
1250         return $this->_iscurrent;
1251     }
1252
1253     /**
1254      * Get the transformed content of a page.
1255      *
1256      * @param string $pagetype  Override the page-type of the revision.
1257      *
1258      * @return object An XmlContent-like object containing the page transformed
1259      * contents.
1260      */
1261     function getTransformedContent($pagetype_override=false) {
1262         $backend = &$this->_wikidb->_backend;
1263         
1264         if ($pagetype_override) {
1265             // Figure out the normal page-type for this page.
1266             $type = PageType::GetPageType($this->get('pagetype'));
1267             if ($type->getName() == $pagetype_override)
1268                 $pagetype_override = false; // Not really an override...
1269         }
1270
1271         if ($pagetype_override) {
1272             // Overriden page type, don't cache (or check cache).
1273             return new TransformedText($this->getPage(),
1274                                        $this->getPackedContent(),
1275                                        $this->getMetaData(),
1276                                        $pagetype_override);
1277         }
1278
1279         $possibly_cache_results = true;
1280
1281         if (defined('WIKIDB_NOCACHE_MARKUP') and WIKIDB_NOCACHE_MARKUP) {
1282             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1283                 // flush cache for this page.
1284                 $page = $this->getPage();
1285                 $page->set('_cached_html', false);
1286             }
1287             $possibly_cache_results = false;
1288         }
1289         elseif (!$this->_transformedContent) {
1290             //$backend->lock();
1291             if ($this->isCurrent()) {
1292                 $page = $this->getPage();
1293                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1294             }
1295             else {
1296                 $possibly_cache_results = false;
1297             }
1298             //$backend->unlock();
1299         }
1300         
1301         if (!$this->_transformedContent) {
1302             $this->_transformedContent
1303                 = new TransformedText($this->getPage(),
1304                                       $this->getPackedContent(),
1305                                       $this->getMetaData());
1306             
1307             if ($possibly_cache_results) {
1308                 // If we're still the current version, cache the transfomed page.
1309                 //$backend->lock();
1310                 if ($this->isCurrent()) {
1311                     $page->set('_cached_html', $this->_transformedContent->pack());
1312                 }
1313                 //$backend->unlock();
1314             }
1315         }
1316
1317         return $this->_transformedContent;
1318     }
1319
1320     /**
1321      * Get the content as a string.
1322      *
1323      * @access public
1324      *
1325      * @return string The page content.
1326      * Lines are separated by new-lines.
1327      */
1328     function getPackedContent() {
1329         $data = &$this->_data;
1330
1331         
1332         if (empty($data['%content'])) {
1333             include_once('lib/InlineParser.php');
1334             // Replace empty content with default value.
1335             return sprintf(_("Describe %s here."), 
1336                            "[" . WikiEscape($this->_pagename) . "]");
1337         }
1338
1339         // There is (non-default) content.
1340         assert($this->_version > 0);
1341         
1342         if (!is_string($data['%content'])) {
1343             // Content was not provided to us at init time.
1344             // (This is allowed because for some backends, fetching
1345             // the content may be expensive, and often is not wanted
1346             // by the user.)
1347             //
1348             // In any case, now we need to get it.
1349             $data['%content'] = $this->_get_content();
1350             assert(is_string($data['%content']));
1351         }
1352         
1353         return $data['%content'];
1354     }
1355
1356     function _get_content() {
1357         $cache = &$this->_wikidb->_cache;
1358         $pagename = $this->_pagename;
1359         $version = $this->_version;
1360
1361         assert($version > 0);
1362         
1363         $newdata = $cache->get_versiondata($pagename, $version, true);
1364         if ($newdata) {
1365             assert(is_string($newdata['%content']));
1366             return $newdata['%content'];
1367         }
1368         else {
1369             // else revision has been deleted... What to do?
1370             return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1371                              $version, $pagename);
1372         }
1373     }
1374
1375     /**
1376      * Get meta-data for this revision.
1377      *
1378      *
1379      * @access public
1380      *
1381      * @param string $key Which meta-data to access.
1382      *
1383      * Some reserved revision meta-data keys are:
1384      * <dl>
1385      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1386      *        The 'mtime' meta-value is normally set automatically by the database
1387      *        backend, but it may be specified explicitly when creating a new revision.
1388      * <dt> orig_mtime
1389      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1390      *       of a page must be monotonically increasing.  If an attempt is
1391      *       made to create a new revision with an mtime less than that of
1392      *       the preceeding revision, the new revisions timestamp is force
1393      *       to be equal to that of the preceeding revision.  In that case,
1394      *       the originally requested mtime is preserved in 'orig_mtime'.
1395      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1396      *        This meta-value is <em>always</em> automatically maintained by the database
1397      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1398      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1399      *
1400      * FIXME: this could be refactored:
1401      * <dt> author
1402      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1403      * <dt> author_id
1404      *  <dd> Authenticated author of a page.  This is used to identify
1405      *       the distinctness of authors when cleaning old revisions from
1406      *       the database.
1407      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1408      * <dt> 'summary' <dd> Short change summary entered by page author.
1409      * </dl>
1410      *
1411      * Meta-data keys must be valid C identifers (they have to start with a letter
1412      * or underscore, and can contain only alphanumerics and underscores.)
1413      *
1414      * @return string The requested value, or false if the requested value
1415      * is not defined.
1416      */
1417     function get($key) {
1418         if (!$key || $key[0] == '%')
1419             return false;
1420         $data = &$this->_data;
1421         return isset($data[$key]) ? $data[$key] : false;
1422     }
1423
1424     /**
1425      * Get all the revision page meta-data as a hash.
1426      *
1427      * @return hash The revision meta-data.
1428      */
1429     function getMetaData() {
1430         $meta = array();
1431         foreach ($this->_data as $key => $val) {
1432             if (!empty($val) && $key[0] != '%')
1433                 $meta[$key] = $val;
1434         }
1435         return $meta;
1436     }
1437     
1438             
1439     /**
1440      * Return a string representation of the revision.
1441      *
1442      * This is really only for debugging.
1443      *
1444      * @access public
1445      *
1446      * @return string Printable representation of the WikiDB_Page.
1447      */
1448     function asString () {
1449         ob_start();
1450         printf("[%s:%d\n", get_class($this), $this->get('version'));
1451         print_r($this->_data);
1452         echo $this->getPackedContent() . "\n]\n";
1453         $strval = ob_get_contents();
1454         ob_end_clean();
1455         return $strval;
1456     }
1457 };
1458
1459
1460 /**
1461  * A class which represents a sequence of WikiDB_Pages.
1462  */
1463 class WikiDB_PageIterator
1464 {
1465     function WikiDB_PageIterator(&$wikidb, &$pages) {
1466         $this->_pages = $pages;
1467         $this->_wikidb = &$wikidb;
1468     }
1469     
1470     function count () {
1471         return $this->_pages->count();
1472     }
1473
1474     /**
1475      * Get next WikiDB_Page in sequence.
1476      *
1477      * @access public
1478      *
1479      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1480      */
1481     function next () {
1482         if ( ! ($next = $this->_pages->next()) )
1483             return false;
1484
1485         $pagename = &$next['pagename'];
1486         if (!$pagename) {
1487             trigger_error(__FILE__.':'.__LINE__.' empty pagename in WikiDB_PageIterator::next()',E_USER_WARNING);
1488             var_dump($next);
1489             return false;
1490         }
1491         if (isset($next['pagedata']))
1492             $this->_wikidb->_cache->cache_data($next);
1493
1494         return new WikiDB_Page($this->_wikidb, $pagename);
1495     }
1496
1497     /**
1498      * Release resources held by this iterator.
1499      *
1500      * The iterator may not be used after free() is called.
1501      *
1502      * There is no need to call free(), if next() has returned false.
1503      * (I.e. if you iterate through all the pages in the sequence,
1504      * you do not need to call free() --- you only need to call it
1505      * if you stop before the end of the iterator is reached.)
1506      *
1507      * @access public
1508      */
1509     function free() {
1510         $this->_pages->free();
1511     }
1512
1513     
1514     function asArray() {
1515         $result = array();
1516         while ($page = $this->next())
1517             $result[] = $page;
1518         $this->free();
1519         return $result;
1520     }
1521     
1522     // Not yet used and problematic. Order should be set in the query, not afterwards.
1523     // See PageList::sortby
1524     function setSortby ($arg = false) {
1525         if (!$arg) {
1526             $arg = @$_GET['sortby'];
1527             if ($arg) {
1528                 $sortby = substr($arg,1);
1529                 $order  = substr($arg,0,1)=='+' ? 'ASC' : 'DESC';
1530             }
1531         }
1532         if (is_array($arg)) { // array('mtime' => 'desc')
1533             $sortby = $arg[0];
1534             $order = $arg[1];
1535         } else {
1536             $sortby = $arg;
1537             $order  = 'ASC';
1538         }
1539         // available column types to sort by:
1540         // todo: we must provide access methods for the generic dumb/iterator
1541         $this->_types = explode(',','pagename,mtime,hits,version,author,locked,minor,markup');
1542         if (in_array($sortby,$this->_types))
1543             $this->_options['sortby'] = $sortby;
1544         else
1545             trigger_error(sprintf("Argument %s '%s' ignored",'sortby',$sortby), E_USER_WARNING);
1546         if (in_array(strtoupper($order),'ASC','DESC')) 
1547             $this->_options['order'] = strtoupper($order);
1548         else
1549             trigger_error(sprintf("Argument %s '%s' ignored",'order',$order), E_USER_WARNING);
1550     }
1551
1552 };
1553
1554 /**
1555  * A class which represents a sequence of WikiDB_PageRevisions.
1556  */
1557 class WikiDB_PageRevisionIterator
1558 {
1559     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions) {
1560         $this->_revisions = $revisions;
1561         $this->_wikidb = &$wikidb;
1562     }
1563     
1564     function count () {
1565         return $this->_revisions->count();
1566     }
1567
1568     /**
1569      * Get next WikiDB_PageRevision in sequence.
1570      *
1571      * @access public
1572      *
1573      * @return WikiDB_PageRevision
1574      * The next WikiDB_PageRevision in the sequence.
1575      */
1576     function next () {
1577         if ( ! ($next = $this->_revisions->next()) )
1578             return false;
1579
1580         $this->_wikidb->_cache->cache_data($next);
1581
1582         $pagename = $next['pagename'];
1583         $version = $next['version'];
1584         $versiondata = $next['versiondata'];
1585         if (DEBUG) {
1586             if (!(is_string($pagename) and $pagename != '')) {
1587                 trigger_error("empty pagename",E_USER_WARNING);
1588                 return false;
1589             }
1590         } else assert(is_string($pagename) and $pagename != '');
1591         if (DEBUG) {
1592             if (!is_array($versiondata)) {
1593                 trigger_error("empty versiondata",E_USER_WARNING);
1594                 return false;
1595             }
1596         } else assert(is_array($versiondata));
1597         if (DEBUG) {
1598             if (!($version > 0)) {
1599                 trigger_error("invalid version",E_USER_WARNING);
1600                 return false;
1601             }
1602         } else assert($version > 0);
1603
1604         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1605                                        $versiondata);
1606     }
1607
1608     /**
1609      * Release resources held by this iterator.
1610      *
1611      * The iterator may not be used after free() is called.
1612      *
1613      * There is no need to call free(), if next() has returned false.
1614      * (I.e. if you iterate through all the revisions in the sequence,
1615      * you do not need to call free() --- you only need to call it
1616      * if you stop before the end of the iterator is reached.)
1617      *
1618      * @access public
1619      */
1620     function free() { 
1621         $this->_revisions->free();
1622     }
1623 };
1624
1625
1626 /**
1627  * Data cache used by WikiDB.
1628  *
1629  * FIXME: Maybe rename this to caching_backend (or some such).
1630  *
1631  * @access private
1632  */
1633 class WikiDB_cache 
1634 {
1635     // FIXME: beautify versiondata cache.  Cache only limited data?
1636
1637     function WikiDB_cache (&$backend) {
1638         $this->_backend = &$backend;
1639
1640         $this->_pagedata_cache = array();
1641         $this->_versiondata_cache = array();
1642         array_push ($this->_versiondata_cache, array());
1643         $this->_glv_cache = array();
1644     }
1645     
1646     function close() {
1647         $this->_pagedata_cache = false;
1648         $this->_versiondata_cache = false;
1649         $this->_glv_cache = false;
1650     }
1651
1652     function get_pagedata($pagename) {
1653         assert(is_string($pagename) && $pagename != '');
1654         $cache = &$this->_pagedata_cache;
1655
1656         if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
1657             $cache[$pagename] = $this->_backend->get_pagedata($pagename);
1658             if (empty($cache[$pagename]))
1659                 $cache[$pagename] = array();
1660         }
1661
1662         return $cache[$pagename];
1663     }
1664     
1665     function update_pagedata($pagename, $newdata) {
1666         assert(is_string($pagename) && $pagename != '');
1667
1668         $this->_backend->update_pagedata($pagename, $newdata);
1669
1670         if (is_array($this->_pagedata_cache[$pagename])) {
1671             $cachedata = &$this->_pagedata_cache[$pagename];
1672             foreach($newdata as $key => $val)
1673                 $cachedata[$key] = $val;
1674         }
1675     }
1676
1677     function invalidate_cache($pagename) {
1678         unset ($this->_pagedata_cache[$pagename]);
1679         unset ($this->_versiondata_cache[$pagename]);
1680         unset ($this->_glv_cache[$pagename]);
1681     }
1682     
1683     function delete_page($pagename) {
1684         $this->_backend->delete_page($pagename);
1685         unset ($this->_pagedata_cache[$pagename]);
1686         unset ($this->_glv_cache[$pagename]);
1687     }
1688
1689     // FIXME: ugly
1690     function cache_data($data) {
1691         if (isset($data['pagedata']))
1692             $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
1693     }
1694     
1695     function get_versiondata($pagename, $version, $need_content = false) {
1696         //  FIXME: Seriously ugly hackage
1697         if (defined('USECACHE') and USECACHE) {   //temporary - for debugging
1698             assert(is_string($pagename) && $pagename != '');
1699             // there is a bug here somewhere which results in an assertion failure at line 105
1700             // of ArchiveCleaner.php  It goes away if we use the next line.
1701             $need_content = true;
1702             $nc = $need_content ? '1':'0';
1703             $cache = &$this->_versiondata_cache;
1704             if (!isset($cache[$pagename][$version][$nc])||
1705                 !(is_array ($cache[$pagename])) || !(is_array ($cache[$pagename][$version]))) {
1706                 $cache[$pagename][$version][$nc] = 
1707                     $this->_backend->get_versiondata($pagename,$version, $need_content);
1708                 // If we have retrieved all data, we may as well set the cache for $need_content = false
1709                 if ($need_content){
1710                     $cache[$pagename][$version]['0'] = $cache[$pagename][$version]['1'];
1711                 }
1712             }
1713             $vdata = $cache[$pagename][$version][$nc];
1714         } else {
1715             $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
1716         }
1717         // FIXME: ugly
1718         if ($vdata && !empty($vdata['%pagedata']))
1719             $this->_pagedata_cache[$pagename] = $vdata['%pagedata'];
1720         return $vdata;
1721     }
1722
1723     function set_versiondata($pagename, $version, $data) {
1724         $new = $this->_backend->set_versiondata($pagename, $version, $data);
1725         // Update the cache
1726         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1727         // FIXME: hack
1728         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1729         // Is this necessary?
1730         unset($this->_glv_cache[$pagename]);
1731     }
1732
1733     function update_versiondata($pagename, $version, $data) {
1734         $new = $this->_backend->update_versiondata($pagename, $version, $data);
1735         // Update the cache
1736         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
1737         // FIXME: hack
1738         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
1739         // Is this necessary?
1740         unset($this->_glv_cache[$pagename]);
1741     }
1742
1743     function delete_versiondata($pagename, $version) {
1744         $new = $this->_backend->delete_versiondata($pagename, $version);
1745         unset ($this->_versiondata_cache[$pagename][$version]['1']);
1746         unset ($this->_versiondata_cache[$pagename][$version]['0']);
1747         unset ($this->_glv_cache[$pagename]);
1748     }
1749         
1750     function get_latest_version($pagename)  {
1751         if (defined('USECACHE')){
1752             assert (is_string($pagename) && $pagename != '');
1753             $cache = &$this->_glv_cache;        
1754             if (!isset($cache[$pagename])) {
1755                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
1756                 if (empty($cache[$pagename]))
1757                     $cache[$pagename] = 0;
1758             }
1759             return $cache[$pagename];
1760         } else {
1761             return $this->_backend->get_latest_version($pagename); 
1762         }
1763     }
1764
1765 };
1766
1767 // $Log: not supported by cvs2svn $
1768 // Revision 1.54  2004/05/12 10:49:55  rurban
1769 // require_once fix for those libs which are loaded before FileFinder and
1770 //   its automatic include_path fix, and where require_once doesn't grok
1771 //   dirname(__FILE__) != './lib'
1772 // upgrade fix with PearDB
1773 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1774 //
1775 // Revision 1.53  2004/05/08 14:06:12  rurban
1776 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
1777 // minor stability and portability fixes
1778 //
1779 // Revision 1.52  2004/05/06 19:26:16  rurban
1780 // improve stability, trying to find the InlineParser endless loop on sf.net
1781 //
1782 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1783 //
1784 // Revision 1.51  2004/05/06 17:30:37  rurban
1785 // CategoryGroup: oops, dos2unix eol
1786 // improved phpwiki_version:
1787 //   pre -= .0001 (1.3.10pre: 1030.099)
1788 //   -p1 += .001 (1.3.9-p1: 1030.091)
1789 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1790 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1791 //   backend->backendType(), backend->database(),
1792 //   backend->listOfFields(),
1793 //   backend->listOfTables(),
1794 //
1795 // Revision 1.50  2004/05/04 22:34:25  rurban
1796 // more pdf support
1797 //
1798 // Revision 1.49  2004/05/03 11:16:40  rurban
1799 // fixed sendPageChangeNotification
1800 // subject rewording
1801 //
1802 // Revision 1.48  2004/04/29 23:03:54  rurban
1803 // fixed sf.net bug #940996
1804 //
1805 // Revision 1.47  2004/04/29 19:39:44  rurban
1806 // special support for formatted plugins (one-liners)
1807 //   like <small><plugin BlaBla ></small>
1808 // iter->asArray() helper for PopularNearby
1809 // db_session for older php's (no &func() allowed)
1810 //
1811 // Revision 1.46  2004/04/26 20:44:34  rurban
1812 // locking table specific for better databases
1813 //
1814 // Revision 1.45  2004/04/20 00:06:03  rurban
1815 // themable paging support
1816 //
1817 // Revision 1.44  2004/04/19 18:27:45  rurban
1818 // Prevent from some PHP5 warnings (ref args, no :: object init)
1819 //   php5 runs now through, just one wrong XmlElement object init missing
1820 // Removed unneccesary UpgradeUser lines
1821 // Changed WikiLink to omit version if current (RecentChanges)
1822 //
1823 // Revision 1.43  2004/04/18 01:34:20  rurban
1824 // protect most_popular from sortby=mtime
1825 //
1826 // Revision 1.42  2004/04/18 01:11:51  rurban
1827 // more numeric pagename fixes.
1828 // fixed action=upload with merge conflict warnings.
1829 // charset changed from constant to global (dynamic utf-8 switching)
1830 //
1831
1832 // Local Variables:
1833 // mode: php
1834 // tab-width: 8
1835 // c-basic-offset: 4
1836 // c-hanging-comment-ender-p: nil
1837 // indent-tabs-mode: nil
1838 // End:   
1839 ?>