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