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