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