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