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