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