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