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