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