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