]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB.php
improve description
[SourceForge/phpwiki.git] / lib / WikiDB.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiDB.php,v 1.136 2005-10-03 16:14:57 rurban Exp $');
3
4 require_once('lib/PageType.php');
5
6 /**
7  * The classes in the file define the interface to the
8  * page database.
9  *
10  * @package WikiDB
11  * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
12  *         Reini Urban
13  */
14
15 /**
16  * Force the creation of a new revision.
17  * @see WikiDB_Page::createRevision()
18  */
19 if (!defined('WIKIDB_FORCE_CREATE'))
20     define('WIKIDB_FORCE_CREATE', -1);
21
22 /** 
23  * Abstract base class for the database used by PhpWiki.
24  *
25  * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
26  * turn contain <tt>WikiDB_PageRevision</tt>s.
27  *
28  * Conceptually a <tt>WikiDB</tt> contains all possible
29  * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
30  * Since all possible pages are already contained in a WikiDB, a call
31  * to WikiDB::getPage() will never fail (barring bugs and
32  * e.g. filesystem or SQL database problems.)
33  *
34  * Also each <tt>WikiDB_Page</tt> always contains at least one
35  * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
36  * [PageName] here.").  This default content has a version number of
37  * zero.
38  *
39  * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
40  * only create new revisions or delete old ones --- one can not modify
41  * an existing revision.
42  */
43 class WikiDB {
44     /**
45      * Open a WikiDB database.
46      *
47      * This is a static member function. This function inspects its
48      * arguments to determine the proper subclass of WikiDB to
49      * instantiate, and then it instantiates it.
50      *
51      * @access public
52      *
53      * @param hash $dbparams Database configuration parameters.
54      * Some pertinent paramters are:
55      * <dl>
56      * <dt> dbtype
57      * <dd> The back-end type.  Current supported types are:
58      *   <dl>
59      *   <dt> SQL
60      *     <dd> Generic SQL backend based on the PEAR/DB database abstraction
61      *       library. (More stable and conservative)
62      *   <dt> ADODB
63      *     <dd> Another generic SQL backend. (More current features are tested here. Much faster)
64      *   <dt> dba
65      *     <dd> Dba based backend. The default and by far the fastest.
66      *   <dt> cvs
67      *     <dd> 
68      *   <dt> file
69      *     <dd> flat files
70      *   </dl>
71      *
72      * <dt> dsn
73      * <dd> (Used by the SQL and ADODB backends.)
74      *      The DSN specifying which database to connect to.
75      *
76      * <dt> prefix
77      * <dd> Prefix to be prepended to database tables (and file names).
78      *
79      * <dt> directory
80      * <dd> (Used by the dba backend.)
81      *      Which directory db files reside in.
82      *
83      * <dt> timeout
84      * <dd> Used only by the dba backend so far. 
85      *      And: When optimizing mysql it closes timed out mysql processes.
86      *      otherwise only used for dba: Timeout in seconds for opening (and 
87      *      obtaining lock) on the dbm file.
88      *
89      * <dt> dba_handler
90      * <dd> (Used by the dba backend.)
91      *
92      *      Which dba handler to use. Good choices are probably either
93      *      'gdbm' or 'db2'.
94      * </dl>
95      *
96      * @return WikiDB A WikiDB object.
97      **/
98     function open ($dbparams) {
99         $dbtype = $dbparams{'dbtype'};
100         include_once("lib/WikiDB/$dbtype.php");
101                                 
102         $class = 'WikiDB_' . $dbtype;
103         return new $class ($dbparams);
104     }
105
106
107     /**
108      * Constructor.
109      *
110      * @access private
111      * @see open()
112      */
113     function WikiDB (&$backend, $dbparams) {
114         $this->_backend = &$backend;
115         // don't do the following with the auth_dsn!
116         if (isset($dbparams['auth_dsn'])) return;
117         
118         $this->_cache = new WikiDB_cache($backend);
119         if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;
120
121         // If the database doesn't yet have a timestamp, initialize it now.
122         if ($this->get('_timestamp') === false)
123             $this->touch();
124         
125         //FIXME: devel checking.
126         //$this->_backend->check();
127     }
128     
129     /**
130      * Close database connection.
131      *
132      * The database may no longer be used after it is closed.
133      *
134      * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
135      * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
136      * which have been obtained from it.
137      *
138      * @access public
139      */
140     function close () {
141         $this->_backend->close();
142         $this->_cache->close();
143     }
144     
145     /**
146      * Get a WikiDB_Page from a WikiDB.
147      *
148      * A {@link WikiDB} consists of the (infinite) set of all possible pages,
149      * therefore this method never fails.
150      *
151      * @access public
152      * @param string $pagename Which page to get.
153      * @return WikiDB_Page The requested WikiDB_Page.
154      */
155     function getPage($pagename) {
156         static $error_displayed = false;
157         $pagename = (string) $pagename;
158         if (DEBUG) {
159             if ($pagename === '') {
160                 if ($error_displayed) return false;
161                 $error_displayed = true;
162                 if (function_exists("xdebug_get_function_stack"))
163                     var_dump(xdebug_get_function_stack());
164                 trigger_error("empty pagename", E_USER_WARNING);
165                 return false;
166             }
167         } else {
168             assert($pagename != '');
169         }
170         return new WikiDB_Page($this, $pagename);
171     }
172
173     /**
174      * Determine whether page exists (in non-default form).
175      *
176      * <pre>
177      *   $is_page = $dbi->isWikiPage($pagename);
178      * </pre>
179      * is equivalent to
180      * <pre>
181      *   $page = $dbi->getPage($pagename);
182      *   $current = $page->getCurrentRevision();
183      *   $is_page = ! $current->hasDefaultContents();
184      * </pre>
185      * however isWikiPage may be implemented in a more efficient
186      * manner in certain back-ends.
187      *
188      * @access public
189      *
190      * @param string $pagename string Which page to check.
191      *
192      * @return boolean True if the page actually exists with
193      * non-default contents in the WikiDataBase.
194      */
195     function isWikiPage ($pagename) {
196         $page = $this->getPage($pagename);
197         return $page->exists();
198     }
199
200     /**
201      * Delete page from the WikiDB. 
202      *
203      * Deletes the page from the WikiDB with the possibility to revert and diff.
204      * //Also resets all page meta-data to the default values.
205      *
206      * Note: purgePage() effectively destroys all revisions of the page from the WikiDB. 
207      *
208      * @access public
209      *
210      * @param string $pagename Name of page to delete.
211      */
212     function deletePage($pagename) {
213         // don't create empty revisions of already purged pages.
214         if ($this->_backend->get_latest_version($pagename))
215             $result = $this->_cache->delete_page($pagename);
216         else 
217             $result = -1;
218
219         /* Generate notification emails? */
220         if (! $this->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
221             $notify = $this->get('notify');
222             if (!empty($notify) and is_array($notify)) {
223                 //TODO: deferr it (quite a massive load if you remove some pages).
224                 //TODO: notification class which catches all changes,
225                 //  and decides at the end of the request what to mail. (type, page, who, what, users, emails)
226                 // could be used for PageModeration and RSS2 Cloud xml-rpc also.
227                 $page = new WikiDB_Page($this, $pagename);
228                 list($emails, $userids) = $page->getPageChangeEmails($notify);
229                 if (!empty($emails)) {
230                     $editedby = sprintf(_("Removed by: %s"), $GLOBALS['request']->_user->getId()); // Todo: host_id
231                     $emails = join(',', $emails);
232                     $subject = sprintf(_("Page removed %s"), urlencode($pagename));
233                     if (mail($emails,"[".WIKI_NAME."] ".$subject, 
234                              $subject."\n".
235                              $editedby."\n\n".
236                              "Deleted $pagename"))
237                         trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
238                                               $pagename, join(',',$userids)), E_USER_NOTICE);
239                     else
240                         trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
241                                               $pagename, join(',',$userids)), E_USER_WARNING);
242                 }
243             }
244         }
245
246         //How to create a RecentChanges entry with explaining summary? Dynamically
247         /*
248         $page = $this->getPage($pagename);
249         $current = $page->getCurrentRevision();
250         $meta = $current->_data;
251         $version = $current->getVersion();
252         $meta['summary'] = _("removed");
253         $page->save($current->getPackedContent(), $version + 1, $meta);
254         */
255         return $result;
256     }
257
258     /**
259      * Completely remove the page from the WikiDB, without undo possibility.
260      */
261     function purgePage($pagename) {
262         $result = $this->_cache->purge_page($pagename);
263         $this->deletePage($pagename); // just for the notification
264         return $result;
265     }
266     
267     /**
268      * Retrieve all pages.
269      *
270      * Gets the set of all pages with non-default contents.
271      *
272      * @access public
273      *
274      * @param boolean $include_defaulted Normally pages whose most
275      * recent revision has empty content are considered to be
276      * non-existant. Unless $include_defaulted is set to true, those
277      * pages will not be returned.
278      *
279      * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
280      *     in the WikiDB which have non-default contents.
281      */
282     function getAllPages($include_empty=false, $sortby=false, $limit=false, 
283                          $exclude=false) 
284     {
285         // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
286         if (USECACHE) {
287             $mem = ini_get("memory_limit");
288             if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
289                 $limit = 450;
290                 $GLOBALS['request']->setArg('limit', $limit);
291                 $GLOBALS['request']->setArg('paging', 'auto');
292             }
293         }
294         $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit, 
295                                                  $exclude);
296         return new WikiDB_PageIterator($this, $result, 
297                                        array('include_empty' => $include_empty, 
298                                              'exclude' => $exclude,
299                                              'limit' => $limit));
300     }
301
302     /**
303      * $include_empty = true: include also empty pages
304      * exclude: comma-seperated list pagenames: TBD: array of pagenames
305      */
306     function numPages($include_empty=false, $exclude='') {
307         if (method_exists($this->_backend, 'numPages'))
308             // FIXME: currently are all args ignored.
309             $count = $this->_backend->numPages($include_empty, $exclude);
310         else {
311             // FIXME: exclude ignored.
312             $iter = $this->getAllPages($include_empty, false, false, $exclude);
313             $count = $iter->count();
314             $iter->free();
315         }
316         return (int)$count;
317     }
318     
319     /**
320      * Title search.
321      *
322      * Search for pages containing (or not containing) certain words
323      * in their names.
324      *
325      * Pages are returned in alphabetical order whenever it is
326      * practical to do so.
327      *
328      * FIXME: clarify $search syntax. provide glob=>TextSearchQuery converters
329      *
330      * @access public
331      * @param TextSearchQuery $search A TextSearchQuery object
332      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
333      * @see TextSearchQuery
334      */
335     function titleSearch($search, $sortby='pagename', $limit=false, $exclude=false) {
336         $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
337         return new WikiDB_PageIterator($this, $result,
338                                        array('exclude' => $exclude,
339                                              'limit' => $limit));
340     }
341
342     /**
343      * Full text search.
344      *
345      * Search for pages containing (or not containing) certain words
346      * in their entire text (this includes the page content and the
347      * page name).
348      *
349      * Pages are returned in alphabetical order whenever it is
350      * practical to do so.
351      *
352      * @access public
353      *
354      * @param TextSearchQuery $search A TextSearchQuery object.
355      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
356      * @see TextSearchQuery
357      */
358     function fullSearch($search, $sortby='pagename', $limit=false, $exclude=false) {
359         $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
360         return new WikiDB_PageIterator($this, $result,
361                                        array('exclude' => $exclude,
362                                              'limit' => $limit));
363     }
364
365     /**
366      * Find the pages with the greatest hit counts.
367      *
368      * Pages are returned in reverse order by hit count.
369      *
370      * @access public
371      *
372      * @param integer $limit The maximum number of pages to return.
373      * Set $limit to zero to return all pages.  If $limit < 0, pages will
374      * be sorted in decreasing order of popularity.
375      *
376      * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
377      * pages.
378      */
379     function mostPopular($limit = 20, $sortby = '-hits') {
380         $result = $this->_backend->most_popular($limit, $sortby);
381         return new WikiDB_PageIterator($this, $result);
382     }
383
384     /**
385      * Find recent page revisions.
386      *
387      * Revisions are returned in reverse order by creation time.
388      *
389      * @access public
390      *
391      * @param hash $params This hash is used to specify various optional
392      *   parameters:
393      * <dl>
394      * <dt> limit 
395      *    <dd> (integer) At most this many revisions will be returned.
396      * <dt> since
397      *    <dd> (integer) Only revisions since this time (unix-timestamp) will be returned. 
398      * <dt> include_minor_revisions
399      *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
400      * <dt> exclude_major_revisions
401      *    <dd> (boolean) Don't include non-minor revisions.
402      *         (Exclude_major_revisions implies include_minor_revisions.)
403      * <dt> include_all_revisions
404      *    <dd> (boolean) Return all matching revisions for each page.
405      *         Normally only the most recent matching revision is returned
406      *         for each page.
407      * </dl>
408      *
409      * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator containing the
410      * matching revisions.
411      */
412     function mostRecent($params = false) {
413         $result = $this->_backend->most_recent($params);
414         return new WikiDB_PageRevisionIterator($this, $result);
415     }
416
417     /**
418      * @access public
419      *
420      * @return Iterator A generic iterator containing rows of (duplicate) pagename, wantedfrom.
421      */
422     function wantedPages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
423         return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
424         //return new WikiDB_PageIterator($this, $result);
425     }
426
427
428     /**
429      * Call the appropriate backend method.
430      *
431      * @access public
432      * @param string $from Page to rename
433      * @param string $to   New name
434      * @param boolean $updateWikiLinks If the text in all pages should be replaced.
435      * @return boolean     true or false
436      */
437     function renamePage($from, $to, $updateWikiLinks = false) {
438         assert(is_string($from) && $from != '');
439         assert(is_string($to) && $to != '');
440         $result = false;
441         if (method_exists($this->_backend, 'rename_page')) {
442             $oldpage = $this->getPage($from);
443             $newpage = $this->getPage($to);
444             //update all WikiLinks in existing pages
445             //non-atomic! i.e. if rename fails the links are not undone
446             if ($updateWikiLinks) {
447                 require_once('lib/plugin/WikiAdminSearchReplace.php');
448                 $links = $oldpage->getBackLinks();
449                 while ($linked_page = $links->next()) {
450                     WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
451                                                                      $linked_page->getName(),
452                                                                      $from, $to);
453                 }
454                 $links = $newpage->getBackLinks();
455                 while ($linked_page = $links->next()) {
456                     WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
457                                                                      $linked_page->getName(),
458                                                                      $from, $to);
459                 }
460             }
461             if ($oldpage->exists() and ! $newpage->exists()) {
462                 if ($result = $this->_backend->rename_page($from, $to)) {
463                     //create a RecentChanges entry with explaining summary
464                     $page = $this->getPage($to);
465                     $current = $page->getCurrentRevision();
466                     $meta = $current->_data;
467                     $version = $current->getVersion();
468                     $meta['summary'] = sprintf(_("renamed from %s"), $from);
469                     $page->save($current->getPackedContent(), $version + 1, $meta);
470                 }
471             } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
472                 // if a version 0 exists try it also.
473                 $result = $this->_backend->rename_page($from, $to);
474             }
475         } else {
476             trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
477                           E_USER_WARNING);
478         }
479         /* Generate notification emails? */
480         if ($result and !isa($GLOBALS['request'], 'MockRequest')) {
481             $notify = $this->get('notify');
482             if (!empty($notify) and is_array($notify)) {
483                 list($emails, $userids) = $oldpage->getPageChangeEmails($notify);
484                 if (!empty($emails)) {
485                     $oldpage->sendPageRenameNotification($to, $meta, $emails, $userids);
486                 }
487             }
488         }
489         return $result;
490     }
491
492     /** Get timestamp when database was last modified.
493      *
494      * @return string A string consisting of two integers,
495      * separated by a space.  The first is the time in
496      * unix timestamp format, the second is a modification
497      * count for the database.
498      *
499      * The idea is that you can cast the return value to an
500      * int to get a timestamp, or you can use the string value
501      * as a good hash for the entire database.
502      */
503     function getTimestamp() {
504         $ts = $this->get('_timestamp');
505         return sprintf("%d %d", $ts[0], $ts[1]);
506     }
507     
508     /**
509      * Update the database timestamp.
510      *
511      */
512     function touch() {
513         $ts = $this->get('_timestamp');
514         $this->set('_timestamp', array(time(), $ts[1] + 1));
515     }
516
517         
518     /**
519      * Access WikiDB global meta-data.
520      *
521      * NOTE: this is currently implemented in a hackish and
522      * not very efficient manner.
523      *
524      * @access public
525      *
526      * @param string $key Which meta data to get.
527      * Some reserved meta-data keys are:
528      * <dl>
529      * <dt>'_timestamp' <dd> Data used by getTimestamp().
530      * </dl>
531      *
532      * @return scalar The requested value, or false if the requested data
533      * is not set.
534      */
535     function get($key) {
536         if (!$key || $key[0] == '%')
537             return false;
538         /*
539          * Hack Alert: We can use any page (existing or not) to store
540          * this data (as long as we always use the same one.)
541          */
542         $gd = $this->getPage('global_data');
543         $data = $gd->get('__global');
544
545         if ($data && isset($data[$key]))
546             return $data[$key];
547         else
548             return false;
549     }
550
551     /**
552      * Set global meta-data.
553      *
554      * NOTE: this is currently implemented in a hackish and
555      * not very efficient manner.
556      *
557      * @see get
558      * @access public
559      *
560      * @param string $key  Meta-data key to set.
561      * @param string $newval  New value.
562      */
563     function set($key, $newval) {
564         if (!$key || $key[0] == '%')
565             return;
566         
567         $gd = $this->getPage('global_data');
568         $data = $gd->get('__global');
569         if ($data === false)
570             $data = array();
571
572         if (empty($newval))
573             unset($data[$key]);
574         else
575             $data[$key] = $newval;
576
577         $gd->set('__global', $data);
578     }
579
580     /* TODO: these are really backend methods */
581
582     // SQL result: for simple select or create/update queries
583     // returns the database specific resource type
584     function genericSqlQuery($sql, $args=false) {
585         if (function_exists('debug_backtrace')) { // >= 4.3.0
586             echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
587         }
588         trigger_error("no SQL database", E_USER_ERROR);
589         return false;
590     }
591
592     // SQL iter: for simple select or create/update queries
593     // returns the generic iterator object (count,next)
594     function genericSqlIter($sql, $field_list = NULL) {
595         if (function_exists('debug_backtrace')) { // >= 4.3.0
596             echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
597         }
598         trigger_error("no SQL database", E_USER_ERROR);
599         return false;
600     }
601     
602     // see backend upstream methods
603     // ADODB adds surrounding quotes, SQL not yet!
604     function quote ($s) {
605         return $s;
606     }
607
608     function isOpen () {
609         global $request;
610         if (!$request->_dbi) return false;
611         else return false; /* so far only needed for sql so false it. 
612                             later we have to check dba also */
613     }
614
615     function getParam($param) {
616         global $DBParams;
617         if (isset($DBParams[$param])) return $DBParams[$param];
618         elseif ($param == 'prefix') return '';
619         else return false;
620     }
621
622     function getAuthParam($param) {
623         global $DBAuthParams;
624         if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
625         elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
626         elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
627         else return false;
628     }
629 };
630
631
632 /**
633  * An abstract base class which representing a wiki-page within a
634  * WikiDB.
635  *
636  * A WikiDB_Page contains a number (at least one) of
637  * WikiDB_PageRevisions.
638  */
639 class WikiDB_Page 
640 {
641     function WikiDB_Page(&$wikidb, $pagename) {
642         $this->_wikidb = &$wikidb;
643         $this->_pagename = $pagename;
644         if (DEBUG) {
645             if (!(is_string($pagename) and $pagename != '')) {
646                 if (function_exists("xdebug_get_function_stack")) {
647                     echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
648                 } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
649                     printSimpleTrace(debug_backtrace());
650                 }
651                 trigger_error("empty pagename", E_USER_WARNING);
652                 return false;
653             }
654         } else 
655             assert(is_string($pagename) and $pagename != '');
656     }
657
658     /**
659      * Get the name of the wiki page.
660      *
661      * @access public
662      *
663      * @return string The page name.
664      */
665     function getName() {
666         return $this->_pagename;
667     }
668     
669     // To reduce the memory footprint for larger sets of pagelists,
670     // we don't cache the content (only true or false) and 
671     // we purge the pagedata (_cached_html) also
672     function exists() {
673         if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
674         $current = $this->getCurrentRevision(false);
675         if (!$current) return false;
676         return ! $current->hasDefaultContents();
677     }
678
679     /**
680      * Delete an old revision of a WikiDB_Page.
681      *
682      * Deletes the specified revision of the page.
683      * It is a fatal error to attempt to delete the current revision.
684      *
685      * @access public
686      *
687      * @param integer $version Which revision to delete.  (You can also
688      *  use a WikiDB_PageRevision object here.)
689      */
690     function deleteRevision($version) {
691         $backend = &$this->_wikidb->_backend;
692         $cache = &$this->_wikidb->_cache;
693         $pagename = &$this->_pagename;
694
695         $version = $this->_coerce_to_version($version);
696         if ($version == 0)
697             return;
698
699         $backend->lock(array('page','version'));
700         $latestversion = $cache->get_latest_version($pagename);
701         if ($latestversion && ($version == $latestversion)) {
702             $backend->unlock(array('page','version'));
703             trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
704                                   $pagename), E_USER_ERROR);
705             return;
706         }
707
708         $cache->delete_versiondata($pagename, $version);
709         $backend->unlock(array('page','version'));
710     }
711
712     /*
713      * Delete a revision, or possibly merge it with a previous
714      * revision.
715      *
716      * The idea is this:
717      * Suppose an author make a (major) edit to a page.  Shortly
718      * after that the same author makes a minor edit (e.g. to fix
719      * spelling mistakes he just made.)
720      *
721      * Now some time later, where cleaning out old saved revisions,
722      * and would like to delete his minor revision (since there's
723      * really no point in keeping minor revisions around for a long
724      * time.)
725      *
726      * Note that the text after the minor revision probably represents
727      * what the author intended to write better than the text after
728      * the preceding major edit.
729      *
730      * So what we really want to do is merge the minor edit with the
731      * preceding edit.
732      *
733      * We will only do this when:
734      * <ul>
735      * <li>The revision being deleted is a minor one, and
736      * <li>It has the same author as the immediately preceding revision.
737      * </ul>
738      */
739     function mergeRevision($version) {
740         $backend = &$this->_wikidb->_backend;
741         $cache = &$this->_wikidb->_cache;
742         $pagename = &$this->_pagename;
743
744         $version = $this->_coerce_to_version($version);
745         if ($version == 0)
746             return;
747
748         $backend->lock(array('version'));
749         $latestversion = $cache->get_latest_version($pagename);
750         if ($latestversion && $version == $latestversion) {
751             $backend->unlock(array('version'));
752             trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
753                                   $pagename), E_USER_ERROR);
754             return;
755         }
756
757         $versiondata = $cache->get_versiondata($pagename, $version, true);
758         if (!$versiondata) {
759             // Not there? ... we're done!
760             $backend->unlock(array('version'));
761             return;
762         }
763
764         if ($versiondata['is_minor_edit']) {
765             $previous = $backend->get_previous_version($pagename, $version);
766             if ($previous) {
767                 $prevdata = $cache->get_versiondata($pagename, $previous);
768                 if ($prevdata['author_id'] == $versiondata['author_id']) {
769                     // This is a minor revision, previous version is
770                     // by the same author. We will merge the
771                     // revisions.
772                     $cache->update_versiondata($pagename, $previous,
773                                                array('%content' => $versiondata['%content'],
774                                                      '_supplanted' => $versiondata['_supplanted']));
775                 }
776             }
777         }
778
779         $cache->delete_versiondata($pagename, $version);
780         $backend->unlock(array('version'));
781     }
782
783     
784     /**
785      * Create a new revision of a {@link WikiDB_Page}.
786      *
787      * @access public
788      *
789      * @param int $version Version number for new revision.  
790      * To ensure proper serialization of edits, $version must be
791      * exactly one higher than the current latest version.
792      * (You can defeat this check by setting $version to
793      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
794      *
795      * @param string $content Contents of new revision.
796      *
797      * @param hash $metadata Metadata for new revision.
798      * All values in the hash should be scalars (strings or integers).
799      *
800      * @param array $links List of pagenames which this page links to.
801      *
802      * @return WikiDB_PageRevision  Returns the new WikiDB_PageRevision object. If
803      * $version was incorrect, returns false
804      */
805     function createRevision($version, &$content, $metadata, $links) {
806         $backend = &$this->_wikidb->_backend;
807         $cache = &$this->_wikidb->_cache;
808         $pagename = &$this->_pagename;
809         $cache->invalidate_cache($pagename);
810         
811         $backend->lock(array('version','page','recent','link','nonempty'));
812
813         $latestversion = $backend->get_latest_version($pagename);
814         $newversion = ($latestversion ? $latestversion : 0) + 1;
815         assert($newversion >= 1);
816
817         if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
818             $backend->unlock(array('version','page','recent','link','nonempty'));
819             return false;
820         }
821
822         $data = $metadata;
823         
824         foreach ($data as $key => $val) {
825             if (empty($val) || $key[0] == '_' || $key[0] == '%')
826                 unset($data[$key]);
827         }
828                         
829         assert(!empty($data['author']));
830         if (empty($data['author_id']))
831             @$data['author_id'] = $data['author'];
832                 
833         if (empty($data['mtime']))
834             $data['mtime'] = time();
835
836         if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
837             // Ensure mtimes are monotonic.
838             $pdata = $cache->get_versiondata($pagename, $latestversion);
839             if ($data['mtime'] < $pdata['mtime']) {
840                 trigger_error(sprintf(_("%s: Date of new revision is %s"),
841                                       $pagename,"'non-monotonic'"),
842                               E_USER_NOTICE);
843                 $data['orig_mtime'] = $data['mtime'];
844                 $data['mtime'] = $pdata['mtime'];
845             }
846             
847             // FIXME: use (possibly user specified) 'mtime' time or
848             // time()?
849             $cache->update_versiondata($pagename, $latestversion,
850                                        array('_supplanted' => $data['mtime']));
851         }
852
853         $data['%content'] = &$content;
854
855         $cache->set_versiondata($pagename, $newversion, $data);
856
857         //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
858         //':deleted' => empty($content)));
859         
860         $backend->set_links($pagename, $links);
861
862         $backend->unlock(array('version','page','recent','link','nonempty'));
863
864         return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
865                                        $data);
866     }
867
868     /** A higher-level interface to createRevision.
869      *
870      * This takes care of computing the links, and storing
871      * a cached version of the transformed wiki-text.
872      *
873      * @param string $wikitext  The page content.
874      *
875      * @param int $version Version number for new revision.  
876      * To ensure proper serialization of edits, $version must be
877      * exactly one higher than the current latest version.
878      * (You can defeat this check by setting $version to
879      * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
880      *
881      * @param hash $meta  Meta-data for new revision.
882      */
883     function save($wikitext, $version, $meta) {
884         $formatted = new TransformedText($this, $wikitext, $meta);
885         $type = $formatted->getType();
886         $meta['pagetype'] = $type->getName();
887         $links = $formatted->getWikiPageLinks();
888
889         $backend = &$this->_wikidb->_backend;
890         $newrevision = $this->createRevision($version, $wikitext, $meta, $links);
891         if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
892             $this->set('_cached_html', $formatted->pack());
893
894         // FIXME: probably should have some global state information
895         // in the backend to control when to optimize.
896         //
897         // We're doing this here rather than in createRevision because
898         // postgres can't optimize while locked.
899         if ((DEBUG & _DEBUG_SQL) or (time() % 5 == 0)) {
900             if ($backend->optimize())
901                 trigger_error(_("Optimizing database"), E_USER_NOTICE);
902         }
903
904         /* Generate notification emails? */
905         if (isa($newrevision, 'WikiDB_PageRevision')) {
906             // Save didn't fail because of concurrent updates.
907             $notify = $this->_wikidb->get('notify');
908             if (!empty($notify) and is_array($notify) and !isa($GLOBALS['request'],'MockRequest')) {
909                 list($emails, $userids) = $this->getPageChangeEmails($notify);
910                 if (!empty($emails)) {
911                     $this->sendPageChangeNotification($wikitext, $version, $meta, $emails, $userids);
912                 }
913             }
914             $newrevision->_transformedContent = $formatted;
915         }
916
917         return $newrevision;
918     }
919
920     function getPageChangeEmails($notify) {
921         $emails = array(); $userids = array();
922         foreach ($notify as $page => $users) {
923             if (glob_match($page, $this->_pagename)) {
924                 foreach ($users as $userid => $user) {
925                     if (!$user) { // handle the case for ModeratePage: no prefs, just userid's.
926                         global $request;
927                         $u = $request->getUser();
928                         if ($u->UserName() == $userid) {
929                             $prefs = $u->getPreferences();
930                         } else {
931                             // not current user
932                             if (ENABLE_USER_NEW) {
933                                 $u = WikiUser($userid);
934                                 $u->getPreferences();
935                                 $prefs = &$u->_prefs;
936                             } else {
937                                 $u = new WikiUser($GLOBALS['request'], $userid);
938                                 $prefs = $u->getPreferences();
939                             }
940                         }
941                         $emails[] = $prefs->get('email');
942                         $userids[] = $userid;
943                     } else {
944                       if (!empty($user['verified']) and !empty($user['email'])) {
945                         $emails[]  = $user['email'];
946                         $userids[] = $userid;
947                       } elseif (!empty($user['email'])) {
948                         global $request;
949                         // do a dynamic emailVerified check update
950                         $u = $request->getUser();
951                         if ($u->UserName() == $userid) {
952                             if ($request->_prefs->get('emailVerified')) {
953                                 $emails[] = $user['email'];
954                                 $userids[] = $userid;
955                                 $notify[$page][$userid]['verified'] = 1;
956                                 $request->_dbi->set('notify', $notify);
957                             }
958                         } else {
959                             // not current user
960                             if (ENABLE_USER_NEW) {
961                                 $u = WikiUser($userid);
962                                 $u->getPreferences();
963                                 $prefs = &$u->_prefs;
964                             } else {
965                                 $u = new WikiUser($GLOBALS['request'], $userid);
966                                 $prefs = $u->getPreferences();
967                             }
968                             if ($prefs->get('emailVerified')) {
969                                 $emails[] = $user['email'];
970                                 $userids[] = $userid;
971                                 $notify[$page][$userid]['verified'] = 1;
972                                 $request->_dbi->set('notify', $notify);
973                             }
974                         }
975                         // ignore verification
976                         /*
977                         if (DEBUG) {
978                             if (!in_array($user['email'],$emails))
979                                 $emails[] = $user['email'];
980                         }
981                         */
982                     }
983                   }
984                 }
985             }
986         }
987         $emails = array_unique($emails);
988         $userids = array_unique($userids);
989         return array($emails, $userids);
990     }
991
992     /**
993      * Send udiff for a changed page to multiple users.
994      * See rename and remove methods also
995      */
996     function sendPageChangeNotification(&$wikitext, $version, $meta, $emails, $userids) {
997         global $request;
998         if (@is_array($request->_deferredPageChangeNotification)) {
999             // collapse multiple changes (loaddir) into one email
1000             $request->_deferredPageChangeNotification[] = array($this->_pagename, $emails, $userids);
1001             return;
1002         }
1003         $backend = &$this->_wikidb->_backend;
1004         //$backend = &$request->_dbi->_backend;
1005         $subject = _("Page change").' '.urlencode($this->_pagename);
1006         $previous = $backend->get_previous_version($this->_pagename, $version);
1007         if (!isset($meta['mtime'])) $meta['mtime'] = time();
1008         if ($previous) {
1009             $difflink = WikiURL($this->_pagename, array('action'=>'diff'), true);
1010             $cache = &$this->_wikidb->_cache;
1011             //$cache = &$request->_dbi->_cache;
1012             $this_content = explode("\n", $wikitext);
1013             $prevdata = $cache->get_versiondata($this->_pagename, $previous, true);
1014             if (empty($prevdata['%content']))
1015                 $prevdata = $backend->get_versiondata($this->_pagename, $previous, true);
1016             $other_content = explode("\n", $prevdata['%content']);
1017             
1018             include_once("lib/difflib.php");
1019             $diff2 = new Diff($other_content, $this_content);
1020             //$context_lines = max(4, count($other_content) + 1,
1021             //                     count($this_content) + 1);
1022             $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
1023             $content  = $this->_pagename . " " . $previous . " " . 
1024                 Iso8601DateTime($prevdata['mtime']) . "\n";
1025             $content .= $this->_pagename . " " . $version . " " .  
1026                 Iso8601DateTime($meta['mtime']) . "\n";
1027             $content .= $fmt->format($diff2);
1028             
1029         } else {
1030             $difflink = WikiURL($this->_pagename,array(),true);
1031             $content = $this->_pagename . " " . $version . " " .  
1032                 Iso8601DateTime($meta['mtime']) . "\n";
1033             $content .= _("New page");
1034         }
1035         $editedby = sprintf(_("Edited by: %s"), $meta['author']);
1036         $emails = join(',',$emails);
1037         if (mail($emails,"[".WIKI_NAME."] ".$subject, 
1038                  $subject."\n".
1039                  $editedby."\n".
1040                  $difflink."\n\n".
1041                  $content))
1042             trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
1043                                   $this->_pagename, join(',',$userids)), E_USER_NOTICE);
1044         else
1045             trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
1046                                   $this->_pagename, join(',',$userids)), E_USER_WARNING);
1047     }
1048
1049     /** support mass rename / remove (not yet tested)
1050      */
1051     function sendPageRenameNotification($to, &$meta, $emails, $userids) {
1052         global $request;
1053         if (@is_array($request->_deferredPageRenameNotification)) {
1054             $request->_deferredPageRenameNotification[] = array($this->_pagename, 
1055                                                                 $to, $meta, $emails, $userids);
1056         } else {
1057             $from = $this->_pagename;
1058             $editedby = sprintf(_("Edited by: %s"), $meta['author']) . ' ' . $meta['author_id'];
1059             $emails = join(',',$emails);
1060             $subject = sprintf(_("Page rename %s to %s"), urlencode($from), urlencode($to));
1061             $link = WikiURL($to, true);
1062             if (mail($emails,"[".WIKI_NAME."] ".$subject, 
1063                      $subject."\n".
1064                      $editedby."\n".
1065                      $link."\n\n".
1066                      "Renamed $from to $to"))
1067                 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
1068                                       $from, join(',',$userids)), E_USER_NOTICE);
1069             else
1070                 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
1071                                       $from, join(',',$userids)), E_USER_WARNING);
1072         }
1073     }
1074
1075     /**
1076      * Get the most recent revision of a page.
1077      *
1078      * @access public
1079      *
1080      * @return WikiDB_PageRevision The current WikiDB_PageRevision object. 
1081      */
1082     function getCurrentRevision($need_content = true) {
1083         $backend = &$this->_wikidb->_backend;
1084         $cache = &$this->_wikidb->_cache;
1085         $pagename = &$this->_pagename;
1086         
1087         // Prevent deadlock in case of memory exhausted errors
1088         // Pure selection doesn't really need locking here.
1089         //   sf.net bug#927395
1090         // I know it would be better to lock, but with lots of pages this deadlock is more 
1091         // severe than occasionally get not the latest revision.
1092         // In spirit to wikiwiki: read fast, edit slower.
1093         //$backend->lock();
1094         $version = $cache->get_latest_version($pagename);
1095         // getRevision gets the content also!
1096         $revision = $this->getRevision($version, $need_content);
1097         //$backend->unlock();
1098         assert($revision);
1099         return $revision;
1100     }
1101
1102     /**
1103      * Get a specific revision of a WikiDB_Page.
1104      *
1105      * @access public
1106      *
1107      * @param integer $version  Which revision to get.
1108      *
1109      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
1110      * false if the requested revision does not exist in the {@link WikiDB}.
1111      * Note that version zero of any page always exists.
1112      */
1113     function getRevision($version, $need_content=true) {
1114         $cache = &$this->_wikidb->_cache;
1115         $pagename = &$this->_pagename;
1116         
1117         if (! $version or $version == -1) // 0 or false
1118             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1119
1120         assert($version > 0);
1121         $vdata = $cache->get_versiondata($pagename, $version, $need_content);
1122         if (!$vdata) {
1123             return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
1124         }
1125         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1126                                        $vdata);
1127     }
1128
1129     /**
1130      * Get previous page revision.
1131      *
1132      * This method find the most recent revision before a specified
1133      * version.
1134      *
1135      * @access public
1136      *
1137      * @param integer $version  Find most recent revision before this version.
1138      *  You can also use a WikiDB_PageRevision object to specify the $version.
1139      *
1140      * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
1141      * requested revision does not exist in the {@link WikiDB}.  Note that
1142      * unless $version is greater than zero, a revision (perhaps version zero,
1143      * the default revision) will always be found.
1144      */
1145     function getRevisionBefore($version=false, $need_content=true) {
1146         $backend = &$this->_wikidb->_backend;
1147         $pagename = &$this->_pagename;
1148         if ($version === false)
1149             $version = $this->_wikidb->_cache->get_latest_version($pagename);
1150         else
1151             $version = $this->_coerce_to_version($version);
1152
1153         if ($version == 0)
1154             return false;
1155         //$backend->lock();
1156         $previous = $backend->get_previous_version($pagename, $version);
1157         $revision = $this->getRevision($previous, $need_content);
1158         //$backend->unlock();
1159         assert($revision);
1160         return $revision;
1161     }
1162
1163     /**
1164      * Get all revisions of the WikiDB_Page.
1165      *
1166      * This does not include the version zero (default) revision in the
1167      * returned revision set.
1168      *
1169      * @return WikiDB_PageRevisionIterator A
1170      *   WikiDB_PageRevisionIterator containing all revisions of this
1171      *   WikiDB_Page in reverse order by version number.
1172      */
1173     function getAllRevisions() {
1174         $backend = &$this->_wikidb->_backend;
1175         $revs = $backend->get_all_revisions($this->_pagename);
1176         return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
1177     }
1178     
1179     /**
1180      * Find pages which link to or are linked from a page.
1181      *
1182      * @access public
1183      *
1184      * @param boolean $reversed Which links to find: true for backlinks (default).
1185      *
1186      * @return WikiDB_PageIterator A WikiDB_PageIterator containing
1187      * all matching pages.
1188      */
1189     function getLinks($reversed = true, $include_empty=false, $sortby=false, 
1190                       $limit=false, $exclude=false) {
1191         $backend = &$this->_wikidb->_backend;
1192         $result =  $backend->get_links($this->_pagename, $reversed, 
1193                                        $include_empty, $sortby, $limit, $exclude);
1194         return new WikiDB_PageIterator($this->_wikidb, $result, 
1195                                        array('include_empty' => $include_empty,
1196                                              'sortby' => $sortby, 
1197                                              'limit' => $limit, 
1198                                              'exclude' => $exclude));
1199     }
1200
1201     /**
1202      * All Links from other pages to this page.
1203      */
1204     function getBackLinks($include_empty=false, $sortby=false, $limit=false, $exclude=false) {
1205         return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
1206     }
1207     /**
1208      * Forward Links: All Links from this page to other pages.
1209      */
1210     function getPageLinks($include_empty=false, $sortby=false, $limit=false, $exclude=false) {
1211         return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
1212     }
1213     
1214     /**
1215      * possibly faster link existance check. not yet accelerated.
1216      */
1217     function existLink($link, $reversed=false) {
1218         $backend = &$this->_wikidb->_backend;
1219         if (method_exists($backend,'exists_link'))
1220             return $backend->exists_link($this->_pagename, $link, $reversed);
1221         //$cache = &$this->_wikidb->_cache;
1222         // TODO: check cache if it is possible
1223         $iter = $this->getLinks($reversed, false);
1224         while ($page = $iter->next()) {
1225             if ($page->getName() == $link)
1226                 return $page;
1227         }
1228         $iter->free();
1229         return false;
1230     }
1231             
1232     /**
1233      * Access WikiDB_Page non version-specific meta-data.
1234      *
1235      * @access public
1236      *
1237      * @param string $key Which meta data to get.
1238      * Some reserved meta-data keys are:
1239      * <dl>
1240      * <dt>'date'  <dd> Created as unixtime
1241      * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
1242      * <dt>'hits'  <dd> Page hit counter.
1243      * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
1244      *                         In SQL stored now in an extra column.
1245      * Optional data:
1246      * <dt>'pref'  <dd> Users preferences, stored only in homepages.
1247      * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
1248      *                  E.g. "owner.users"
1249      * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
1250      *                  page-headers and content.
1251      + <dt>'moderation'<dd> ModeratedPage data
1252      * <dt>'score' <dd> Page score (not yet implement, do we need?)
1253      * </dl>
1254      *
1255      * @return scalar The requested value, or false if the requested data
1256      * is not set.
1257      */
1258     function get($key) {
1259         $cache = &$this->_wikidb->_cache;
1260         $backend = &$this->_wikidb->_backend;
1261         if (!$key || $key[0] == '%')
1262             return false;
1263         // several new SQL backends optimize this.
1264         if (!WIKIDB_NOCACHE_MARKUP
1265             and $key == '_cached_html' 
1266             and method_exists($backend, 'get_cached_html')) 
1267         {
1268             return $backend->get_cached_html($this->_pagename);
1269         }
1270         $data = $cache->get_pagedata($this->_pagename);
1271         return isset($data[$key]) ? $data[$key] : false;
1272     }
1273
1274     /**
1275      * Get all the page meta-data as a hash.
1276      *
1277      * @return hash The page meta-data.
1278      */
1279     function getMetaData() {
1280         $cache = &$this->_wikidb->_cache;
1281         $data = $cache->get_pagedata($this->_pagename);
1282         $meta = array();
1283         foreach ($data as $key => $val) {
1284             if (/*!empty($val) &&*/ $key[0] != '%')
1285                 $meta[$key] = $val;
1286         }
1287         return $meta;
1288     }
1289
1290     /**
1291      * Set page meta-data.
1292      *
1293      * @see get
1294      * @access public
1295      *
1296      * @param string $key  Meta-data key to set.
1297      * @param string $newval  New value.
1298      */
1299     function set($key, $newval) {
1300         $cache = &$this->_wikidb->_cache;
1301         $backend = &$this->_wikidb->_backend;
1302         $pagename = &$this->_pagename;
1303         
1304         assert($key && $key[0] != '%');
1305
1306         // several new SQL backends optimize this.
1307         if (!WIKIDB_NOCACHE_MARKUP 
1308             and $key == '_cached_html' 
1309             and method_exists($backend, 'set_cached_html'))
1310         {
1311             return $backend->set_cached_html($pagename, $newval);
1312         }
1313
1314         $data = $cache->get_pagedata($pagename);
1315
1316         if (!empty($newval)) {
1317             if (!empty($data[$key]) && $data[$key] == $newval)
1318                 return;         // values identical, skip update.
1319         }
1320         else {
1321             if (empty($data[$key]))
1322                 return;         // values identical, skip update.
1323         }
1324
1325         $cache->update_pagedata($pagename, array($key => $newval));
1326     }
1327
1328     /**
1329      * Increase page hit count.
1330      *
1331      * FIXME: IS this needed?  Probably not.
1332      *
1333      * This is a convenience function.
1334      * <pre> $page->increaseHitCount(); </pre>
1335      * is functionally identical to
1336      * <pre> $page->set('hits',$page->get('hits')+1); </pre>
1337      * but less expensive (ignores the pagadata string)
1338      *
1339      * Note that this method may be implemented in more efficient ways
1340      * in certain backends.
1341      *
1342      * @access public
1343      */
1344     function increaseHitCount() {
1345         if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
1346             $this->_wikidb->_backend->increaseHitCount($this->_pagename);
1347         else {
1348             @$newhits = $this->get('hits') + 1;
1349             $this->set('hits', $newhits);
1350         }
1351     }
1352
1353     /**
1354      * Return a string representation of the WikiDB_Page
1355      *
1356      * This is really only for debugging.
1357      *
1358      * @access public
1359      *
1360      * @return string Printable representation of the WikiDB_Page.
1361      */
1362     function asString () {
1363         ob_start();
1364         printf("[%s:%s\n", get_class($this), $this->getName());
1365         print_r($this->getMetaData());
1366         echo "]\n";
1367         $strval = ob_get_contents();
1368         ob_end_clean();
1369         return $strval;
1370     }
1371
1372
1373     /**
1374      * @access private
1375      * @param integer_or_object $version_or_pagerevision
1376      * Takes either the version number (and int) or a WikiDB_PageRevision
1377      * object.
1378      * @return integer The version number.
1379      */
1380     function _coerce_to_version($version_or_pagerevision) {
1381         if (method_exists($version_or_pagerevision, "getContent"))
1382             $version = $version_or_pagerevision->getVersion();
1383         else
1384             $version = (int) $version_or_pagerevision;
1385
1386         assert($version >= 0);
1387         return $version;
1388     }
1389
1390     function isUserPage ($include_empty = true) {
1391         if (!$include_empty and !$this->exists()) return false;
1392         return $this->get('pref') ? true : false;
1393     }
1394
1395     // May be empty. Either the stored owner (/Chown), or the first authorized author
1396     function getOwner() {
1397         if ($owner = $this->get('owner'))
1398             return ($owner == "The PhpWiki programming team") ? ADMIN_USER : $owner;
1399         // check all revisions forwards for the first author_id
1400         $backend = &$this->_wikidb->_backend;
1401         $pagename = &$this->_pagename;
1402         $latestversion = $backend->get_latest_version($pagename);
1403         for ($v=1; $v <= $latestversion; $v++) {
1404             $rev = $this->getRevision($v,false);
1405             if ($rev and $owner = $rev->get('author_id')) {
1406                 return ($owner == "The PhpWiki programming team") ? ADMIN_USER : $owner;
1407             }
1408         }
1409         return '';
1410     }
1411
1412     // The authenticated author of the first revision or empty if not authenticated then.
1413     function getCreator() {
1414         if ($current = $this->getRevision(1,false)) return $current->get('author_id');
1415         else return '';
1416     }
1417
1418     // The authenticated author of the current revision.
1419     function getAuthor() {
1420         if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
1421         else return '';
1422     }
1423
1424 };
1425
1426 /**
1427  * This class represents a specific revision of a WikiDB_Page within
1428  * a WikiDB.
1429  *
1430  * A WikiDB_PageRevision has read-only semantics. You may only create
1431  * new revisions (and delete old ones) --- you cannot modify existing
1432  * revisions.
1433  */
1434 class WikiDB_PageRevision
1435 {
1436     //var $_transformedContent = false; // set by WikiDB_Page::save()
1437     
1438     function WikiDB_PageRevision(&$wikidb, $pagename, $version, $versiondata = false) {
1439         $this->_wikidb = &$wikidb;
1440         $this->_pagename = $pagename;
1441         $this->_version = $version;
1442         $this->_data = $versiondata ? $versiondata : array();
1443         $this->_transformedContent = false; // set by WikiDB_Page::save()
1444     }
1445     
1446     /**
1447      * Get the WikiDB_Page which this revision belongs to.
1448      *
1449      * @access public
1450      *
1451      * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
1452      */
1453     function getPage() {
1454         return new WikiDB_Page($this->_wikidb, $this->_pagename);
1455     }
1456
1457     /**
1458      * Get the version number of this revision.
1459      *
1460      * @access public
1461      *
1462      * @return integer The version number of this revision.
1463      */
1464     function getVersion() {
1465         return $this->_version;
1466     }
1467     
1468     /**
1469      * Determine whether this revision has defaulted content.
1470      *
1471      * The default revision (version 0) of each page, as well as any
1472      * pages which are created with empty content have their content
1473      * defaulted to something like:
1474      * <pre>
1475      *   Describe [ThisPage] here.
1476      * </pre>
1477      *
1478      * @access public
1479      *
1480      * @return boolean Returns true if the page has default content.
1481      */
1482     function hasDefaultContents() {
1483         $data = &$this->_data;
1484         return empty($data['%content']); // FIXME: what if it's the number 0? <>'' or === false
1485     }
1486
1487     /**
1488      * Get the content as an array of lines.
1489      *
1490      * @access public
1491      *
1492      * @return array An array of lines.
1493      * The lines should contain no trailing white space.
1494      */
1495     function getContent() {
1496         return explode("\n", $this->getPackedContent());
1497     }
1498         
1499    /**
1500      * Get the pagename of the revision.
1501      *
1502      * @access public
1503      *
1504      * @return string pagename.
1505      */
1506     function getPageName() {
1507         return $this->_pagename;
1508     }
1509     function getName() {
1510         return $this->_pagename;
1511     }
1512
1513     /**
1514      * Determine whether revision is the latest.
1515      *
1516      * @access public
1517      *
1518      * @return boolean True iff the revision is the latest (most recent) one.
1519      */
1520     function isCurrent() {
1521         if (!isset($this->_iscurrent)) {
1522             $page = $this->getPage();
1523             $current = $page->getCurrentRevision(false);
1524             $this->_iscurrent = $this->getVersion() == $current->getVersion();
1525         }
1526         return $this->_iscurrent;
1527     }
1528
1529     /**
1530      * Get the transformed content of a page.
1531      *
1532      * @param string $pagetype  Override the page-type of the revision.
1533      *
1534      * @return object An XmlContent-like object containing the page transformed
1535      * contents.
1536      */
1537     function getTransformedContent($pagetype_override=false) {
1538         $backend = &$this->_wikidb->_backend;
1539         
1540         if ($pagetype_override) {
1541             // Figure out the normal page-type for this page.
1542             $type = PageType::GetPageType($this->get('pagetype'));
1543             if ($type->getName() == $pagetype_override)
1544                 $pagetype_override = false; // Not really an override...
1545         }
1546
1547         if ($pagetype_override) {
1548             // Overriden page type, don't cache (or check cache).
1549             return new TransformedText($this->getPage(),
1550                                        $this->getPackedContent(),
1551                                        $this->getMetaData(),
1552                                        $pagetype_override);
1553         }
1554
1555         $possibly_cache_results = true;
1556
1557         if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
1558             if (WIKIDB_NOCACHE_MARKUP == 'purge') {
1559                 // flush cache for this page.
1560                 $page = $this->getPage();
1561                 $page->set('_cached_html', ''); // ignored with !USECACHE 
1562             }
1563             $possibly_cache_results = false;
1564         }
1565         elseif (USECACHE and !$this->_transformedContent) {
1566             //$backend->lock();
1567             if ($this->isCurrent()) {
1568                 $page = $this->getPage();
1569                 $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
1570             }
1571             else {
1572                 $possibly_cache_results = false;
1573             }
1574             //$backend->unlock();
1575         }
1576         
1577         if (!$this->_transformedContent) {
1578             $this->_transformedContent
1579                 = new TransformedText($this->getPage(),
1580                                       $this->getPackedContent(),
1581                                       $this->getMetaData());
1582             
1583             if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
1584                 // If we're still the current version, cache the transfomed page.
1585                 //$backend->lock();
1586                 if ($this->isCurrent()) {
1587                     $page->set('_cached_html', $this->_transformedContent->pack());
1588                 }
1589                 //$backend->unlock();
1590             }
1591         }
1592
1593         return $this->_transformedContent;
1594     }
1595
1596     /**
1597      * Get the content as a string.
1598      *
1599      * @access public
1600      *
1601      * @return string The page content.
1602      * Lines are separated by new-lines.
1603      */
1604     function getPackedContent() {
1605         $data = &$this->_data;
1606
1607         
1608         if (empty($data['%content'])) {
1609             include_once('lib/InlineParser.php');
1610
1611             // A feature similar to taglines at http://www.wlug.org.nz/
1612             // Lib from http://www.aasted.org/quote/
1613             if (defined('FORTUNE_DIR') 
1614                 and is_dir(FORTUNE_DIR) 
1615                 and in_array($GLOBALS['request']->getArg('action'), 
1616                              array('create','edit')))
1617             {
1618                 include_once("lib/fortune.php");
1619                 $fortune = new Fortune();
1620                 $quote = str_replace("\n<br>","\n", $fortune->quoteFromDir(FORTUNE_DIR));
1621                 return sprintf("<verbatim>\n%s</verbatim>\n\n"._("Describe %s here."), 
1622                                $quote, "[" . WikiEscape($this->_pagename) . "]");
1623             }
1624             // Replace empty content with default value.
1625             return sprintf(_("Describe %s here."), 
1626                            "[" . WikiEscape($this->_pagename) . "]");
1627         }
1628
1629         // There is (non-default) content.
1630         assert($this->_version > 0);
1631         
1632         if (!is_string($data['%content'])) {
1633             // Content was not provided to us at init time.
1634             // (This is allowed because for some backends, fetching
1635             // the content may be expensive, and often is not wanted
1636             // by the user.)
1637             //
1638             // In any case, now we need to get it.
1639             $data['%content'] = $this->_get_content();
1640             assert(is_string($data['%content']));
1641         }
1642         
1643         return $data['%content'];
1644     }
1645
1646     function _get_content() {
1647         $cache = &$this->_wikidb->_cache;
1648         $pagename = $this->_pagename;
1649         $version = $this->_version;
1650
1651         assert($version > 0);
1652         
1653         $newdata = $cache->get_versiondata($pagename, $version, true);
1654         if ($newdata) {
1655             assert(is_string($newdata['%content']));
1656             return $newdata['%content'];
1657         }
1658         else {
1659             // else revision has been deleted... What to do?
1660             return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
1661                              $version, $pagename);
1662         }
1663     }
1664
1665     /**
1666      * Get meta-data for this revision.
1667      *
1668      *
1669      * @access public
1670      *
1671      * @param string $key Which meta-data to access.
1672      *
1673      * Some reserved revision meta-data keys are:
1674      * <dl>
1675      * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
1676      *        The 'mtime' meta-value is normally set automatically by the database
1677      *        backend, but it may be specified explicitly when creating a new revision.
1678      * <dt> orig_mtime
1679      *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
1680      *       of a page must be monotonically increasing.  If an attempt is
1681      *       made to create a new revision with an mtime less than that of
1682      *       the preceeding revision, the new revisions timestamp is force
1683      *       to be equal to that of the preceeding revision.  In that case,
1684      *       the originally requested mtime is preserved in 'orig_mtime'.
1685      * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
1686      *        This meta-value is <em>always</em> automatically maintained by the database
1687      *        backend.  (It is set from the 'mtime' meta-value of the superceding
1688      *        revision.)  '_supplanted' has a value of 'false' for the current revision.
1689      *
1690      * FIXME: this could be refactored:
1691      * <dt> author
1692      *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
1693      * <dt> author_id
1694      *  <dd> Authenticated author of a page.  This is used to identify
1695      *       the distinctness of authors when cleaning old revisions from
1696      *       the database.
1697      * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
1698      * <dt> 'summary' <dd> Short change summary entered by page author.
1699      * </dl>
1700      *
1701      * Meta-data keys must be valid C identifers (they have to start with a letter
1702      * or underscore, and can contain only alphanumerics and underscores.)
1703      *
1704      * @return string The requested value, or false if the requested value
1705      * is not defined.
1706      */
1707     function get($key) {
1708         if (!$key || $key[0] == '%')
1709             return false;
1710         $data = &$this->_data;
1711         return isset($data[$key]) ? $data[$key] : false;
1712     }
1713
1714     /**
1715      * Get all the revision page meta-data as a hash.
1716      *
1717      * @return hash The revision meta-data.
1718      */
1719     function getMetaData() {
1720         $meta = array();
1721         foreach ($this->_data as $key => $val) {
1722             if (!empty($val) && $key[0] != '%')
1723                 $meta[$key] = $val;
1724         }
1725         return $meta;
1726     }
1727     
1728             
1729     /**
1730      * Return a string representation of the revision.
1731      *
1732      * This is really only for debugging.
1733      *
1734      * @access public
1735      *
1736      * @return string Printable representation of the WikiDB_Page.
1737      */
1738     function asString () {
1739         ob_start();
1740         printf("[%s:%d\n", get_class($this), $this->get('version'));
1741         print_r($this->_data);
1742         echo $this->getPackedContent() . "\n]\n";
1743         $strval = ob_get_contents();
1744         ob_end_clean();
1745         return $strval;
1746     }
1747 };
1748
1749
1750 /**
1751  * Class representing a sequence of WikiDB_Pages.
1752  * TODO: Enhance to php5 iterators
1753  * TODO: 
1754  *   apply filters for options like 'sortby', 'limit', 'exclude'
1755  *   for simple queries like titleSearch, where the backend is not ready yet.
1756  */
1757 class WikiDB_PageIterator
1758 {
1759     function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
1760         $this->_iter = $iter; // a WikiDB_backend_iterator
1761         $this->_wikidb = &$wikidb;
1762         $this->_options = $options;
1763     }
1764     
1765     function count () {
1766         return $this->_iter->count();
1767     }
1768
1769     /**
1770      * Get next WikiDB_Page in sequence.
1771      *
1772      * @access public
1773      *
1774      * @return WikiDB_Page The next WikiDB_Page in the sequence.
1775      */
1776     function next () {
1777         if ( ! ($next = $this->_iter->next()) )
1778             return false;
1779
1780         $pagename = &$next['pagename'];
1781         if (!$pagename) {
1782             trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
1783             var_dump($next);
1784             return false;
1785         }
1786         // there's always hits, but we cache only if more 
1787         // (well not with file, cvs and dba)
1788         if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
1789             $this->_wikidb->_cache->cache_data($next);
1790         // cache existing page id's since we iterate over all links in GleanDescription 
1791         // and need them later for LinkExistingWord
1792         } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
1793                   and !$this->_options['include_empty'] and isset($next['id'])) {
1794             $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
1795         }
1796         return new WikiDB_Page($this->_wikidb, $pagename);
1797     }
1798
1799     /**
1800      * Release resources held by this iterator.
1801      *
1802      * The iterator may not be used after free() is called.
1803      *
1804      * There is no need to call free(), if next() has returned false.
1805      * (I.e. if you iterate through all the pages in the sequence,
1806      * you do not need to call free() --- you only need to call it
1807      * if you stop before the end of the iterator is reached.)
1808      *
1809      * @access public
1810      */
1811     function free() {
1812         $this->_iter->free();
1813     }
1814     
1815     function asArray() {
1816         $result = array();
1817         while ($page = $this->next())
1818             $result[] = $page;
1819         //$this->reset();
1820         return $result;
1821     }
1822     
1823     /**
1824      * Apply filters for options like 'sortby', 'limit', 'exclude'
1825      * for simple queries like titleSearch, where the backend is not ready yet.
1826      * Since iteration is usually destructive for SQL results,
1827      * we have to generate a copy.
1828      */
1829     function applyFilters($options = false) {
1830         if (!$options) $options = $this->_options;
1831         if (isset($options['sortby'])) {
1832             $array = array();
1833             /* this is destructive */
1834             while ($page = $this->next())
1835                 $result[] = $page->getName();
1836             $this->_doSort($array, $options['sortby']);
1837         }
1838         /* the rest is not destructive.
1839          * reconstruct a new iterator 
1840          */
1841         $pagenames = array(); $i = 0;
1842         if (isset($options['limit']))
1843             $limit = $options['limit'];
1844         else 
1845             $limit = 0;
1846         if (isset($options['exclude']))
1847             $exclude = $options['exclude'];
1848         if (is_string($exclude) and !is_array($exclude))
1849             $exclude = PageList::explodePageList($exclude, false, false, $limit);
1850         foreach($array as $pagename) {
1851             if ($limit and $i++ > $limit)
1852                 return new WikiDB_Array_PageIterator($pagenames);
1853             if (!empty($exclude) and !in_array($pagename, $exclude))
1854                 $pagenames[] = $pagename;
1855             elseif (empty($exclude))
1856                 $pagenames[] = $pagename;
1857         }
1858         return new WikiDB_Array_PageIterator($pagenames);
1859     }
1860
1861     /* pagename only */
1862     function _doSort(&$array, $sortby) {
1863         $sortby = PageList::sortby($sortby, 'init');
1864         if ($sortby == '+pagename')
1865             sort($array, SORT_STRING);
1866         elseif ($sortby == '-pagename')
1867             rsort($array, SORT_STRING);
1868         reset($array);
1869     }
1870
1871 };
1872
1873 /**
1874  * A class which represents a sequence of WikiDB_PageRevisions.
1875  * TODO: Enhance to php5 iterators
1876  */
1877 class WikiDB_PageRevisionIterator
1878 {
1879     function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
1880         $this->_revisions = $revisions;
1881         $this->_wikidb = &$wikidb;
1882         $this->_options = $options;
1883     }
1884     
1885     function count () {
1886         return $this->_revisions->count();
1887     }
1888
1889     /**
1890      * Get next WikiDB_PageRevision in sequence.
1891      *
1892      * @access public
1893      *
1894      * @return WikiDB_PageRevision
1895      * The next WikiDB_PageRevision in the sequence.
1896      */
1897     function next () {
1898         if ( ! ($next = $this->_revisions->next()) )
1899             return false;
1900
1901         //$this->_wikidb->_cache->cache_data($next);
1902
1903         $pagename = $next['pagename'];
1904         $version = $next['version'];
1905         $versiondata = $next['versiondata'];
1906         if (DEBUG) {
1907             if (!(is_string($pagename) and $pagename != '')) {
1908                 trigger_error("empty pagename",E_USER_WARNING);
1909                 return false;
1910             }
1911         } else assert(is_string($pagename) and $pagename != '');
1912         if (DEBUG) {
1913             if (!is_array($versiondata)) {
1914                 trigger_error("empty versiondata",E_USER_WARNING);
1915                 return false;
1916             }
1917         } else assert(is_array($versiondata));
1918         if (DEBUG) {
1919             if (!($version > 0)) {
1920                 trigger_error("invalid version",E_USER_WARNING);
1921                 return false;
1922             }
1923         } else assert($version > 0);
1924
1925         return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
1926                                        $versiondata);
1927     }
1928
1929     /**
1930      * Release resources held by this iterator.
1931      *
1932      * The iterator may not be used after free() is called.
1933      *
1934      * There is no need to call free(), if next() has returned false.
1935      * (I.e. if you iterate through all the revisions in the sequence,
1936      * you do not need to call free() --- you only need to call it
1937      * if you stop before the end of the iterator is reached.)
1938      *
1939      * @access public
1940      */
1941     function free() { 
1942         $this->_revisions->free();
1943     }
1944
1945     function asArray() {
1946         $result = array();
1947         while ($rev = $this->next())
1948             $result[] = $rev;
1949         $this->free();
1950         return $result;
1951     }
1952 };
1953
1954 /** pseudo iterator
1955  */
1956 class WikiDB_Array_PageIterator
1957 {
1958     function WikiDB_Array_PageIterator($pagenames) {
1959         global $request;
1960         $this->_dbi = $request->getDbh();
1961         $this->_pages = $pagenames;
1962         reset($this->_pages);
1963     }
1964     function next() {
1965         $c =& current($this->_pages);
1966         next($this->_pages);
1967         return $c !== false ? $this->_dbi->getPage($c) : false;
1968     }
1969     function count() {
1970         return count($this->_pages);
1971     }
1972     function free() {}
1973     function asArray() {
1974         reset($this->_pages);
1975         return $this->_pages;
1976     }
1977 }
1978
1979 class WikiDB_Array_generic_iter
1980 {
1981     function WikiDB_Array_generic_iter($result) {
1982         // $result may be either an array or a query result
1983         if (is_array($result)) {
1984             $this->_array = $result;
1985         } elseif (is_object($result)) {
1986             $this->_array = $result->asArray();
1987         } else {
1988             $this->_array = array();
1989         }
1990         if (!empty($this->_array))
1991             reset($this->_array);
1992     }
1993     function next() {
1994         $c =& current($this->_array);
1995         next($this->_array);
1996         return $c !== false ? $c : false;
1997     }
1998     function count() {
1999         return count($this->_array);
2000     }
2001     function free() {}
2002     function asArray() {
2003         if (!empty($this->_array))
2004             reset($this->_array);
2005         return $this->_array;
2006     }
2007 }
2008
2009 /**
2010  * Data cache used by WikiDB.
2011  *
2012  * FIXME: Maybe rename this to caching_backend (or some such).
2013  *
2014  * @access private
2015  */
2016 class WikiDB_cache 
2017 {
2018     // FIXME: beautify versiondata cache.  Cache only limited data?
2019
2020     function WikiDB_cache (&$backend) {
2021         $this->_backend = &$backend;
2022
2023         $this->_pagedata_cache = array();
2024         $this->_versiondata_cache = array();
2025         array_push ($this->_versiondata_cache, array());
2026         $this->_glv_cache = array();
2027         $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
2028     }
2029     
2030     function close() {
2031         $this->_pagedata_cache = array();
2032         $this->_versiondata_cache = array();
2033         $this->_glv_cache = array();
2034         $this->_id_cache = array();
2035     }
2036
2037     function get_pagedata($pagename) {
2038         assert(is_string($pagename) && $pagename != '');
2039         if (USECACHE) {
2040             $cache = &$this->_pagedata_cache;
2041             if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
2042                 $cache[$pagename] = $this->_backend->get_pagedata($pagename);
2043                 if (empty($cache[$pagename]))
2044                     $cache[$pagename] = array();
2045             }
2046             return $cache[$pagename];
2047         } else {
2048             return $this->_backend->get_pagedata($pagename);
2049         }
2050     }
2051     
2052     function update_pagedata($pagename, $newdata) {
2053         assert(is_string($pagename) && $pagename != '');
2054        
2055         $this->_backend->update_pagedata($pagename, $newdata);
2056
2057         if (USECACHE) {
2058             if (!empty($this->_pagedata_cache[$pagename]) 
2059                 and is_array($this->_pagedata_cache[$pagename])) 
2060             {
2061                 $cachedata = &$this->_pagedata_cache[$pagename];
2062                 foreach($newdata as $key => $val)
2063                     $cachedata[$key] = $val;
2064             } else 
2065                 $this->_pagedata_cache[$pagename] = $newdata;
2066         }
2067     }
2068
2069     function invalidate_cache($pagename) {
2070         unset ($this->_pagedata_cache[$pagename]);
2071         unset ($this->_versiondata_cache[$pagename]);
2072         unset ($this->_glv_cache[$pagename]);
2073         unset ($this->_id_cache[$pagename]);
2074         //unset ($this->_backend->_page_data);
2075     }
2076     
2077     function delete_page($pagename) {
2078         $result = $this->_backend->delete_page($pagename);
2079         $this->invalidate_cache($pagename);
2080         return $result;
2081     }
2082
2083     function purge_page($pagename) {
2084         $result = $this->_backend->purge_page($pagename);
2085         $this->invalidate_cache($pagename);
2086         return $result;
2087     }
2088
2089     // FIXME: ugly and wrong. may overwrite full cache with partial cache
2090     function cache_data($data) {
2091         ;
2092         //if (isset($data['pagedata']))
2093         //    $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
2094     }
2095     
2096     function get_versiondata($pagename, $version, $need_content = false) {
2097         //  FIXME: Seriously ugly hackage
2098         $readdata = false;
2099         if (USECACHE) {   //temporary - for debugging
2100             assert(is_string($pagename) && $pagename != '');
2101             // There is a bug here somewhere which results in an assertion failure at line 105
2102             // of ArchiveCleaner.php  It goes away if we use the next line.
2103             //$need_content = true;
2104             $nc = $need_content ? '1':'0';
2105             $cache = &$this->_versiondata_cache;
2106             if (!isset($cache[$pagename][$version][$nc]) 
2107                 || !(is_array ($cache[$pagename])) 
2108                 || !(is_array ($cache[$pagename][$version]))) 
2109             {
2110                 $cache[$pagename][$version][$nc] = 
2111                     $this->_backend->get_versiondata($pagename, $version, $need_content);
2112                 $readdata = true;
2113                 // If we have retrieved all data, we may as well set the cache for 
2114                 // $need_content = false
2115                 if ($need_content){
2116                     $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
2117                 }
2118             }
2119             $vdata = $cache[$pagename][$version][$nc];
2120         } else {
2121             $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
2122             $readdata = true;
2123         }
2124         if ($readdata && $vdata && !empty($vdata['%pagedata'])) {
2125             $this->_pagedata_cache[$pagename] =& $vdata['%pagedata'];
2126         }
2127         return $vdata;
2128     }
2129
2130     function set_versiondata($pagename, $version, $data) {
2131         //unset($this->_versiondata_cache[$pagename][$version]);
2132         
2133         $new = $this->_backend->set_versiondata($pagename, $version, $data);
2134         // Update the cache
2135         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2136         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2137         // Is this necessary?
2138         unset($this->_glv_cache[$pagename]);
2139     }
2140
2141     function update_versiondata($pagename, $version, $data) {
2142         $new = $this->_backend->update_versiondata($pagename, $version, $data);
2143         // Update the cache
2144         $this->_versiondata_cache[$pagename][$version]['1'] = $data;
2145         // FIXME: hack
2146         $this->_versiondata_cache[$pagename][$version]['0'] = $data;
2147         // Is this necessary?
2148         unset($this->_glv_cache[$pagename]);
2149     }
2150
2151     function delete_versiondata($pagename, $version) {
2152         $new = $this->_backend->delete_versiondata($pagename, $version);
2153         if (isset($this->_versiondata_cache[$pagename][$version]))
2154             unset ($this->_versiondata_cache[$pagename][$version]);
2155         // dirty latest version cache only if latest version gets deleted
2156         if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
2157             unset ($this->_glv_cache[$pagename]);
2158     }
2159         
2160     function get_latest_version($pagename)  {
2161         if (USECACHE) {
2162             assert (is_string($pagename) && $pagename != '');
2163             $cache = &$this->_glv_cache;
2164             if (!isset($cache[$pagename])) {
2165                 $cache[$pagename] = $this->_backend->get_latest_version($pagename);
2166                 if (empty($cache[$pagename]))
2167                     $cache[$pagename] = 0;
2168             }
2169             return $cache[$pagename];
2170         } else {
2171             return $this->_backend->get_latest_version($pagename); 
2172         }
2173     }
2174 };
2175
2176 function _sql_debuglog($msg, $newline=true, $shutdown=false) {
2177     static $fp = false;
2178     static $i = 0;
2179     if (!$fp) {
2180         $stamp = strftime("%y%m%d-%H%M%S");
2181         $fp = fopen("/tmp/sql-$stamp.log", "a");
2182         register_shutdown_function("_sql_debuglog_shutdown_function");
2183     } elseif ($shutdown) {
2184         fclose($fp);
2185         return;
2186     }
2187     if ($newline) fputs($fp, "[$i++] $msg");
2188     else fwrite($fp, $msg);
2189 }
2190
2191 function _sql_debuglog_shutdown_function() {
2192     _sql_debuglog('',false,true);
2193 }
2194
2195 // $Log: not supported by cvs2svn $
2196 // Revision 1.135  2005/09/11 14:19:44  rurban
2197 // enable LIMIT support for fulltext search
2198 //
2199 // Revision 1.134  2005/09/10 21:28:10  rurban
2200 // applyFilters hack to use filters after methods, which do not support them (titleSearch)
2201 //
2202 // Revision 1.133  2005/08/27 09:39:10  rurban
2203 // dumphtml when not at admin page: dump the current or given page
2204 //
2205 // Revision 1.132  2005/08/07 10:10:07  rurban
2206 // clean whole version cache
2207 //
2208 // Revision 1.131  2005/04/23 11:30:12  rurban
2209 // allow emtpy WikiDB::getRevisionBefore(), for simplier templates (revert)
2210 //
2211 // Revision 1.130  2005/04/06 06:19:30  rurban
2212 // Revert the previous wrong bugfix #1175761: USECACHE was mixed with WIKIDB_NOCACHE_MARKUP.
2213 // Fix WIKIDB_NOCACHE_MARKUP in main (always set it) and clarify it in WikiDB
2214 //
2215 // Revision 1.129  2005/04/06 05:50:29  rurban
2216 // honor !USECACHE for _cached_html, fixes #1175761
2217 //
2218 // Revision 1.128  2005/04/01 16:11:42  rurban
2219 // just whitespace
2220 //
2221 // Revision 1.127  2005/02/18 20:43:40  uckelman
2222 // WikiDB::genericWarnings() is no longer used.
2223 //
2224 // Revision 1.126  2005/02/04 17:58:06  rurban
2225 // minor versioncache improvement. part 2/3 of Charles Corrigan cache patch. not sure about the 0/1 issue
2226 //
2227 // Revision 1.125  2005/02/03 05:08:39  rurban
2228 // ref fix by Charles Corrigan
2229 //
2230 // Revision 1.124  2005/01/29 20:43:32  rurban
2231 // protect against empty request: on some occasion this happens
2232 //
2233 // Revision 1.123  2005/01/25 06:58:21  rurban
2234 // reformatting
2235 //
2236 // Revision 1.122  2005/01/20 10:18:17  rurban
2237 // reformatting
2238 //
2239 // Revision 1.121  2005/01/04 20:25:01  rurban
2240 // remove old [%pagedata][_cached_html] code
2241 //
2242 // Revision 1.120  2004/12/23 14:12:31  rurban
2243 // dont email on unittest
2244 //
2245 // Revision 1.119  2004/12/20 16:05:00  rurban
2246 // gettext msg unification
2247 //
2248 // Revision 1.118  2004/12/13 13:22:57  rurban
2249 // new BlogArchives plugin for the new blog theme. enable default box method
2250 // for all plugins. Minor search improvement.
2251 //
2252 // Revision 1.117  2004/12/13 08:15:09  rurban
2253 // false is wrong. null might be better but lets play safe.
2254 //
2255 // Revision 1.116  2004/12/10 22:15:00  rurban
2256 // fix $page->get('_cached_html)
2257 // refactor upgrade db helper _convert_cached_html() to be able to call them from WikiAdminUtils also.
2258 // support 2nd genericSqlQuery param (bind huge arg)
2259 //
2260 // Revision 1.115  2004/12/10 02:45:27  rurban
2261 // SQL optimization:
2262 //   put _cached_html from pagedata into a new seperate blob, not huge serialized string.
2263 //   it is only rarelely needed: for current page only, if-not-modified
2264 //   but was extracted for every simple page iteration.
2265 //
2266 // Revision 1.114  2004/12/09 22:24:44  rurban
2267 // optimize on _DEBUG_SQL only. but now again on every 50th request, not just save.
2268 //
2269 // Revision 1.113  2004/12/06 19:49:55  rurban
2270 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2271 // renamed delete_page to purge_page.
2272 // enable action=edit&version=-1 to force creation of a new version.
2273 // added BABYCART_PATH config
2274 // fixed magiqc in adodb.inc.php
2275 // and some more docs
2276 //
2277 // Revision 1.112  2004/11/30 17:45:53  rurban
2278 // exists_links backend implementation
2279 //
2280 // Revision 1.111  2004/11/28 20:39:43  rurban
2281 // deactivate pagecache overwrite: it is wrong
2282 //
2283 // Revision 1.110  2004/11/26 18:39:01  rurban
2284 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2285 //
2286 // Revision 1.109  2004/11/25 17:20:50  rurban
2287 // and again a couple of more native db args: backlinks
2288 //
2289 // Revision 1.108  2004/11/23 13:35:31  rurban
2290 // add case_exact search
2291 //
2292 // Revision 1.107  2004/11/21 11:59:16  rurban
2293 // remove final \n to be ob_cache independent
2294 //
2295 // Revision 1.106  2004/11/20 17:35:56  rurban
2296 // improved WantedPages SQL backends
2297 // PageList::sortby new 3rd arg valid_fields (override db fields)
2298 // WantedPages sql pager inexact for performance reasons:
2299 //   assume 3 wantedfrom per page, to be correct, no getTotal()
2300 // support exclude argument for get_all_pages, new _sql_set()
2301 //
2302 // Revision 1.105  2004/11/20 09:16:27  rurban
2303 // Fix bad-style Cut&Paste programming errors, detected by Charles Corrigan.
2304 //
2305 // Revision 1.104  2004/11/19 19:22:03  rurban
2306 // ModeratePage part1: change status
2307 //
2308 // Revision 1.103  2004/11/16 17:29:04  rurban
2309 // fix remove notification error
2310 // fix creation + update id_cache update
2311 //
2312 // Revision 1.102  2004/11/11 18:31:26  rurban
2313 // add simple backtrace on such general failures to get at least an idea where
2314 //
2315 // Revision 1.101  2004/11/10 19:32:22  rurban
2316 // * optimize increaseHitCount, esp. for mysql.
2317 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
2318 // * Pear_DB version logic (awful but needed)
2319 // * fix broken ADODB quote
2320 // * _extract_page_data simplification
2321 //
2322 // Revision 1.100  2004/11/10 15:29:20  rurban
2323 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
2324 // * ACCESS_LOG_SQL: fix cause request not yet initialized
2325 // * WikiDB: moved SQL specific methods upwards
2326 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
2327 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
2328 //
2329 // Revision 1.99  2004/11/09 17:11:05  rurban
2330 // * revert to the wikidb ref passing. there's no memory abuse there.
2331 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
2332 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
2333 //   are also needed at the rendering for linkExistingWikiWord().
2334 //   pass options to pageiterator.
2335 //   use this cache also for _get_pageid()
2336 //   This saves about 8 SELECT count per page (num all pagelinks).
2337 // * fix passing of all page fields to the pageiterator.
2338 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
2339 //
2340 // Revision 1.98  2004/11/07 18:34:29  rurban
2341 // more logging fixes
2342 //
2343 // Revision 1.97  2004/11/07 16:02:51  rurban
2344 // new sql access log (for spam prevention), and restructured access log class
2345 // dbh->quote (generic)
2346 // pear_db: mysql specific parts seperated (using replace)
2347 //
2348 // Revision 1.96  2004/11/05 22:32:15  rurban
2349 // encode the subject to be 7-bit safe
2350 //
2351 // Revision 1.95  2004/11/05 20:53:35  rurban
2352 // login cleanup: better debug msg on failing login,
2353 // checked password less immediate login (bogo or anon),
2354 // checked olduser pref session error,
2355 // better PersonalPage without password warning on minimal password length=0
2356 //   (which is default now)
2357 //
2358 // Revision 1.94  2004/11/01 10:43:56  rurban
2359 // seperate PassUser methods into seperate dir (memory usage)
2360 // fix WikiUser (old) overlarge data session
2361 // remove wikidb arg from various page class methods, use global ->_dbi instead
2362 // ...
2363 //
2364 // Revision 1.93  2004/10/14 17:17:57  rurban
2365 // remove dbi WikiDB_Page param: use global request object instead. (memory)
2366 // allow most_popular sortby arguments
2367 //
2368 // Revision 1.92  2004/10/05 17:00:04  rurban
2369 // support paging for simple lists
2370 // fix RatingDb sql backend.
2371 // remove pages from AllPages (this is ListPages then)
2372 //
2373 // Revision 1.91  2004/10/04 23:41:19  rurban
2374 // delete notify: fix, @unset syntax error
2375 //
2376 // Revision 1.90  2004/09/28 12:50:22  rurban
2377 // https://sourceforge.net/forum/forum.php?thread_id=1150924&forum_id=18929
2378 //
2379 // Revision 1.89  2004/09/26 10:54:42  rurban
2380 // silence deferred check
2381 //
2382 // Revision 1.88  2004/09/25 18:16:40  rurban
2383 // unset more unneeded _cached_html. (Guess this should fix sf.net now)
2384 //
2385 // Revision 1.87  2004/09/25 16:25:40  rurban
2386 // notify on rename and remove (to be improved)
2387 //
2388 // Revision 1.86  2004/09/23 18:52:06  rurban
2389 // only fortune at create
2390 //
2391 // Revision 1.85  2004/09/16 08:00:51  rurban
2392 // just some comments
2393 //
2394 // Revision 1.84  2004/09/14 10:34:30  rurban
2395 // fix TransformedText call to use refs
2396 //
2397 // Revision 1.83  2004/09/08 13:38:00  rurban
2398 // improve loadfile stability by using markup=2 as default for undefined markup-style.
2399 // use more refs for huge objects.
2400 // fix debug=static issue in WikiPluginCached
2401 //
2402 // Revision 1.82  2004/09/06 12:08:49  rurban
2403 // memory_limit on unix workaround
2404 // VisualWiki: default autosize image
2405 //
2406 // Revision 1.81  2004/09/06 08:28:00  rurban
2407 // rename genericQuery to genericSqlQuery
2408 //
2409 // Revision 1.80  2004/07/09 13:05:34  rurban
2410 // just aesthetics
2411 //
2412 // Revision 1.79  2004/07/09 10:06:49  rurban
2413 // Use backend specific sortby and sortable_columns method, to be able to
2414 // select between native (Db backend) and custom (PageList) sorting.
2415 // Fixed PageList::AddPageList (missed the first)
2416 // Added the author/creator.. name to AllPagesBy...
2417 //   display no pages if none matched.
2418 // Improved dba and file sortby().
2419 // Use &$request reference
2420 //
2421 // Revision 1.78  2004/07/08 21:32:35  rurban
2422 // Prevent from more warnings, minor db and sort optimizations
2423 //
2424 // Revision 1.77  2004/07/08 19:04:42  rurban
2425 // more unittest fixes (file backend, metadata RatingsDb)
2426 //
2427 // Revision 1.76  2004/07/08 17:31:43  rurban
2428 // improve numPages for file (fixing AllPagesTest)
2429 //
2430 // Revision 1.75  2004/07/05 13:56:22  rurban
2431 // sqlite autoincrement fix
2432 //
2433 // Revision 1.74  2004/07/03 16:51:05  rurban
2434 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
2435 // added atomic mysql REPLACE for PearDB as in ADODB
2436 // fixed _lock_tables typo links => link
2437 // fixes unserialize ADODB bug in line 180
2438 //
2439 // Revision 1.73  2004/06/29 08:52:22  rurban
2440 // Use ...version() $need_content argument in WikiDB also:
2441 // To reduce the memory footprint for larger sets of pagelists,
2442 // we don't cache the content (only true or false) and
2443 // we purge the pagedata (_cached_html) also.
2444 // _cached_html is only cached for the current pagename.
2445 // => Vastly improved page existance check, ACL check, ...
2446 //
2447 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2448 //
2449 // Revision 1.72  2004/06/25 14:15:08  rurban
2450 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
2451 //
2452 // Revision 1.71  2004/06/21 16:22:30  rurban
2453 // add DEFAULT_DUMP_DIR and HTML_DUMP_DIR constants, for easier cmdline dumps,
2454 // fixed dumping buttons locally (images/buttons/),
2455 // support pages arg for dumphtml,
2456 // optional directory arg for dumpserial + dumphtml,
2457 // fix a AllPages warning,
2458 // show dump warnings/errors on DEBUG,
2459 // don't warn just ignore on wikilens pagelist columns, if not loaded.
2460 // RateIt pagelist column is called "rating", not "ratingwidget" (Dan?)
2461 //
2462 // Revision 1.70  2004/06/18 14:39:31  rurban
2463 // actually check USECACHE
2464 //
2465 // Revision 1.69  2004/06/13 15:33:20  rurban
2466 // new support for arguments owner, author, creator in most relevant
2467 // PageList plugins. in WikiAdmin* via preSelectS()
2468 //
2469 // Revision 1.68  2004/06/08 21:03:20  rurban
2470 // updated RssParser for XmlParser quirks (store parser object params in globals)
2471 //
2472 // Revision 1.67  2004/06/07 19:12:49  rurban
2473 // fixed rename version=0, bug #966284
2474 //
2475 // Revision 1.66  2004/06/07 18:57:27  rurban
2476 // fix rename: Change pagename in all linked pages
2477 //
2478 // Revision 1.65  2004/06/04 20:32:53  rurban
2479 // Several locale related improvements suggested by Pierrick Meignen
2480 // LDAP fix by John Cole
2481 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2482 //
2483 // Revision 1.64  2004/06/04 16:50:00  rurban
2484 // add random quotes to empty pages
2485 //
2486 // Revision 1.63  2004/06/04 11:58:38  rurban
2487 // added USE_TAGLINES
2488 //
2489 // Revision 1.62  2004/06/03 22:24:41  rurban
2490 // reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after Remove
2491 //
2492 // Revision 1.61  2004/06/02 17:13:48  rurban
2493 // fix getRevisionBefore assertion
2494 //
2495 // Revision 1.60  2004/05/28 10:09:58  rurban
2496 // fix bug #962117, incorrect init of auth_dsn
2497 //
2498 // Revision 1.59  2004/05/27 17:49:05  rurban
2499 // renamed DB_Session to DbSession (in CVS also)
2500 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
2501 // remove leading slash in error message
2502 // added force_unlock parameter to File_Passwd (no return on stale locks)
2503 // fixed adodb session AffectedRows
2504 // added FileFinder helpers to unify local filenames and DATA_PATH names
2505 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
2506 //
2507 // Revision 1.58  2004/05/18 13:59:14  rurban
2508 // rename simpleQuery to genericQuery
2509 //
2510 // Revision 1.57  2004/05/16 22:07:35  rurban
2511 // check more config-default and predefined constants
2512 // various PagePerm fixes:
2513 //   fix default PagePerms, esp. edit and view for Bogo and Password users
2514 //   implemented Creator and Owner
2515 //   BOGOUSERS renamed to BOGOUSER
2516 // fixed syntax errors in signin.tmpl
2517 //
2518 // Revision 1.56  2004/05/15 22:54:49  rurban
2519 // fixed important WikiDB bug with DEBUG > 0: wrong assertion
2520 // improved SetAcl (works) and PagePerms, some WikiGroup helpers.
2521 //
2522 // Revision 1.55  2004/05/12 19:27:47  rurban
2523 // revert wrong inline optimization.
2524 //
2525 // Revision 1.54  2004/05/12 10:49:55  rurban
2526 // require_once fix for those libs which are loaded before FileFinder and
2527 //   its automatic include_path fix, and where require_once doesn't grok
2528 //   dirname(__FILE__) != './lib'
2529 // upgrade fix with PearDB
2530 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2531 //
2532 // Revision 1.53  2004/05/08 14:06:12  rurban
2533 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2534 // minor stability and portability fixes
2535 //
2536 // Revision 1.52  2004/05/06 19:26:16  rurban
2537 // improve stability, trying to find the InlineParser endless loop on sf.net
2538 //
2539 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
2540 //
2541 // Revision 1.51  2004/05/06 17:30:37  rurban
2542 // CategoryGroup: oops, dos2unix eol
2543 // improved phpwiki_version:
2544 //   pre -= .0001 (1.3.10pre: 1030.099)
2545 //   -p1 += .001 (1.3.9-p1: 1030.091)
2546 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2547 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2548 //   backend->backendType(), backend->database(),
2549 //   backend->listOfFields(),
2550 //   backend->listOfTables(),
2551 //
2552 // Revision 1.50  2004/05/04 22:34:25  rurban
2553 // more pdf support
2554 //
2555 // Revision 1.49  2004/05/03 11:16:40  rurban
2556 // fixed sendPageChangeNotification
2557 // subject rewording
2558 //
2559 // Revision 1.48  2004/04/29 23:03:54  rurban
2560 // fixed sf.net bug #940996
2561 //
2562 // Revision 1.47  2004/04/29 19:39:44  rurban
2563 // special support for formatted plugins (one-liners)
2564 //   like <small><plugin BlaBla ></small>
2565 // iter->asArray() helper for PopularNearby
2566 // db_session for older php's (no &func() allowed)
2567 //
2568 // Revision 1.46  2004/04/26 20:44:34  rurban
2569 // locking table specific for better databases
2570 //
2571 // Revision 1.45  2004/04/20 00:06:03  rurban
2572 // themable paging support
2573 //
2574 // Revision 1.44  2004/04/19 18:27:45  rurban
2575 // Prevent from some PHP5 warnings (ref args, no :: object init)
2576 //   php5 runs now through, just one wrong XmlElement object init missing
2577 // Removed unneccesary UpgradeUser lines
2578 // Changed WikiLink to omit version if current (RecentChanges)
2579 //
2580 // Revision 1.43  2004/04/18 01:34:20  rurban
2581 // protect most_popular from sortby=mtime
2582 //
2583 // Revision 1.42  2004/04/18 01:11:51  rurban
2584 // more numeric pagename fixes.
2585 // fixed action=upload with merge conflict warnings.
2586 // charset changed from constant to global (dynamic utf-8 switching)
2587 //
2588
2589 // Local Variables:
2590 // mode: php
2591 // tab-width: 8
2592 // c-basic-offset: 4
2593 // c-hanging-comment-ender-p: nil
2594 // indent-tabs-mode: nil
2595 // End:   
2596 ?>