]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
better wording
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.21 2004-04-01 06:29:51 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('lib/WikiDB/backend.php');
43 // Error handling - calls trigger_error.  NB - does not close the connection.  Does it need to?
44 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
45 // include the main adodb file
46 require_once('lib/WikiDB/adodb/adodb.inc.php');
47
48 class WikiDB_backend_ADODB
49 extends WikiDB_backend
50 {
51
52     function WikiDB_backend_ADODB ($dbparams) {
53         /*
54         $dbh->setFetchMode(ADODB_FETCH_ASSOC);
55         */
56         $parsed = parseDSN($dbparams['dsn']);
57         $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
58         $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], 
59                                      $parsed['password'], $parsed['database']);
60
61         //  Uncomment the following line to enable debugging output (not very pretty!)          
62         //      $this->_dbh->debug = true;
63                 
64         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
65
66         //  The next line should speed up queries if enabled, but:
67         //  1)  It only works with PHP >= 4.0.6; and
68         //  2)  At the moment, I haven't figured out why the wrong results are returned'
69         //$GLOBALS['ADODB_COUNTRECS'] = false;
70
71         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
72
73         $this->_table_names
74             = array('page_tbl'     => $prefix . 'page',
75                     'version_tbl'  => $prefix . 'version',
76                     'link_tbl'     => $prefix . 'link',
77                     'recent_tbl'   => $prefix . 'recent',
78                     'nonempty_tbl' => $prefix . 'nonempty');
79         $page_tbl = $this->_table_names['page_tbl'];
80         $version_tbl = $this->_table_names['version_tbl'];
81         $this->page_tbl_fields = "$page_tbl.id as id, $page_tbl.pagename as pagename, " .
82             "$page_tbl.hits as hits, $page_tbl.pagedata as pagedata";
83         $this->version_tbl_fields = "$version_tbl.version as version, $version_tbl.mtime as mtime, ".
84             "$version_tbl.minor_edit as minor_edit, $version_tbl.content as content, ".
85             "$version_tbl.versiondata as versiondata";
86
87         $this->_expressions
88             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
89                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
90                     'maxversion'   => "MAX(version)");
91         
92         $this->_lock_count = 0;
93     }
94     
95     /**
96      * Close database connection.
97      */
98     function close () {
99         if (!$this->_dbh)
100             return;
101         if ($this->_lock_count) {
102             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
103                           E_USER_WARNING);
104         }
105 //      $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
106         $this->unlock('force');
107
108         $this->_dbh->close();
109         $this->_dbh = false;
110     }
111
112     /*
113      * Fast test for wikipage.
114      */
115     function is_wiki_page($pagename) {
116         $dbh = &$this->_dbh;
117         extract($this->_table_names);
118         $rs = $dbh->Execute(sprintf("SELECT $page_tbl.id AS id"
119                                     . " FROM $nonempty_tbl, $page_tbl"
120                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
121                                     . "   AND pagename=%s",
122                                     $dbh->qstr($pagename)));
123         if (!$rs->EOF) {
124             $result = $rs->fields["id"];
125             $rs->Close();
126             return $result;
127         } else {
128             $rs->Close();
129             return false;
130         }
131     }
132         
133     function get_all_pagenames() {
134         $dbh = &$this->_dbh;
135         extract($this->_table_names);
136         //return $dbh->getCol("SELECT pagename"
137         //                    . " FROM $nonempty_tbl, $page_tbl"
138         //                    . " WHERE $nonempty_tbl.id=$page_tbl.id");
139
140         //Original code (above) return the column in an indexed array - 0 based
141         //So, hopefully, does this
142         $result = $dbh->Execute("SELECT pagename"
143                                 . " FROM $nonempty_tbl, $page_tbl"
144                                 . " WHERE $nonempty_tbl.id=$page_tbl.id");
145         return $result->GetArray();
146     }
147             
148     /**
149      * Read page information from database.
150      */
151     function get_pagedata($pagename) {
152         $dbh = &$this->_dbh;
153         $page_tbl = $this->_table_names['page_tbl'];
154         $result = $dbh->GetRow(sprintf("SELECT * FROM $page_tbl WHERE pagename=%s",
155                                        $dbh->qstr($pagename)));
156         if (!$result)
157             return false;
158         return $this->_extract_page_data($result);
159     }
160
161     function  _extract_page_data(&$query_result) {
162         extract($query_result);
163         $data = empty($pagedata) ? array() : unserialize($pagedata);
164         $data['hits'] = $hits;
165         return $data;
166     }
167
168     function update_pagedata($pagename, $newdata) {
169         $dbh = &$this->_dbh;
170         $page_tbl = $this->_table_names['page_tbl'];
171
172         // Hits is the only thing we can update in a fast manner.
173         if (count($newdata) == 1 && isset($newdata['hits'])) {
174             // Note that this will fail silently if the page does not
175             // have a record in the page table.  Since it's just the
176             // hit count, who cares?
177             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
178                                 $newdata['hits'], $dbh->qstr($pagename)));
179             return;
180         }
181
182         $this->lock();
183         $data = $this->get_pagedata($pagename);
184         if (!$data) {
185             $data = array();
186             $this->_get_pageid($pagename, true); // Creates page record
187         }
188         
189         @$hits = (int)$data['hits'];
190         unset($data['hits']);
191
192         foreach ($newdata as $key => $val) {
193             if ($key == 'hits')
194                 $hits = (int)$val;
195             else if (empty($val))
196                 unset($data[$key]);
197             else
198                 $data[$key] = $val;
199         }
200
201         $dbh->Execute(sprintf("UPDATE $page_tbl"
202                             . " SET hits=%d, pagedata=%s"
203                             . " WHERE pagename=%s",
204                             $hits,
205                             $dbh->qstr(serialize($data)),
206                             $dbh->qstr($pagename)));
207
208         $this->unlock();
209     }
210
211     function _get_pageid($pagename, $create_if_missing = false) {
212         
213         $dbh = &$this->_dbh;
214         $page_tbl = $this->_table_names['page_tbl'];
215         
216         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
217                          $dbh->qstr($pagename));
218
219         if (!$create_if_missing) {
220             $rs = $dbh->Execute($query);
221             return $rs->fields['id'];
222         }
223         $this->lock();
224         $rs = $dbh->Execute($query);
225         $id = $rs->fields['id'];
226         if (empty($id)) {
227             // kludge necessary because an assoc array is returned with a reserved name as the key
228             $rs = $dbh->Execute("SELECT MAX(id) AS M FROM $page_tbl");
229             $id = $rs->fields['M'] + 1;
230             $dbh->Execute(sprintf("INSERT INTO $page_tbl"
231                                   . " (id,pagename,hits)"
232                                   . " VALUES (%d,%s,0)",
233                                   $id, $dbh->qstr($pagename)));
234         }
235         $this->unlock();
236         return $id;
237     }
238
239     function get_latest_version($pagename) {
240         $dbh = &$this->_dbh;
241         extract($this->_table_names);
242         $rs = $dbh->Execute(sprintf("SELECT latestversion"
243                                       . " FROM $page_tbl, $recent_tbl"
244                                       . " WHERE $page_tbl.id=$recent_tbl.id"
245                                       . "  AND pagename=%s",
246                                       $dbh->qstr($pagename)));
247         return (int)$rs->fields['latestversion'];
248     }
249
250     function get_previous_version($pagename, $version) {
251         $dbh = &$this->_dbh;
252         extract($this->_table_names);
253         // Use SELECTLIMIT for maximum portability
254         $rs = $dbh->SelectLimit(sprintf("SELECT version"
255                                       . " FROM $version_tbl, $page_tbl"
256                                       . " WHERE $version_tbl.id=$page_tbl.id"
257                                       . "  AND pagename=%s"
258                                       . "  AND version < %d"
259                                       . " ORDER BY version DESC"
260                                       ,$dbh->qstr($pagename),
261                                       $version),
262                                                                           1);
263         return (int)$rs->fields['version'];
264     }
265     
266     /**
267      * Get version data.
268      *
269      * @param $version int Which version to get.
270      *
271      * @return hash The version data, or false if specified version does not
272      *              exist.
273      */
274     function get_versiondata($pagename, $version, $want_content = false) {
275         $dbh = &$this->_dbh;
276         extract($this->_table_names);
277                 
278         assert(!empty($pagename));
279         assert($version > 0);
280         
281         // FIXME: optimization: sometimes don't get page data?
282         if ($want_content) {
283             $fields = $this->page_tbl_fields.','.$this->version_tbl_fields;
284         } else {
285             $fields =  $this->page_tbl_fields . ", "
286                        . "mtime, minor_edit, versiondata,"
287                        . "content<>'' AS have_content";
288         }
289         // removed ref to FETCH_MODE in next line
290         $result = $dbh->GetRow(sprintf("SELECT $fields"
291                                        . " FROM $page_tbl, $version_tbl"
292                                        . " WHERE $page_tbl.id=$version_tbl.id"
293                                        . "  AND pagename=%s"
294                                        . "  AND version=%d",
295                                        $dbh->qstr($pagename), $version));
296
297         return $this->_extract_version_data($result);
298     }
299
300     function _extract_version_data(&$query_result) {
301         if (!$query_result)
302             return false;
303
304         extract($query_result);
305         $data = empty($versiondata) ? array() : unserialize($versiondata);
306
307         $data['mtime'] = $mtime;
308         $data['is_minor_edit'] = !empty($minor_edit);
309         
310         if (isset($content))
311             $data['%content'] = $content;
312         elseif ($have_content)
313             $data['%content'] = true;
314         else
315             $data['%content'] = '';
316
317         // FIXME: this is ugly.
318         if (isset($pagename)) {
319             // Query also includes page data.
320             // We might as well send that back too...
321             $data['%pagedata'] = $this->_extract_page_data($query_result);
322         }
323
324         return $data;
325     }
326
327
328     /**
329      * Create a new revision of a page.
330      */
331     function set_versiondata($pagename, $version, $data) {
332         $dbh = &$this->_dbh;
333         $version_tbl = $this->_table_names['version_tbl'];
334         
335         $minor_edit = (int) !empty($data['is_minor_edit']);
336         unset($data['is_minor_edit']);
337         
338         $mtime = (int)$data['mtime'];
339         unset($data['mtime']);
340         assert(!empty($mtime));
341
342         @$content = (string) $data['%content'];
343         unset($data['%content']);
344         unset($data['%pagedata']);
345         
346         $this->lock();
347         $id = $this->_get_pageid($pagename, true);
348
349         // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
350         $dbh->Execute(sprintf("DELETE FROM $version_tbl"
351                             . " WHERE id=%d AND version=%d",
352                             $id, $version));
353         $dbh->Execute(sprintf("INSERT INTO $version_tbl"
354                             . " (id,version,mtime,minor_edit,content,versiondata)"
355                             . " VALUES(%d,%d,%d,%d,%s,%s)",
356                             $id, $version, $mtime, $minor_edit,
357                             $dbh->qstr($content),
358                             $dbh->qstr(serialize($data))));
359
360         $this->_update_recent_table($id);
361         $this->_update_nonempty_table($id);
362         
363         $this->unlock();
364     }
365     
366     /**
367      * Delete an old revision of a page.
368      */
369     function delete_versiondata($pagename, $version) {
370         $dbh = &$this->_dbh;
371         extract($this->_table_names);
372
373         $this->lock();
374         if ( ($id = $this->_get_pageid($pagename)) ) {
375             $dbh->Execute("DELETE FROM $version_tbl"
376                         . " WHERE id=$id AND version=$version");
377             $this->_update_recent_table($id);
378             // This shouldn't be needed (as long as the latestversion
379             // never gets deleted.)  But, let's be safe.
380             $this->_update_nonempty_table($id);
381         }
382         $this->unlock();
383     }
384
385     /**
386      * Delete page from the database.
387      */
388     function delete_page($pagename) {
389         $dbh = &$this->_dbh;
390         extract($this->_table_names);
391         
392         $this->lock();
393         if ( ($id = $this->_get_pageid($pagename, false)) ) {
394             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
395             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
396             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
397             $dbh->Execute("DELETE FROM $link_tbl     WHERE linkfrom=$id");
398             $rs = $dbh->Execute("SELECT COUNT(*) AS C FROM $link_tbl WHERE linkto=$id");
399             $nlinks = $rs->fields['C'];
400             if ($nlinks) {
401                 // We're still in the link table (dangling link) so we can't delete this
402                 // altogether.
403                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
404             }
405             else {
406                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
407             }
408             $this->_update_recent_table();
409             $this->_update_nonempty_table();
410         }
411         $this->unlock();
412     }
413             
414
415     // The only thing we might be interested in updating which we can
416     // do fast in the flags (minor_edit).   I think the default
417     // update_versiondata will work fine...
418     //function update_versiondata($pagename, $version, $data) {
419     //}
420
421     function set_links($pagename, $links) {
422         // Update link table.
423         // FIXME: optimize: mysql can do this all in one big INSERT.
424
425         $dbh = &$this->_dbh;
426         extract($this->_table_names);
427
428         $this->lock();
429         $pageid = $this->_get_pageid($pagename, true);
430
431         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
432
433         if ($links) {
434             foreach($links as $link) {
435                 if (isset($linkseen[$link]))
436                     continue;
437                 $linkseen[$link] = true;
438                 $linkid = $this->_get_pageid($link, true);
439                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
440                             . " VALUES ($pageid, $linkid)");
441             }
442         }
443         $this->unlock();
444     }
445     
446     /**
447      * Find pages which link to or are linked from a page.
448      */
449     function get_links($pagename, $reversed = true) {
450         $dbh = &$this->_dbh;
451         extract($this->_table_names);
452
453         if ($reversed)
454             list($have,$want) = array('linkee', 'linker');
455         else
456             list($have,$want) = array('linker', 'linkee');
457
458         $qpagename = $dbh->qstr($pagename);
459         // removed ref to FETCH_MODE in next line        
460         $result = $dbh->Execute("SELECT $want.id as id, $want.pagename as pagename,"
461                                 . " $want.hits as hits, $want.pagedata as pagedata"
462                                 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
463                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
464                                 . " AND $have.pagename=$qpagename"
465                                 //. " GROUP BY $want.id"
466                                 . " ORDER BY $want.pagename");
467         
468         return new WikiDB_backend_ADODB_iter($this, $result);
469     }
470
471     function get_all_pages($include_deleted=false,$sortby = false,$limit = false) {
472         $dbh = &$this->_dbh;
473         extract($this->_table_names);
474         if ($limit)  $limit = "LIMIT $limit";
475         else         $limit = '';
476         if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
477         else         $orderby = '';
478         if (strstr($orderby,' mtime')) {
479             if ($include_deleted) {
480                 $result = $dbh->Execute("SELECT * FROM $page_tbl, $recent_tbl, $version_tbl"
481                                         . " WHERE $page_tbl.id=$recent_tbl.id"
482                                         . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
483                                         . " $orderby $limit");
484             }
485             else {
486                 $result = $dbh->Execute("SELECT "
487                                         . $this->page_tbl_fields
488                                         . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
489                                         . " WHERE $nonempty_tbl.id=$page_tbl.id"
490                                         . " AND $page_tbl.id=$recent_tbl.id"
491                                         . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
492                                         . " $orderby $limit");
493             }
494         } else {
495             if ($include_deleted) {
496                 $result = $dbh->Execute("SELECT * FROM $page_tbl $orderby $limit");
497             } else {
498                 $result = $dbh->Execute("SELECT "
499                                         . $this->page_tbl_fields
500                                         . " FROM $nonempty_tbl, $page_tbl"
501                                         . " WHERE $nonempty_tbl.id=$page_tbl.id"
502                                         . " $orderby $limit");
503             }
504         }
505         return new WikiDB_backend_ADODB_iter($this, $result);
506     }
507         
508     /**
509      * Title search.
510      */
511     function text_search($search = '', $fullsearch = false) {
512         $dbh = &$this->_dbh;
513         extract($this->_table_names);
514         
515         $table = "$nonempty_tbl, $page_tbl";
516         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
517         $fields = $this->page_tbl_fields;
518         $callback = new WikiMethodCb($this, '_sql_match_clause');
519         
520         if ($fullsearch) {
521             $table .= ", $recent_tbl";
522             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
523
524             $table .= ", $version_tbl";
525             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
526
527             $fields .= "," . $this->version_tbl_fields;
528             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
529         }
530         
531         $search_clause = $search->makeSqlClause($callback);
532         
533         $result = $dbh->Execute("SELECT $fields FROM $table"
534                                 . " WHERE $join_clause"
535                                 . "  AND ($search_clause)"
536                                 . " ORDER BY pagename");
537
538         return new WikiDB_backend_ADODB_iter($this, $result);
539     }
540
541     function _sql_match_clause($word) {
542         //not sure if we need this.  ADODB may do it for us
543         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  
544
545         // (we need it for at least % and _ --- they're the wildcard characters
546         //  for the LIKE operator, and we need to quote them if we're searching
547         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
548         //  work as is.
549         $word = $this->_dbh->qstr("%$word%");
550         $page_tbl = $this->_table_names['page_tbl'];
551         return "LOWER($page_tbl.pagename) LIKE $word";
552     }
553
554     function _fullsearch_sql_match_clause($word) {
555         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
556         // (see above)
557         $word = $this->_dbh->qstr("%$word%");
558         $page_tbl = $this->_table_names['page_tbl'];
559         return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
560     }
561
562     /**
563      * Find highest or lowest hit counts.
564      */
565     function most_popular($limit=20,$sortby = '') {
566         $dbh = &$this->_dbh;
567         extract($this->_table_names);
568         $order = "DESC";
569         if ($limit < 0){ 
570             $order = "ASC"; 
571             $limit = -$limit;
572         }
573         if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
574         else         $orderby = "ORDER BY hits $order";
575         $limit = $limit ? $limit : -1;
576         $result = $dbh->SelectLimit("SELECT " 
577                                     . $this->page_tbl_fields
578                                     . " FROM $nonempty_tbl, $page_tbl"
579                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
580                                     . " $orderby"
581                                     , $limit);
582
583         return new WikiDB_backend_ADODB_iter($this, $result);
584     }
585
586     /**
587      * Find recent changes.
588      */
589     function most_recent($params) {
590         $limit = 0;
591         $since = 0;
592         $include_minor_revisions = false;
593         $exclude_major_revisions = false;
594         $include_all_revisions = false;
595         extract($params);
596
597         $dbh = &$this->_dbh;
598         extract($this->_table_names);
599
600         $pick = array();
601         if ($since)
602             $pick[] = "mtime >= $since";
603         
604         if ($include_all_revisions) {
605             // Include all revisions of each page.
606             $table = "$page_tbl, $version_tbl";
607             $join_clause = "$page_tbl.id=$version_tbl.id";
608
609             if ($exclude_major_revisions) {
610                 // Include only minor revisions
611                 $pick[] = "minor_edit <> 0";
612             }
613             elseif (!$include_minor_revisions) {
614                 // Include only major revisions
615                 $pick[] = "minor_edit = 0";
616             }
617         }
618         else {
619             $table = "$page_tbl, $recent_tbl";
620             $join_clause = "$page_tbl.id=$recent_tbl.id";
621             $table .= ", $version_tbl";
622             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
623                 
624             if ($exclude_major_revisions) {
625                 // Include only most recent minor revision
626                 $pick[] = 'version=latestminor';
627             }
628             elseif (!$include_minor_revisions) {
629                 // Include only most recent major revision
630                 $pick[] = 'version=latestmajor';
631             }
632             else {
633                 // Include only the latest revision (whether major or minor).
634                 $pick[] ='version=latestversion';
635             }
636         }
637         $order = "DESC";
638         if($limit < 0){
639             $order = "ASC";
640             $limit = -$limit;
641         }
642         $limit = $limit ? $limit : -1;
643         $where_clause = $join_clause;
644         if ($pick)
645             $where_clause .= " AND " . join(" AND ", $pick);
646
647         // FIXME: use SQL_BUFFER_RESULT for mysql?
648         // Use SELECTLIMIT for portability
649         $result = $dbh->SelectLimit("SELECT "
650                                     . $this->page_tbl_fields . ", " . $this->version_tbl_fields
651                                     . " FROM $table"
652                                     . " WHERE $where_clause"
653                                     . " ORDER BY mtime $order",
654                                     $limit);
655
656         return new WikiDB_backend_ADODB_iter($this, $result);
657     }
658
659     /**
660      * Rename page in the database.
661      */
662     function rename_page($pagename, $to) {
663         $dbh = &$this->_dbh;
664         extract($this->_table_names);
665         
666         $this->lock();
667         if ( ($id = $this->_get_pageid($pagename, false)) ) {
668             if ($new = $this->_get_pageid($to, false)) {
669                 //cludge alert!
670                 //this page does not exist (already verified before), but exists in the page table.
671                 //so we delete this page.
672                 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
673                                     $dbh->qstr($to)));
674             }
675             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
676                                 $dbh->qstr($to)));
677         }
678         $this->unlock();
679         return $id;
680     }
681
682     function _update_recent_table($pageid = false) {
683         $dbh = &$this->_dbh;
684         extract($this->_table_names);
685         extract($this->_expressions);
686
687         $pageid = (int)$pageid;
688
689         $this->lock();
690
691         $dbh->Execute("DELETE FROM $recent_tbl"
692                       . ( $pageid ? " WHERE id=$pageid" : ""));
693         
694         $dbh->Execute( "INSERT INTO $recent_tbl"
695                        . " (id, latestversion, latestmajor, latestminor)"
696                        . " SELECT id, $maxversion, $maxmajor, $maxminor"
697                        . " FROM $version_tbl"
698                      . ( $pageid ? " WHERE id=$pageid" : "")
699                        . " GROUP BY id" );
700         $this->unlock();
701     }
702
703     function _update_nonempty_table($pageid = false) {
704         $dbh = &$this->_dbh;
705         extract($this->_table_names);
706
707         $pageid = (int)$pageid;
708
709         $this->lock();
710
711         $dbh->Execute("DELETE FROM $nonempty_tbl"
712                       . ( $pageid ? " WHERE id=$pageid" : ""));
713
714         $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
715                       . " SELECT $recent_tbl.id"
716                       . " FROM $recent_tbl, $version_tbl"
717                       . " WHERE $recent_tbl.id=$version_tbl.id"
718                       . "       AND version=latestversion"
719                       . "  AND content<>''"
720                       . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
721
722         $this->unlock();
723     }
724
725
726     /**
727      * Grab a write lock on the tables in the SQL database.
728      *
729      * Calls can be nested.  The tables won't be unlocked until
730      * _unlock_database() is called as many times as _lock_database().
731      *
732      * @access protected
733      */
734     function lock($write_lock = true) {
735         if ($this->_lock_count++ == 0)
736             $this->_lock_tables($write_lock);
737     }
738
739     /**
740      * Actually lock the required tables.
741      */
742     function _lock_tables($write_lock) {
743         trigger_error("virtual", E_USER_ERROR);
744     }
745     
746     /**
747      * Release a write lock on the tables in the SQL database.
748      *
749      * @access protected
750      *
751      * @param $force boolean Unlock even if not every call to lock() has been matched
752      * by a call to unlock().
753      *
754      * @see _lock_database
755      */
756     function unlock($force = false) {
757         if ($this->_lock_count == 0)
758             return;
759         if (--$this->_lock_count <= 0 || $force) {
760             $this->_unlock_tables();
761             $this->_lock_count = 0;
762         }
763     }
764
765     /**
766      * Actually unlock the required tables.
767      */
768     function _unlock_tables($write_lock) {
769         trigger_error("virtual", E_USER_ERROR);
770     }
771 };
772
773 class WikiDB_backend_ADODB_generic_iter
774 extends WikiDB_backend_iterator
775 {
776     function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
777         $this->_backend = &$backend;
778         $this->_result = $query_result;
779     }
780     
781     function count() {
782         if (!$this->_result)
783             return false;
784         return $this->_result->numRows();
785     }
786
787     function next() {
788         $result = &$this->_result;
789         if (!$result || $result->EOF) {
790             $this->free();
791             return false;
792         }
793         $backend = &$this->_backend;
794
795 //      $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
796         $record = $result->fields;
797         $result->MoveNext();
798         return $record;
799     }
800
801     function free () {
802         if ($this->_result) {
803 //          $this->_result->free();
804             $this->_result->Close();
805             $this->_result = false;
806         }
807     }
808 }
809
810 class WikiDB_backend_ADODB_iter
811 extends WikiDB_backend_ADODB_generic_iter
812 {
813     function next() {
814         $result = &$this->_result;
815         if (!$result || $result->EOF) {
816             $this->free();
817             return false;
818         }
819
820 //      $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
821         $record = $result->fields;
822         $result->MoveNext();
823         
824         $backend = &$this->_backend;
825
826         $pagedata = $backend->_extract_page_data($record);
827         $rec = array('pagename' => $record['pagename'],
828                      'pagedata' => $pagedata);
829
830         if (!empty($record['version'])) {
831             $rec['versiondata'] = $backend->_extract_version_data($record);
832             $rec['version'] = $record['version'];
833         }
834         
835         return $rec;
836     }
837 }
838
839 // Following function taken from adodb-pear.inc.php.  
840 // Eventually, change index.php to provide the relevant information
841 // directly?
842     /**
843      * Parse a data source name
844      *
845      * @param $dsn string Data Source Name to be parsed
846      *
847      * @return array an associative array with the following keys:
848      *
849      *  phptype: Database backend used in PHP (mysql, odbc etc.)
850      *  dbsyntax: Database used with regards to SQL syntax etc.
851      *  protocol: Communication protocol to use (tcp, unix etc.)
852      *  hostspec: Host specification (hostname[:port])
853      *  database: Database to use on the DBMS server
854      *  username: User name for login
855      *  password: Password for login
856      *
857      * The format of the supplied DSN is in its fullest form:
858      *
859      *  phptype(dbsyntax)://username:password@protocol+hostspec/database
860      *
861      * Most variations are allowed:
862      *
863      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
864      *  phptype://username:password@hostspec/database_name
865      *  phptype://username:password@hostspec
866      *  phptype://username@hostspec
867      *  phptype://hostspec/database
868      *  phptype://hostspec
869      *  phptype(dbsyntax)
870      *  phptype
871      *
872      * @author Tomas V.V.Cox <cox@idecnet.com>
873      */
874     function parseDSN($dsn) {
875         if (is_array($dsn)) {
876             return $dsn;
877         }
878
879         $parsed = array(
880             'phptype'  => false,
881             'dbsyntax' => false,
882             'protocol' => false,
883             'hostspec' => false,
884             'database' => false,
885             'username' => false,
886             'password' => false
887         );
888
889         // Find phptype and dbsyntax
890         if (($pos = strpos($dsn, '://')) !== false) {
891             $str = substr($dsn, 0, $pos);
892             $dsn = substr($dsn, $pos + 3);
893         } else {
894             $str = $dsn;
895             $dsn = NULL;
896         }
897
898         // Get phptype and dbsyntax
899         // $str => phptype(dbsyntax)
900         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
901             $parsed['phptype'] = $arr[1];
902             $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
903         } else {
904             $parsed['phptype'] = $str;
905             $parsed['dbsyntax'] = $str;
906         }
907
908         if (empty($dsn)) {
909             return $parsed;
910         }
911
912         // Get (if found): username and password
913         // $dsn => username:password@protocol+hostspec/database
914         if (($at = strpos($dsn,'@')) !== false) {
915             $str = substr($dsn, 0, $at);
916             $dsn = substr($dsn, $at + 1);
917             if (($pos = strpos($str, ':')) !== false) {
918                 $parsed['username'] = urldecode(substr($str, 0, $pos));
919                 $parsed['password'] = urldecode(substr($str, $pos + 1));
920             } else {
921                 $parsed['username'] = urldecode($str);
922             }
923         }
924
925         // Find protocol and hostspec
926         // $dsn => protocol+hostspec/database
927         if (($pos = strpos($dsn, '/')) !== false) {
928             $str = substr($dsn, 0, $pos);
929             $dsn = substr($dsn, $pos + 1);
930         } else {
931             $str = $dsn;
932             $dsn = NULL;
933         }
934
935         // Get protocol + hostspec
936         // $str => protocol+hostspec
937         if (($pos = strpos($str, '+')) !== false) {
938             $parsed['protocol'] = substr($str, 0, $pos);
939             $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
940         } else {
941             $parsed['hostspec'] = urldecode($str);
942         }
943
944         // Get dabase if any
945         // $dsn => database
946         if (!empty($dsn)) {
947             $parsed['database'] = $dsn;
948         }
949
950         return $parsed;
951     }
952
953
954
955 // (c-file-style: "gnu")
956 // Local Variables:
957 // mode: php
958 // tab-width: 8
959 // c-basic-offset: 4
960 // c-hanging-comment-ender-p: nil
961 // indent-tabs-mode: nil
962 // End:   
963 ?>