]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
A fix the text searches.
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.3 2002-02-03 01:59:54 dairiki Exp $');
3
4 /*This file is part of PhpWiki.
5
6 PhpWiki is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 PhpWiki is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with PhpWiki; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 */ 
21 //  Based on PearDB.php
22 //
23 //  Comments:
24 //  1)  ADODB's GetRow() is slightly different from that in PEAR.  It does not accept a fetchmode parameter
25 //      That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
26 //  
27 //  2)  No need for ''s arond strings in sprintf arguments - qstr puts them there automatically
28 //  
29 //  3)  ADODB has a version of GetOne, but it is difficult to use it when FETCH_ASSOC is in effect.
30 //      Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
31 //  4)  No error handling yet - could use ADOConnection->raiseErrorFn
32
33 //require_once('DB.php');
34 require_once('lib/WikiDB/backend.php');
35 //require_once('lib/FileFinder.php');
36 //require_once('lib/ErrorManager.php');
37 // Error handling - calls trigger_error.  NB - does not close the connection.  Does it need to?
38 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
39 // include the main adodb file
40 require_once('lib/WikiDB/adodb/adodb.inc.php');
41
42 class WikiDB_backend_ADODB
43 extends WikiDB_backend
44 {
45     function WikiDB_backend_ADODB ($dbparams) {
46         // Find and include PEAR's DB.php.
47         //$pearFinder = new PearFileFinder;
48         //$pearFinder->includeOnce('DB.php');
49
50         // Install filter to handle bogus error notices from buggy DB.php's.
51 //        global $ErrorManager;
52 //        $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
53         
54         // Open connection to database
55 //        $this->_dsn = $dbparams['dsn'];
56      /*   $dboptions = array('persistent' => true,
57                            'debug' => 2);
58         $this->_dbh = DB::connect($this->_dsn, $dboptions);
59         $dbh = &$this->_dbh;
60         if (DB::isError($dbh)) {
61             trigger_error(sprintf("Can't connect to database: %s",
62                                   $this->_pear_error_message($dbh)),
63                           E_USER_ERROR);
64         }
65         $dbh->setErrorHandling(PEAR_ERROR_CALLBACK,
66                                array($this, '_pear_error_callback'));
67         $dbh->setFetchMode(ADODB_FETCH_ASSOC);
68 */
69                 $parsed = parseDSN($dbparams['dsn']);
70         $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
71                 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'], 
72                                         $parsed['password'], $parsed['database']);
73
74 //  Error handling not needed here -all dealt with by adodb-errorhandler.inc.php                
75 /*              if ($conn === false)  {
76                         trigger_error(sprintf("Can't connect to database: %s",
77                                   $this->_pear_error_message($conn)),
78                           E_USER_ERROR);}
79 */
80
81
82 //  Uncomment the following line to enable debugging output (not very pretty!)          
83 //              $this->_dbh->debug = true;
84                 
85                 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
86
87 //  The next line should speed up queries if enabled, but:
88 //  1)  It only works with PHP >= 4.0.6; and
89 //  2)  At the moment, I haven't figured out why thw wrong results are returned'
90 //              $GLOBALS['ADODB_COUNTRECS'] = false;
91
92         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
93
94         $this->_table_names
95             = array('page_tbl'     => $prefix . 'page',
96                     'version_tbl'  => $prefix . 'version',
97                     'link_tbl'     => $prefix . 'link',
98                     'recent_tbl'   => $prefix . 'recent',
99                     'nonempty_tbl' => $prefix . 'nonempty');
100
101         $this->_expressions
102             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
103                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
104                     'maxversion'   => "MAX(version)");
105         
106         $this->_lock_count = 0;
107     }
108     
109     /**
110      * Close database connection.
111      */
112     function close () {
113         if (!$this->_dbh)
114             return;
115         if ($this->_lock_count) {
116             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
117                           E_USER_WARNING);
118         }
119 //        $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);      // prevent recursive loops.
120         $this->unlock('force');
121
122         $this->_dbh->close();
123         $this->_dbh = false;
124     }
125
126
127     /*
128      * Test fast wikipage.
129      */
130     function is_wiki_page($pagename) {
131         $dbh = &$this->_dbh;
132         extract($this->_table_names);
133         $rs = $dbh->Execute(sprintf("SELECT $page_tbl.id AS id"
134                                     . " FROM $nonempty_tbl, $page_tbl"
135                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
136                                     . "   AND pagename=%s",
137                                     $dbh->qstr($pagename)));
138                 if (!$rs->EOF)
139                 {
140                         $result = $rs->fields["id"];
141                         $rs->Close();
142                         return $result;
143                 }
144                 else 
145                 {
146                         $rs->Close();
147                         return false;
148         }
149         }
150         
151     function get_all_pagenames() {
152         $dbh = &$this->_dbh;
153         extract($this->_table_names);
154       //return $dbh->getCol("SELECT pagename"
155       //                    . " FROM $nonempty_tbl, $page_tbl"
156       //                    . " WHERE $nonempty_tbl.id=$page_tbl.id");
157           
158
159 //Original code (above) return the column in an indexed array - 0 based
160 //So, hopefully, does this
161             $result = $dbh->Execute("SELECT pagename"
162                             . " FROM $nonempty_tbl, $page_tbl"
163                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
164             return $result->GetArray();
165     }
166             
167     /**
168      * Read page information from database.
169      */
170     function get_pagedata($pagename) {
171         $dbh = &$this->_dbh;
172         $page_tbl = $this->_table_names['page_tbl'];
173
174         //trigger_error("GET_PAGEDATA $pagename", E_USER_NOTICE);
175
176         $result = $dbh->GetRow(sprintf("SELECT * FROM $page_tbl WHERE pagename=%s",
177                                        $dbh->qstr($pagename)));
178         if (!$result)
179             return false;
180         return $this->_extract_page_data($result);
181     }
182
183     function  _extract_page_data(&$query_result) {
184         extract($query_result);
185         $data = empty($pagedata) ? array() : unserialize($pagedata);
186         $data['hits'] = $hits;
187         return $data;
188     }
189
190     function update_pagedata($pagename, $newdata) {
191         $dbh = &$this->_dbh;
192         $page_tbl = $this->_table_names['page_tbl'];
193
194         // Hits is the only thing we can update in a fast manner.
195         if (count($newdata) == 1 && isset($newdata['hits'])) {
196             // Note that this will fail silently if the page does not
197             // have a record in the page table.  Since it's just the
198             // hit count, who cares?
199             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
200                                 $newdata['hits'], $dbh->qstr($pagename)));
201             return;
202         }
203
204         $this->lock();
205         $data = $this->get_pagedata($pagename);
206         if (!$data) {
207             $data = array();
208             $this->_get_pageid($pagename, true); // Creates page record
209         }
210         
211         @$hits = (int)$data['hits'];
212         unset($data['hits']);
213
214         foreach ($newdata as $key => $val) {
215             if ($key == 'hits')
216                 $hits = (int)$val;
217             else if (empty($val))
218                 unset($data[$key]);
219             else
220                 $data[$key] = $val;
221         }
222
223         $dbh->Execute(sprintf("UPDATE $page_tbl"
224                             . " SET hits=%d, pagedata=%s"
225                             . " WHERE pagename=%s",
226                             $hits,
227                             $dbh->qstr(serialize($data)),
228                             $dbh->qstr($pagename)));
229
230         $this->unlock();
231     }
232
233     function _get_pageid($pagename, $create_if_missing = false) {
234         
235         $dbh = &$this->_dbh;
236         $page_tbl = $this->_table_names['page_tbl'];
237         
238         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
239                          $dbh->qstr($pagename));
240
241         if (!$create_if_missing)
242             {
243                                 $rs = $dbh->Execute($query);
244                                 return $rs->fields['id'];
245                         }
246         $this->lock();
247         $rs = $dbh->Execute($query);
248                 $id = $rs->fields['id'];
249             if (empty($id)) {
250                         // kludge necessary because an assoc array is returned with a reserved name as the key
251             $rs = $dbh->Execute("SELECT MAX(id) AS M FROM $page_tbl");
252                     $id = $rs->fields['M'] + 1;
253             $dbh->Execute(sprintf("INSERT INTO $page_tbl"
254                                 . " (id,pagename,hits)"
255                                 . " VALUES (%d,%s,0)",
256                                 $id, $dbh->qstr($pagename)));
257         }
258         $this->unlock();
259         return $id;
260     }
261
262     function get_latest_version($pagename) {
263         $dbh = &$this->_dbh;
264         extract($this->_table_names);
265         $rs = $dbh->Execute(sprintf("SELECT latestversion"
266                                       . " FROM $page_tbl, $recent_tbl"
267                                       . " WHERE $page_tbl.id=$recent_tbl.id"
268                                       . "  AND pagename=%s",
269                                       $dbh->qstr($pagename)));
270                 return (int)$rs->fields['latestversion'];
271     }
272
273     function get_previous_version($pagename, $version) {
274         $dbh = &$this->_dbh;
275         extract($this->_table_names);
276                 //Use SELECTLIMIT for maximum portability
277         $rs = $dbh->SelectLimit(sprintf("SELECT version"
278                                       . " FROM $version_tbl, $page_tbl"
279                                       . " WHERE $version_tbl.id=$page_tbl.id"
280                                       . "  AND pagename=%s"
281                                       . "  AND version < %d"
282                                       . " ORDER BY version DESC"
283                                       ,$dbh->qstr($pagename),
284                                       $version),
285                                                                           1);
286                 return (int)$rs->fields['version'];
287     }
288     
289     /**
290      * Get version data.
291      *
292      * @param $version int Which version to get.
293      *
294      * @return hash The version data, or false if specified version does not
295      *              exist.
296      */
297     function get_versiondata($pagename, $version, $want_content = false) {
298         $dbh = &$this->_dbh;
299         extract($this->_table_names);
300                 
301         assert(!empty($pagename));
302         assert($version > 0);
303         
304         //trigger_error("GET_REVISION $pagename $version $want_content", E_USER_NOTICE);
305         // FIXME: optimization: sometimes don't get page data?
306
307         if ($want_content) {
308             $fields = "*";
309         }
310         else {
311             $fields = ("$page_tbl.*,"
312                        . "mtime,minor_edit,versiondata,"
313                        . "content<>'' AS have_content");
314         }
315 // removed ref to FETCH_MODE in next line
316         $result = $dbh->GetRow(sprintf("SELECT $fields"
317                                        . " FROM $page_tbl, $version_tbl"
318                                        . " WHERE $page_tbl.id=$version_tbl.id"
319                                        . "  AND pagename=%s"
320                                        . "  AND version=%d",
321                                        $dbh->qstr($pagename), $version));
322
323         return $this->_extract_version_data($result);
324     }
325
326     function _extract_version_data(&$query_result) {
327         if (!$query_result)
328             return false;
329
330         extract($query_result);
331         $data = empty($versiondata) ? array() : unserialize($versiondata);
332
333         $data['mtime'] = $mtime;
334         $data['is_minor_edit'] = !empty($minor_edit);
335         
336         if (isset($content))
337             $data['%content'] = $content;
338         elseif ($have_content)
339             $data['%content'] = true;
340         else
341             $data['%content'] = '';
342
343         // FIXME: this is ugly.
344         if (isset($pagename)) {
345             // Query also includes page data.
346             // We might as well send that back too...
347             $data['%pagedata'] = $this->_extract_page_data($query_result);
348         }
349
350         return $data;
351     }
352
353
354     /**
355      * Create a new revision of a page.
356      */
357     function set_versiondata($pagename, $version, $data) {
358         $dbh = &$this->_dbh;
359         $version_tbl = $this->_table_names['version_tbl'];
360         
361         $minor_edit = (int) !empty($data['is_minor_edit']);
362         unset($data['is_minor_edit']);
363         
364         $mtime = (int)$data['mtime'];
365         unset($data['mtime']);
366         assert(!empty($mtime));
367
368         @$content = (string) $data['%content'];
369         unset($data['%content']);
370
371         unset($data['%pagedata']);
372         
373         $this->lock();
374         $id = $this->_get_pageid($pagename, true);
375
376         // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
377         $dbh->Execute(sprintf("DELETE FROM $version_tbl"
378                             . " WHERE id=%d AND version=%d",
379                             $id, $version));
380
381         $dbh->Execute(sprintf("INSERT INTO $version_tbl"
382                             . " (id,version,mtime,minor_edit,content,versiondata)"
383                             . " VALUES(%d,%d,%d,%d,%s,%s)",
384                             $id, $version, $mtime, $minor_edit,
385                             $dbh->qstr($content),
386                             $dbh->qstr(serialize($data))));
387
388         $this->_update_recent_table($id);
389         $this->_update_nonempty_table($id);
390         
391         $this->unlock();
392     }
393     
394     /**
395      * Delete an old revision of a page.
396      */
397     function delete_versiondata($pagename, $version) {
398         $dbh = &$this->_dbh;
399         extract($this->_table_names);
400
401         $this->lock();
402         if ( ($id = $this->_get_pageid($pagename)) ) {
403             $dbh->Execute("DELETE FROM $version_tbl"
404                         . " WHERE id=$id AND version=$version");
405             $this->_update_recent_table($id);
406             // This shouldn't be needed (as long as the latestversion
407             // never gets deleted.)  But, let's be safe.
408             $this->_update_nonempty_table($id);
409         }
410         $this->unlock();
411     }
412
413     /**
414      * Delete page from the database.
415      */
416     function delete_page($pagename) {
417         $dbh = &$this->_dbh;
418         extract($this->_table_names);
419         
420         $this->lock();
421         if ( ($id = $this->_get_pageid($pagename, 'id')) ) {
422             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
423             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
424             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
425             $dbh->Execute("DELETE FROM $link_tbl     WHERE linkfrom=$id");
426                         $rs = $dbh->Execute("SELECT COUNT(*) AS C FROM $link_tbl WHERE linkto=$id");
427             $nlinks = $rs->fields['C'];
428             if ($nlinks) {
429                 // We're still in the link table (dangling link) so we can't delete this
430                 // altogether.
431                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
432             }
433             else {
434                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
435             }
436             $this->_update_recent_table();
437             $this->_update_nonempty_table();
438         }
439         $this->unlock();
440     }
441             
442
443     // The only thing we might be interested in updating which we can
444     // do fast in the flags (minor_edit).   I think the default
445     // update_versiondata will work fine...
446     //function update_versiondata($pagename, $version, $data) {
447     //}
448
449     function set_links($pagename, $links) {
450         // Update link table.
451         // FIXME: optimize: mysql can do this all in one big INSERT.
452
453         $dbh = &$this->_dbh;
454         extract($this->_table_names);
455
456         $this->lock();
457         $pageid = $this->_get_pageid($pagename, true);
458
459         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
460
461         if ($links) {
462             foreach($links as $link) {
463                 if (isset($linkseen[$link]))
464                     continue;
465                 $linkseen[$link] = true;
466                 $linkid = $this->_get_pageid($link, true);
467                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
468                             . " VALUES ($pageid, $linkid)");
469             }
470         }
471         $this->unlock();
472     }
473     
474     /**
475      * Find pages which link to or are linked from a page.
476      */
477     function get_links($pagename, $reversed = true) {
478         $dbh = &$this->_dbh;
479         extract($this->_table_names);
480
481         if ($reversed)
482             list($have,$want) = array('linkee', 'linker');
483         else
484             list($have,$want) = array('linker', 'linkee');
485
486         $qpagename = $dbh->qstr($pagename);
487 // removed ref to FETCH_MODE in next line        
488         $result = $dbh->Execute("SELECT $want.*"
489                               . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
490                               . " WHERE linkfrom=linker.id AND linkto=linkee.id"
491                               . "  AND $have.pagename='$qpagename'"
492                               //. " GROUP BY $want.id"
493                               . " ORDER BY $want.pagename");
494         
495         return new WikiDB_backend_ADODB_iter($this, $result);
496     }
497
498     function get_all_pages($include_deleted) {
499         $dbh = &$this->_dbh;
500         extract($this->_table_names);
501
502         if ($include_deleted) {
503             $result = $dbh->Execute("SELECT * FROM $page_tbl ORDER BY pagename");
504         }
505         else {
506             $result = $dbh->Execute("SELECT $page_tbl.*"
507                                   . " FROM $nonempty_tbl, $page_tbl"
508                                   . " WHERE $nonempty_tbl.id=$page_tbl.id"
509                                   . " ORDER BY pagename");
510         }
511
512         return new WikiDB_backend_ADODB_iter($this, $result);
513     }
514         
515     /**
516      * Title search.
517      */
518     function text_search($search = '', $fullsearch = false) {
519         $dbh = &$this->_dbh;
520         extract($this->_table_names);
521         
522         $table = "$nonempty_tbl, $page_tbl";
523         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
524         $fields = "$page_tbl.*";
525         $callback = new WikiMethodCb($this, '_sql_match_clause');
526         
527         if ($fullsearch) {
528             $table .= ", $recent_tbl";
529             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
530
531             $table .= ", $version_tbl";
532             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
533
534             $fields .= ",$version_tbl.*";
535             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
536         }
537         
538         $search_clause = $search->makeSqlClause($callback);
539         
540         $result = $dbh->Execute("SELECT $fields FROM $table"
541                               . " WHERE $join_clause"
542                               . "  AND ($search_clause)"
543                               . " ORDER BY pagename");
544         
545         return new WikiDB_backend_ADODB_iter($this, $result);
546     }
547
548     function _sql_match_clause($word) {
549         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this.  ADODB may do it for us
550         // (we need it for at least % and _ --- they're the wildcard characters
551         //  for the LIKE operator, and we need to quote them if we're searching
552         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
553         //  work as is.
554         $word = $this->_dbh->qstr("%$word%");
555         return "LOWER(pagename) LIKE $word";
556     }
557
558     function _fullsearch_sql_match_clause($word) {
559         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
560         // (see above)
561         $word = $this->_dbh->qstr("%$word%");
562         return "LOWER(pagename) LIKE $word OR content LIKE $word";
563     }
564
565     /**
566      * Find highest hit counts.
567      */
568     function most_popular($limit) {
569         $dbh = &$this->_dbh;
570         extract($this->_table_names);
571
572         $limit = $limit ? $limit : -1;
573         $result = $dbh->SelectLimit("SELECT $page_tbl.*"
574                               . " FROM $nonempty_tbl, $page_tbl"
575                               . " WHERE $nonempty_tbl.id=$page_tbl.id"
576                               . " ORDER BY hits DESC"
577                               , $limit);
578
579         return new WikiDB_backend_ADODB_iter($this, $result);
580     }
581
582     /**
583      * Find recent changes.
584      */
585     function most_recent($params) {
586         $limit = 0;
587         $since = 0;
588         $include_minor_revisions = false;
589         $exclude_major_revisions = false;
590         $include_all_revisions = false;
591         extract($params);
592
593         $dbh = &$this->_dbh;
594         extract($this->_table_names);
595
596         $pick = array();
597         if ($since)
598             $pick[] = "mtime >= $since";
599         
600         if ($include_all_revisions) {
601             // Include all revisions of each page.
602             $table = "$page_tbl, $version_tbl";
603             $join_clause = "$page_tbl.id=$version_tbl.id";
604
605             if ($exclude_major_revisions) {
606                 // Include only minor revisions
607                 $pick[] = "minor_edit <> 0";
608             }
609             elseif (!$include_minor_revisions) {
610                 // Include only major revisions
611                 $pick[] = "minor_edit = 0";
612             }
613         }
614         else {
615             $table = "$page_tbl, $recent_tbl";
616             $join_clause = "$page_tbl.id=$recent_tbl.id";
617             $table .= ", $version_tbl";
618             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
619                 
620             if ($exclude_major_revisions) {
621                 // Include only most recent minor revision
622                 $pick[] = 'version=latestminor';
623             }
624             elseif (!$include_minor_revisions) {
625                 // Include only most recent major revision
626                 $pick[] = 'version=latestmajor';
627             }
628             else {
629                 // Include only the latest revision (whether major or minor).
630                 $pick[] ='version=latestversion';
631             }
632         }
633
634         $limit = $limit ? $limit : -1;
635         $where_clause = $join_clause;
636         if ($pick)
637             $where_clause .= " AND " . join(" AND ", $pick);
638
639         // FIXME: use SQL_BUFFER_RESULT for mysql?
640                 //Use SELECTLIMIT for portability
641         $result = $dbh->SelectLimit("SELECT $page_tbl.*,$version_tbl.*"
642                               . " FROM $table"
643                               . " WHERE $where_clause"
644                               . " ORDER BY mtime DESC",
645                               $limit);
646
647         return new WikiDB_backend_ADODB_iter($this, $result);
648     }
649
650     function _update_recent_table($pageid = false) {
651         $dbh = &$this->_dbh;
652         extract($this->_table_names);
653         extract($this->_expressions);
654
655         $pageid = (int)$pageid;
656
657         $this->lock();
658
659         $dbh->Execute("DELETE FROM $recent_tbl"
660                     . ( $pageid ? " WHERE id=$pageid" : ""));
661         
662         $dbh->Execute( "INSERT INTO $recent_tbl"
663                      . " (id, latestversion, latestmajor, latestminor)"
664                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
665                      . " FROM $version_tbl"
666                      . ( $pageid ? " WHERE id=$pageid" : "")
667                      . " GROUP BY id" );
668         $this->unlock();
669     }
670
671     function _update_nonempty_table($pageid = false) {
672         $dbh = &$this->_dbh;
673         extract($this->_table_names);
674
675         $pageid = (int)$pageid;
676
677         $this->lock();
678
679         $dbh->Execute("DELETE FROM $nonempty_tbl"
680                     . ( $pageid ? " WHERE id=$pageid" : ""));
681
682         $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
683                     . " SELECT $recent_tbl.id"
684                     . " FROM $recent_tbl, $version_tbl"
685                     . " WHERE $recent_tbl.id=$version_tbl.id"
686                     . "       AND version=latestversion"
687                     . "  AND content<>''"
688                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
689
690         $this->unlock();
691     }
692
693
694     /**
695      * Grab a write lock on the tables in the SQL database.
696      *
697      * Calls can be nested.  The tables won't be unlocked until
698      * _unlock_database() is called as many times as _lock_database().
699      *
700      * @access protected
701      */
702     function lock($write_lock = true) {
703         if ($this->_lock_count++ == 0)
704             $this->_lock_tables($write_lock);
705     }
706
707     /**
708      * Actually lock the required tables.
709      */
710     function _lock_tables($write_lock) {
711         trigger_error("virtual", E_USER_ERROR);
712     }
713     
714     /**
715      * Release a write lock on the tables in the SQL database.
716      *
717      * @access protected
718      *
719      * @param $force boolean Unlock even if not every call to lock() has been matched
720      * by a call to unlock().
721      *
722      * @see _lock_database
723      */
724     function unlock($force = false) {
725         if ($this->_lock_count == 0)
726             return;
727         if (--$this->_lock_count <= 0 || $force) {
728             $this->_unlock_tables();
729             $this->_lock_count = 0;
730         }
731     }
732
733     /**
734      * Actually unlock the required tables.
735      */
736     function _unlock_tables($write_lock) {
737         trigger_error("virtual", E_USER_ERROR);
738     }
739     
740     /**
741      * Callback for PEAR (DB) errors.
742      *
743      * @access protected
744      *
745      * @param A PEAR_error object.
746      */
747 /*  function _pear_error_callback($error) {
748         if ($this->_is_false_error($error))
749             return;
750         
751         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
752         $this->close();
753         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
754     }
755 */
756     /**
757      * Detect false errors messages from PEAR DB.
758      *
759      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
760      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
761      * return any data.  (So when a "LOCK" command doesn't return any data,
762      * DB reports it as an error, when in fact, it's not.)
763      *
764      * @access private
765      * @return bool True iff error is not really an error.
766      */
767 /*    function _is_false_error($error) {
768         if ($error->getCode() != DB_ERROR)
769             return false;
770
771         $query = $this->_dbh->last_query;
772
773         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
774                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
775             // Last query was not of the sort which doesn't return any data.
776             //" <--kludge for brain-dead syntax coloring
777             return false;
778         }
779         
780         if (! in_array('ismanip', get_class_methods('DB'))) {
781             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
782             // does not have the DB::isManip method.
783             return true;
784         }
785         
786         if (DB::isManip($query)) {
787             // If Pear thinks it's an isManip then it wouldn't have thrown
788             // the error we're testing for....
789             return false;
790         }
791
792         return true;
793     }
794 */
795 /*    function _pear_error_message($error) {
796         $class = get_class($this);
797         $message = "$class: fatal database error\n"
798              . "\t" . $error->getMessage() . "\n"
799              . "\t(" . $error->getDebugInfo() . ")\n";
800
801         // Prevent password from being exposed during a connection error
802         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
803                                  '\\1:XXXXXXXX', $this->_dsn);
804         return str_replace($this->_dsn, $safe_dsn, $message);
805     }
806 */
807     /**
808      * Filter PHP errors notices from PEAR DB code.
809      *
810      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
811      * errors and notices.  This is an error callback (for use with
812      * ErrorManager which will filter out those spurious messages.)
813      * @see _is_false_error, ErrorManager
814      * @access private
815      */
816 /*    function _pear_notice_filter($err) {
817         return ( $err->isNotice()
818                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
819                  && $err->errline == 126
820                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
821     }
822 */
823 };
824
825 class WikiDB_backend_ADODB_iter
826 extends WikiDB_backend_iterator
827 {
828     function WikiDB_backend_ADODB_iter(&$backend, &$query_result) {
829 // ADODB equivalent of this?  May not matter, since we should never get here
830 /*        if (DB::isError($query_result)) {
831             // This shouldn't happen, I thought.
832             $backend->_pear_error_callback($query_result);
833         }
834 */        
835         $this->_backend = &$backend;
836         $this->_result = $query_result;
837     }
838     
839     function next() {
840         $result = &$this->_result;
841         if (!$result || $result->EOF) {
842             $this->free();
843             return false;
844         }
845
846 //      $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
847         $record = $result->fields;
848         $result->MoveNext();
849         
850         $backend = &$this->_backend;
851
852         $pagedata = $backend->_extract_page_data($record);
853         $rec = array('pagename' => $record['pagename'],
854                      'pagedata' => $pagedata);
855
856         if (!empty($record['version'])) {
857             $rec['versiondata'] = $backend->_extract_version_data($record);
858             $rec['version'] = $record['version'];
859         }
860         
861         return $rec;
862     }
863
864     function free () {
865         if ($this->_result) {
866 //          $this->_result->free();
867             $this->_result->Close();
868             $this->_result = false;
869         }
870     }
871 }
872
873 // Following function taken from adodb-pear.inc.php.  Eventually, change index.php to provide the relevant information
874 // directly?
875     /**
876      * Parse a data source name
877      *
878      * @param $dsn string Data Source Name to be parsed
879      *
880      * @return array an associative array with the following keys:
881      *
882      *  phptype: Database backend used in PHP (mysql, odbc etc.)
883      *  dbsyntax: Database used with regards to SQL syntax etc.
884      *  protocol: Communication protocol to use (tcp, unix etc.)
885      *  hostspec: Host specification (hostname[:port])
886      *  database: Database to use on the DBMS server
887      *  username: User name for login
888      *  password: Password for login
889      *
890      * The format of the supplied DSN is in its fullest form:
891      *
892      *  phptype(dbsyntax)://username:password@protocol+hostspec/database
893      *
894      * Most variations are allowed:
895      *
896      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
897      *  phptype://username:password@hostspec/database_name
898      *  phptype://username:password@hostspec
899      *  phptype://username@hostspec
900      *  phptype://hostspec/database
901      *  phptype://hostspec
902      *  phptype(dbsyntax)
903      *  phptype
904      *
905      * @author Tomas V.V.Cox <cox@idecnet.com>
906      */
907     function parseDSN($dsn)
908     {
909         if (is_array($dsn)) {
910             return $dsn;
911         }
912
913         $parsed = array(
914             'phptype'  => false,
915             'dbsyntax' => false,
916             'protocol' => false,
917             'hostspec' => false,
918             'database' => false,
919             'username' => false,
920             'password' => false
921         );
922
923         // Find phptype and dbsyntax
924         if (($pos = strpos($dsn, '://')) !== false) {
925             $str = substr($dsn, 0, $pos);
926             $dsn = substr($dsn, $pos + 3);
927         } else {
928             $str = $dsn;
929             $dsn = NULL;
930         }
931
932         // Get phptype and dbsyntax
933         // $str => phptype(dbsyntax)
934         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
935             $parsed['phptype'] = $arr[1];
936             $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
937         } else {
938             $parsed['phptype'] = $str;
939             $parsed['dbsyntax'] = $str;
940         }
941
942         if (empty($dsn)) {
943             return $parsed;
944         }
945
946         // Get (if found): username and password
947         // $dsn => username:password@protocol+hostspec/database
948         if (($at = strpos($dsn,'@')) !== false) {
949             $str = substr($dsn, 0, $at);
950             $dsn = substr($dsn, $at + 1);
951             if (($pos = strpos($str, ':')) !== false) {
952                 $parsed['username'] = urldecode(substr($str, 0, $pos));
953                 $parsed['password'] = urldecode(substr($str, $pos + 1));
954             } else {
955                 $parsed['username'] = urldecode($str);
956             }
957         }
958
959         // Find protocol and hostspec
960         // $dsn => protocol+hostspec/database
961         if (($pos=strpos($dsn, '/')) !== false) {
962             $str = substr($dsn, 0, $pos);
963             $dsn = substr($dsn, $pos + 1);
964         } else {
965             $str = $dsn;
966             $dsn = NULL;
967         }
968
969         // Get protocol + hostspec
970         // $str => protocol+hostspec
971         if (($pos=strpos($str, '+')) !== false) {
972             $parsed['protocol'] = substr($str, 0, $pos);
973             $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
974         } else {
975             $parsed['hostspec'] = urldecode($str);
976         }
977
978         // Get dabase if any
979         // $dsn => database
980         if (!empty($dsn)) {
981             $parsed['database'] = $dsn;
982         }
983
984         return $parsed;
985     }
986
987
988
989 // (c-file-style: "gnu")
990 // Local Variables:
991 // mode: php
992 // tab-width: 8
993 // c-basic-offset: 4
994 // c-hanging-comment-ender-p: nil
995 // indent-tabs-mode: nil
996 // End:   
997 ?>