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