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