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