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