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