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