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