]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
A few tweaks. Error handling etc. Title search still does not work.
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.2 2002-02-02 22:50:24 lakka 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         $word = $this->_dbh->qstr($word, get_magic_quotes_runtime());
551         return "LOWER(pagename) LIKE %$word%";
552     }
553
554     function _fullsearch_sql_match_clause($word) {
555         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
556         $word = $this->_dbh->qstr($word, get_magic_quotes_runtime());
557         return "LOWER(pagename) LIKE %$word% OR content LIKE %$word%";
558     }
559
560     /**
561      * Find highest hit counts.
562      */
563     function most_popular($limit) {
564         $dbh = &$this->_dbh;
565         extract($this->_table_names);
566
567         $limit = $limit ? $limit : -1;
568         $result = $dbh->SelectLimit("SELECT $page_tbl.*"
569                               . " FROM $nonempty_tbl, $page_tbl"
570                               . " WHERE $nonempty_tbl.id=$page_tbl.id"
571                               . " ORDER BY hits DESC"
572                               , $limit);
573
574         return new WikiDB_backend_ADODB_iter($this, $result);
575     }
576
577     /**
578      * Find recent changes.
579      */
580     function most_recent($params) {
581         $limit = 0;
582         $since = 0;
583         $include_minor_revisions = false;
584         $exclude_major_revisions = false;
585         $include_all_revisions = false;
586         extract($params);
587
588         $dbh = &$this->_dbh;
589         extract($this->_table_names);
590
591         $pick = array();
592         if ($since)
593             $pick[] = "mtime >= $since";
594         
595         if ($include_all_revisions) {
596             // Include all revisions of each page.
597             $table = "$page_tbl, $version_tbl";
598             $join_clause = "$page_tbl.id=$version_tbl.id";
599
600             if ($exclude_major_revisions) {
601                 // Include only minor revisions
602                 $pick[] = "minor_edit <> 0";
603             }
604             elseif (!$include_minor_revisions) {
605                 // Include only major revisions
606                 $pick[] = "minor_edit = 0";
607             }
608         }
609         else {
610             $table = "$page_tbl, $recent_tbl";
611             $join_clause = "$page_tbl.id=$recent_tbl.id";
612             $table .= ", $version_tbl";
613             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
614                 
615             if ($exclude_major_revisions) {
616                 // Include only most recent minor revision
617                 $pick[] = 'version=latestminor';
618             }
619             elseif (!$include_minor_revisions) {
620                 // Include only most recent major revision
621                 $pick[] = 'version=latestmajor';
622             }
623             else {
624                 // Include only the latest revision (whether major or minor).
625                 $pick[] ='version=latestversion';
626             }
627         }
628
629         $limit = $limit ? $limit : -1;
630         $where_clause = $join_clause;
631         if ($pick)
632             $where_clause .= " AND " . join(" AND ", $pick);
633
634         // FIXME: use SQL_BUFFER_RESULT for mysql?
635                 //Use SELECTLIMIT for portability
636         $result = $dbh->SelectLimit("SELECT $page_tbl.*,$version_tbl.*"
637                               . " FROM $table"
638                               . " WHERE $where_clause"
639                               . " ORDER BY mtime DESC",
640                               $limit);
641
642         return new WikiDB_backend_ADODB_iter($this, $result);
643     }
644
645     function _update_recent_table($pageid = false) {
646         $dbh = &$this->_dbh;
647         extract($this->_table_names);
648         extract($this->_expressions);
649
650         $pageid = (int)$pageid;
651
652         $this->lock();
653
654         $dbh->Execute("DELETE FROM $recent_tbl"
655                     . ( $pageid ? " WHERE id=$pageid" : ""));
656         
657         $dbh->Execute( "INSERT INTO $recent_tbl"
658                      . " (id, latestversion, latestmajor, latestminor)"
659                      . " SELECT id, $maxversion, $maxmajor, $maxminor"
660                      . " FROM $version_tbl"
661                      . ( $pageid ? " WHERE id=$pageid" : "")
662                      . " GROUP BY id" );
663         $this->unlock();
664     }
665
666     function _update_nonempty_table($pageid = false) {
667         $dbh = &$this->_dbh;
668         extract($this->_table_names);
669
670         $pageid = (int)$pageid;
671
672         $this->lock();
673
674         $dbh->Execute("DELETE FROM $nonempty_tbl"
675                     . ( $pageid ? " WHERE id=$pageid" : ""));
676
677         $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
678                     . " SELECT $recent_tbl.id"
679                     . " FROM $recent_tbl, $version_tbl"
680                     . " WHERE $recent_tbl.id=$version_tbl.id"
681                     . "       AND version=latestversion"
682                     . "  AND content<>''"
683                     . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
684
685         $this->unlock();
686     }
687
688
689     /**
690      * Grab a write lock on the tables in the SQL database.
691      *
692      * Calls can be nested.  The tables won't be unlocked until
693      * _unlock_database() is called as many times as _lock_database().
694      *
695      * @access protected
696      */
697     function lock($write_lock = true) {
698         if ($this->_lock_count++ == 0)
699             $this->_lock_tables($write_lock);
700     }
701
702     /**
703      * Actually lock the required tables.
704      */
705     function _lock_tables($write_lock) {
706         trigger_error("virtual", E_USER_ERROR);
707     }
708     
709     /**
710      * Release a write lock on the tables in the SQL database.
711      *
712      * @access protected
713      *
714      * @param $force boolean Unlock even if not every call to lock() has been matched
715      * by a call to unlock().
716      *
717      * @see _lock_database
718      */
719     function unlock($force = false) {
720         if ($this->_lock_count == 0)
721             return;
722         if (--$this->_lock_count <= 0 || $force) {
723             $this->_unlock_tables();
724             $this->_lock_count = 0;
725         }
726     }
727
728     /**
729      * Actually unlock the required tables.
730      */
731     function _unlock_tables($write_lock) {
732         trigger_error("virtual", E_USER_ERROR);
733     }
734     
735     /**
736      * Callback for PEAR (DB) errors.
737      *
738      * @access protected
739      *
740      * @param A PEAR_error object.
741      */
742 /*  function _pear_error_callback($error) {
743         if ($this->_is_false_error($error))
744             return;
745         
746         $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
747         $this->close();
748         trigger_error($this->_pear_error_message($error), E_USER_ERROR);
749     }
750 */
751     /**
752      * Detect false errors messages from PEAR DB.
753      *
754      * The version of PEAR DB which ships with PHP 4.0.6 has a bug in that
755      * it doesn't recognize "LOCK" and "UNLOCK" as SQL commands which don't
756      * return any data.  (So when a "LOCK" command doesn't return any data,
757      * DB reports it as an error, when in fact, it's not.)
758      *
759      * @access private
760      * @return bool True iff error is not really an error.
761      */
762 /*    function _is_false_error($error) {
763         if ($error->getCode() != DB_ERROR)
764             return false;
765
766         $query = $this->_dbh->last_query;
767
768         if (! preg_match('/^\s*"?(INSERT|UPDATE|DELETE|REPLACE|CREATE'
769                          . '|DROP|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s/', $query)) {
770             // Last query was not of the sort which doesn't return any data.
771             //" <--kludge for brain-dead syntax coloring
772             return false;
773         }
774         
775         if (! in_array('ismanip', get_class_methods('DB'))) {
776             // Pear shipped with PHP 4.0.4pl1 (and before, presumably)
777             // does not have the DB::isManip method.
778             return true;
779         }
780         
781         if (DB::isManip($query)) {
782             // If Pear thinks it's an isManip then it wouldn't have thrown
783             // the error we're testing for....
784             return false;
785         }
786
787         return true;
788     }
789 */
790 /*    function _pear_error_message($error) {
791         $class = get_class($this);
792         $message = "$class: fatal database error\n"
793              . "\t" . $error->getMessage() . "\n"
794              . "\t(" . $error->getDebugInfo() . ")\n";
795
796         // Prevent password from being exposed during a connection error
797         $safe_dsn = preg_replace('| ( :// .*? ) : .* (?=@) |xs',
798                                  '\\1:XXXXXXXX', $this->_dsn);
799         return str_replace($this->_dsn, $safe_dsn, $message);
800     }
801 */
802     /**
803      * Filter PHP errors notices from PEAR DB code.
804      *
805      * The PEAR DB code which ships with PHP 4.0.6 produces spurious
806      * errors and notices.  This is an error callback (for use with
807      * ErrorManager which will filter out those spurious messages.)
808      * @see _is_false_error, ErrorManager
809      * @access private
810      */
811 /*    function _pear_notice_filter($err) {
812         return ( $err->isNotice()
813                  && preg_match('|DB[/\\\\]common.php$|', $err->errfile)
814                  && $err->errline == 126
815                  && preg_match('/Undefined offset: +0\b/', $err->errstr) );
816     }
817 */
818 };
819
820 class WikiDB_backend_ADODB_iter
821 extends WikiDB_backend_iterator
822 {
823     function WikiDB_backend_ADODB_iter(&$backend, &$query_result) {
824 // ADODB equivalent of this?  May not matter, since we should never get here
825 /*        if (DB::isError($query_result)) {
826             // This shouldn't happen, I thought.
827             $backend->_pear_error_callback($query_result);
828         }
829 */        
830         $this->_backend = &$backend;
831         $this->_result = $query_result;
832     }
833     
834     function next() {
835         $backend = &$this->_backend;
836         if (!$this->_result)
837             return false;
838
839 //      $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
840                 $record = $this->_result->fields;
841         $this->_result->MoveNext();
842                 if ($this->_result->EOF) {
843             $this->free();
844             return false;
845         }
846         
847         $pagedata = $backend->_extract_page_data($record);
848         $rec = array('pagename' => $record['pagename'],
849                      'pagedata' => $pagedata);
850
851         if (!empty($record['version'])) {
852             $rec['versiondata'] = $backend->_extract_version_data($record);
853             $rec['version'] = $record['version'];
854         }
855         
856         return $rec;
857     }
858
859     function free () {
860         if ($this->_result) {
861 //          $this->_result->free();
862                         $this->_result->Close();
863             $this->_result = false;
864         }
865     }
866 }
867
868 // Following function taken from adodb-pear.inc.php.  Eventually, change index.php to provide the relevant information
869 // directly?
870     /**
871      * Parse a data source name
872      *
873      * @param $dsn string Data Source Name to be parsed
874      *
875      * @return array an associative array with the following keys:
876      *
877      *  phptype: Database backend used in PHP (mysql, odbc etc.)
878      *  dbsyntax: Database used with regards to SQL syntax etc.
879      *  protocol: Communication protocol to use (tcp, unix etc.)
880      *  hostspec: Host specification (hostname[:port])
881      *  database: Database to use on the DBMS server
882      *  username: User name for login
883      *  password: Password for login
884      *
885      * The format of the supplied DSN is in its fullest form:
886      *
887      *  phptype(dbsyntax)://username:password@protocol+hostspec/database
888      *
889      * Most variations are allowed:
890      *
891      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
892      *  phptype://username:password@hostspec/database_name
893      *  phptype://username:password@hostspec
894      *  phptype://username@hostspec
895      *  phptype://hostspec/database
896      *  phptype://hostspec
897      *  phptype(dbsyntax)
898      *  phptype
899      *
900      * @author Tomas V.V.Cox <cox@idecnet.com>
901      */
902     function parseDSN($dsn)
903     {
904         if (is_array($dsn)) {
905             return $dsn;
906         }
907
908         $parsed = array(
909             'phptype'  => false,
910             'dbsyntax' => false,
911             'protocol' => false,
912             'hostspec' => false,
913             'database' => false,
914             'username' => false,
915             'password' => false
916         );
917
918         // Find phptype and dbsyntax
919         if (($pos = strpos($dsn, '://')) !== false) {
920             $str = substr($dsn, 0, $pos);
921             $dsn = substr($dsn, $pos + 3);
922         } else {
923             $str = $dsn;
924             $dsn = NULL;
925         }
926
927         // Get phptype and dbsyntax
928         // $str => phptype(dbsyntax)
929         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
930             $parsed['phptype'] = $arr[1];
931             $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
932         } else {
933             $parsed['phptype'] = $str;
934             $parsed['dbsyntax'] = $str;
935         }
936
937         if (empty($dsn)) {
938             return $parsed;
939         }
940
941         // Get (if found): username and password
942         // $dsn => username:password@protocol+hostspec/database
943         if (($at = strpos($dsn,'@')) !== false) {
944             $str = substr($dsn, 0, $at);
945             $dsn = substr($dsn, $at + 1);
946             if (($pos = strpos($str, ':')) !== false) {
947                 $parsed['username'] = urldecode(substr($str, 0, $pos));
948                 $parsed['password'] = urldecode(substr($str, $pos + 1));
949             } else {
950                 $parsed['username'] = urldecode($str);
951             }
952         }
953
954         // Find protocol and hostspec
955         // $dsn => protocol+hostspec/database
956         if (($pos=strpos($dsn, '/')) !== false) {
957             $str = substr($dsn, 0, $pos);
958             $dsn = substr($dsn, $pos + 1);
959         } else {
960             $str = $dsn;
961             $dsn = NULL;
962         }
963
964         // Get protocol + hostspec
965         // $str => protocol+hostspec
966         if (($pos=strpos($str, '+')) !== false) {
967             $parsed['protocol'] = substr($str, 0, $pos);
968             $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
969         } else {
970             $parsed['hostspec'] = urldecode($str);
971         }
972
973         // Get dabase if any
974         // $dsn => database
975         if (!empty($dsn)) {
976             $parsed['database'] = $dsn;
977         }
978
979         return $parsed;
980     }
981
982
983
984 // (c-file-style: "gnu")
985 // Local Variables:
986 // mode: php
987 // tab-width: 8
988 // c-basic-offset: 4
989 // c-hanging-comment-ender-p: nil
990 // indent-tabs-mode: nil
991 // End:   
992 ?>