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