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