]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
add fast exclude support to SQL get_all_pages
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.69 2004-11-20 17:49:39 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, $exclude=false) {
497         $dbh = &$this->_dbh;
498         extract($this->_table_names);
499         $orderby = $this->sortby($sortby, 'db');
500         if ($orderby) $orderby = 'ORDER BY ' . $orderby;
501         if ($exclude) // array of pagenames
502             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
503         if (strstr($orderby, 'mtime ')) { // multiple columns possible
504             if ($include_empty) {
505                 $sql = "SELECT "
506                     . $this->page_tbl_fields
507                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
508                     . " WHERE $page_tbl.id=$recent_tbl.id"
509                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
510                     . " $orderby";
511             }
512             else {
513                 $sql = "SELECT "
514                     . $this->page_tbl_fields
515                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
516                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
517                     . " AND $page_tbl.id=$recent_tbl.id"
518                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
519                     . " $orderby";
520             }
521         } else {
522             if ($include_empty) {
523                 $sql = "SELECT "
524                     . $this->page_tbl_fields 
525                     ." FROM $page_tbl $orderby";
526             }
527             else {
528                 $sql = "SELECT "
529                     . $this->page_tbl_fields
530                     . " FROM $nonempty_tbl, $page_tbl"
531                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
532                     . " $orderby";
533             }
534         }
535         if ($limit) {
536             // extract from,count from limit
537             list($from,$count) = $this->limit($limit);
538             $result = $dbh->limitQuery($sql, $from, $count);
539         } else {
540             $result = $dbh->query($sql);
541         }
542         return new WikiDB_backend_PearDB_iter($this, $result);
543     }
544         
545     /**
546      * Title search.
547      */
548     function text_search($search = '', $fullsearch = false) {
549         $dbh = &$this->_dbh;
550         extract($this->_table_names);
551         
552         $table = "$nonempty_tbl, $page_tbl";
553         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
554         $fields = $this->page_tbl_fields;
555         $callback = new WikiMethodCb($this, '_sql_match_clause');
556         
557         if ($fullsearch) {
558             $table .= ", $recent_tbl";
559             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
560
561             $table .= ", $version_tbl";
562             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
563
564             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
565             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
566         }
567         
568         $search_clause = $search->makeSqlClause($callback);
569         
570         $result = $dbh->query("SELECT $fields FROM $table"
571                               . " WHERE $join_clause"
572                               . "  AND ($search_clause)"
573                               . " ORDER BY pagename");
574         
575         return new WikiDB_backend_PearDB_iter($this, $result);
576     }
577
578     //Todo: check if the better Mysql MATCH operator is supported,
579     // (ranked search) and also google like expressions.
580     function _sql_match_clause($word) {
581         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
582         $word = $this->_dbh->escapeSimple($word);
583         //$page_tbl = $this->_table_names['page_tbl'];
584         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
585         //      e.g. if word is lowercased.
586         // http://bugs.mysql.com/bug.php?id=1491
587         return "LOWER(pagename) LIKE '%$word%'";
588     }
589
590     function _fullsearch_sql_match_clause($word) {
591         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
592         $word = $this->_dbh->escapeSimple($word);
593         //$page_tbl = $this->_table_names['page_tbl'];
594         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
595         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
596     }
597
598     /**
599      * Find highest or lowest hit counts.
600      */
601     function most_popular($limit=0, $sortby='-hits') {
602         $dbh = &$this->_dbh;
603         extract($this->_table_names);
604         if ($limit < 0){ 
605             $order = "hits ASC";
606             $limit = -$limit;
607             $where = ""; 
608         } else {
609             $order = "hits DESC";
610             $where = " AND hits > 0";
611         }
612         $orderby = '';
613         if ($sortby != '-hits') {
614             if ($order = $this->sortby($sortby, 'db'))
615                 $orderby = " ORDER BY " . $order;
616         } else {
617             $orderby = " ORDER BY $order";
618         }
619         //$limitclause = $limit ? " LIMIT $limit" : '';
620         $sql = "SELECT "
621             . $this->page_tbl_fields
622             . " FROM $nonempty_tbl, $page_tbl"
623             . " WHERE $nonempty_tbl.id=$page_tbl.id" 
624             . $where
625             . $orderby;
626          if ($limit) {
627              list($from, $count) = $this->limit($limit);
628              $result = $dbh->limitQuery($sql, $from, $count);
629          } else {
630              $result = $dbh->query($sql);
631          }
632
633         return new WikiDB_backend_PearDB_iter($this, $result);
634     }
635
636     /**
637      * Find recent changes.
638      */
639     function most_recent($params) {
640         $limit = 0;
641         $since = 0;
642         $include_minor_revisions = false;
643         $exclude_major_revisions = false;
644         $include_all_revisions = false;
645         extract($params);
646
647         $dbh = &$this->_dbh;
648         extract($this->_table_names);
649
650         $pick = array();
651         if ($since)
652             $pick[] = "mtime >= $since";
653                         
654         
655         if ($include_all_revisions) {
656             // Include all revisions of each page.
657             $table = "$page_tbl, $version_tbl";
658             $join_clause = "$page_tbl.id=$version_tbl.id";
659
660             if ($exclude_major_revisions) {
661                 // Include only minor revisions
662                 $pick[] = "minor_edit <> 0";
663             }
664             elseif (!$include_minor_revisions) {
665                 // Include only major revisions
666                 $pick[] = "minor_edit = 0";
667             }
668         }
669         else {
670             $table = "$page_tbl, $recent_tbl";
671             $join_clause = "$page_tbl.id=$recent_tbl.id";
672             $table .= ", $version_tbl";
673             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
674             
675             if ($exclude_major_revisions) {
676                 // Include only most recent minor revision
677                 $pick[] = 'version=latestminor';
678             }
679             elseif (!$include_minor_revisions) {
680                 // Include only most recent major revision
681                 $pick[] = 'version=latestmajor';
682             }
683             else {
684                 // Include only the latest revision (whether major or minor).
685                 $pick[] ='version=latestversion';
686             }
687         }
688         $order = "DESC";
689         if($limit < 0){
690             $order = "ASC";
691             $limit = -$limit;
692         }
693         // $limitclause = $limit ? " LIMIT $limit" : '';
694         $where_clause = $join_clause;
695         if ($pick)
696             $where_clause .= " AND " . join(" AND ", $pick);
697
698         // FIXME: use SQL_BUFFER_RESULT for mysql?
699         $sql = "SELECT " 
700                . $this->page_tbl_fields . ", " . $this->version_tbl_fields
701                . " FROM $table"
702                . " WHERE $where_clause"
703                . " ORDER BY mtime $order";
704         if ($limit) {
705              list($from, $count) = $this->limit($limit);
706              $result = $dbh->limitQuery($sql, $from, $count);
707         } else {
708             $result = $dbh->query($sql);
709         }
710         return new WikiDB_backend_PearDB_iter($this, $result);
711     }
712
713     /**
714      * Find referenced empty pages.
715      */
716     function wanted_pages($exclude_from='', $exclude='', $sortby=false, $limit=false) {
717         $dbh = &$this->_dbh;
718         extract($this->_table_names);
719         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
720             $orderby = 'ORDER BY ' . $orderby;
721
722         if ($exclude_from) // array of pagenames
723             $exclude_from = " AND linked.pagename NOT IN ".$this->_sql_set($exclude_from);
724         if ($exclude) // array of pagenames
725             $exclude = " AND $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
726
727         $sql = "SELECT $page_tbl.pagename,linked.pagename as wantedfrom"
728             . " FROM $link_tbl,$page_tbl as linked "
729             . " LEFT JOIN $page_tbl ON($link_tbl.linkto=$page_tbl.id)"
730             . " LEFT JOIN $nonempty_tbl ON($link_tbl.linkto=$nonempty_tbl.id)" 
731             . " WHERE ISNULL($nonempty_tbl.id) AND linked.id=$link_tbl.linkfrom"
732             . $exclude_from
733             . $exclude
734             . $orderby;
735         if ($limit) {
736             list($from, $count) = $this->limit($limit);
737             $result = $dbh->limitQuery($sql, $from, $count * 3);
738         } else {
739             $result = $dbh->query($sql);
740         }
741         return new WikiDB_backend_PearDB_generic_iter($this, $result);
742     }
743
744     function _sql_set(&$pagenames) {
745         $s = '(';
746         foreach ($pagenames as $p) {
747             $s .= ("'".$this->_dbh->escapeSimple($p)."',");
748         }
749         return substr($s,0,-1).")";
750     }
751
752     /**
753      * Rename page in the database.
754      */
755     function rename_page($pagename, $to) {
756         $dbh = &$this->_dbh;
757         extract($this->_table_names);
758         
759         $this->lock();
760         if ( ($id = $this->_get_pageid($pagename, false)) ) {
761             if ($new = $this->_get_pageid($to, false)) {
762                 //cludge alert!
763                 //this page does not exist (already verified before), but exists in the page table.
764                 //so we delete this page.
765                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
766             }
767             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
768                                 $dbh->escapeSimple($to)));
769         }
770         $this->unlock();
771         return $id;
772     }
773
774     function _update_recent_table($pageid = false) {
775         $dbh = &$this->_dbh;
776         extract($this->_table_names);
777         extract($this->_expressions);
778
779         $pageid = (int)$pageid;
780
781         $this->lock();
782         $dbh->query("DELETE FROM $recent_tbl"
783                     . ( $pageid ? " WHERE id=$pageid" : ""));
784         $dbh->query( "INSERT INTO $recent_tbl"
785                      . " (id, latestversion, latestmajor, latestminor)"
786                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
787                      . " FROM $version_tbl"
788                      . ( $pageid ? " WHERE id=$pageid" : "")
789                      . " GROUP BY id" );
790         $this->unlock();
791     }
792
793     function _update_nonempty_table($pageid = false) {
794         $dbh = &$this->_dbh;
795         extract($this->_table_names);
796
797         $pageid = (int)$pageid;
798
799         extract($this->_expressions);
800         $this->lock();
801         $dbh->query("DELETE FROM $nonempty_tbl"
802                     . ( $pageid ? " WHERE id=$pageid" : ""));
803         $dbh->query("INSERT INTO $nonempty_tbl (id)"
804                     . " SELECT $recent_tbl.id"
805                     . " FROM $recent_tbl, $version_tbl"
806                     . " WHERE $recent_tbl.id=$version_tbl.id"
807                     . "       AND version=latestversion"
808                     // We have some specifics here (Oracle)
809                     //. "  AND content<>''"
810                     . "  AND content $notempty"
811                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
812         
813         $this->unlock();
814     }
815
816
817     /**
818      * Grab a write lock on the tables in the SQL database.
819      *
820      * Calls can be nested.  The tables won't be unlocked until
821      * _unlock_database() is called as many times as _lock_database().
822      *
823      * @access protected
824      */
825     function lock($tables = false, $write_lock = true) {
826         if ($this->_lock_count++ == 0)
827             $this->_lock_tables($write_lock);
828     }
829
830     /**
831      * Actually lock the required tables.
832      */
833     function _lock_tables($write_lock) {
834         trigger_error("virtual", E_USER_ERROR);
835     }
836     
837     /**
838      * Release a write lock on the tables in the SQL database.
839      *
840      * @access protected
841      *
842      * @param $force boolean Unlock even if not every call to lock() has been matched
843      * by a call to unlock().
844      *
845      * @see _lock_database
846      */
847     function unlock($tables = false, $force = false) {
848         if ($this->_lock_count == 0)
849             return;
850         if (--$this->_lock_count <= 0 || $force) {
851             $this->_unlock_tables();
852             $this->_lock_count = 0;
853         }
854     }
855
856     /**
857      * Actually unlock the required tables.
858      */
859     function _unlock_tables($write_lock) {
860         trigger_error("virtual", E_USER_ERROR);
861     }
862
863
864     /**
865      * Serialize data
866      */
867     function _serialize($data) {
868         if (empty($data))
869             return '';
870         assert(is_array($data));
871         return serialize($data);
872     }
873
874     /**
875      * Unserialize data
876      */
877     function _unserialize($data) {
878         return empty($data) ? array() : unserialize($data);
879     }
880     
881     /**
882      * Callback for PEAR (DB) errors.
883      *
884      * @access protected
885      *
886      * @param A PEAR_error object.
887      */
888     function _pear_error_callback($error) {
889         if ($this->_is_false_error($error))
890             return;
891         
892         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
893         $this->close();
894         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
895     }
896
897     /**
898      * Detect false errors messages from PEAR DB.
899      *
900      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
901      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
902      * return any data.  (So when a "LOCK" command doesn't return any data,
903      * DB reports it as an error, when in fact, it's not.)
904      *
905      * @access private
906      * @return bool True iff error is not really an error.
907      */
908     function _is_false_error($error) {
909         if ($error->getCode() != DB_ERROR)
910             return false;
911
912         $query = $this->_dbh->last_query;
913
914         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
915                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
916             // Last query was not of the sort which doesn't return any data.
917             //" <--kludge for brain-dead syntax coloring
918             return false;
919         }
920         
921         if (! in_array('ismanip', get_class_methods('DB'))) {
922             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
923             // does not have the DB::isManip method.
924             return true;
925         }
926         
927         if (DB::isManip($query)) {
928             // If Pear thinks it's an isManip then it wouldn't have thrown
929             // the error we're testing for....
930             return false;
931         }
932
933         return true;
934     }
935
936     function _pear_error_message($error) {
937         $class = get_class($this);
938         $message = "$class: fatal database error\n"
939              . "\t" . $error->getMessage() . "\n"
940              . "\t(" . $error->getDebugInfo() . ")\n";
941
942         // Prevent password from being exposed during a connection error
943         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
944                                  '\\1:XXXXXXXX', $this->_dsn);
945         return str_replace($this->_dsn, $safe_dsn, $message);
946     }
947
948     /**
949      * Filter PHP errors notices from PEAR DB code.
950      *
951      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
952      * errors and notices.  This is an error callback (for use with
953      * ErrorManager which will filter out those spurious messages.)
954      * @see _is_false_error, ErrorManager
955      * @access private
956      */
957     function _pear_notice_filter($err) {
958         return ( $err->isNotice()
959                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
960                  && $err->errline == 126
961                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
962     }
963
964     /* some variables and functions for DB backend abstraction (action=upgrade) */
965     function database () {
966         return $this->_dbh->dsn['database'];
967     }
968     function backendType() {
969         return $this->_dbh->phptype;
970     }
971     function connection() {
972         return $this->_dbh->connection;
973     }
974
975     function listOfTables() {
976         return $this->_dbh->getListOf('tables');
977     }
978     function listOfFields($database,$table) {
979         if ($this->backendType() == 'mysql') {
980             $fields = array();
981             assert(!empty($database));
982             assert(!empty($table));
983             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or 
984                 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
985             if (!$result) return array();
986               $columns = mysql_num_fields($result);
987             for ($i = 0; $i < $columns; $i++) {
988                 $fields[] = mysql_field_name($result, $i);
989             }
990             mysql_free_result($result);
991             return $fields;
992         } else {
993             // TODO: try ADODB version?
994             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
995         }
996     }
997
998 };
999
1000 /**
1001  * This class is a generic iterator.
1002  *
1003  * WikiDB_backend_PearDB_iter only iterates over things that have
1004  * 'pagename', 'pagedata', etc. etc.
1005  *
1006  * Probably WikiDB_backend_PearDB_iter and this class should be merged
1007  * (most of the code is cut-and-paste :-( ), but I am trying to make
1008  * changes that could be merged easily.
1009  *
1010  * @author: Dan Frankowski
1011  */
1012 class WikiDB_backend_PearDB_generic_iter
1013 extends WikiDB_backend_iterator
1014 {
1015     function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1016         if (DB::isError($query_result)) {
1017             // This shouldn't happen, I thought.
1018             $backend->_pear_error_callback($query_result);
1019         }
1020         
1021         $this->_backend = &$backend;
1022         $this->_result = $query_result;
1023     }
1024
1025     function count() {
1026         if (!$this->_result)
1027             return false;
1028         return $this->_result->numRows();
1029     }
1030     
1031     function next() {
1032         $backend = &$this->_backend;
1033         if (!$this->_result)
1034             return false;
1035
1036         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1037         if (!$record) {
1038             $this->free();
1039             return false;
1040         }
1041         
1042         return $record;
1043     }
1044
1045     function free () {
1046         if ($this->_result) {
1047             $this->_result->free();
1048             $this->_result = false;
1049         }
1050     }
1051 }
1052
1053 class WikiDB_backend_PearDB_iter
1054 extends WikiDB_backend_PearDB_generic_iter
1055 {
1056
1057     function next() {
1058         $backend = &$this->_backend;
1059         if (!$this->_result)
1060             return false;
1061
1062         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1063         if (!$record) {
1064             $this->free();
1065             return false;
1066         }
1067         
1068         $pagedata = $backend->_extract_page_data($record);
1069         $rec = array('pagename' => $record['pagename'],
1070                      'pagedata' => $pagedata);
1071
1072         if (!empty($record['version'])) {
1073             $rec['versiondata'] = $backend->_extract_version_data($record);
1074             $rec['version'] = $record['version'];
1075         }
1076         
1077         return $rec;
1078     }
1079 }
1080
1081 // $Log: not supported by cvs2svn $
1082 // Revision 1.68  2004/11/20 17:35:58  rurban
1083 // improved WantedPages SQL backends
1084 // PageList::sortby new 3rd arg valid_fields (override db fields)
1085 // WantedPages sql pager inexact for performance reasons:
1086 //   assume 3 wantedfrom per page, to be correct, no getTotal()
1087 // support exclude argument for get_all_pages, new _sql_set()
1088 //
1089 // Revision 1.67  2004/11/10 19:32:24  rurban
1090 // * optimize increaseHitCount, esp. for mysql.
1091 // * prepend dirs to the include_path (phpwiki_dir for faster searches)
1092 // * Pear_DB version logic (awful but needed)
1093 // * fix broken ADODB quote
1094 // * _extract_page_data simplification
1095 //
1096 // Revision 1.66  2004/11/10 15:29:21  rurban
1097 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1098 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1099 // * WikiDB: moved SQL specific methods upwards
1100 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1101 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1102 //
1103 // Revision 1.65  2004/11/09 17:11:17  rurban
1104 // * revert to the wikidb ref passing. there's no memory abuse there.
1105 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1106 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1107 //   are also needed at the rendering for linkExistingWikiWord().
1108 //   pass options to pageiterator.
1109 //   use this cache also for _get_pageid()
1110 //   This saves about 8 SELECT count per page (num all pagelinks).
1111 // * fix passing of all page fields to the pageiterator.
1112 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1113 //
1114 // Revision 1.64  2004/11/07 16:02:52  rurban
1115 // new sql access log (for spam prevention), and restructured access log class
1116 // dbh->quote (generic)
1117 // pear_db: mysql specific parts seperated (using replace)
1118 //
1119 // Revision 1.63  2004/11/01 10:43:58  rurban
1120 // seperate PassUser methods into seperate dir (memory usage)
1121 // fix WikiUser (old) overlarge data session
1122 // remove wikidb arg from various page class methods, use global ->_dbi instead
1123 // ...
1124 //
1125 // Revision 1.62  2004/10/14 19:19:34  rurban
1126 // loadsave: check if the dumped file will be accessible from outside.
1127 // and some other minor fixes. (cvsclient native not yet ready)
1128 //
1129 // Revision 1.61  2004/10/14 17:19:17  rurban
1130 // allow most_popular sortby arguments
1131 //
1132 // Revision 1.60  2004/07/09 10:06:50  rurban
1133 // Use backend specific sortby and sortable_columns method, to be able to
1134 // select between native (Db backend) and custom (PageList) sorting.
1135 // Fixed PageList::AddPageList (missed the first)
1136 // Added the author/creator.. name to AllPagesBy...
1137 //   display no pages if none matched.
1138 // Improved dba and file sortby().
1139 // Use &$request reference
1140 //
1141 // Revision 1.59  2004/07/08 21:32:36  rurban
1142 // Prevent from more warnings, minor db and sort optimizations
1143 //
1144 // Revision 1.58  2004/07/08 16:56:16  rurban
1145 // use the backendType abstraction
1146 //
1147 // Revision 1.57  2004/07/05 12:57:54  rurban
1148 // add mysql timeout
1149 //
1150 // Revision 1.56  2004/07/04 10:24:43  rurban
1151 // forgot the expressions
1152 //
1153 // Revision 1.55  2004/07/03 16:51:06  rurban
1154 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1155 // added atomic mysql REPLACE for PearDB as in ADODB
1156 // fixed _lock_tables typo links => link
1157 // fixes unserialize ADODB bug in line 180
1158 //
1159 // Revision 1.54  2004/06/29 08:52:24  rurban
1160 // Use ...version() $need_content argument in WikiDB also:
1161 // To reduce the memory footprint for larger sets of pagelists,
1162 // we don't cache the content (only true or false) and
1163 // we purge the pagedata (_cached_html) also.
1164 // _cached_html is only cached for the current pagename.
1165 // => Vastly improved page existance check, ACL check, ...
1166 //
1167 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
1168 //
1169 // Revision 1.53  2004/06/27 10:26:03  rurban
1170 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1171 //
1172 // Revision 1.52  2004/06/25 14:15:08  rurban
1173 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1174 //
1175 // Revision 1.51  2004/05/12 10:49:55  rurban
1176 // require_once fix for those libs which are loaded before FileFinder and
1177 //   its automatic include_path fix, and where require_once doesn't grok
1178 //   dirname(__FILE__) != './lib'
1179 // upgrade fix with PearDB
1180 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1181 //
1182 // Revision 1.50  2004/05/06 17:30:39  rurban
1183 // CategoryGroup: oops, dos2unix eol
1184 // improved phpwiki_version:
1185 //   pre -= .0001 (1.3.10pre: 1030.099)
1186 //   -p1 += .001 (1.3.9-p1: 1030.091)
1187 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1188 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1189 //   backend->backendType(), backend->database(),
1190 //   backend->listOfFields(),
1191 //   backend->listOfTables(),
1192 //
1193 // Revision 1.49  2004/05/03 21:35:30  rurban
1194 // don't use persistent connections with postgres
1195 //
1196 // Revision 1.48  2004/04/26 20:44:35  rurban
1197 // locking table specific for better databases
1198 //
1199 // Revision 1.47  2004/04/20 00:06:04  rurban
1200 // themable paging support
1201 //
1202 // Revision 1.46  2004/04/19 21:51:41  rurban
1203 // php5 compatibility: it works!
1204 //
1205 // Revision 1.45  2004/04/16 14:19:39  rurban
1206 // updated ADODB notes
1207 //
1208
1209 // (c-file-style: "gnu")
1210 // Local Variables:
1211 // mode: php
1212 // tab-width: 8
1213 // c-basic-offset: 4
1214 // c-hanging-comment-ender-p: nil
1215 // indent-tabs-mode: nil
1216 // End:   
1217 ?>