]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/backend/ADODB.php
Use backend specific sortby and sortable_columns method, to be able to
[SourceForge/phpwiki.git] / lib / WikiDB / backend / ADODB.php
1 <?php // -*-php-*-
2 rcs_id('$Id: ADODB.php,v 1.42 2004-07-09 10:06:50 rurban Exp $');
3
4 /*
5  Copyright 2002,2004 $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, Reini Urban
28  *
29  * Now (phpwiki-1.3.10) with adodb-4.22, by Reini Urban:
30  * 1) Extended to use all available database backend, not only mysql.
31  * 2) It uses the ultra-fast binary adodb extension if loaded.
32  * 3) We use FETCH_NUM instead of FETCH_ASSOC (faster and more generic)
33  * 4) To support generic iterators which return ASSOC fields, and to support queries with 
34  *    variable columns, some trickery was needed to use recordset specific fetchMode.
35  *    The first Execute uses the global fetchMode (ASSOC), then it's resetted back to NUM 
36  *    and the recordset fetchmode is set to ASSOC.
37  * 5) Transaction support, and locking as fallback.
38  *
39  * ADODB basic differences to PearDB: It pre-fetches the first row into fields, 
40  * is dirtier in style, layout and more low-level ("worse is better").
41  * It has less needed basic features (modifyQuery, locks, ...), but some more 
42  * unneeded features included: paging, monitoring and sessions, and much more drivers.
43  * No locking (which PearDB supports in some backends), and sequences are very 
44  * bad compared to PearDB.
45
46  * Old Comments, by Lawrence Akka:
47  * 1)  ADODB's GetRow() is slightly different from that in PEAR.  It does not 
48  *     accept a fetchmode parameter
49  *     That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
50  * 2)  No need for ''s around strings in sprintf arguments - qstr puts them 
51  *     there automatically
52  * 3)  ADODB has a version of GetOne, but it is difficult to use it when 
53  *     FETCH_ASSOC is in effect.
54  *     Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
55  * 4)  No error handling yet - could use ADOConnection->raiseErrorFn
56  * 5)  It used to be faster then PEAR/DB at the beginning of 2002. 
57  *     Now at August 2002 PEAR/DB with our own page cache added, 
58  *     performance is comparable.
59  */
60
61 require_once('lib/WikiDB/backend.php');
62 // Error handling - calls trigger_error.  NB - does not close the connection.  Does it need to?
63 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
64 // include the main adodb file
65 require_once('lib/WikiDB/adodb/adodb.inc.php');
66
67 class WikiDB_backend_ADODB
68 extends WikiDB_backend
69 {
70
71     function WikiDB_backend_ADODB ($dbparams) {
72         $parsed = parseDSN($dbparams['dsn']);
73         $this->_dbparams = $dbparams;
74         $this->_dbh = &ADONewConnection($parsed['phptype']);
75         $this->_dsn = $parsed;
76         if (!empty($parsed['persistent']))
77             $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'], 
78                                          $parsed['password'], $parsed['database']);
79         else
80             $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'], 
81                                          $parsed['password'], $parsed['database']);
82
83         //$this->_dbh->debug = true;
84         
85         // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
86         // with some ASSOC based recordsets.
87         $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
88         $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
89
90         // Old comment:
91         //  With ADODB_COUNTRECS false it should speed up queries, but:
92         //  1)  It only works with PHP >= 4.0.6; and
93         //  2)  At the moment, I haven't figured out why the wrong results are returned'
94         $GLOBALS['ADODB_COUNTRECS'] = false;
95
96         $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
97         $this->_table_names
98             = array('page_tbl'     => $prefix . 'page',
99                     'version_tbl'  => $prefix . 'version',
100                     'link_tbl'     => $prefix . 'link',
101                     'recent_tbl'   => $prefix . 'recent',
102                     'nonempty_tbl' => $prefix . 'nonempty');
103         $page_tbl = $this->_table_names['page_tbl'];
104         $version_tbl = $this->_table_names['version_tbl'];
105         $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
106             . "$page_tbl.hits hits";
107         $this->version_tbl_fields = "$version_tbl.version AS version, "
108             . "$version_tbl.mtime AS mtime, "
109             . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
110             . "$version_tbl.versiondata AS versiondata";
111
112         $this->_expressions
113             = array('maxmajor'     => "MAX(CASE WHEN minor_edit=0 THEN version END)",
114                     'maxminor'     => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
115                     'maxversion'   => "MAX(version)",
116                     'notempty'     => "<>''",
117                     'iscontent'    => "content<>''");
118         $this->_lock_count = 0;
119     }
120
121     /**
122      * Close database connection.
123      */
124     function close () {
125         if (!$this->_dbh)
126             return;
127         if ($this->_lock_count) {
128             trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
129                           E_USER_WARNING);
130         }
131 //      $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT);        // prevent recursive loops.
132         $this->unlock(false,'force');
133
134         $this->_dbh->close();
135         $this->_dbh = false;
136     }
137
138     /*
139      * Fast test for wikipage.
140      */
141     function is_wiki_page($pagename) {
142         $dbh = &$this->_dbh;
143         extract($this->_table_names);
144         $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
145                                     . " FROM $nonempty_tbl, $page_tbl"
146                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
147                                     . "   AND pagename=%s",
148                                     $dbh->qstr($pagename)));
149         return $row ? $row[0] : false;
150     }
151         
152     function get_all_pagenames() {
153         $dbh = &$this->_dbh;
154         extract($this->_table_names);
155         $result = $dbh->Execute("SELECT pagename"
156                                 . " FROM $nonempty_tbl, $page_tbl"
157                                 . " WHERE $nonempty_tbl.id=$page_tbl.id");
158         return $result->GetArray();
159     }
160
161     function numPages($filter=false, $exclude='') {
162         $dbh = &$this->_dbh;
163         extract($this->_table_names);
164         $result = $dbh->getRow("SELECT count(*)"
165                             . " FROM $nonempty_tbl, $page_tbl"
166                             . " WHERE $nonempty_tbl.id=$page_tbl.id");
167         return $result[0];
168     }
169     
170     /**
171      * Read page information from database.
172      */
173     function get_pagedata($pagename) {
174         $dbh = &$this->_dbh;
175         $page_tbl = $this->_table_names['page_tbl'];
176         $row = $dbh->GetRow(sprintf("SELECT hits, pagedata FROM $page_tbl WHERE pagename=%s",
177                                        $dbh->qstr($pagename)));
178         return $row ? $this->_extract_page_data($row[1],$row[0]) : false;
179     }
180
181     function  _extract_page_data(&$data, $hits) {
182         $pagedata = empty($data) ? array() : unserialize($data);
183         $pagedata['hits'] = $hits;
184         return $pagedata;
185     }
186
187     function update_pagedata($pagename, $newdata) {
188         $dbh = &$this->_dbh;
189         $page_tbl = $this->_table_names['page_tbl'];
190
191         // Hits is the only thing we can update in a fast manner.
192         if (count($newdata) == 1 && isset($newdata['hits'])) {
193             // Note that this will fail silently if the page does not
194             // have a record in the page table.  Since it's just the
195             // hit count, who cares?
196             $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
197                                   $newdata['hits'], $dbh->qstr($pagename)));
198             return;
199         }
200         $where = sprintf("pagename=%s",$dbh->qstr($pagename));
201         $dbh->BeginTrans( );
202         $dbh->RowLock($page_tbl,$where);
203         
204         $data = $this->get_pagedata($pagename);
205         if (!$data) {
206             $data = array();
207             $this->_get_pageid($pagename, true); // Creates page record
208         }
209         
210         @$hits = (int)$data['hits'];
211         unset($data['hits']);
212
213         foreach ($newdata as $key => $val) {
214             if ($key == 'hits')
215                 $hits = (int)$val;
216             else if (empty($val))
217                 unset($data[$key]);
218             else
219                 $data[$key] = $val;
220         }
221         // FIXME: some DBMs dont support huge strings (pagedata), so we have to bind it.
222         if ($dbh->Execute(sprintf("UPDATE $page_tbl"
223                                   . " SET hits=%d, pagedata=%s"
224                                   . " WHERE pagename=%s",
225                                   $hits,
226                                   $dbh->qstr(serialize($data)),
227                                   $dbh->qstr($pagename))))
228             $dbh->CommitTrans( );
229         else
230             $dbh->RollbackTrans( );
231     }
232
233     function _get_pageid($pagename, $create_if_missing = false) {
234         
235         $dbh = &$this->_dbh;
236         $page_tbl = $this->_table_names['page_tbl'];
237         $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
238                          $dbh->qstr($pagename));
239         if (! $create_if_missing ) {
240             $row = $dbh->GetRow($query);
241             return $row ? $row[0] : false;
242         }
243         $row = $dbh->GetRow($query);
244         if (! $row ) {
245             //mysql, mysqli or mysqlt
246             if (substr($dbh->databaseType,0,5) == 'mysql') {
247                 // have auto-incrementing, atomic version
248                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
249                                             . " (pagename,hits)"
250                                             . " VALUES(%s,0)",
251                                             $dbh->qstr($pagename)));
252                 $id = $dbh->_insertid();
253             } else {
254                 //$id = $dbh->GenID($page_tbl . 'seq');
255                 // Better generic version than with adodob::genID
256                 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
257                 $this->lock(array('page'));
258                 $dbh->BeginTrans( );
259                 $dbh->CommitLock($page_tbl);
260                 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
261                 $id = $row[0] + 1;
262                 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
263                                             . " (id,pagename,hits)"
264                                             . " VALUES (%d,%s,0)",
265                                             $id, $dbh->qstr($pagename)));
266                 if ($rs) $dbh->CommitTrans( );
267                 else $dbh->RollbackTrans( );
268                 $this->unlock(array('page'));
269             }
270         } else {
271             $id = $row[0];
272         }
273         return $id;
274     }
275
276     function get_latest_version($pagename) {
277         $dbh = &$this->_dbh;
278         extract($this->_table_names);
279         $row = $dbh->GetRow(sprintf("SELECT latestversion"
280                                     . " FROM $page_tbl, $recent_tbl"
281                                     . " WHERE $page_tbl.id=$recent_tbl.id"
282                                     . "  AND pagename=%s",
283                                     $dbh->qstr($pagename)));
284         return $row ? (int)$row[0] : false;
285     }
286
287     function get_previous_version($pagename, $version) {
288         $dbh = &$this->_dbh;
289         extract($this->_table_names);
290         // Use SELECTLIMIT for maximum portability
291         $rs = $dbh->SelectLimit(sprintf("SELECT version"
292                                         . " FROM $version_tbl, $page_tbl"
293                                         . " WHERE $version_tbl.id=$page_tbl.id"
294                                         . "  AND pagename=%s"
295                                         . "  AND version < %d"
296                                         . " ORDER BY version DESC"
297                                         ,$dbh->qstr($pagename),
298                                         $version),
299                                 1);
300         return $rs->fields[0] ? (int)$rs->fields[0] : false;
301     }
302     
303     /**
304      * Get version data.
305      *
306      * @param $version int Which version to get.
307      *
308      * @return hash The version data, or false if specified version does not
309      *              exist.
310      */
311     function get_versiondata($pagename, $version, $want_content = false) {
312         $dbh = &$this->_dbh;
313         extract($this->_table_names);
314                 
315         assert(is_string($pagename) and $pagename != '');
316         assert($version > 0);
317         
318         // FIXME: optimization: sometimes don't get page data?
319         if ($want_content) {
320             $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
321                 . ', ' . $this->version_tbl_fields;
322         } else {
323             $fields = $this->page_tbl_fields . ", ''"
324                 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
325                 . "$version_tbl.minor_edit AS minor_edit, ". $this->_expressions['iscontent']. " as have_content, "
326                 . "$version_tbl.versiondata as versiondata";
327         }
328         $row = $dbh->GetRow(sprintf("SELECT $fields"
329                                     . " FROM $page_tbl, $version_tbl"
330                                     . " WHERE $page_tbl.id=$version_tbl.id"
331                                     . "  AND pagename=%s"
332                                     . "  AND version=%d",
333                                     $dbh->qstr($pagename), $version));
334         return $row ? $this->_extract_version_data_num($row, $want_content) : false;
335     }
336
337     function _extract_version_data_num(&$row, $want_content) {
338         if (!$row)
339             return false;
340
341         //$id       &= $row[0];
342         //$pagename &= $row[1];
343         $data = empty($row[8]) ? array() : unserialize($row[8]);
344         $data['mtime']         = $row[5];
345         $data['is_minor_edit'] = !empty($row[6]);
346         if ($want_content) {
347             $data['%content'] = $row[7];
348         } else {
349             $data['%content'] = !empty($row[7]);
350         }
351         if (!empty($row[3])) {
352             $data['%pagedata'] = $this->_extract_page_data($row[3],$row[2]);
353         }
354         return $data;
355     }
356
357     function _extract_version_data_assoc(&$row) {
358         if (!$row)
359             return false;
360
361         extract($row);
362         $data = empty($versiondata) ? array() : unserialize($versiondata);
363         $data['mtime'] = $mtime;
364         $data['is_minor_edit'] = !empty($minor_edit);
365         if (isset($content))
366             $data['%content'] = $content;
367         elseif ($have_content)
368             $data['%content'] = true;
369         else
370             $data['%content'] = '';
371         if (!empty($pagedata)) {
372             $data['%pagedata'] = $this->_extract_page_data($pagedata,$hits);
373         }
374         return $data;
375     }
376
377     /**
378      * Create a new revision of a page.
379      */
380     function set_versiondata($pagename, $version, $data) {
381         $dbh = &$this->_dbh;
382         $version_tbl = $this->_table_names['version_tbl'];
383         
384         $minor_edit = (int) !empty($data['is_minor_edit']);
385         unset($data['is_minor_edit']);
386         
387         $mtime = (int)$data['mtime'];
388         unset($data['mtime']);
389         assert(!empty($mtime));
390
391         @$content = (string) $data['%content'];
392         unset($data['%content']);
393         unset($data['%pagedata']);
394         
395         $this->lock(array('page','recent','version','nonempty'));
396         $dbh->BeginTrans( );
397         $dbh->CommitLock($version_tbl);
398         $id = $this->_get_pageid($pagename, true);
399         $backend_type = $this->backendType();
400         // optimize: mysql can do this with one REPLACE INTO.
401         if (substr($backend_type,0,5) == 'mysql') {
402             $rs = $dbh->Execute(sprintf("REPLACE INTO $version_tbl"
403                                   . " (id,version,mtime,minor_edit,content,versiondata)"
404                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
405                                   $id, $version, $mtime, $minor_edit,
406                                   $dbh->qstr($content),
407                                   $dbh->qstr(serialize($data))));
408         } else {
409             $dbh->Execute(sprintf("DELETE FROM $version_tbl"
410                                   . " WHERE id=%d AND version=%d",
411                                   $id, $version));
412             $rs = $dbh->Execute(sprintf("INSERT INTO $version_tbl"
413                                   . " (id,version,mtime,minor_edit,content,versiondata)"
414                                   . " VALUES(%d,%d,%d,%d,%s,%s)",
415                                   $id, $version, $mtime, $minor_edit,
416                                   $dbh->qstr($content),
417                                   $dbh->qstr(serialize($data))));
418         }
419         $this->_update_recent_table($id);
420         $this->_update_nonempty_table($id);
421         if ($rs) $dbh->CommitTrans( );
422         else $dbh->RollbackTrans( );
423         $this->unlock(array('page','recent','version','nonempty'));
424     }
425     
426     /**
427      * Delete an old revision of a page.
428      */
429     function delete_versiondata($pagename, $version) {
430         $dbh = &$this->_dbh;
431         extract($this->_table_names);
432
433         $this->lock(array('version'));
434         if ( ($id = $this->_get_pageid($pagename)) ) {
435             $dbh->Execute("DELETE FROM $version_tbl"
436                         . " WHERE id=$id AND version=$version");
437             $this->_update_recent_table($id);
438             // This shouldn't be needed (as long as the latestversion
439             // never gets deleted.)  But, let's be safe.
440             $this->_update_nonempty_table($id);
441         }
442         $this->unlock(array('version'));
443     }
444
445     /**
446      * Delete page from the database.
447      */
448     function delete_page($pagename) {
449         $dbh = &$this->_dbh;
450         extract($this->_table_names);
451         
452         $this->lock(array('version','recent','nonempty','page','link'));
453         if ( ($id = $this->_get_pageid($pagename, false)) ) {
454             $dbh->Execute("DELETE FROM $version_tbl  WHERE id=$id");
455             $dbh->Execute("DELETE FROM $recent_tbl   WHERE id=$id");
456             $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
457             $dbh->Execute("DELETE FROM $link_tbl     WHERE linkfrom=$id");
458             $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
459             if ($row and $row[0]) {
460                 // We're still in the link table (dangling link) so we can't delete this
461                 // altogether.
462                 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
463             }
464             else {
465                 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
466             }
467             $this->_update_recent_table();
468             $this->_update_nonempty_table();
469         }
470         $this->unlock(array('version','recent','nonempty','page','link'));
471     }
472             
473
474     // The only thing we might be interested in updating which we can
475     // do fast in the flags (minor_edit).   I think the default
476     // update_versiondata will work fine...
477     //function update_versiondata($pagename, $version, $data) {
478     //}
479
480     function set_links($pagename, $links) {
481         // Update link table.
482         // FIXME: optimize: mysql can do this all in one big INSERT.
483
484         $dbh = &$this->_dbh;
485         extract($this->_table_names);
486
487         $this->lock(array('link'));
488         $pageid = $this->_get_pageid($pagename, true);
489
490         $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
491
492         if ($links) {
493             foreach($links as $link) {
494                 if (isset($linkseen[$link]))
495                     continue;
496                 $linkseen[$link] = true;
497                 $linkid = $this->_get_pageid($link, true);
498                 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
499                             . " VALUES ($pageid, $linkid)");
500             }
501         }
502         $this->unlock(array('link'));
503     }
504     
505     /**
506      * Find pages which link to or are linked from a page.
507      */
508     function get_links($pagename, $reversed = true) {
509         $dbh = &$this->_dbh;
510         extract($this->_table_names);
511
512         if ($reversed)
513             list($have,$want) = array('linkee', 'linker');
514         else
515             list($have,$want) = array('linker', 'linkee');
516
517         $qpagename = $dbh->qstr($pagename);
518         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
519         // removed ref to FETCH_MODE in next line
520         $result = $dbh->Execute("SELECT $want.id AS id, $want.pagename AS pagename,"
521                                 . " $want.hits AS hits"
522                                 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
523                                 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
524                                 . " AND $have.pagename=$qpagename"
525                                 //. " GROUP BY $want.id"
526                                 . " ORDER BY $want.pagename");
527         $dbh->SetFetchMode(ADODB_FETCH_NUM);
528         return new WikiDB_backend_ADODB_iter($this, $result);
529     }
530
531     function get_all_pages($include_deleted=false, $sortby=false, $limit=false) {
532         $dbh = &$this->_dbh;
533         extract($this->_table_names);
534         //if ($limit)  $limit = "LIMIT $limit";
535         //else         $limit = '';
536         $orderby = $this->sortby($sortby, 'db');
537         if ($orderby) $orderby = 'ORDER BY ' . $orderby;
538         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
539         if (strstr($orderby, 'mtime')) { // was ' mtime'
540             if ($include_deleted) {
541                 $sql = "SELECT "
542                     . $this->page_tbl_fields
543                     ." FROM $page_tbl, $recent_tbl, $version_tbl"
544                     . " WHERE $page_tbl.id=$recent_tbl.id"
545                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
546                     . " $orderby";
547             }
548             else {
549                 $sql = "SELECT "
550                     . $this->page_tbl_fields
551                     . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
552                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
553                     . " AND $page_tbl.id=$recent_tbl.id"
554                     . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
555                     . " $orderby";
556             }
557         } else {
558             if ($include_deleted) {
559                 $sql = "SELECT "
560                     . $this->page_tbl_fields
561                     . " FROM $page_tbl $orderby";
562             } else {
563                 $sql = "SELECT "
564                     . $this->page_tbl_fields
565                     . " FROM $nonempty_tbl, $page_tbl"
566                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
567                     . " $orderby";
568             }
569         }
570         if ($limit) {
571             // extract from,count from limit
572             list($offset,$count) = $this->limit($limit);
573             $result = $dbh->SelectLimit($sql, $count, $offset);
574         } else {
575             $result = $dbh->Execute($sql);
576         }
577         $dbh->SetFetchMode(ADODB_FETCH_NUM);
578         return new WikiDB_backend_ADODB_iter($this, $result);
579     }
580         
581     /**
582      * Title search.
583      */
584     function text_search($search = '', $fullsearch = false) {
585         $dbh = &$this->_dbh;
586         extract($this->_table_names);
587         
588         $table = "$nonempty_tbl, $page_tbl";
589         $join_clause = "$nonempty_tbl.id=$page_tbl.id";
590         $fields = $this->page_tbl_fields;
591         $callback = new WikiMethodCb($this, '_sql_match_clause');
592         
593         if ($fullsearch) {
594             $table .= ", $recent_tbl";
595             $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
596
597             $table .= ", $version_tbl";
598             $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
599
600             $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
601             $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
602         }
603         
604         $search_clause = $search->makeSqlClause($callback);
605         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
606         $result = $dbh->Execute("SELECT $fields FROM $table"
607                                 . " WHERE $join_clause"
608                                 . "  AND ($search_clause)"
609                                 . " ORDER BY pagename");
610
611         $dbh->SetFetchMode(ADODB_FETCH_NUM);
612         return new WikiDB_backend_ADODB_iter($this, $result);
613     }
614
615     function _sql_match_clause($word) {
616         //not sure if we need this.  ADODB may do it for us
617         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  
618
619         // (we need it for at least % and _ --- they're the wildcard characters
620         //  for the LIKE operator, and we need to quote them if we're searching
621         //  for literal '%'s or '_'s.  --- I'm not sure about \, but it seems to
622         //  work as is.
623         $word = $this->_dbh->qstr("%".strtolower($word)."%");
624         $page_tbl = $this->_table_names['page_tbl'];
625         return "LOWER($page_tbl.pagename) LIKE $word";
626     }
627
628     function _fullsearch_sql_match_clause($word) {
629         $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);  //not sure if we need this
630         // (see above)
631         $word = $this->_dbh->qstr("%".strtolower($word)."%");
632         $page_tbl = $this->_table_names['page_tbl'];
633         return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
634     }
635
636     /**
637      * Find highest or lowest hit counts.
638      */
639     function most_popular($limit=0, $sortby = '') {
640         $dbh = &$this->_dbh;
641         extract($this->_table_names);
642         $order = "DESC";
643         if ($limit < 0){ 
644             $order = "ASC"; 
645             $limit = -$limit;
646             $where = "";
647         } else {
648             $where = " AND hits > 0";
649         }
650         if ($sortby) $orderby = " ORDER BY " . $this->sortby($sortby, 'db');
651         else         $orderby = " ORDER BY hits $order";
652         $limit = $limit ? $limit : -1;
653
654         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
655         $result = $dbh->SelectLimit("SELECT " 
656                                     . $this->page_tbl_fields
657                                     . " FROM $nonempty_tbl, $page_tbl"
658                                     . " WHERE $nonempty_tbl.id=$page_tbl.id"
659                                     . $where
660                                     . $orderby, $limit);
661         $dbh->SetFetchMode(ADODB_FETCH_NUM);
662         return new WikiDB_backend_ADODB_iter($this, $result);
663     }
664
665     /**
666      * Find recent changes.
667      */
668     function most_recent($params) {
669         $limit = 0;
670         $since = 0;
671         $include_minor_revisions = false;
672         $exclude_major_revisions = false;
673         $include_all_revisions = false;
674         extract($params);
675
676         $dbh = &$this->_dbh;
677         extract($this->_table_names);
678
679         $pick = array();
680         if ($since)
681             $pick[] = "mtime >= $since";
682         
683         if ($include_all_revisions) {
684             // Include all revisions of each page.
685             $table = "$page_tbl, $version_tbl";
686             $join_clause = "$page_tbl.id=$version_tbl.id";
687
688             if ($exclude_major_revisions) {
689                 // Include only minor revisions
690                 $pick[] = "minor_edit <> 0";
691             }
692             elseif (!$include_minor_revisions) {
693                 // Include only major revisions
694                 $pick[] = "minor_edit = 0";
695             }
696         }
697         else {
698             $table = "$page_tbl, $recent_tbl";
699             $join_clause = "$page_tbl.id=$recent_tbl.id";
700             $table .= ", $version_tbl";
701             $join_clause .= " AND $version_tbl.id=$page_tbl.id";
702                 
703             if ($exclude_major_revisions) {
704                 // Include only most recent minor revision
705                 $pick[] = 'version=latestminor';
706             }
707             elseif (!$include_minor_revisions) {
708                 // Include only most recent major revision
709                 $pick[] = 'version=latestmajor';
710             }
711             else {
712                 // Include only the latest revision (whether major or minor).
713                 $pick[] ='version=latestversion';
714             }
715         }
716         $order = "DESC";
717         if($limit < 0){
718             $order = "ASC";
719             $limit = -$limit;
720         }
721         $limit = $limit ? $limit : -1;
722         $where_clause = $join_clause;
723         if ($pick)
724             $where_clause .= " AND " . join(" AND ", $pick);
725
726         // FIXME: use SQL_BUFFER_RESULT for mysql?
727         // Use SELECTLIMIT for portability
728         $dbh->SetFetchMode(ADODB_FETCH_ASSOC);
729         $result = $dbh->SelectLimit("SELECT "
730                                     . $this->page_tbl_fields . ", " . $this->version_tbl_fields
731                                     . " FROM $table"
732                                     . " WHERE $where_clause"
733                                     . " ORDER BY mtime $order",
734                                     $limit);
735         $dbh->SetFetchMode(ADODB_FETCH_NUM);
736         //$result->fields['version'] = $result->fields[6];
737         return new WikiDB_backend_ADODB_iter($this, $result);
738     }
739
740     /**
741      * Rename page in the database.
742      */
743     function rename_page($pagename, $to) {
744         $dbh = &$this->_dbh;
745         extract($this->_table_names);
746         
747         $this->lock(array('page'));
748         if ( ($id = $this->_get_pageid($pagename, false)) ) {
749             if ($new = $this->_get_pageid($to, false)) {
750                 //cludge alert!
751                 //this page does not exist (already verified before), but exists in the page table.
752                 //so we delete this page.
753                 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
754                                     $dbh->qstr($to)));
755             }
756             $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
757                                 $dbh->qstr($to)));
758         }
759         $this->unlock(array('page'));
760         return $id;
761     }
762
763     function _update_recent_table($pageid = false) {
764         $dbh = &$this->_dbh;
765         extract($this->_table_names);
766         extract($this->_expressions);
767
768         $pageid = (int)$pageid;
769
770         // optimize: mysql can do this with one REPLACE INTO.
771         $backend_type = $this->backendType();
772         if (substr($backend_type,0,5) == 'mysql') {
773             $dbh->Execute("REPLACE INTO $recent_tbl"
774                           . " (id, latestversion, latestmajor, latestminor)"
775                           . " SELECT id, $maxversion, $maxmajor, $maxminor"
776                           . " FROM $version_tbl"
777                           . ( $pageid ? " WHERE id=$pageid" : "")
778                           . " GROUP BY id" );
779         } else {
780             $this->lock(array('recent'));
781             $dbh->Execute("DELETE FROM $recent_tbl"
782                       . ( $pageid ? " WHERE id=$pageid" : ""));
783             $dbh->Execute( "INSERT INTO $recent_tbl"
784                            . " (id, latestversion, latestmajor, latestminor)"
785                            . " SELECT id, $maxversion, $maxmajor, $maxminor"
786                            . " FROM $version_tbl"
787                            . ( $pageid ? " WHERE id=$pageid" : "")
788                            . " GROUP BY id" );
789             $this->unlock(array('recent'));
790         }
791     }
792
793     function _update_nonempty_table($pageid = false) {
794         $dbh = &$this->_dbh;
795         extract($this->_table_names);
796
797         $pageid = (int)$pageid;
798
799         // Optimize: mysql can do this with one REPLACE INTO.
800         // FIXME: This treally should be moved into ADODB_mysql.php but 
801         // then it must be duplicated for mysqli and mysqlt also.
802         $backend_type = $this->backendType();
803         if (substr($backend_type,0,5) == 'mysql') {
804             $dbh->Execute("REPLACE INTO $nonempty_tbl (id)"
805                           . " SELECT $recent_tbl.id"
806                           . " FROM $recent_tbl, $version_tbl"
807                           . " WHERE $recent_tbl.id=$version_tbl.id"
808                           . "       AND version=latestversion"
809                           . "  AND content<>''"
810                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
811         } else {
812             extract($this->_expressions);
813             $this->lock(array('nonempty'));
814             $dbh->Execute("DELETE FROM $nonempty_tbl"
815                           . ( $pageid ? " WHERE id=$pageid" : ""));
816             $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
817                           . " SELECT $recent_tbl.id"
818                           . " FROM $recent_tbl, $version_tbl"
819                           . " WHERE $recent_tbl.id=$version_tbl.id"
820                           . "       AND version=latestversion"
821                           // We have some specifics here (Oracle)
822                           //. "  AND content<>''"
823                           . "  AND content $notempty"
824                           . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
825             $this->unlock(array('nonempty'));
826         }
827     }
828
829
830     /**
831      * Grab a write lock on the tables in the SQL database.
832      *
833      * Calls can be nested.  The tables won't be unlocked until
834      * _unlock_database() is called as many times as _lock_database().
835      *
836      * @access protected
837      */
838     function lock($tables, $write_lock = true) {
839         $this->_dbh->StartTrans();
840         if ($this->_lock_count++ == 0) {
841             $this->_current_lock = $tables;
842             $this->_lock_tables($tables, $write_lock);
843         }
844     }
845
846     /**
847      * Overridden by non-transaction safe backends.
848      */
849     function _lock_tables($tables, $write_lock) {
850         return $this->_current_lock;
851     }
852     
853     /**
854      * Release a write lock on the tables in the SQL database.
855      *
856      * @access protected
857      *
858      * @param $force boolean Unlock even if not every call to lock() has been matched
859      * by a call to unlock().
860      *
861      * @see _lock_database
862      */
863     function unlock($tables = false, $force = false) {
864         if ($this->_lock_count == 0) {
865             $this->_dbh->CompleteTrans(! $force);
866             $this->_current_lock = false;
867             return;
868         }
869         if (--$this->_lock_count <= 0 || $force) {
870             $this->_unlock_tables($tables);
871             $this->_current_lock = false;
872             $this->_lock_count = 0;
873         }
874         $this->_dbh->CompleteTrans(! $force);
875     }
876
877     /**
878      * overridden by non-transaction safe backends
879      */
880     function _unlock_tables($tables, $write_lock) {
881         return;
882     }
883
884     /* some variables and functions for DB backend abstraction (action=upgrade) */
885     function database () {
886         return $this->_dbh->database;
887     }
888     function backendType() {
889         return $this->_dbh->databaseType;
890     }
891     function connection() {
892         return $this->_dbh->_connectionID;
893     }
894
895     function listOfTables() {
896         return $this->_dbh->MetaTables();
897     }
898     function listOfFields($database,$table) {
899         $field_list = array();
900         foreach ($this->_dbh->MetaColumns($table,false) as $field) {
901             $field_list[] = $field->name;
902         }
903         return $field_list;
904     }
905
906 };
907
908 class WikiDB_backend_ADODB_generic_iter
909 extends WikiDB_backend_iterator
910 {
911     function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
912         $this->_backend = &$backend;
913         $this->_result = $query_result;
914     }
915     
916     function count() {
917         if (!$this->_result) {
918             return false;
919         }
920         return $this->_result->numRows();
921     }
922
923     function next() {
924         $result = &$this->_result;
925         $backend = &$this->_backend;
926         if (!$result || $result->EOF) {
927             $this->free();
928             return false;
929         }
930         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
931             $result->fetchMode = 1;
932         else
933             $result->fetchMode = 2;
934         $record = $result->fields;
935         if (isset($record[0])) {
936             $record = $result->GetRowAssoc(2);
937         } else {
938             $record = $result->fields;
939         }
940         $result->MoveNext();
941         return $record;
942     }
943
944     function free () {
945         if ($this->_result) {
946             $this->_result->Close();
947             $this->_result = false;
948         }
949     }
950 }
951
952 class WikiDB_backend_ADODB_iter
953 extends WikiDB_backend_ADODB_generic_iter
954 {
955     function next() {
956         $result = &$this->_result;
957         $backend = &$this->_backend;
958         if (!$result || $result->EOF) {
959             $this->free();
960             return false;
961         }
962         if (substr($backend->_dbh->databaseType,0,5) == 'mysql')
963             $result->fetchMode = 1;
964         else
965             $result->fetchMode = 2;
966         $record = $result->fields;
967         if (isset($record[0])) {
968             $record = $result->GetRowAssoc(2);
969         } else {
970             $record = $result->fields;
971         }
972         $result->MoveNext();
973         
974         $pagedata = $backend->_extract_page_data($record['pagedata'], $record['hits']);
975         $rec = array('pagename' => $record['pagename'],
976                      'pagedata' => $pagedata);
977         if (!empty($record['version'])) {
978             $rec['versiondata'] = $backend->_extract_version_data_assoc($record);
979             $rec['version'] = $record['version'];
980         }
981         return $rec;
982     }
983 }
984
985 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
986 // Eventually, change index.php to provide the relevant information
987 // directly?
988     /**
989      * Parse a data source name.
990      *
991      * Additional keys can be added by appending a URI query string to the
992      * end of the DSN.
993      *
994      * The format of the supplied DSN is in its fullest form:
995      * <code>
996      *  phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
997      * </code>
998      *
999      * Most variations are allowed:
1000      * <code>
1001      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1002      *  phptype://username:password@hostspec/database_name
1003      *  phptype://username:password@hostspec
1004      *  phptype://username@hostspec
1005      *  phptype://hostspec/database
1006      *  phptype://hostspec
1007      *  phptype(dbsyntax)
1008      *  phptype
1009      * </code>
1010      *
1011      * @param string $dsn Data Source Name to be parsed
1012      *
1013      * @return array an associative array with the following keys:
1014      *  + phptype:  Database backend used in PHP (mysql, odbc etc.)
1015      *  + dbsyntax: Database used with regards to SQL syntax etc.
1016      *  + protocol: Communication protocol to use (tcp, unix etc.)
1017      *  + hostspec: Host specification (hostname[:port])
1018      *  + database: Database to use on the DBMS server
1019      *  + username: User name for login
1020      *  + password: Password for login
1021      *
1022      * @author Tomas V.V.Cox <cox@idecnet.com>
1023      */
1024     function parseDSN($dsn)
1025     {
1026         $parsed = array(
1027             'phptype'  => false,
1028             'dbsyntax' => false,
1029             'username' => false,
1030             'password' => false,
1031             'protocol' => false,
1032             'hostspec' => false,
1033             'port'     => false,
1034             'socket'   => false,
1035             'database' => false,
1036         );
1037
1038         if (is_array($dsn)) {
1039             $dsn = array_merge($parsed, $dsn);
1040             if (!$dsn['dbsyntax']) {
1041                 $dsn['dbsyntax'] = $dsn['phptype'];
1042             }
1043             return $dsn;
1044         }
1045
1046         // Find phptype and dbsyntax
1047         if (($pos = strpos($dsn, '://')) !== false) {
1048             $str = substr($dsn, 0, $pos);
1049             $dsn = substr($dsn, $pos + 3);
1050         } else {
1051             $str = $dsn;
1052             $dsn = null;
1053         }
1054
1055         // Get phptype and dbsyntax
1056         // $str => phptype(dbsyntax)
1057         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1058             $parsed['phptype']  = $arr[1];
1059             $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1060         } else {
1061             $parsed['phptype']  = $str;
1062             $parsed['dbsyntax'] = $str;
1063         }
1064
1065         if (!count($dsn)) {
1066             return $parsed;
1067         }
1068
1069         // Get (if found): username and password
1070         // $dsn => username:password@protocol+hostspec/database
1071         if (($at = strrpos($dsn,'@')) !== false) {
1072             $str = substr($dsn, 0, $at);
1073             $dsn = substr($dsn, $at + 1);
1074             if (($pos = strpos($str, ':')) !== false) {
1075                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1076                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1077             } else {
1078                 $parsed['username'] = rawurldecode($str);
1079             }
1080         }
1081
1082         // Find protocol and hostspec
1083
1084         // $dsn => proto(proto_opts)/database
1085         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1086             $proto       = $match[1];
1087             $proto_opts  = $match[2] ? $match[2] : false;
1088             $dsn         = $match[3];
1089
1090         // $dsn => protocol+hostspec/database (old format)
1091         } else {
1092             if (strpos($dsn, '+') !== false) {
1093                 list($proto, $dsn) = explode('+', $dsn, 2);
1094             }
1095             if (strpos($dsn, '/') !== false) {
1096                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1097             } else {
1098                 $proto_opts = $dsn;
1099                 $dsn = null;
1100             }
1101         }
1102
1103         // process the different protocol options
1104         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1105         $proto_opts = rawurldecode($proto_opts);
1106         if ($parsed['protocol'] == 'tcp') {
1107             if (strpos($proto_opts, ':') !== false) {
1108                 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1109             } else {
1110                 $parsed['hostspec'] = $proto_opts;
1111             }
1112         } elseif ($parsed['protocol'] == 'unix') {
1113             $parsed['socket'] = $proto_opts;
1114         }
1115
1116         // Get dabase if any
1117         // $dsn => database
1118         if ($dsn) {
1119             // /database
1120             if (($pos = strpos($dsn, '?')) === false) {
1121                 $parsed['database'] = $dsn;
1122             // /database?param1=value1&param2=value2
1123             } else {
1124                 $parsed['database'] = substr($dsn, 0, $pos);
1125                 $dsn = substr($dsn, $pos + 1);
1126                 if (strpos($dsn, '&') !== false) {
1127                     $opts = explode('&', $dsn);
1128                 } else { // database?param1=value1
1129                     $opts = array($dsn);
1130                 }
1131                 foreach ($opts as $opt) {
1132                     list($key, $value) = explode('=', $opt);
1133                     if (!isset($parsed[$key])) {
1134                         // don't allow params overwrite
1135                         $parsed[$key] = rawurldecode($value);
1136                     }
1137                 }
1138             }
1139         }
1140
1141         return $parsed;
1142     }
1143
1144 // $Log: not supported by cvs2svn $
1145 // Revision 1.41  2004/07/08 21:32:35  rurban
1146 // Prevent from more warnings, minor db and sort optimizations
1147 //
1148 // Revision 1.40  2004/07/08 16:56:16  rurban
1149 // use the backendType abstraction
1150 //
1151 // Revision 1.39  2004/07/05 13:56:22  rurban
1152 // sqlite autoincrement fix
1153 //
1154 // Revision 1.38  2004/07/05 12:57:54  rurban
1155 // add mysql timeout
1156 //
1157 // Revision 1.37  2004/07/04 10:24:43  rurban
1158 // forgot the expressions
1159 //
1160 // Revision 1.36  2004/07/03 16:51:06  rurban
1161 // optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
1162 // added atomic mysql REPLACE for PearDB as in ADODB
1163 // fixed _lock_tables typo links => link
1164 // fixes unserialize ADODB bug in line 180
1165 //
1166 // Revision 1.35  2004/06/28 14:45:12  rurban
1167 // fix adodb_sqlite to have the same dsn syntax as pear, use pconnect if requested
1168 //
1169 // Revision 1.34  2004/06/28 14:17:38  rurban
1170 // updated DSN parser from Pear. esp. for sqlite
1171 //
1172 // Revision 1.33  2004/06/27 10:26:02  rurban
1173 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1174 //
1175 // Revision 1.32  2004/06/25 14:15:08  rurban
1176 // reduce memory footprint by caching only requested pagedate content (improving most page iterators)
1177 //
1178 // Revision 1.31  2004/06/16 10:38:59  rurban
1179 // Disallow refernces in calls if the declaration is a reference
1180 // ("allow_call_time_pass_reference clean").
1181 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
1182 //   but several external libraries may not.
1183 //   In detail these libs look to be affected (not tested):
1184 //   * Pear_DB odbc
1185 //   * adodb oracle
1186 //
1187 // Revision 1.30  2004/06/07 19:31:31  rurban
1188 // fixed ADOOB upgrade: listOfFields()
1189 //
1190 // Revision 1.29  2004/05/12 10:49:55  rurban
1191 // require_once fix for those libs which are loaded before FileFinder and
1192 //   its automatic include_path fix, and where require_once doesn't grok
1193 //   dirname(__FILE__) != './lib'
1194 // upgrade fix with PearDB
1195 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1196 //
1197 // Revision 1.28  2004/05/06 19:26:16  rurban
1198 // improve stability, trying to find the InlineParser endless loop on sf.net
1199 //
1200 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1201 //
1202 // Revision 1.27  2004/05/06 17:30:38  rurban
1203 // CategoryGroup: oops, dos2unix eol
1204 // improved phpwiki_version:
1205 //   pre -= .0001 (1.3.10pre: 1030.099)
1206 //   -p1 += .001 (1.3.9-p1: 1030.091)
1207 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1208 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1209 //   backend->backendType(), backend->database(),
1210 //   backend->listOfFields(),
1211 //   backend->listOfTables(),
1212 //
1213 // Revision 1.26  2004/04/26 20:44:35  rurban
1214 // locking table specific for better databases
1215 //
1216 // Revision 1.25  2004/04/20 00:06:04  rurban
1217 // themable paging support
1218 //
1219 // Revision 1.24  2004/04/18 01:34:20  rurban
1220 // protect most_popular from sortby=mtime
1221 //
1222 // Revision 1.23  2004/04/16 14:19:39  rurban
1223 // updated ADODB notes
1224 //
1225
1226 // (c-file-style: "gnu")
1227 // Local Variables:
1228 // mode: php
1229 // tab-width: 8
1230 // c-basic-offset: 4
1231 // c-hanging-comment-ender-p: nil
1232 // indent-tabs-mode: nil
1233 // End:   
1234 ?>