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