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