]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/PearDB.php
* changed stored pref representation as before.
[SourceForge/phpwiki.git] / lib / WikiDB / backend / PearDB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: PearDB.php,v 1.35 2004-01-26 09:17:51 rurban Exp $');
3
4 require_once('lib/WikiDB/backend.php');
5 //require_once('lib/FileFinder.php');
6 require_once('lib/ErrorManager.php');
7 require_once('lib/pear/DB.php'); // Always favor use our local pear copy
8
9 class WikiDB_backend_PearDB
10 extends WikiDB_backend
11 {
12     var $_dbh;
13
14     function WikiDB_backend_PearDB ($dbparams) {
15         // Find and include PEAR's DB.php.
16         //$pearFinder = new PearFileFinder;
17         //$pearFinder->includeOnce('DB.php');
18
19         // Install filter to handle bogus error notices from buggy DB.php's.
20         global $ErrorManager;
21         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
22         
23         // Open connection to database
24         $this->_dsn = $dbparams['dsn'];
25         $dboptions = array('persistent' => true,
26                            'debug' => 2);
27         $this->_dbh = DB::connect($this->_dsn, $dboptions);
28         $dbh = &$this->_dbh;
29         if (DB::isError($dbh)) {
30             trigger_error(sprintf("Can't connect to database: %s",
31                                   $this->_pear_error_message($dbh)),
32                           E_USER_ERROR);
33         }
34         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
35                                array(&$this, '_pear_error_callback'));
36         $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
37
38         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
39
40         $this->_table_names
41             = array('page_tbl'     => $prefix . 'page',
42                     'version_tbl'  => $prefix . 'version',
43                     'link_tbl'     => $prefix . 'link',
44                     'recent_tbl'   => $prefix . 'recent',
45                     'nonempty_tbl' => $prefix . 'nonempty');
46
47         $this->_expressions
48             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
49                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
50                     'maxversion'   => "MAX(version)");
51         
52         $this->_lock_count = 0;
53     }
54     
55     /**
56      * Close database connection.
57      */
58     function close () {
59         if (!$this->_dbh)
60             return;
61         if ($this->_lock_count) {
62             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
63                           E_USER_WARNING);
64         }
65         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
66         $this->unlock('force');
67
68         $this->_dbh->disconnect();
69     }
70
71
72     /*
73      * Test fast wikipage.
74      */
75     function is_wiki_page($pagename) {
76         $dbh = &$this->_dbh;
77         extract($this->_table_names);
78         return $dbh->getOne(sprintf("SELECT $page_tbl.id"
79                                     . " FROM $nonempty_tbl, $page_tbl"
80                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
81                                     . "   AND pagename='%s'",
82                                     $dbh->quoteString($pagename)));
83     }
84         
85     function get_all_pagenames() {
86         $dbh = &$this->_dbh;
87         extract($this->_table_names);
88         return $dbh->getCol("SELECT pagename"
89                             . " FROM $nonempty_tbl, $page_tbl"
90                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
91     }
92             
93     /**
94      * Read page information from database.
95      */
96     function get_pagedata($pagename) {
97         $dbh = &$this->_dbh;
98         $page_tbl = $this->_table_names['page_tbl'];
99
100         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
101
102         $result = $dbh->getRow(sprintf("SELECT * FROM $page_tbl WHERE pagename='%s'",
103                                        $dbh->quoteString($pagename)),
104                                DB_FETCHMODE_ASSOC);
105         if (!$result)
106             return false;
107         return $this->_extract_page_data($result);
108     }
109
110     function  _extract_page_data(&$query_result) {
111         extract($query_result);
112         $data = $this->_unserialize($pagedata);
113         $data['hits'] = $hits;
114         return $data;
115     }
116
117     function update_pagedata($pagename, $newdata) {
118         $dbh = &$this->_dbh;
119         $page_tbl = $this->_table_names['page_tbl'];
120
121         // Hits is the only thing we can update in a fast manner.
122         if (count($newdata) == 1 && isset($newdata['hits'])) {
123             // Note that this will fail silently if the page does not
124             // have a record in the page table.  Since it's just the
125             // hit count, who cares?
126             $dbh->query(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename='%s'",
127                                 $newdata['hits'], $dbh->quoteString($pagename)));
128             return;
129         }
130
131         $this->lock();
132         $data = $this->get_pagedata($pagename);
133         if (!$data) {
134             $data = array();
135             $this->_get_pageid($pagename, true); // Creates page record
136         }
137         
138         @$hits = (int)$data['hits'];
139         unset($data['hits']);
140
141         foreach ($newdata as $key => $val) {
142             if ($key == 'hits')
143                 $hits = (int)$val;
144             else if (empty($val))
145                 unset($data[$key]);
146             else
147                 $data[$key] = $val;
148         }
149
150         $dbh->query(sprintf("UPDATE $page_tbl"
151                             . " SET hits=%d, pagedata='%s'"
152                             . " WHERE pagename='%s'",
153                             $hits,
154                             $dbh->quoteString($this->_serialize($data)),
155                             $dbh->quoteString($pagename)));
156
157         $this->unlock();
158     }
159
160     function _get_pageid($pagename, $create_if_missing = false) {
161         
162         $dbh = &$this->_dbh;
163         $page_tbl = $this->_table_names['page_tbl'];
164         
165         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename='%s'",
166                          $dbh->quoteString($pagename));
167
168         if (!$create_if_missing)
169             return $dbh->getOne($query);
170
171         $this->lock();
172         $id = $dbh->getOne($query);
173         if (empty($id)) {
174             $max_id = $dbh->getOne("SELECT MAX(id) FROM $page_tbl");
175             $id = $max_id + 1;
176             $dbh->query(sprintf("INSERT INTO $page_tbl"
177                                 . " (id,pagename,hits)"
178                                 . " VALUES (%d,'%s',0)",
179                                 $id, $dbh->quoteString($pagename)));
180         }
181         $this->unlock();
182         return $id;
183     }
184
185     function get_latest_version($pagename) {
186         $dbh = &$this->_dbh;
187         extract($this->_table_names);
188         return
189             (int)$dbh->getOne(sprintf("SELECT latestversion"
190                                       . " FROM $page_tbl, $recent_tbl"
191                                       . " WHERE $page_tbl.id=$recent_tbl.id"
192                                       . "  AND pagename='%s'",
193                                       $dbh->quoteString($pagename)));
194     }
195
196     function get_previous_version($pagename, $version) {
197         $dbh = &$this->_dbh;
198         extract($this->_table_names);
199         
200         return
201             (int)$dbh->getOne(sprintf("SELECT version"
202                                       . " FROM $version_tbl, $page_tbl"
203                                       . " WHERE $version_tbl.id=$page_tbl.id"
204                                       . "  AND pagename='%s'"
205                                       . "  AND version < %d"
206                                       . " ORDER BY version DESC"
207                                       . " LIMIT 1",
208                                       $dbh->quoteString($pagename),
209                                       $version));
210     }
211     
212     /**
213      * Get version data.
214      *
215      * @param $version int Which version to get.
216      *
217      * @return hash The version data, or false if specified version does not
218      *              exist.
219      */
220     function get_versiondata($pagename, $version, $want_content = false) {
221         $dbh = &$this->_dbh;
222         extract($this->_table_names);
223                 
224         assert(!empty($pagename));
225         assert($version > 0);
226         
227         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
228         // FIXME: optimization: sometimes don't get page data?
229
230         if ($want_content) {
231             $fields = "*";
232         }
233         else {
234             $fields = ("$page_tbl.*,"
235                        . "mtime,minor_edit,versiondata,"
236                        . "content<>'' AS have_content");
237         }
238
239         $result = $dbh->getRow(sprintf("SELECT $fields"
240                                        . " FROM $page_tbl, $version_tbl"
241                                        . " WHERE $page_tbl.id=$version_tbl.id"
242                                        . "  AND pagename='%s'"
243                                        . "  AND version=%d",
244                                        $dbh->quoteString($pagename), $version),
245                                DB_FETCHMODE_ASSOC);
246
247         return $this->_extract_version_data($result);
248     }
249
250     function _extract_version_data(&$query_result) {
251         if (!$query_result)
252             return false;
253
254         extract($query_result);
255         $data = $this->_unserialize($versiondata);
256         
257         $data['mtime'] = $mtime;
258         $data['is_minor_edit'] = !empty($minor_edit);
259         
260         if (isset($content))
261             $data['%content'] = $content;
262         elseif ($have_content)
263             $data['%content'] = true;
264         else
265             $data['%content'] = '';
266
267         // FIXME: this is ugly.
268         if (isset($pagename)) {
269             // Query also includes page data.
270             // We might as well send that back too...
271             $data['%pagedata'] = $this->_extract_page_data($query_result);
272         }
273
274         return $data;
275     }
276
277
278     /**
279      * Create a new revision of a page.
280      */
281     function set_versiondata($pagename, $version, $data) {
282         $dbh = &$this->_dbh;
283         $version_tbl = $this->_table_names['version_tbl'];
284         
285         $minor_edit = (int) !empty($data['is_minor_edit']);
286         unset($data['is_minor_edit']);
287         
288         $mtime = (int)$data['mtime'];
289         unset($data['mtime']);
290         assert(!empty($mtime));
291
292         @$content = (string) $data['%content'];
293         unset($data['%content']);
294
295         unset($data['%pagedata']);
296         
297         $this->lock();
298         $id = $this->_get_pageid($pagename, true);
299
300         // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
301         $dbh->query(sprintf("DELETE FROM $version_tbl"
302                             . " WHERE id=%d AND version=%d",
303                             $id, $version));
304
305         $dbh->query(sprintf("INSERT INTO $version_tbl"
306                             . " (id,version,mtime,minor_edit,content,versiondata)"
307                             . " VALUES(%d,%d,%d,%d,'%s','%s')",
308                             $id, $version, $mtime, $minor_edit,
309                             $dbh->quoteString($content),
310                             $dbh->quoteString($this->_serialize($data))));
311
312         $this->_update_recent_table($id);
313         $this->_update_nonempty_table($id);
314         
315         $this->unlock();
316     }
317     
318     /**
319      * Delete an old revision of a page.
320      */
321     function delete_versiondata($pagename, $version) {
322         $dbh = &$this->_dbh;
323         extract($this->_table_names);
324
325         $this->lock();
326         if ( ($id = $this->_get_pageid($pagename)) ) {
327             $dbh->query("DELETE FROM $version_tbl"
328                         . " WHERE id=$id AND version=$version");
329             $this->_update_recent_table($id);
330             // This shouldn't be needed (as long as the latestversion
331             // never gets deleted.)  But, let's be safe.
332             $this->_update_nonempty_table($id);
333         }
334         $this->unlock();
335     }
336
337     /**
338      * Delete page from the database.
339      */
340     function delete_page($pagename) {
341         $dbh = &$this->_dbh;
342         extract($this->_table_names);
343         
344         $this->lock();
345         if ( ($id = $this->_get_pageid($pagename, false)) ) {
346             $dbh->query("DELETE FROM $version_tbl  WHERE id=$id");
347             $dbh->query("DELETE FROM $recent_tbl   WHERE id=$id");
348             $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
349             $dbh->query("DELETE FROM $link_tbl     WHERE linkfrom=$id");
350             $nlinks = $dbh->getOne("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
351             if ($nlinks) {
352                 // We're still in the link table (dangling link) so we can't delete this
353                 // altogether.
354                 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
355             }
356             else {
357                 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
358             }
359             $this->_update_recent_table();
360             $this->_update_nonempty_table();
361         }
362         $this->unlock();
363     }
364             
365
366     // The only thing we might be interested in updating which we can
367     // do fast in the flags (minor_edit).   I think the default
368     // update_versiondata will work fine...
369     //function update_versiondata($pagename, $version, $data) {
370     //}
371
372     function set_links($pagename, $links) {
373         // Update link table.
374         // FIXME: optimize: mysql can do this all in one big INSERT.
375
376         $dbh = &$this->_dbh;
377         extract($this->_table_names);
378
379         $this->lock();
380         $pageid = $this->_get_pageid($pagename, true);
381
382         $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
383
384         if ($links) {
385             foreach($links as $link) {
386                 if (isset($linkseen[$link]))
387                     continue;
388                 $linkseen[$link] = true;
389                 $linkid = $this->_get_pageid($link, true);
390                 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
391                             . " VALUES ($pageid, $linkid)");
392             }
393         }
394         $this->unlock();
395     }
396     
397     /**
398      * Find pages which link to or are linked from a page.
399      */
400     function get_links($pagename, $reversed = true) {
401         $dbh = &$this->_dbh;
402         extract($this->_table_names);
403
404         if ($reversed)
405             list($have,$want) = array('linkee', 'linker');
406         else
407             list($have,$want) = array('linker', 'linkee');
408
409         
410         $qpagename = $dbh->quoteString($pagename);
411         
412         $result = $dbh->query("SELECT $want.*"
413                               . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
414                               . " WHERE linkfrom=linker.id AND linkto=linkee.id"
415                               . "  AND $have.pagename='$qpagename'"
416                               //. " GROUP BY $want.id"
417                               . " ORDER BY $want.pagename");
418         
419         return new WikiDB_backend_PearDB_iter($this, $result);
420     }
421
422     function get_all_pages($include_deleted=false,$orderby='pagename') {
423         $dbh = &$this->_dbh;
424         extract($this->_table_names);
425
426         if (substr($orderby,0,5) == 'mtime') {
427             //$orderby = $version_tbl . '.' . $orderby;
428             if ($include_deleted) {
429                 $result = $dbh->query("SELECT * FROM $page_tbl, $recent_tbl, $version_tbl"
430                                       . " WHERE $page_tbl.id=$recent_tbl.id"
431                                       . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
432                                       . " ORDER BY $orderby");
433             }
434             else {
435                 $result = $dbh->query("SELECT $page_tbl.*"
436                                       . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
437                                       . " WHERE $nonempty_tbl.id=$page_tbl.id"
438                                       . " AND $page_tbl.id=$recent_tbl.id"
439                                       . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
440                                       . " ORDER BY $orderby");
441             }
442         } else {
443             if ($include_deleted) {
444                 $result = $dbh->query("SELECT * FROM $page_tbl ORDER BY $orderby");
445             }
446             else {
447                 $result = $dbh->query("SELECT $page_tbl.*"
448                                       . " FROM $nonempty_tbl, $page_tbl"
449                                       . " WHERE $nonempty_tbl.id=$page_tbl.id"
450                                       . " ORDER BY $orderby");
451             }
452         }
453         return new WikiDB_backend_PearDB_iter($this, $result);
454     }
455         
456     /**
457      * Title search.
458      */
459     function text_search($search = '', $fullsearch = false) {
460         $dbh = &$this->_dbh;
461         extract($this->_table_names);
462         
463         $table = "$nonempty_tbl, $page_tbl";
464         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
465         $fields = "$page_tbl.*";
466         $callback = new WikiMethodCb($this, '_sql_match_clause');
467         
468         if ($fullsearch) {
469             $table .= ", $recent_tbl";
470             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
471
472             $table .= ", $version_tbl";
473             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
474
475             $fields .= ",$version_tbl.*";
476             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
477         }
478         
479         $search_clause = $search->makeSqlClause($callback);
480         
481         $result = $dbh->query("SELECT $fields FROM $table"
482                               . " WHERE $join_clause"
483                               . "  AND ($search_clause)"
484                               . " ORDER BY pagename");
485         
486         return new WikiDB_backend_PearDB_iter($this, $result);
487     }
488
489     function _sql_match_clause($word) {
490         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
491         $word = $this->_dbh->quoteString($word);
492         return "LOWER(pagename) LIKE '%$word%'";
493     }
494
495     function _fullsearch_sql_match_clause($word) {
496         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
497         $word = $this->_dbh->quoteString($word);
498         return "LOWER(pagename) LIKE '%$word%' OR content LIKE '%$word%'";
499     }
500
501     /**
502      * Find highest hit counts.
503      */
504     function most_popular($limit) {
505         $dbh = &$this->_dbh;
506         extract($this->_table_names);
507         $order = "DESC";
508         if ($limit < 0){ 
509             $order = "ASC";
510             $limit = -$limit;
511         }
512         $limitclause = $limit ? " LIMIT $limit" : '';
513         $result = $dbh->query("SELECT $page_tbl.*"
514                               . " FROM $nonempty_tbl, $page_tbl"
515                               . " WHERE $nonempty_tbl.id=$page_tbl.id"
516                               . " ORDER BY hits $order"
517                               . " $limitclause");
518
519         return new WikiDB_backend_PearDB_iter($this, $result);
520     }
521
522     /**
523      * Find recent changes.
524      */
525     function most_recent($params) {
526         $limit = 0;
527         $since = 0;
528         $include_minor_revisions = false;
529         $exclude_major_revisions = false;
530         $include_all_revisions = false;
531         extract($params);
532
533         $dbh = &$this->_dbh;
534         extract($this->_table_names);
535
536         $pick = array();
537         if ($since)
538             $pick[] = "mtime >= $since";
539                         
540         
541         if ($include_all_revisions) {
542             // Include all revisions of each page.
543             $table = "$page_tbl, $version_tbl";
544             $join_clause = "$page_tbl.id=$version_tbl.id";
545
546             if ($exclude_major_revisions) {
547                 // Include only minor revisions
548                 $pick[] = "minor_edit <> 0";
549             }
550             elseif (!$include_minor_revisions) {
551                 // Include only major revisions
552                 $pick[] = "minor_edit = 0";
553             }
554         }
555         else {
556             $table = "$page_tbl, $recent_tbl";
557             $join_clause = "$page_tbl.id=$recent_tbl.id";
558             $table .= ", $version_tbl";
559             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
560                 
561             if ($exclude_major_revisions) {
562                 // Include only most recent minor revision
563                 $pick[] = 'version=latestminor';
564             }
565             elseif (!$include_minor_revisions) {
566                 // Include only most recent major revision
567                 $pick[] = 'version=latestmajor';
568             }
569             else {
570                 // Include only the latest revision (whether major or minor).
571                 $pick[] ='version=latestversion';
572             }
573         }
574         $order = "DESC";
575         if($limit < 0){
576             $order = "ASC";
577             $limit = -$limit;
578         }
579         $limitclause = $limit ? " LIMIT $limit" : '';
580         $where_clause = $join_clause;
581         if ($pick)
582             $where_clause .= " AND " . join(" AND ", $pick);
583
584         // FIXME: use SQL_BUFFER_RESULT for mysql?
585         $result = $dbh->query("SELECT $page_tbl.*,$version_tbl.*"
586                               . " FROM $table"
587                               . " WHERE $where_clause"
588                               . " ORDER BY mtime $order"
589                               . $limitclause);
590
591         return new WikiDB_backend_PearDB_iter($this, $result);
592     }
593
594     function _update_recent_table($pageid = false) {
595         $dbh = &$this->_dbh;
596         extract($this->_table_names);
597         extract($this->_expressions);
598
599         $pageid = (int)$pageid;
600
601         $this->lock();
602
603         $dbh->query("DELETE FROM $recent_tbl"
604                     . ( $pageid ? " WHERE id=$pageid" : ""));
605         
606         $dbh->query( "INSERT INTO $recent_tbl"
607                      . " (id, latestversion, latestmajor, latestminor)"
608                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
609                      . " FROM $version_tbl"
610                      . ( $pageid ? " WHERE id=$pageid" : "")
611                      . " GROUP BY id" );
612         $this->unlock();
613     }
614
615     function _update_nonempty_table($pageid = false) {
616         $dbh = &$this->_dbh;
617         extract($this->_table_names);
618
619         $pageid = (int)$pageid;
620
621         $this->lock();
622
623         $dbh->query("DELETE FROM $nonempty_tbl"
624                     . ( $pageid ? " WHERE id=$pageid" : ""));
625
626         $dbh->query("INSERT INTO $nonempty_tbl (id)"
627                     . " SELECT $recent_tbl.id"
628                     . " FROM $recent_tbl, $version_tbl"
629                     . " WHERE $recent_tbl.id=$version_tbl.id"
630                     . "       AND version=latestversion"
631                     . "  AND content<>''"
632                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
633
634         $this->unlock();
635     }
636
637
638     /**
639      * Grab a write lock on the tables in the SQL database.
640      *
641      * Calls can be nested.  The tables won't be unlocked until
642      * _unlock_database() is called as many times as _lock_database().
643      *
644      * @access protected
645      */
646     function lock($write_lock = true) {
647         if ($this->_lock_count++ == 0)
648             $this->_lock_tables($write_lock);
649     }
650
651     /**
652      * Actually lock the required tables.
653      */
654     function _lock_tables($write_lock) {
655         trigger_error("virtual", E_USER_ERROR);
656     }
657     
658     /**
659      * Release a write lock on the tables in the SQL database.
660      *
661      * @access protected
662      *
663      * @param $force boolean Unlock even if not every call to lock() has been matched
664      * by a call to unlock().
665      *
666      * @see _lock_database
667      */
668     function unlock($force = false) {
669         if ($this->_lock_count == 0)
670             return;
671         if (--$this->_lock_count <= 0 || $force) {
672             $this->_unlock_tables();
673             $this->_lock_count = 0;
674         }
675     }
676
677     /**
678      * Actually unlock the required tables.
679      */
680     function _unlock_tables($write_lock) {
681         trigger_error("virtual", E_USER_ERROR);
682     }
683
684
685     /**
686      * Serialize data
687      */
688     function _serialize($data) {
689         if (empty($data))
690             return '';
691         assert(is_array($data));
692         return serialize($data);
693     }
694
695     /**
696      * Unserialize data
697      */
698     function _unserialize($data) {
699         return empty($data) ? array() : unserialize($data);
700     }
701     
702     /**
703      * Callback for PEAR (DB) errors.
704      *
705      * @access protected
706      *
707      * @param A PEAR_error object.
708      */
709     function _pear_error_callback($error) {
710         if ($this->_is_false_error($error))
711             return;
712         
713         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
714         $this->close();
715         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
716     }
717
718     /**
719      * Detect false errors messages from PEAR DB.
720      *
721      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
722      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
723      * return any data.  (So when a "LOCK" command doesn't return any data,
724      * DB reports it as an error, when in fact, it's not.)
725      *
726      * @access private
727      * @return bool True iff error is not really an error.
728      */
729     function _is_false_error($error) {
730         if ($error->getCode() != DB_ERROR)
731             return false;
732
733         $query = $this->_dbh->last_query;
734
735         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
736                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
737             // Last query was not of the sort which doesn't return any data.
738             //" <--kludge for brain-dead syntax coloring
739             return false;
740         }
741         
742         if (! in_array('ismanip', get_class_methods('DB'))) {
743             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
744             // does not have the DB::isManip method.
745             return true;
746         }
747         
748         if (DB::isManip($query)) {
749             // If Pear thinks it's an isManip then it wouldn't have thrown
750             // the error we're testing for....
751             return false;
752         }
753
754         return true;
755     }
756
757     function _pear_error_message($error) {
758         $class = get_class($this);
759         $message = "$class: fatal database error\n"
760              . "\t" . $error->getMessage() . "\n"
761              . "\t(" . $error->getDebugInfo() . ")\n";
762
763         // Prevent password from being exposed during a connection error
764         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
765                                  '\\1:XXXXXXXX', $this->_dsn);
766         return str_replace($this->_dsn, $safe_dsn, $message);
767     }
768
769     /**
770      * Filter PHP errors notices from PEAR DB code.
771      *
772      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
773      * errors and notices.  This is an error callback (for use with
774      * ErrorManager which will filter out those spurious messages.)
775      * @see _is_false_error, ErrorManager
776      * @access private
777      */
778     function _pear_notice_filter($err) {
779         return ( $err->isNotice()
780                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
781                  && $err->errline == 126
782                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
783     }
784 };
785
786 class WikiDB_backend_PearDB_iter
787 extends WikiDB_backend_iterator
788 {
789     function WikiDB_backend_PearDB_iter(&$backend, &$query_result) {
790         if (DB::isError($query_result)) {
791             // This shouldn't happen, I thought.
792             $backend->_pear_error_callback($query_result);
793         }
794         
795         $this->_backend = &$backend;
796         $this->_result = $query_result;
797     }
798     
799     function next() {
800         $backend = &$this->_backend;
801         if (!$this->_result)
802             return false;
803
804         $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
805         if (!$record) {
806             $this->free();
807             return false;
808         }
809         
810         $pagedata = $backend->_extract_page_data($record);
811         $rec = array('pagename' => $record['pagename'],
812                      'pagedata' => $pagedata);
813
814         if (!empty($record['version'])) {
815             $rec['versiondata'] = $backend->_extract_version_data($record);
816             $rec['version'] = $record['version'];
817         }
818         
819         return $rec;
820     }
821
822     function free () {
823         if ($this->_result) {
824             $this->_result->free();
825             $this->_result = false;
826         }
827     }
828 }
829
830 // (c-file-style: "gnu")
831 // Local Variables:
832 // mode: php
833 // tab-width: 8
834 // c-basic-offset: 4
835 // c-hanging-comment-ender-p: nil
836 // indent-tabs-mode: nil
837 // End:   
838 ?>