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