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