]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
Use ...version() $need_content argument in WikiDB also:
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.54 2004-06-29 08:52:24 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         $dboptions = array('persistent' => true,
26                            'debug' => 2);
27         if (preg_match('/^pgsql/',$this->_dsn))
28             $dboptions['persistent'] = false;
29         $this->_dbh = DB::connect($this->_dsn, $dboptions);
30         $dbh = &$this->_dbh;
31         if (DB::isError($dbh)) {
32             trigger_error(sprintf("Can't connect to database: %s",
33                                   $this->_pear_error_message($dbh)),
34                           E_USER_ERROR);
35         }
36         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
37                                array(&$this, '_pear_error_callback'));
38         $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
39
40         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
41
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();
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();
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         $this->lock();
202         $id = $dbh->getOne($query);
203         if (empty($id)) {
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         }
211         $this->unlock();
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         
450         $qpagename = $dbh->quoteString($pagename);
451         
452         $result = $dbh->query("SELECT $want.id as id, $want.pagename as pagename, $want.hits as hits"
453                                // Looks like 'AS' in column alias is a MySQL thing, Oracle does not like it
454                                // and the PostgresSQL manual does not have it either
455                                // Since it is optional in mySQL, just remove it...
456                               . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
457                               . " WHERE linkfrom=linker.id AND linkto=linkee.id"
458                               . "  AND $have.pagename='$qpagename'"
459                               //. " GROUP BY $want.id"
460                               . " ORDER BY $want.pagename");
461         
462         return new WikiDB_backend_PearDB_iter($this, $result);
463     }
464
465     function get_all_pages($include_deleted=false,$sortby=false,$limit=false) {
466         $dbh = &$this->_dbh;
467         extract($this->_table_names);
468         // Limit clause is NOT portable!
469         // if ($limit)  $limit = "LIMIT $limit";
470         // else         $limit = '';
471         if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
472         else         $orderby = '';
473         if (strstr($orderby,'mtime')) { // multiple columns possible
474             if ($include_deleted) {
475                 $sql = "SELECT "
476                     . $this->page_tbl_fields
477                     . " FROM $page_tbl, $recent_tbl, $version_tbl"
478                     . " WHERE $page_tbl.id=$recent_tbl.id"
479                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
480                     . " $orderby";
481             }
482             else {
483                 $sql = "SELECT "
484                     . $this->page_tbl_fields
485                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
486                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
487                     . " AND $page_tbl.id=$recent_tbl.id"
488                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
489                     . " $orderby";
490             }
491         } else {
492             if ($include_deleted) {
493                 $sql = "SELECT "
494                     . $this->page_tbl_fields 
495                     ." FROM $page_tbl $orderby";
496             }
497             else {
498                 $sql = "SELECT "
499                     . $this->page_tbl_fields
500                     . " FROM $nonempty_tbl, $page_tbl"
501                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
502                     . " $orderby";
503             }
504         }
505         if ($limit) {
506             // extract from,count from limit
507             require_once("lib/PageList.php");
508             list($from,$count) = PageList::limit($limit);
509             $result = $dbh->limitQuery($sql, $from, $count);
510         } else {
511             $result = $dbh->query($sql);
512         }
513         return new WikiDB_backend_PearDB_iter($this, $result);
514     }
515         
516     /**
517      * Title search.
518      */
519     function text_search($search = '', $fullsearch = false) {
520         $dbh = &$this->_dbh;
521         extract($this->_table_names);
522         
523         $table = "$nonempty_tbl, $page_tbl";
524         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
525         $fields = $this->page_tbl_fields;
526         $callback = new WikiMethodCb($this, '_sql_match_clause');
527         
528         if ($fullsearch) {
529             $table .= ", $recent_tbl";
530             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
531
532             $table .= ", $version_tbl";
533             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
534
535             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
536             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
537         }
538         
539         $search_clause = $search->makeSqlClause($callback);
540         
541         $result = $dbh->query("SELECT $fields FROM $table"
542                               . " WHERE $join_clause"
543                               . "  AND ($search_clause)"
544                               . " ORDER BY pagename");
545         
546         return new WikiDB_backend_PearDB_iter($this, $result);
547     }
548
549     //Todo: check if the better Mysql MATCH operator is supported,
550     // (ranked search) and also google like expressions.
551     function _sql_match_clause($word) {
552         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
553         $word = $this->_dbh->quoteString($word);
554         //$page_tbl = $this->_table_names['page_tbl'];
555         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
556         //      e.g. if word is lowercased.
557         // http://bugs.mysql.com/bug.php?id=1491
558         return "LOWER(pagename) LIKE '%$word%'";
559     }
560
561     function _fullsearch_sql_match_clause($word) {
562         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
563         $word = $this->_dbh->quoteString($word);
564         //$page_tbl = $this->_table_names['page_tbl'];
565         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
566         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
567     }
568
569     /**
570      * Find highest or lowest hit counts.
571      */
572     function most_popular($limit=false,$sortby = '') {
573         $dbh = &$this->_dbh;
574         extract($this->_table_names);
575         $order = "DESC";
576         if ($limit < 0){ 
577             $order = "ASC";
578             $limit = -$limit;
579             $where = ""; 
580         } else {
581             $where = " AND hits > 0";
582         }
583         if ($sortby) $orderby = ' ORDER BY ' . PageList::sortby($sortby,'db');
584         else         $orderby = " ORDER BY hits $order";
585         //$limitclause = $limit ? " LIMIT $limit" : '';
586         $sql = "SELECT "
587             . $this->page_tbl_fields
588             . " FROM $nonempty_tbl, $page_tbl"
589             . " WHERE $nonempty_tbl.id=$page_tbl.id" 
590             . $where
591             . $orderby;
592          if ($limit) {
593              require_once("lib/PageList.php");
594              list($from,$count) = PageList::limit($limit);
595              $result = $dbh->limitQuery($sql, $from, $count);
596          } else {
597              $result = $dbh->query($sql);
598          }
599
600         return new WikiDB_backend_PearDB_iter($this, $result);
601     }
602
603     /**
604      * Find recent changes.
605      */
606     function most_recent($params) {
607         $limit = 0;
608         $since = 0;
609         $include_minor_revisions = false;
610         $exclude_major_revisions = false;
611         $include_all_revisions = false;
612         extract($params);
613
614         $dbh = &$this->_dbh;
615         extract($this->_table_names);
616
617         $pick = array();
618         if ($since)
619             $pick[] = "mtime >= $since";
620                         
621         
622         if ($include_all_revisions) {
623             // Include all revisions of each page.
624             $table = "$page_tbl, $version_tbl";
625             $join_clause = "$page_tbl.id=$version_tbl.id";
626
627             if ($exclude_major_revisions) {
628                 // Include only minor revisions
629                 $pick[] = "minor_edit <> 0";
630             }
631             elseif (!$include_minor_revisions) {
632                 // Include only major revisions
633                 $pick[] = "minor_edit = 0";
634             }
635         }
636         else {
637             $table = "$page_tbl, $recent_tbl";
638             $join_clause = "$page_tbl.id=$recent_tbl.id";
639             $table .= ", $version_tbl";
640             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
641             
642             if ($exclude_major_revisions) {
643                 // Include only most recent minor revision
644                 $pick[] = 'version=latestminor';
645             }
646             elseif (!$include_minor_revisions) {
647                 // Include only most recent major revision
648                 $pick[] = 'version=latestmajor';
649             }
650             else {
651                 // Include only the latest revision (whether major or minor).
652                 $pick[] ='version=latestversion';
653             }
654         }
655         $order = "DESC";
656         if($limit < 0){
657             $order = "ASC";
658             $limit = -$limit;
659         }
660         // $limitclause = $limit ? " LIMIT $limit" : '';
661         $where_clause = $join_clause;
662         if ($pick)
663             $where_clause .= " AND " . join(" AND ", $pick);
664
665         // FIXME: use SQL_BUFFER_RESULT for mysql?
666         $sql = "SELECT " 
667                . $this->page_tbl_fields . ", " . $this->version_tbl_fields
668                . " FROM $table"
669                . " WHERE $where_clause"
670                . " ORDER BY mtime $order";
671
672         if ($limit) {
673             $result = $dbh->limitQuery($sql, 0, $limit);
674         } else {
675             $result = $dbh->query($sql);
676         }
677
678         return new WikiDB_backend_PearDB_iter($this, $result);
679     }
680
681     /**
682      * Rename page in the database.
683      */
684     function rename_page($pagename, $to) {
685         $dbh = &$this->_dbh;
686         extract($this->_table_names);
687         
688         $this->lock();
689         if ( ($id = $this->_get_pageid($pagename, false)) ) {
690             if ($new = $this->_get_pageid($to, false)) {
691                 //cludge alert!
692                 //this page does not exist (already verified before), but exists in the page table.
693                 //so we delete this page.
694                 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
695                                     $dbh->quoteString($to)));
696             }
697             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
698                                 $dbh->quoteString($to)));
699         }
700         $this->unlock();
701         return $id;
702     }
703
704     function _update_recent_table($pageid = false) {
705         $dbh = &$this->_dbh;
706         extract($this->_table_names);
707         extract($this->_expressions);
708
709         $pageid = (int)$pageid;
710
711         $this->lock();
712
713         $dbh->query("DELETE FROM $recent_tbl"
714                     . ( $pageid ? " WHERE id=$pageid" : ""));
715         
716         $dbh->query( "INSERT 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         $this->unlock();
723     }
724
725     function _update_nonempty_table($pageid = false) {
726         $dbh = &$this->_dbh;
727         extract($this->_table_names);
728         extract($this->_expressions);
729
730         $pageid = (int)$pageid;
731
732         $this->lock();
733
734         $dbh->query("DELETE FROM $nonempty_tbl"
735                     . ( $pageid ? " WHERE id=$pageid" : ""));
736
737         $dbh->query("INSERT INTO $nonempty_tbl (id)"
738                     . " SELECT $recent_tbl.id"
739                     . " FROM $recent_tbl, $version_tbl"
740                     . " WHERE $recent_tbl.id=$version_tbl.id"
741                     . "       AND version=latestversion"
742                     // We have some specifics here (Oracle)
743                     //. "  AND content<>''"
744                     . "  AND content $notempty"
745                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
746
747         $this->unlock();
748     }
749
750
751     /**
752      * Grab a write lock on the tables in the SQL database.
753      *
754      * Calls can be nested.  The tables won't be unlocked until
755      * _unlock_database() is called as many times as _lock_database().
756      *
757      * @access protected
758      */
759     function lock($tables = false, $write_lock = true) {
760         if ($this->_lock_count++ == 0)
761             $this->_lock_tables($write_lock);
762     }
763
764     /**
765      * Actually lock the required tables.
766      */
767     function _lock_tables($write_lock) {
768         trigger_error("virtual", E_USER_ERROR);
769     }
770     
771     /**
772      * Release a write lock on the tables in the SQL database.
773      *
774      * @access protected
775      *
776      * @param $force boolean Unlock even if not every call to lock() has been matched
777      * by a call to unlock().
778      *
779      * @see _lock_database
780      */
781     function unlock($tables = false, $force = false) {
782         if ($this->_lock_count == 0)
783             return;
784         if (--$this->_lock_count <= 0 || $force) {
785             $this->_unlock_tables();
786             $this->_lock_count = 0;
787         }
788     }
789
790     /**
791      * Actually unlock the required tables.
792      */
793     function _unlock_tables($write_lock) {
794         trigger_error("virtual", E_USER_ERROR);
795     }
796
797
798     /**
799      * Serialize data
800      */
801     function _serialize($data) {
802         if (empty($data))
803             return '';
804         assert(is_array($data));
805         return serialize($data);
806     }
807
808     /**
809      * Unserialize data
810      */
811     function _unserialize($data) {
812         return empty($data) ? array() : unserialize($data);
813     }
814     
815     /**
816      * Callback for PEAR (DB) errors.
817      *
818      * @access protected
819      *
820      * @param A PEAR_error object.
821      */
822     function _pear_error_callback($error) {
823         if ($this->_is_false_error($error))
824             return;
825         
826         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
827         $this->close();
828         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
829     }
830
831     /**
832      * Detect false errors messages from PEAR DB.
833      *
834      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
835      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
836      * return any data.  (So when a "LOCK" command doesn't return any data,
837      * DB reports it as an error, when in fact, it's not.)
838      *
839      * @access private
840      * @return bool True iff error is not really an error.
841      */
842     function _is_false_error($error) {
843         if ($error->getCode() != DB_ERROR)
844             return false;
845
846         $query = $this->_dbh->last_query;
847
848         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
849                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
850             // Last query was not of the sort which doesn't return any data.
851             //" <--kludge for brain-dead syntax coloring
852             return false;
853         }
854         
855         if (! in_array('ismanip', get_class_methods('DB'))) {
856             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
857             // does not have the DB::isManip method.
858             return true;
859         }
860         
861         if (DB::isManip($query)) {
862             // If Pear thinks it's an isManip then it wouldn't have thrown
863             // the error we're testing for....
864             return false;
865         }
866
867         return true;
868     }
869
870     function _pear_error_message($error) {
871         $class = get_class($this);
872         $message = "$class: fatal database error\n"
873              . "\t" . $error->getMessage() . "\n"
874              . "\t(" . $error->getDebugInfo() . ")\n";
875
876         // Prevent password from being exposed during a connection error
877         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
878                                  '\\1:XXXXXXXX', $this->_dsn);
879         return str_replace($this->_dsn, $safe_dsn, $message);
880     }
881
882     /**
883      * Filter PHP errors notices from PEAR DB code.
884      *
885      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
886      * errors and notices.  This is an error callback (for use with
887      * ErrorManager which will filter out those spurious messages.)
888      * @see _is_false_error, ErrorManager
889      * @access private
890      */
891     function _pear_notice_filter($err) {
892         return ( $err->isNotice()
893                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
894                  && $err->errline == 126
895                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
896     }
897
898     /* some variables and functions for DB backend abstraction (action=upgrade) */
899     function database () {
900         return $this->_dbh->dsn['database'];
901     }
902     function backendType() {
903         return $this->_dbh->phptype;
904     }
905     function connection() {
906         return $this->_dbh->connection;
907     }
908
909     function listOfTables() {
910         return $this->_dbh->getListOf('tables');
911     }
912     function listOfFields($database,$table) {
913         if ($this->backendType() == 'mysql') {
914             $fields = array();
915             assert(!empty($database));
916             assert(!empty($table));
917             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or 
918                 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
919             if (!$result) return array();
920               $columns = mysql_num_fields($result);
921             for ($i = 0; $i < $columns; $i++) {
922                 $fields[] = mysql_field_name($result, $i);
923             }
924             mysql_free_result($result);
925             return $fields;
926         } else {
927             // TODO: try ADODB version?
928             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
929         }
930     }
931
932 };
933
934 /**
935  * This class is a generic iterator.
936  *
937  * WikiDB_backend_PearDB_iter only iterates over things that have
938  * 'pagename', 'pagedata', etc. etc.
939  *
940  * Probably WikiDB_backend_PearDB_iter and this class should be merged
941  * (most of the code is cut-and-paste :-( ), but I am trying to make
942  * changes that could be merged easily.
943  *
944  * @author: Dan Frankowski
945  */
946 class WikiDB_backend_PearDB_generic_iter
947 extends WikiDB_backend_iterator
948 {
949     function WikiDB_backend_PearDB_generic_iter(&$backend, &$query_result) {
950         if (DB::isError($query_result)) {
951             // This shouldn't happen, I thought.
952             $backend->_pear_error_callback($query_result);
953         }
954         
955         $this->_backend = &$backend;
956         $this->_result = $query_result;
957     }
958
959     function count() {
960         if (!$this->_result)
961             return false;
962         return $this->_result->numRows();
963     }
964     
965     function next() {
966         $backend = &$this->_backend;
967         if (!$this->_result)
968             return false;
969
970         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
971         if (!$record) {
972             $this->free();
973             return false;
974         }
975         
976         return $record;
977     }
978
979     function free () {
980         if ($this->_result) {
981             $this->_result->free();
982             $this->_result = false;
983         }
984     }
985 }
986
987 class WikiDB_backend_PearDB_iter
988 extends WikiDB_backend_PearDB_generic_iter
989 {
990
991     function next() {
992         $backend = &$this->_backend;
993         if (!$this->_result)
994             return false;
995
996         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
997         if (!$record) {
998             $this->free();
999             return false;
1000         }
1001         
1002         $pagedata = $backend->_extract_page_data($record);
1003         $rec = array('pagename' => $record['pagename'],
1004                      'pagedata' => $pagedata);
1005
1006         if (!empty($record['version'])) {
1007             $rec['versiondata'] = $backend->_extract_version_data($record);
1008             $rec['version'] = $record['version'];
1009         }
1010         
1011         return $rec;
1012     }
1013 }
1014 // $Log: not supported by cvs2svn $
1015 // Revision 1.53  2004/06/27 10:26:03  rurban
1016 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1017 //
1018 // Revision 1.52  2004/06/25 14:15:08  rurban
1019 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1020 //
1021 // Revision 1.51  2004/05/12 10:49:55  rurban
1022 // require_once fix for those libs which are loaded before FileFinder and
1023 //   its automatic include_path fix, and where require_once doesn't grok
1024 //   dirname(__FILE__) != './lib'
1025 // upgrade fix with PearDB
1026 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1027 //
1028 // Revision 1.50  2004/05/06 17:30:39  rurban
1029 // CategoryGroup: oops, dos2unix eol
1030 // improved phpwiki_version:
1031 //   pre -= .0001 (1.3.10pre: 1030.099)
1032 //   -p1 += .001 (1.3.9-p1: 1030.091)
1033 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1034 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1035 //   backend->backendType(), backend->database(),
1036 //   backend->listOfFields(),
1037 //   backend->listOfTables(),
1038 //
1039 // Revision 1.49  2004/05/03 21:35:30  rurban
1040 // don't use persistent connections with postgres
1041 //
1042 // Revision 1.48  2004/04/26 20:44:35  rurban
1043 // locking table specific for better databases
1044 //
1045 // Revision 1.47  2004/04/20 00:06:04  rurban
1046 // themable paging support
1047 //
1048 // Revision 1.46  2004/04/19 21:51:41  rurban
1049 // php5 compatibility: it works!
1050 //
1051 // Revision 1.45  2004/04/16 14:19:39  rurban
1052 // updated ADODB notes
1053 //
1054
1055 // (c-file-style: "gnu")
1056 // Local Variables:
1057 // mode: php
1058 // tab-width: 8
1059 // c-basic-offset: 4
1060 // c-hanging-comment-ender-p: nil
1061 // indent-tabs-mode: nil
1062 // End:   
1063 ?>