]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
rcs_id no longer makes sense with Subversion global version number
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 // rcs_id('$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 = (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 ($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) {
665             // extract from,count from limit
666             list($from,$count) = $this->limit($limit);
667             $result = $dbh->limitQuery($sql, $from, $count);
668         } else {
669             $result = $dbh->query($sql);
670         }
671         return new WikiDB_backend_PearDB_iter($this, $result);
672     }
673         
674     /**
675      * Title search.
676      * Todo: exclude
677      */
678     function text_search($search, $fulltext=false, $sortby='', $limit='', 
679                          $exclude='') 
680     {
681         $dbh = &$this->_dbh;
682         extract($this->_table_names);
683         $orderby = $this->sortby($sortby, 'db');
684         if ($orderby) $orderby = ' ORDER BY ' . $orderby;
685         //else " ORDER BY rank($field, to_tsquery('$searchon')) DESC";
686
687         $searchclass = get_class($this)."_search";
688         // no need to define it everywhere and then fallback. memory!
689         if (!class_exists($searchclass))
690             $searchclass = "WikiDB_backend_PearDB_search";
691         $searchobj = new $searchclass($search, $dbh);
692         
693         $table = "$nonempty_tbl, $page_tbl";
694         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
695         $fields = $this->page_tbl_fields;
696
697         if ($fulltext) {
698             $table .= ", $recent_tbl";
699             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
700
701             $table .= ", $version_tbl";
702             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
703
704             $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
705             $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
706         } else {
707             $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
708         }
709         $search_clause = $search->makeSqlClauseObj($callback);
710         
711         $sql = "SELECT $fields FROM $table"
712             . " WHERE $join_clause"
713             . "  AND ($search_clause)"
714             . $orderby;
715          if ($limit) {
716              list($from, $count) = $this->limit($limit);
717              $result = $dbh->limitQuery($sql, $from, $count);
718          } else {
719              $result = $dbh->query($sql);
720          }
721         
722         $iter = new WikiDB_backend_PearDB_iter($this, $result);
723         $iter->stoplisted = @$searchobj->stoplisted;
724         return $iter;
725     }
726
727     //Todo: check if the better Mysql MATCH operator is supported,
728     // (ranked search) and also google like expressions.
729     function _sql_match_clause($word) {
730         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
731         $word = $this->_dbh->escapeSimple($word);
732         //$page_tbl = $this->_table_names['page_tbl'];
733         //Note: Mysql 4.1.0 has a bug which fails with binary fields.
734         //      e.g. if word is lowercased.
735         // http://bugs.mysql.com/bug.php?id=1491
736         return "LOWER(pagename) LIKE '%$word%'";
737     }
738     function _sql_casematch_clause($word) {
739         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
740         $word = $this->_dbh->escapeSimple($word);
741         return "pagename LIKE '%$word%'";
742     }
743     function _fullsearch_sql_match_clause($word) {
744         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
745         $word = $this->_dbh->escapeSimple($word);
746         //$page_tbl = $this->_table_names['page_tbl'];
747         //Mysql 4.1.1 has a bug which fails here if word is lowercased.
748         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
749     }
750     function _fullsearch_sql_casematch_clause($word) {
751         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
752         $word = $this->_dbh->escapeSimple($word);
753         return "pagename LIKE '%$word%' OR content LIKE '%$word%'";
754     }
755
756     /**
757      * Find highest or lowest hit counts.
758      */
759     function most_popular($limit=20, $sortby='-hits') {
760         $dbh = &$this->_dbh;
761         extract($this->_table_names);
762         if ($limit < 0){ 
763             $order = "hits ASC";
764             $limit = -$limit;
765             $where = ""; 
766         } else {
767             $order = "hits DESC";
768             $where = " AND hits > 0";
769         }
770         $orderby = '';
771         if ($sortby != '-hits') {
772             if ($order = $this->sortby($sortby, 'db'))
773                 $orderby = " ORDER BY " . $order;
774         } else {
775             $orderby = " ORDER BY $order";
776         }
777         //$limitclause = $limit ? " LIMIT $limit" : '';
778         $sql = "SELECT "
779             . $this->page_tbl_fields
780             . " FROM $nonempty_tbl, $page_tbl"
781             . " WHERE $nonempty_tbl.id=$page_tbl.id" 
782             . $where
783             . $orderby;
784          if ($limit) {
785              list($from, $count) = $this->limit($limit);
786              $result = $dbh->limitQuery($sql, $from, $count);
787          } else {
788              $result = $dbh->query($sql);
789          }
790
791         return new WikiDB_backend_PearDB_iter($this, $result);
792     }
793
794     /**
795      * Find recent changes.
796      */
797     function most_recent($params) {
798         $limit = 0;
799         $since = 0;
800         $include_minor_revisions = false;
801         $exclude_major_revisions = false;
802         $include_all_revisions = false;
803         extract($params);
804
805         $dbh = &$this->_dbh;
806         extract($this->_table_names);
807
808         $pick = array();
809         if ($since)
810             $pick[] = "mtime >= $since";
811                         
812         
813         if ($include_all_revisions) {
814             // Include all revisions of each page.
815             $table = "$page_tbl, $version_tbl";
816             $join_clause = "$page_tbl.id=$version_tbl.id";
817
818             if ($exclude_major_revisions) {
819                 // Include only minor revisions
820                 $pick[] = "minor_edit <> 0";
821             }
822             elseif (!$include_minor_revisions) {
823                 // Include only major revisions
824                 $pick[] = "minor_edit = 0";
825             }
826         }
827         else {
828             $table = "$page_tbl, $recent_tbl";
829             $join_clause = "$page_tbl.id=$recent_tbl.id";
830             $table .= ", $version_tbl";
831             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
832             
833             if ($exclude_major_revisions) {
834                 // Include only most recent minor revision
835                 $pick[] = 'version=latestminor';
836             }
837             elseif (!$include_minor_revisions) {
838                 // Include only most recent major revision
839                 $pick[] = 'version=latestmajor';
840             }
841             else {
842                 // Include only the latest revision (whether major or minor).
843                 $pick[] ='version=latestversion';
844             }
845         }
846         $order = "DESC";
847         if($limit < 0){
848             $order = "ASC";
849             $limit = -$limit;
850         }
851         // $limitclause = $limit ? " LIMIT $limit" : '';
852         $where_clause = $join_clause;
853         if ($pick)
854             $where_clause .= " AND " . join(" AND ", $pick);
855
856         // FIXME: use SQL_BUFFER_RESULT for mysql?
857         $sql = "SELECT " 
858                . $this->page_tbl_fields . ", " . $this->version_tbl_fields
859                . " FROM $table"
860                . " WHERE $where_clause"
861                . " ORDER BY mtime $order";
862         if ($limit) {
863              list($from, $count) = $this->limit($limit);
864              $result = $dbh->limitQuery($sql, $from, $count);
865         } else {
866             $result = $dbh->query($sql);
867         }
868         return new WikiDB_backend_PearDB_iter($this, $result);
869     }
870
871     /**
872      * Find referenced empty pages.
873      */
874     function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
875         $dbh = &$this->_dbh;
876         extract($this->_table_names);
877         if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
878             $orderby = 'ORDER BY ' . $orderby;
879
880         if ($exclude_from) // array of pagenames
881             $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
882         if ($exclude) // array of pagenames
883             $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
884         $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
885             . " FROM $page_tbl p, $link_tbl linked"
886             .   " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
887             .   " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
888             . " WHERE ne.id IS NULL"
889             .       " AND p.id = linked.linkfrom"
890             . $exclude_from
891             . $exclude
892             . $orderby;
893         if ($limit) {
894             // oci8 error: WHERE NULL = NULL appended
895             list($from, $count) = $this->limit($limit);
896             $result = $dbh->limitQuery($sql, $from, $count * 3);
897         } else {
898             $result = $dbh->query($sql);
899         }
900         return new WikiDB_backend_PearDB_generic_iter($this, $result);
901     }
902
903     function _sql_set(&$pagenames) {
904         $s = '(';
905         foreach ($pagenames as $p) {
906             $s .= ("'".$this->_dbh->escapeSimple($p)."',");
907         }
908         return substr($s,0,-1).")";
909     }
910
911     /**
912      * Rename page in the database.
913      */
914     function rename_page ($pagename, $to) {
915         $dbh = &$this->_dbh;
916         extract($this->_table_names);
917         
918         $this->lock();
919         if (($id = $this->_get_pageid($pagename, false)) ) {
920             if ($new = $this->_get_pageid($to, false)) {
921                 // Cludge Alert!
922                 // This page does not exist (already verified before), but exists in the page table.
923                 // So we delete this page.
924                 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
925                 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
926                 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
927                 // We have to fix all referring tables to the old id
928                 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
929                 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
930                 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
931             }
932             $dbh->query(sprintf("UPDATE $page_tbl SET pagename='%s' WHERE id=$id",
933                                 $dbh->escapeSimple($to)));
934         }
935         $this->unlock();
936         return $id;
937     }
938
939     function _update_recent_table($pageid = false) {
940         $dbh = &$this->_dbh;
941         extract($this->_table_names);
942         extract($this->_expressions);
943
944         $pageid = (int)$pageid;
945
946         $this->lock();
947         $dbh->query("DELETE FROM $recent_tbl"
948                     . ( $pageid ? " WHERE id=$pageid" : ""));
949         $dbh->query( "INSERT INTO $recent_tbl"
950                      . " (id, latestversion, latestmajor, latestminor)"
951                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
952                      . " FROM $version_tbl"
953                      . ( $pageid ? " WHERE id=$pageid" : "")
954                      . " GROUP BY id" );
955         $this->unlock();
956     }
957
958     function _update_nonempty_table($pageid = false) {
959         $dbh = &$this->_dbh;
960         extract($this->_table_names);
961
962         $pageid = (int)$pageid;
963
964         extract($this->_expressions);
965         $this->lock();
966         $dbh->query("DELETE FROM $nonempty_tbl"
967                     . ( $pageid ? " WHERE id=$pageid" : ""));
968         $dbh->query("INSERT INTO $nonempty_tbl (id)"
969                     . " SELECT $recent_tbl.id"
970                     . " FROM $recent_tbl, $version_tbl"
971                     . " WHERE $recent_tbl.id=$version_tbl.id"
972                     . "       AND version=latestversion"
973                     // We have some specifics here (Oracle)
974                     //. "  AND content<>''"
975                     . "  AND content $notempty"
976                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
977         
978         $this->unlock();
979     }
980
981
982     /**
983      * Grab a write lock on the tables in the SQL database.
984      *
985      * Calls can be nested.  The tables won't be unlocked until
986      * _unlock_database() is called as many times as _lock_database().
987      *
988      * @access protected
989      */
990     function lock($tables = false, $write_lock = true) {
991         if ($this->_lock_count++ == 0)
992             $this->_lock_tables($write_lock);
993     }
994
995     /**
996      * Actually lock the required tables.
997      */
998     function _lock_tables($write_lock) {
999         trigger_error("virtual", E_USER_ERROR);
1000     }
1001     
1002     /**
1003      * Release a write lock on the tables in the SQL database.
1004      *
1005      * @access protected
1006      *
1007      * @param $force boolean Unlock even if not every call to lock() has been matched
1008      * by a call to unlock().
1009      *
1010      * @see _lock_database
1011      */
1012     function unlock($tables = false, $force = false) {
1013         if ($this->_lock_count == 0)
1014             return;
1015         if (--$this->_lock_count <= 0 || $force) {
1016             $this->_unlock_tables();
1017             $this->_lock_count = 0;
1018         }
1019     }
1020
1021     /**
1022      * Actually unlock the required tables.
1023      */
1024     function _unlock_tables($write_lock) {
1025         trigger_error("virtual", E_USER_ERROR);
1026     }
1027
1028
1029     /**
1030      * Serialize data
1031      */
1032     function _serialize($data) {
1033         if (empty($data))
1034             return '';
1035         assert(is_array($data));
1036         return serialize($data);
1037     }
1038
1039     /**
1040      * Unserialize data
1041      */
1042     function _unserialize($data) {
1043         return empty($data) ? array() : unserialize($data);
1044     }
1045     
1046     /**
1047      * Callback for PEAR (DB) errors.
1048      *
1049      * @access protected
1050      *
1051      * @param A PEAR_error object.
1052      */
1053     function _pear_error_callback($error) {
1054         if ($this->_is_false_error($error))
1055             return;
1056         
1057         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
1058         $this->close();
1059         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
1060     }
1061
1062     /**
1063      * Detect false errors messages from PEAR DB.
1064      *
1065      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
1066      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
1067      * return any data.  (So when a "LOCK" command doesn't return any data,
1068      * DB reports it as an error, when in fact, it's not.)
1069      *
1070      * @access private
1071      * @return bool True iff error is not really an error.
1072      */
1073     function _is_false_error($error) {
1074         if ($error->getCode() != DB_ERROR)
1075             return false;
1076
1077         $query = $this->_dbh->last_query;
1078
1079         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
1080                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
1081             // Last query was not of the sort which doesn't return any data.
1082             //" <--kludge for brain-dead syntax coloring
1083             return false;
1084         }
1085         
1086         if (! in_array('ismanip', get_class_methods('DB'))) {
1087             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
1088             // does not have the DB::isManip method.
1089             return true;
1090         }
1091         
1092         if (DB::isManip($query)) {
1093             // If Pear thinks it's an isManip then it wouldn't have thrown
1094             // the error we're testing for....
1095             return false;
1096         }
1097
1098         return true;
1099     }
1100
1101     function _pear_error_message($error) {
1102         $class = get_class($this);
1103         $message = "$class: fatal database error\n"
1104              . "\t" . $error->getMessage() . "\n"
1105              . "\t(" . $error->getDebugInfo() . ")\n";
1106
1107         // Prevent password from being exposed during a connection error
1108         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
1109                                  '\\1:XXXXXXXX', $this->_dsn);
1110         return str_replace($this->_dsn, $safe_dsn, $message);
1111     }
1112
1113     /**
1114      * Filter PHP errors notices from PEAR DB code.
1115      *
1116      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
1117      * errors and notices.  This is an error callback (for use with
1118      * ErrorManager which will filter out those spurious messages.)
1119      * @see _is_false_error, ErrorManager
1120      * @access private
1121      */
1122     function _pear_notice_filter($err) {
1123         return ( $err->isNotice()
1124                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
1125                  && $err->errline == 126
1126                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
1127     }
1128
1129     /* some variables and functions for DB backend abstraction (action=upgrade) */
1130     function database () {
1131         return $this->_dbh->dsn['database'];
1132     }
1133     function backendType() {
1134         return $this->_dbh->phptype;
1135     }
1136     function connection() {
1137         return $this->_dbh->connection;
1138     }
1139     function getRow($query) {
1140         return $this->_dbh->getRow($query);
1141     }
1142
1143     function listOfTables() {
1144         return $this->_dbh->getListOf('tables');
1145     }
1146     function listOfFields($database,$table) {
1147         if ($this->backendType() == 'mysql') {
1148             $fields = array();
1149             assert(!empty($database));
1150             assert(!empty($table));
1151             $result = mysql_list_fields($database, $table, $this->_dbh->connection) or 
1152                 trigger_error(__FILE__.':'.__LINE__.' '.mysql_error(), E_USER_WARNING);
1153             if (!$result) return array();
1154               $columns = mysql_num_fields($result);
1155             for ($i = 0; $i < $columns; $i++) {
1156                 $fields[] = mysql_field_name($result, $i);
1157             }
1158             mysql_free_result($result);
1159             return $fields;
1160         } else {
1161             // TODO: try ADODB version?
1162             trigger_error("Unsupported dbtype and backend. Either switch to ADODB or check it manually.");
1163             return false;
1164         }
1165     }
1166 };
1167
1168 /**
1169  * This class is a generic iterator.
1170  *
1171  * WikiDB_backend_PearDB_iter only iterates over things that have
1172  * 'pagename', 'pagedata', etc. etc.
1173  *
1174  * Probably WikiDB_backend_PearDB_iter and this class should be merged
1175  * (most of the code is cut-and-paste :-( ), but I am trying to make
1176  * changes that could be merged easily.
1177  *
1178  * @author: Dan Frankowski
1179  */
1180 class WikiDB_backend_PearDB_generic_iter
1181 extends WikiDB_backend_iterator
1182 {
1183     function WikiDB_backend_PearDB_generic_iter($backend, $query_result, $field_list = NULL) {
1184         if (DB::isError($query_result)) {
1185             // This shouldn't happen, I thought.
1186             $backend->_pear_error_callback($query_result);
1187         }
1188         
1189         $this->_backend = &$backend;
1190         $this->_result = $query_result;
1191     }
1192
1193     function count() {
1194         if (!$this->_result)
1195             return false;
1196         return $this->_result->numRows();
1197     }
1198     
1199     function next() {
1200         if (!$this->_result)
1201             return false;
1202
1203         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1204         if (!$record) {
1205             $this->free();
1206             return false;
1207         }
1208         
1209         return $record;
1210     }
1211
1212     function reset () {
1213         if ($this->_result) {
1214             $this->_result->MoveFirst();
1215         }
1216     }
1217
1218     function free () {
1219         if ($this->_result) {
1220             $this->_result->free();
1221             $this->_result = false;
1222         }
1223     }
1224
1225     function asArray () {
1226         $result = array();
1227         while ($page = $this->next())
1228             $result[] = $page;
1229         return $result;
1230     }
1231 }
1232
1233 class WikiDB_backend_PearDB_iter
1234 extends WikiDB_backend_PearDB_generic_iter
1235 {
1236
1237     function next() {
1238         $backend = &$this->_backend;
1239         if (!$this->_result)
1240             return false;
1241
1242         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
1243         if (!$record) {
1244             $this->free();
1245             return false;
1246         }
1247         
1248         $pagedata = $backend->_extract_page_data($record);
1249         $rec = array('pagename' => $record['pagename'],
1250                      'pagedata' => $pagedata);
1251
1252         if (!empty($record['version'])) {
1253             $rec['versiondata'] = $backend->_extract_version_data($record);
1254             $rec['version'] = $record['version'];
1255         }
1256         
1257         return $rec;
1258     }
1259 }
1260
1261 class WikiDB_backend_PearDB_search extends WikiDB_backend_search_sql 
1262 {
1263     // no surrounding quotes because we know it's a string
1264     // function _quote($word) { return $this->_dbh->addq($word); }
1265 }
1266
1267 // (c-file-style: "gnu")
1268 // Local Variables:
1269 // mode: php
1270 // tab-width: 8
1271 // c-basic-offset: 4
1272 // c-hanging-comment-ender-p: nil
1273 // indent-tabs-mode: nil
1274 // End:   
1275 ?>