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