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