]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
* optimize increaseHitCount, esp. for mysql.
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.67 2004-11-10 19:32:24 rurban Exp $');
3
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 //require_once('lib/ErrorManager.php');
7
8 class WikiDB_backend_PearDB
9 extends WikiDB_backend
10 {
11     var $_dbh;
12
13     function WikiDB_backend_PearDB ($dbparams) {
14         // Find and include PEAR's DB.php.
15         // if DB would have exported its version number, it would be easier.
16         @require_once('DB/common.php'); // Either our local pear copy or the system one
17         // check the version!
18         $name = check_php_version(5) ? "escapeSimple" : strtolower("escapeSimple");
19         if (!in_array($name, get_class_methods("DB_common"))) {
20             $finder = new FileFinder;
21             $dir = dirname(__FILE__)."/../../pear";
22             $finder->_prepend_to_include_path($dir);
23             include_once("$dir/DB/common.php"); // use our version instead.
24             if (!in_array($name, get_class_methods("DB_common"))) {
25                 $pearFinder = new PearFileFinder("lib/pear");
26                 $pearFinder->includeOnce('DB.php');
27             } else {
28                 include_once("$dir/DB.php");
29             }
30         } else {
31           include_once("DB.php");
32         }
33
34         // Install filter to handle bogus error notices from buggy DB.php's.
35         //TODO: check the Pear_DB version, but how?
36         if (0) {
37             global $ErrorManager;
38             $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
39             $this->_pearerrhandler = true;
40         }
41         
42         // Open connection to database
43         $this->_dsn = $dbparams['dsn'];
44         $this->_dbparams = $dbparams;
45         $dboptions = array('persistent' => true,
46                            'debug' => 2);
47         if (preg_match('/^pgsql/',$this->_dsn))
48             $dboptions['persistent'] = false;
49         $this->_dbh = DB::connect($this->_dsn, $dboptions);
50         $dbh = &$this->_dbh;
51         if (DB::isError($dbh)) {
52             trigger_error(sprintf("Can't connect to database: %s",
53                                   $this->_pear_error_message($dbh)),
54                           E_USER_ERROR);
55         }
56         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
57                                array($this, '_pear_error_callback'));
58         $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
59
60         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
61         $this->_table_names
62             = array('page_tbl'     => $prefix . 'page',
63                     'version_tbl'  => $prefix . 'version',
64                     'link_tbl'     => $prefix . 'link',
65                     'recent_tbl'   => $prefix . 'recent',
66                     'nonempty_tbl' => $prefix . 'nonempty');
67         $page_tbl = $this->_table_names['page_tbl'];
68         $version_tbl = $this->_table_names['version_tbl'];
69         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, $page_tbl.hits AS hits";
70         $this->version_tbl_fields = "$version_tbl.version AS version, $version_tbl.mtime AS mtime, ".
71             "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, $version_tbl.versiondata AS versiondata";
72
73         $this->_expressions
74             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
75                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
76                     'maxversion'   => "MAX(version)",
77                     'notempty'     => "<>''",
78                     'iscontent'    => "content<>''");
79         
80         $this->_lock_count = 0;
81     }
82     
83     /**
84      * Close database connection.
85      */
86     function close () {
87         if (!$this->_dbh)
88             return;
89         if ($this->_lock_count) {
90             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
91                           E_USER_WARNING);
92         }
93         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
94         $this->unlock('force');
95
96         $this->_dbh->disconnect();
97
98         if (!empty($this->_pearerrhandler)) {
99             $GLOBALS['ErrorManager']->popErrorHandler();
100         }
101     }
102
103
104     /*
105      * Test fast wikipage.
106      */
107     function is_wiki_page($pagename) {
108         $dbh = &$this->_dbh;
109         extract($this->_table_names);
110         return $dbh->getOne(sprintf("SELECT $page_tbl.id as id"
111                                     . " FROM $nonempty_tbl, $page_tbl"
112                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
113                                     . "   AND pagename='%s'",
114                                     $dbh->escapeSimple($pagename)));
115     }
116         
117     function get_all_pagenames() {
118         $dbh = &$this->_dbh;
119         extract($this->_table_names);
120         return $dbh->getCol("SELECT pagename"
121                             . " FROM $nonempty_tbl, $page_tbl"
122                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
123     }
124
125     function numPages($filter=false, $exclude='') {
126         $dbh = &$this->_dbh;
127         extract($this->_table_names);
128         return $dbh->getOne("SELECT count(*)"
129                             . " FROM $nonempty_tbl, $page_tbl"
130                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
131     }
132     
133     function increaseHitCount($pagename) {
134         $dbh = &$this->_dbh;
135         // Hits is the only thing we can update in a fast manner.
136         // Note that this will fail silently if the page does not
137         // have a record in the page table.  Since it's just the
138         // hit count, who cares?
139         $dbh->query(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename='%s'",
140                             $this->_table_names['page_tbl'],
141                             $dbh->escapeSimple($pagename)));
142         return;
143     }
144
145     /**
146      * Read page information from database.
147      */
148     function get_pagedata($pagename) {
149         $dbh = &$this->_dbh;
150         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
151         $result = $dbh->getRow(sprintf("SELECT %s FROM %s WHERE pagename='%s'",
152                                        "hits,pagedata",
153                                        $this->_table_names['page_tbl'],
154                                        $dbh->escapeSimple($pagename)),
155                                DB_FETCHMODE_ASSOC);
156         return $result ? $this->_extract_page_data($result) : false;
157     }
158
159     function  _extract_page_data($data) {
160         if (empty($data)) return array();
161         elseif (empty($data['pagedata'])) return $data;
162         else return array_merge($data, $this->_unserialize($data['pagedata']));
163     }
164
165     function update_pagedata($pagename, $newdata) {
166         $dbh = &$this->_dbh;
167         $page_tbl = $this->_table_names['page_tbl'];
168
169         // Hits is the only thing we can update in a fast manner.
170         if (count($newdata) == 1 && isset($newdata['hits'])) {
171             // Note that this will fail silently if the page does not
172             // have a record in the page table.  Since it's just the
173             // hit count, who cares?
174             $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
175                                 $newdata['hits'], $dbh->escapeSimple($pagename)));
176             return;
177         }
178
179         $this->lock(array($page_tbl), true);
180         $data = $this->get_pagedata($pagename);
181         if (!$data) {
182             $data = array();
183             $this->_get_pageid($pagename, true); // Creates page record
184         }
185         
186         @$hits = (int)$data['hits'];
187         unset($data['hits']);
188
189         foreach ($newdata as $key => $val) {
190             if ($key == 'hits')
191                 $hits = (int)$val;
192             else if (empty($val))
193                 unset($data[$key]);
194             else
195                 $data[$key] = $val;
196         }
197
198         /* Portability issue -- not all DBMS supports huge strings 
199          * so we need to 'bind' instead of building a SQL statment.
200          * Note that we do not need to escapeSimple when we bind
201         $dbh->query(sprintf("UPDATE $page_tbl"
202                             . " SET hits=%d, pagedata='%s'"
203                             . " WHERE pagename='%s'",
204                             $hits,
205                             $dbh->escapeSimple($this->_serialize($data)),
206                             $dbh->escapeSimple($pagename)));
207         */
208         $sth = $dbh->query("UPDATE $page_tbl"
209                            . " SET hits=?, pagedata=?"
210                            . " WHERE pagename=?",
211                            array($hits, $this->_serialize($data), $pagename));
212         $this->unlock(array($page_tbl));
213     }
214
215     function _get_pageid($pagename, $create_if_missing = false) {
216         
217         // check id_cache
218         global $request;
219         $cache =& $request->_dbi->_cache->_id_cache;
220         if (isset($cache[$pagename])) return $cache[$pagename];
221
222         $dbh = &$this->_dbh;
223         $page_tbl = $this->_table_names['page_tbl'];
224         
225         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
226                          $dbh->escapeSimple($pagename));
227
228         if (!$create_if_missing)
229             return $dbh->getOne($query);
230
231         $id = $dbh->getOne($query);
232         if (empty($id)) {
233             $this->lock(array($page_tbl), true); // write lock
234             $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
235             $id = $max_id + 1;
236             $dbh->query(sprintf("INSERT INTO $page_tbl"
237                                 . " (id,pagename,hits)"
238                                 . " VALUES (%d,'%s',0)",
239                                 $id, $dbh->escapeSimple($pagename)));
240             $this->unlock(array($page_tbl));
241         }
242         return $id;
243     }
244
245     function get_latest_version($pagename) {
246         $dbh = &$this->_dbh;
247         extract($this->_table_names);
248         return
249             (int)$dbh->getOne(sprintf("SELECT latestversion"
250                                       . " FROM $page_tbl, $recent_tbl"
251                                       . " WHERE $page_tbl.id=$recent_tbl.id"
252                                       . "  AND pagename='%s'",
253                                       $dbh->escapeSimple($pagename)));
254     }
255
256     function get_previous_version($pagename, $version) {
257         $dbh = &$this->_dbh;
258         extract($this->_table_names);
259         
260         return
261             (int)$dbh->getOne(sprintf("SELECT version"
262                                       . " FROM $version_tbl, $page_tbl"
263                                       . " WHERE $version_tbl.id=$page_tbl.id"
264                                       . "  AND pagename='%s'"
265                                       . "  AND version < %d"
266                                       . " ORDER BY version DESC",
267                                       /* Non portable and useless anyway with getOne
268                                       . " LIMIT 1",
269                                       */
270                                       $dbh->escapeSimple($pagename),
271                                       $version));
272     }
273     
274     /**
275      * Get version data.
276      *
277      * @param $version int Which version to get.
278      *
279      * @return hash The version data, or false if specified version does not
280      *              exist.
281      */
282     function get_versiondata($pagename, $version, $want_content = false) {
283         $dbh = &$this->_dbh;
284         extract($this->_table_names);
285         extract($this->_expressions);
286
287         assert(is_string($pagename) and $pagename != "");
288         assert($version > 0);
289         
290         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
291         // FIXME: optimization: sometimes don't get page data?
292         if ($want_content) {
293             $fields = $this->page_tbl_fields . ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
294         }
295         else {
296             $fields = $this->page_tbl_fields . ","
297                        . "mtime, minor_edit, versiondata,"
298                        . "$iscontent AS have_content";
299         }
300
301         $result = $dbh->getRow(sprintf("SELECT $fields"
302                                        . " FROM $page_tbl, $version_tbl"
303                                        . " WHERE $page_tbl.id=$version_tbl.id"
304                                        . "  AND pagename='%s'"
305                                        . "  AND version=%d",
306                                        $dbh->escapeSimple($pagename), $version),
307                                DB_FETCHMODE_ASSOC);
308
309         return $this->_extract_version_data($result);
310     }
311
312     function _extract_version_data($query_result) {
313         if (!$query_result)
314             return false;
315
316         extract($query_result);
317         $data = $this->_unserialize($versiondata);
318         
319         $data['mtime'] = $mtime;
320         $data['is_minor_edit'] = !empty($minor_edit);
321         
322         if (isset($content))
323             $data['%content'] = $content;
324         elseif ($have_content)
325             $data['%content'] = true;
326         else
327             $data['%content'] = '';
328
329         // FIXME: this is ugly.
330         if (isset($pagename)) {
331             // Query also includes page data.
332             // We might as well send that back too...
333             $data['%pagedata'] = $this->_extract_page_data($query_result);
334         }
335
336         return $data;
337     }
338
339
340     /**
341      * Create a new revision of a page.
342      */
343     function set_versiondata($pagename, $version, $data) {
344         $dbh = &$this->_dbh;
345         $version_tbl = $this->_table_names['version_tbl'];
346         
347         $minor_edit = (int) !empty($data['is_minor_edit']);
348         unset($data['is_minor_edit']);
349         
350         $mtime = (int)$data['mtime'];
351         unset($data['mtime']);
352         assert(!empty($mtime));
353
354         @$content = (string) $data['%content'];
355         unset($data['%content']);
356
357         unset($data['%pagedata']);
358         
359         $this->lock();
360         $id = $this->_get_pageid($pagename, true);
361
362         // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
363         $dbh->query(sprintf("DELETE FROM $version_tbl"
364                             . " WHERE id=%d AND version=%d",
365                             $id, $version));
366
367         /* mysql optimized version. 
368         $dbh->query(sprintf("INSERT INTO $version_tbl"
369                             . " (id,version,mtime,minor_edit,content,versiondata)"
370                             . " VALUES(%d,%d,%d,%d,'%s','%s')",
371                             $id, $version, $mtime, $minor_edit,
372                             $dbh->quoteSmart($content),
373                             $dbh->quoteSmart($this->_serialize($data))));
374         */
375         // generic slow PearDB bind eh quoting.
376         $dbh->query("INSERT INTO $version_tbl"
377                     . " (id,version,mtime,minor_edit,content,versiondata)"
378                     . " VALUES(?, ?, ?, ?, ?, ?)",
379                     array($id, $version, $mtime, $minor_edit, $content,
380                     $this->_serialize($data)));
381
382         $this->_update_recent_table($id);
383         $this->_update_nonempty_table($id);
384         
385         $this->unlock();
386     }
387     
388     /**
389      * Delete an old revision of a page.
390      */
391     function delete_versiondata($pagename, $version) {
392         $dbh = &$this->_dbh;
393         extract($this->_table_names);
394
395         $this->lock();
396         if ( ($id = $this->_get_pageid($pagename)) ) {
397             $dbh->query("DELETE FROM $version_tbl"
398                         . " WHERE id=$id AND version=$version");
399             $this->_update_recent_table($id);
400             // This shouldn't be needed (as long as the latestversion
401             // never gets deleted.)  But, let's be safe.
402             $this->_update_nonempty_table($id);
403         }
404         $this->unlock();
405     }
406
407     /**
408      * Delete page completely from the database.
409      * I'm not sure if this is what we want. Maybe just delete the revisions
410      */
411     function delete_page($pagename) {
412         $dbh = &$this->_dbh;
413         extract($this->_table_names);
414         
415         $this->lock();
416         if ( ($id = $this->_get_pageid($pagename, false)) ) {
417             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
418             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
419             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
420             $dbh->query("DELETE FROM $link_tbl     WHERE linkfrom=$id");
421             $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
422             if ($nlinks) {
423                 // We're still in the link table (dangling link) so we can't delete this
424                 // altogether.
425                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
426             }
427             else {
428                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
429             }
430             $this->_update_recent_table();
431             $this->_update_nonempty_table();
432         }
433         $this->unlock();
434     }
435             
436
437     // The only thing we might be interested in updating which we can
438     // do fast in the flags (minor_edit).   I think the default
439     // update_versiondata will work fine...
440     //function update_versiondata($pagename, $version, $data) {
441     //}
442
443     function set_links($pagename, $links) {
444         // Update link table.
445         // FIXME: optimize: mysql can do this all in one big INSERT.
446
447         $dbh = &$this->_dbh;
448         extract($this->_table_names);
449
450         $this->lock();
451         $pageid = $this->_get_pageid($pagename, true);
452
453         $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
454
455         if ($links) {
456             foreach($links as $link) {
457                 if (isset($linkseen[$link]))
458                     continue;
459                 $linkseen[$link] = true;
460                 $linkid = $this->_get_pageid($link, true);
461                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
462                             . " VALUES ($pageid, $linkid)");
463             }
464         }
465         $this->unlock();
466     }
467     
468     /**
469      * Find pages which link to or are linked from a page.
470      */
471     function get_links($pagename, $reversed=true, $include_empty=false) {
472         $dbh = &$this->_dbh;
473         extract($this->_table_names);
474
475         if ($reversed)
476             list($have,$want) = array('linkee', 'linker');
477         else
478             list($have,$want) = array('linker', 'linkee');
479         
480         $qpagename = $dbh->escapeSimple($pagename);
481         $result = $dbh->query("SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
482                                // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
483                                // and the PostgresSQL manual does not have it either
484                                // Since it is optional in mySQL, just remove it...
485                               . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
486                               . (!$include_empty ? ", $nonempty_tbl" : '')
487                               . " WHERE linkfrom=linker.id AND linkto=linkee.id"
488                               . "  AND $have.pagename='$qpagename'"
489                               . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
490                               //. " GROUP BY $want.id"
491                               . " ORDER BY $want.pagename");
492         
493         return new WikiDB_backend_PearDB_iter($this, $result);
494     }
495
496     function get_all_pages($include_empty=false, $sortby=false, $limit=false) {
497         $dbh = &$this->_dbh;
498         extract($this->_table_names);
499         // Limit clause is NOT portable!
500         // if ($limit)  $limit = "LIMIT $limit";
501         // else         $limit = '';
502         $orderby = $this->sortby($sortby, 'db');
503         if ($orderby) $orderby = 'ORDER BY ' . $orderby;
504         if (strstr($orderby, 'mtime ')) { // multiple columns possible
505             if ($include_empty) {
506                 $sql = "SELECT "
507                     . $this->page_tbl_fields
508                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
509                     . " WHERE $page_tbl.id=$recent_tbl.id"
510                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
511                     . " $orderby";
512             }
513             else {
514                 $sql = "SELECT "
515                     . $this->page_tbl_fields
516                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
517                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
518                     . " AND $page_tbl.id=$recent_tbl.id"
519                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
520                     . " $orderby";
521             }
522         } else {
523             if ($include_empty) {
524                 $sql = "SELECT "
525                     . $this->page_tbl_fields 
526                     ." FROM $page_tbl $orderby";
527             }
528             else {
529                 $sql = "SELECT "
530                     . $this->page_tbl_fields
531                     . " FROM $nonempty_tbl, $page_tbl"
532                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
533                     . " $orderby";
534             }
535         }
536         if ($limit) {
537             // extract from,count from limit
538             list($from,$count) = $this->limit($limit);
539             $result = $dbh->limitQuery($sql, $from, $count);
540         } else {
541             $result = $dbh->query($sql);
542         }
543         return new WikiDB_backend_PearDB_iter($this, $result);
544     }
545         
546     /**
547      * Title search.
548      */
549     function text_search($search = '', $fullsearch = false) {
550         $dbh = &$this->_dbh;
551         extract($this->_table_names);
552         
553         $table = "$nonempty_tbl, $page_tbl";
554         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
555         $fields = $this->page_tbl_fields;
556         $callback = new WikiMethodCb($this, '_sql_match_clause');
557         
558         if ($fullsearch) {
559             $table .= ", $recent_tbl";
560             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
561
562             $table .= ", $version_tbl";
563             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
564
565             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
566             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
567         }
568         
569         $search_clause = $search->makeSqlClause($callback);
570         
571         $result = $dbh->query("SELECT $fields FROM $table"
572                               . " WHERE $join_clause"
573                               . "  AND ($search_clause)"
574                               . " ORDER BY pagename");
575         
576         return new WikiDB_backend_PearDB_iter($this, $result);
577     }
578
579     //Todo: check if the better Mysql MATCH operator is supported,
580     // (ranked search) and also google like expressions.
581     function _sql_match_clause($word) {
582         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
583         $word = $this->_dbh->escapeSimple($word);
584         //$page_tbl = $this->_table_names['page_tbl'];
585         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
586         //      e.g. if word is lowercased.
587         // http://bugs.mysql.com/bug.php?id=1491
588         return "LOWER(pagename) LIKE '%$word%'";
589     }
590
591     function _fullsearch_sql_match_clause($word) {
592         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
593         $word = $this->_dbh->escapeSimple($word);
594         //$page_tbl = $this->_table_names['page_tbl'];
595         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
596         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
597     }
598
599     /**
600      * Find highest or lowest hit counts.
601      */
602     function most_popular($limit=0, $sortby='-hits') {
603         $dbh = &$this->_dbh;
604         extract($this->_table_names);
605         if ($limit < 0){ 
606             $order = "hits ASC";
607             $limit = -$limit;
608             $where = ""; 
609         } else {
610             $order = "hits DESC";
611             $where = " AND hits > 0";
612         }
613         $orderby = '';
614         if ($sortby != '-hits') {
615             if ($order = $this->sortby($sortby, 'db'))
616                 $orderby = " ORDER BY " . $order;
617         } else {
618             $orderby = " ORDER BY $order";
619         }
620         //$limitclause = $limit ? " LIMIT $limit" : '';
621         $sql = "SELECT "
622             . $this->page_tbl_fields
623             . " FROM $nonempty_tbl, $page_tbl"
624             . " WHERE $nonempty_tbl.id=$page_tbl.id" 
625             . $where
626             . $orderby;
627          if ($limit) {
628              list($from, $count) = $this->limit($limit);
629              $result = $dbh->limitQuery($sql, $from, $count);
630          } else {
631              $result = $dbh->query($sql);
632          }
633
634         return new WikiDB_backend_PearDB_iter($this, $result);
635     }
636
637     /**
638      * Find recent changes.
639      */
640     function most_recent($params) {
641         $limit = 0;
642         $since = 0;
643         $include_minor_revisions = false;
644         $exclude_major_revisions = false;
645         $include_all_revisions = false;
646         extract($params);
647
648         $dbh = &$this->_dbh;
649         extract($this->_table_names);
650
651         $pick = array();
652         if ($since)
653             $pick[] = "mtime >= $since";
654                         
655         
656         if ($include_all_revisions) {
657             // Include all revisions of each page.
658             $table = "$page_tbl, $version_tbl";
659             $join_clause = "$page_tbl.id=$version_tbl.id";
660
661             if ($exclude_major_revisions) {
662                 // Include only minor revisions
663                 $pick[] = "minor_edit <> 0";
664             }
665             elseif (!$include_minor_revisions) {
666                 // Include only major revisions
667                 $pick[] = "minor_edit = 0";
668             }
669         }
670         else {
671             $table = "$page_tbl, $recent_tbl";
672             $join_clause = "$page_tbl.id=$recent_tbl.id";
673             $table .= ", $version_tbl";
674             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
675             
676             if ($exclude_major_revisions) {
677                 // Include only most recent minor revision
678                 $pick[] = 'version=latestminor';
679             }
680             elseif (!$include_minor_revisions) {
681                 // Include only most recent major revision
682                 $pick[] = 'version=latestmajor';
683             }
684             else {
685                 // Include only the latest revision (whether major or minor).
686                 $pick[] ='version=latestversion';
687             }
688         }
689         $order = "DESC";
690         if($limit < 0){
691             $order = "ASC";
692             $limit = -$limit;
693         }
694         // $limitclause = $limit ? " LIMIT $limit" : '';
695         $where_clause = $join_clause;
696         if ($pick)
697             $where_clause .= " AND " . join(" AND ", $pick);
698
699         // FIXME: use SQL_BUFFER_RESULT for mysql?
700         $sql = "SELECT " 
701                . $this->page_tbl_fields . ", " . $this->version_tbl_fields
702                . " FROM $table"
703                . " WHERE $where_clause"
704                . " ORDER BY mtime $order";
705
706         if ($limit) {
707             $result = $dbh->limitQuery($sql, 0, $limit);
708         } else {
709             $result = $dbh->query($sql);
710         }
711
712         return new WikiDB_backend_PearDB_iter($this, $result);
713     }
714
715     /**
716      * Rename page in the database.
717      */
718     function rename_page($pagename, $to) {
719         $dbh = &$this->_dbh;
720         extract($this->_table_names);
721         
722         $this->lock();
723         if ( ($id = $this->_get_pageid($pagename, false)) ) {
724             if ($new = $this->_get_pageid($to, false)) {
725                 //cludge alert!
726                 //this page does not exist (already verified before), but exists in the page table.
727                 //so we delete this page.
728                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
729             }
730             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
731                                 $dbh->escapeSimple($to)));
732         }
733         $this->unlock();
734         return $id;
735     }
736
737     function _update_recent_table($pageid = false) {
738         $dbh = &$this->_dbh;
739         extract($this->_table_names);
740         extract($this->_expressions);
741
742         $pageid = (int)$pageid;
743
744         $this->lock();
745         $dbh->query("DELETE FROM $recent_tbl"
746                     . ( $pageid ? " WHERE id=$pageid" : ""));
747         $dbh->query( "INSERT INTO $recent_tbl"
748                      . " (id, latestversion, latestmajor, latestminor)"
749                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
750                      . " FROM $version_tbl"
751                      . ( $pageid ? " WHERE id=$pageid" : "")
752                      . " GROUP BY id" );
753         $this->unlock();
754     }
755
756     function _update_nonempty_table($pageid = false) {
757         $dbh = &$this->_dbh;
758         extract($this->_table_names);
759
760         $pageid = (int)$pageid;
761
762         extract($this->_expressions);
763         $this->lock();
764         $dbh->query("DELETE FROM $nonempty_tbl"
765                     . ( $pageid ? " WHERE id=$pageid" : ""));
766         $dbh->query("INSERT INTO $nonempty_tbl (id)"
767                     . " SELECT $recent_tbl.id"
768                     . " FROM $recent_tbl, $version_tbl"
769                     . " WHERE $recent_tbl.id=$version_tbl.id"
770                     . "       AND version=latestversion"
771                     // We have some specifics here (Oracle)
772                     //. "  AND content<>''"
773                     . "  AND content $notempty"
774                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
775         
776         $this->unlock();
777     }
778
779
780     /**
781      * Grab a write lock on the tables in the SQL database.
782      *
783      * Calls can be nested.  The tables won't be unlocked until
784      * _unlock_database() is called as many times as _lock_database().
785      *
786      * @access protected
787      */
788     function lock($tables = false, $write_lock = true) {
789         if ($this->_lock_count++ == 0)
790             $this->_lock_tables($write_lock);
791     }
792
793     /**
794      * Actually lock the required tables.
795      */
796     function _lock_tables($write_lock) {
797         trigger_error("virtual", E_USER_ERROR);
798     }
799     
800     /**
801      * Release a write lock on the tables in the SQL database.
802      *
803      * @access protected
804      *
805      * @param $force boolean Unlock even if not every call to lock() has been matched
806      * by a call to unlock().
807      *
808      * @see _lock_database
809      */
810     function unlock($tables = false, $force = false) {
811         if ($this->_lock_count == 0)
812             return;
813         if (--$this->_lock_count <= 0 || $force) {
814             $this->_unlock_tables();
815             $this->_lock_count = 0;
816         }
817     }
818
819     /**
820      * Actually unlock the required tables.
821      */
822     function _unlock_tables($write_lock) {
823         trigger_error("virtual", E_USER_ERROR);
824     }
825
826
827     /**
828      * Serialize data
829      */
830     function _serialize($data) {
831         if (empty($data))
832             return '';
833         assert(is_array($data));
834         return serialize($data);
835     }
836
837     /**
838      * Unserialize data
839      */
840     function _unserialize($data) {
841         return empty($data) ? array() : unserialize($data);
842     }
843     
844     /**
845      * Callback for PEAR (DB) errors.
846      *
847      * @access protected
848      *
849      * @param A PEAR_error object.
850      */
851     function _pear_error_callback($error) {
852         if ($this->_is_false_error($error))
853             return;
854         
855         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
856         $this->close();
857         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
858     }
859
860     /**
861      * Detect false errors messages from PEAR DB.
862      *
863      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
864      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
865      * return any data.  (So when a "LOCK" command doesn't return any data,
866      * DB reports it as an error, when in fact, it's not.)
867      *
868      * @access private
869      * @return bool True iff error is not really an error.
870      */
871     function _is_false_error($error) {
872         if ($error->getCode() != DB_ERROR)
873             return false;
874
875         $query = $this->_dbh->last_query;
876
877         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
878                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
879             // Last query was not of the sort which doesn't return any data.
880             //" <--kludge for brain-dead syntax coloring
881             return false;
882         }
883         
884         if (! in_array('ismanip', get_class_methods('DB'))) {
885             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
886             // does not have the DB::isManip method.
887             return true;
888         }
889         
890         if (DB::isManip($query)) {
891             // If Pear thinks it's an isManip then it wouldn't have thrown
892             // the error we're testing for....
893             return false;
894         }
895
896         return true;
897     }
898
899     function _pear_error_message($error) {
900         $class = get_class($this);
901         $message = "$class: fatal database error\n"
902              . "\t" . $error->getMessage() . "\n"
903              . "\t(" . $error->getDebugInfo() . ")\n";
904
905         // Prevent password from being exposed during a connection error
906         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
907                                  '\\1:XXXXXXXX', $this->_dsn);
908         return str_replace($this->_dsn, $safe_dsn, $message);
909     }
910
911     /**
912      * Filter PHP errors notices from PEAR DB code.
913      *
914      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
915      * errors and notices.  This is an error callback (for use with
916      * ErrorManager which will filter out those spurious messages.)
917      * @see _is_false_error, ErrorManager
918      * @access private
919      */
920     function _pear_notice_filter($err) {
921         return ( $err->isNotice()
922                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
923                  && $err->errline == 126
924                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
925     }
926
927     /* some variables and functions for DB backend abstraction (action=upgrade) */
928     function database () {
929         return $this->_dbh->dsn['database'];
930     }
931     function backendType() {
932         return $this->_dbh->phptype;
933     }
934     function connection() {
935         return $this->_dbh->connection;
936     }
937
938     function listOfTables() {
939         return $this->_dbh->getListOf('tables');
940     }
941     function listOfFields($database,$table) {
942         if ($this->backendType() == 'mysql') {
943             $fields = array();
944             assert(!empty($database));
945             assert(!empty($table));
946             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or 
947                 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
948             if (!$result) return array();
949               $columns = mysql_num_fields($result);
950             for ($i = 0; $i < $columns; $i++) {
951                 $fields[] = mysql_field_name($result, $i);
952             }
953             mysql_free_result($result);
954             return $fields;
955         } else {
956             // TODO: try ADODB version?
957             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
958         }
959     }
960
961 };
962
963 /**
964  * This class is a generic iterator.
965  *
966  * WikiDB_backend_PearDB_iter only iterates over things that have
967  * 'pagename', 'pagedata', etc. etc.
968  *
969  * Probably WikiDB_backend_PearDB_iter and this class should be merged
970  * (most of the code is cut-and-paste :-( ), but I am trying to make
971  * changes that could be merged easily.
972  *
973  * @author: Dan Frankowski
974  */
975 class WikiDB_backend_PearDB_generic_iter
976 extends WikiDB_backend_iterator
977 {
978     function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
979         if (DB::isError($query_result)) {
980             // This shouldn't happen, I thought.
981             $backend->_pear_error_callback($query_result);
982         }
983         
984         $this->_backend = &$backend;
985         $this->_result = $query_result;
986     }
987
988     function count() {
989         if (!$this->_result)
990             return false;
991         return $this->_result->numRows();
992     }
993     
994     function next() {
995         $backend = &$this->_backend;
996         if (!$this->_result)
997             return false;
998
999         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1000         if (!$record) {
1001             $this->free();
1002             return false;
1003         }
1004         
1005         return $record;
1006     }
1007
1008     function free () {
1009         if ($this->_result) {
1010             $this->_result->free();
1011             $this->_result = false;
1012         }
1013     }
1014 }
1015
1016 class WikiDB_backend_PearDB_iter
1017 extends WikiDB_backend_PearDB_generic_iter
1018 {
1019
1020     function next() {
1021         $backend = &$this->_backend;
1022         if (!$this->_result)
1023             return false;
1024
1025         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1026         if (!$record) {
1027             $this->free();
1028             return false;
1029         }
1030         
1031         $pagedata = $backend->_extract_page_data($record);
1032         $rec = array('pagename' => $record['pagename'],
1033                      'pagedata' => $pagedata);
1034
1035         if (!empty($record['version'])) {
1036             $rec['versiondata'] = $backend->_extract_version_data($record);
1037             $rec['version'] = $record['version'];
1038         }
1039         
1040         return $rec;
1041     }
1042 }
1043
1044 // $Log: not supported by cvs2svn $
1045 // Revision 1.66  2004/11/10 15:29:21  rurban
1046 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1047 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1048 // * WikiDB: moved SQL specific methods upwards
1049 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1050 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1051 //
1052 // Revision 1.65  2004/11/09 17:11:17  rurban
1053 // * revert to the wikidb ref passing. there's no memory abuse there.
1054 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1055 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1056 //   are also needed at the rendering for linkExistingWikiWord().
1057 //   pass options to pageiterator.
1058 //   use this cache also for _get_pageid()
1059 //   This saves about 8 SELECT count per page (num all pagelinks).
1060 // * fix passing of all page fields to the pageiterator.
1061 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1062 //
1063 // Revision 1.64  2004/11/07 16:02:52  rurban
1064 // new sql access log (for spam prevention), and restructured access log class
1065 // dbh->quote (generic)
1066 // pear_db: mysql specific parts seperated (using replace)
1067 //
1068 // Revision 1.63  2004/11/01 10:43:58  rurban
1069 // seperate PassUser methods into seperate dir (memory usage)
1070 // fix WikiUser (old) overlarge data session
1071 // remove wikidb arg from various page class methods, use global ->_dbi instead
1072 // ...
1073 //
1074 // Revision 1.62  2004/10/14 19:19:34  rurban
1075 // loadsave: check if the dumped file will be accessible from outside.
1076 // and some other minor fixes. (cvsclient native not yet ready)
1077 //
1078 // Revision 1.61  2004/10/14 17:19:17  rurban
1079 // allow most_popular sortby arguments
1080 //
1081 // Revision 1.60  2004/07/09 10:06:50  rurban
1082 // Use backend specific sortby and sortable_columns method, to be able to
1083 // select between native (Db backend) and custom (PageList) sorting.
1084 // Fixed PageList::AddPageList (missed the first)
1085 // Added the author/creator.. name to AllPagesBy...
1086 //   display no pages if none matched.
1087 // Improved dba and file sortby().
1088 // Use &$request reference
1089 //
1090 // Revision 1.59  2004/07/08 21:32:36  rurban
1091 // Prevent from more warnings, minor db and sort optimizations
1092 //
1093 // Revision 1.58  2004/07/08 16:56:16  rurban
1094 // use the backendType abstraction
1095 //
1096 // Revision 1.57  2004/07/05 12:57:54  rurban
1097 // add mysql timeout
1098 //
1099 // Revision 1.56  2004/07/04 10:24:43  rurban
1100 // forgot the expressions
1101 //
1102 // Revision 1.55  2004/07/03 16:51:06  rurban
1103 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1104 // added atomic mysql REPLACE for PearDB as in ADODB
1105 // fixed _lock_tables typo links => link
1106 // fixes unserialize ADODB bug in line 180
1107 //
1108 // Revision 1.54  2004/06/29 08:52:24  rurban
1109 // Use ...version() $need_content argument in WikiDB also:
1110 // To reduce the memory footprint for larger sets of pagelists,
1111 // we don't cache the content (only true or false) and
1112 // we purge the pagedata (_cached_html) also.
1113 // _cached_html is only cached for the current pagename.
1114 // => Vastly improved page existance check, ACL check, ...
1115 //
1116 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1117 //
1118 // Revision 1.53  2004/06/27 10:26:03  rurban
1119 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1120 //
1121 // Revision 1.52  2004/06/25 14:15:08  rurban
1122 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1123 //
1124 // Revision 1.51  2004/05/12 10:49:55  rurban
1125 // require_once fix for those libs which are loaded before FileFinder and
1126 //   its automatic include_path fix, and where require_once doesn't grok
1127 //   dirname(__FILE__) != './lib'
1128 // upgrade fix with PearDB
1129 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1130 //
1131 // Revision 1.50  2004/05/06 17:30:39  rurban
1132 // CategoryGroup: oops, dos2unix eol
1133 // improved phpwiki_version:
1134 //   pre -= .0001 (1.3.10pre: 1030.099)
1135 //   -p1 += .001 (1.3.9-p1: 1030.091)
1136 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1137 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1138 //   backend->backendType(), backend->database(),
1139 //   backend->listOfFields(),
1140 //   backend->listOfTables(),
1141 //
1142 // Revision 1.49  2004/05/03 21:35:30  rurban
1143 // don't use persistent connections with postgres
1144 //
1145 // Revision 1.48  2004/04/26 20:44:35  rurban
1146 // locking table specific for better databases
1147 //
1148 // Revision 1.47  2004/04/20 00:06:04  rurban
1149 // themable paging support
1150 //
1151 // Revision 1.46  2004/04/19 21:51:41  rurban
1152 // php5 compatibility: it works!
1153 //
1154 // Revision 1.45  2004/04/16 14:19:39  rurban
1155 // updated ADODB notes
1156 //
1157
1158 // (c-file-style: "gnu")
1159 // Local Variables:
1160 // mode: php
1161 // tab-width: 8
1162 // c-basic-offset: 4
1163 // c-hanging-comment-ender-p: nil
1164 // indent-tabs-mode: nil
1165 // End:   
1166 ?>