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