2 rcs_id('$Id: ADODB.php,v 1.21 2004-04-01 06:29:51 rurban Exp $');
5 Copyright 2002 $ThePhpWikiProgrammingTeam
7 This file is part of PhpWiki.
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.
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.
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
26 * Based on PearDB.php.
27 * Author: Lawrence Akka.
30 1) ADODB's GetRow() is slightly different from that in PEAR. It does not accept a fetchmode parameter
31 That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
33 2) No need for ''s arond strings in sprintf arguments - qstr puts them there automatically
35 3) ADODB has a version of GetOne, but it is difficult to use it when FETCH_ASSOC is in effect.
36 Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
37 4) No error handling yet - could use ADOConnection->raiseErrorFn
38 5) It used to be faster then PEAR/DB at the beginning of 2002.
39 Now at August 2002 PEAR/DB with our own page cache added, performance is comparable.
42 require_once('lib/WikiDB/backend.php');
43 // Error handling - calls trigger_error. NB - does not close the connection. Does it need to?
44 include_once('lib/WikiDB/adodb/adodb-errorhandler.inc.php');
45 // include the main adodb file
46 require_once('lib/WikiDB/adodb/adodb.inc.php');
48 class WikiDB_backend_ADODB
49 extends WikiDB_backend
52 function WikiDB_backend_ADODB ($dbparams) {
54 $dbh->setFetchMode(ADODB_FETCH_ASSOC);
56 $parsed = parseDSN($dbparams['dsn']);
57 $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
58 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
59 $parsed['password'], $parsed['database']);
61 // Uncomment the following line to enable debugging output (not very pretty!)
62 // $this->_dbh->debug = true;
64 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_ASSOC;
66 // The next line should speed up queries if enabled, but:
67 // 1) It only works with PHP >= 4.0.6; and
68 // 2) At the moment, I haven't figured out why the wrong results are returned'
69 //$GLOBALS['ADODB_COUNTRECS'] = false;
71 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
74 = array('page_tbl' => $prefix . 'page',
75 'version_tbl' => $prefix . 'version',
76 'link_tbl' => $prefix . 'link',
77 'recent_tbl' => $prefix . 'recent',
78 'nonempty_tbl' => $prefix . 'nonempty');
79 $page_tbl = $this->_table_names['page_tbl'];
80 $version_tbl = $this->_table_names['version_tbl'];
81 $this->page_tbl_fields = "$page_tbl.id as id, $page_tbl.pagename as pagename, " .
82 "$page_tbl.hits as hits, $page_tbl.pagedata as pagedata";
83 $this->version_tbl_fields = "$version_tbl.version as version, $version_tbl.mtime as mtime, ".
84 "$version_tbl.minor_edit as minor_edit, $version_tbl.content as content, ".
85 "$version_tbl.versiondata as versiondata";
88 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
89 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
90 'maxversion' => "MAX(version)");
92 $this->_lock_count = 0;
96 * Close database connection.
101 if ($this->_lock_count) {
102 trigger_error( "WARNING: database still locked " . '(lock_count = $this->_lock_count)' . "\n<br />",
105 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
106 $this->unlock('force');
108 $this->_dbh->close();
113 * Fast test for wikipage.
115 function is_wiki_page($pagename) {
117 extract($this->_table_names);
118 $rs = $dbh->Execute(sprintf("SELECT $page_tbl.id AS id"
119 . " FROM $nonempty_tbl, $page_tbl"
120 . " WHERE $nonempty_tbl.id=$page_tbl.id"
121 . " AND pagename=%s",
122 $dbh->qstr($pagename)));
124 $result = $rs->fields["id"];
133 function get_all_pagenames() {
135 extract($this->_table_names);
136 //return $dbh->getCol("SELECT pagename"
137 // . " FROM $nonempty_tbl, $page_tbl"
138 // . " WHERE $nonempty_tbl.id=$page_tbl.id");
140 //Original code (above) return the column in an indexed array - 0 based
141 //So, hopefully, does this
142 $result = $dbh->Execute("SELECT pagename"
143 . " FROM $nonempty_tbl, $page_tbl"
144 . " WHERE $nonempty_tbl.id=$page_tbl.id");
145 return $result->GetArray();
149 * Read page information from database.
151 function get_pagedata($pagename) {
153 $page_tbl = $this->_table_names['page_tbl'];
154 $result = $dbh->GetRow(sprintf("SELECT * FROM $page_tbl WHERE pagename=%s",
155 $dbh->qstr($pagename)));
158 return $this->_extract_page_data($result);
161 function _extract_page_data(&$query_result) {
162 extract($query_result);
163 $data = empty($pagedata) ? array() : unserialize($pagedata);
164 $data['hits'] = $hits;
168 function update_pagedata($pagename, $newdata) {
170 $page_tbl = $this->_table_names['page_tbl'];
172 // Hits is the only thing we can update in a fast manner.
173 if (count($newdata) == 1 && isset($newdata['hits'])) {
174 // Note that this will fail silently if the page does not
175 // have a record in the page table. Since it's just the
176 // hit count, who cares?
177 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
178 $newdata['hits'], $dbh->qstr($pagename)));
183 $data = $this->get_pagedata($pagename);
186 $this->_get_pageid($pagename, true); // Creates page record
189 @$hits = (int)$data['hits'];
190 unset($data['hits']);
192 foreach ($newdata as $key => $val) {
195 else if (empty($val))
201 $dbh->Execute(sprintf("UPDATE $page_tbl"
202 . " SET hits=%d, pagedata=%s"
203 . " WHERE pagename=%s",
205 $dbh->qstr(serialize($data)),
206 $dbh->qstr($pagename)));
211 function _get_pageid($pagename, $create_if_missing = false) {
214 $page_tbl = $this->_table_names['page_tbl'];
216 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
217 $dbh->qstr($pagename));
219 if (!$create_if_missing) {
220 $rs = $dbh->Execute($query);
221 return $rs->fields['id'];
224 $rs = $dbh->Execute($query);
225 $id = $rs->fields['id'];
227 // kludge necessary because an assoc array is returned with a reserved name as the key
228 $rs = $dbh->Execute("SELECT MAX(id) AS M FROM $page_tbl");
229 $id = $rs->fields['M'] + 1;
230 $dbh->Execute(sprintf("INSERT INTO $page_tbl"
231 . " (id,pagename,hits)"
232 . " VALUES (%d,%s,0)",
233 $id, $dbh->qstr($pagename)));
239 function get_latest_version($pagename) {
241 extract($this->_table_names);
242 $rs = $dbh->Execute(sprintf("SELECT latestversion"
243 . " FROM $page_tbl, $recent_tbl"
244 . " WHERE $page_tbl.id=$recent_tbl.id"
245 . " AND pagename=%s",
246 $dbh->qstr($pagename)));
247 return (int)$rs->fields['latestversion'];
250 function get_previous_version($pagename, $version) {
252 extract($this->_table_names);
253 // Use SELECTLIMIT for maximum portability
254 $rs = $dbh->SelectLimit(sprintf("SELECT version"
255 . " FROM $version_tbl, $page_tbl"
256 . " WHERE $version_tbl.id=$page_tbl.id"
258 . " AND version < %d"
259 . " ORDER BY version DESC"
260 ,$dbh->qstr($pagename),
263 return (int)$rs->fields['version'];
269 * @param $version int Which version to get.
271 * @return hash The version data, or false if specified version does not
274 function get_versiondata($pagename, $version, $want_content = false) {
276 extract($this->_table_names);
278 assert(!empty($pagename));
279 assert($version > 0);
281 // FIXME: optimization: sometimes don't get page data?
283 $fields = $this->page_tbl_fields.','.$this->version_tbl_fields;
285 $fields = $this->page_tbl_fields . ", "
286 . "mtime, minor_edit, versiondata,"
287 . "content<>'' AS have_content";
289 // removed ref to FETCH_MODE in next line
290 $result = $dbh->GetRow(sprintf("SELECT $fields"
291 . " FROM $page_tbl, $version_tbl"
292 . " WHERE $page_tbl.id=$version_tbl.id"
295 $dbh->qstr($pagename), $version));
297 return $this->_extract_version_data($result);
300 function _extract_version_data(&$query_result) {
304 extract($query_result);
305 $data = empty($versiondata) ? array() : unserialize($versiondata);
307 $data['mtime'] = $mtime;
308 $data['is_minor_edit'] = !empty($minor_edit);
311 $data['%content'] = $content;
312 elseif ($have_content)
313 $data['%content'] = true;
315 $data['%content'] = '';
317 // FIXME: this is ugly.
318 if (isset($pagename)) {
319 // Query also includes page data.
320 // We might as well send that back too...
321 $data['%pagedata'] = $this->_extract_page_data($query_result);
329 * Create a new revision of a page.
331 function set_versiondata($pagename, $version, $data) {
333 $version_tbl = $this->_table_names['version_tbl'];
335 $minor_edit = (int) !empty($data['is_minor_edit']);
336 unset($data['is_minor_edit']);
338 $mtime = (int)$data['mtime'];
339 unset($data['mtime']);
340 assert(!empty($mtime));
342 @$content = (string) $data['%content'];
343 unset($data['%content']);
344 unset($data['%pagedata']);
347 $id = $this->_get_pageid($pagename, true);
349 // FIXME: optimize: mysql can do this with one REPLACE INTO (I think).
350 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
351 . " WHERE id=%d AND version=%d",
353 $dbh->Execute(sprintf("INSERT INTO $version_tbl"
354 . " (id,version,mtime,minor_edit,content,versiondata)"
355 . " VALUES(%d,%d,%d,%d,%s,%s)",
356 $id, $version, $mtime, $minor_edit,
357 $dbh->qstr($content),
358 $dbh->qstr(serialize($data))));
360 $this->_update_recent_table($id);
361 $this->_update_nonempty_table($id);
367 * Delete an old revision of a page.
369 function delete_versiondata($pagename, $version) {
371 extract($this->_table_names);
374 if ( ($id = $this->_get_pageid($pagename)) ) {
375 $dbh->Execute("DELETE FROM $version_tbl"
376 . " WHERE id=$id AND version=$version");
377 $this->_update_recent_table($id);
378 // This shouldn't be needed (as long as the latestversion
379 // never gets deleted.) But, let's be safe.
380 $this->_update_nonempty_table($id);
386 * Delete page from the database.
388 function delete_page($pagename) {
390 extract($this->_table_names);
393 if ( ($id = $this->_get_pageid($pagename, false)) ) {
394 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
395 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
396 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
397 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$id");
398 $rs = $dbh->Execute("SELECT COUNT(*) AS C FROM $link_tbl WHERE linkto=$id");
399 $nlinks = $rs->fields['C'];
401 // We're still in the link table (dangling link) so we can't delete this
403 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
406 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
408 $this->_update_recent_table();
409 $this->_update_nonempty_table();
415 // The only thing we might be interested in updating which we can
416 // do fast in the flags (minor_edit). I think the default
417 // update_versiondata will work fine...
418 //function update_versiondata($pagename, $version, $data) {
421 function set_links($pagename, $links) {
422 // Update link table.
423 // FIXME: optimize: mysql can do this all in one big INSERT.
426 extract($this->_table_names);
429 $pageid = $this->_get_pageid($pagename, true);
431 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
434 foreach($links as $link) {
435 if (isset($linkseen[$link]))
437 $linkseen[$link] = true;
438 $linkid = $this->_get_pageid($link, true);
439 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
440 . " VALUES ($pageid, $linkid)");
447 * Find pages which link to or are linked from a page.
449 function get_links($pagename, $reversed = true) {
451 extract($this->_table_names);
454 list($have,$want) = array('linkee', 'linker');
456 list($have,$want) = array('linker', 'linkee');
458 $qpagename = $dbh->qstr($pagename);
459 // removed ref to FETCH_MODE in next line
460 $result = $dbh->Execute("SELECT $want.id as id, $want.pagename as pagename,"
461 . " $want.hits as hits, $want.pagedata as pagedata"
462 . " FROM $link_tbl, $page_tbl AS linker, $page_tbl AS linkee"
463 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
464 . " AND $have.pagename=$qpagename"
465 //. " GROUP BY $want.id"
466 . " ORDER BY $want.pagename");
468 return new WikiDB_backend_ADODB_iter($this, $result);
471 function get_all_pages($include_deleted=false,$sortby = false,$limit = false) {
473 extract($this->_table_names);
474 if ($limit) $limit = "LIMIT $limit";
476 if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
478 if (strstr($orderby,' mtime')) {
479 if ($include_deleted) {
480 $result = $dbh->Execute("SELECT * FROM $page_tbl, $recent_tbl, $version_tbl"
481 . " WHERE $page_tbl.id=$recent_tbl.id"
482 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
483 . " $orderby $limit");
486 $result = $dbh->Execute("SELECT "
487 . $this->page_tbl_fields
488 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
489 . " WHERE $nonempty_tbl.id=$page_tbl.id"
490 . " AND $page_tbl.id=$recent_tbl.id"
491 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
492 . " $orderby $limit");
495 if ($include_deleted) {
496 $result = $dbh->Execute("SELECT * FROM $page_tbl $orderby $limit");
498 $result = $dbh->Execute("SELECT "
499 . $this->page_tbl_fields
500 . " FROM $nonempty_tbl, $page_tbl"
501 . " WHERE $nonempty_tbl.id=$page_tbl.id"
502 . " $orderby $limit");
505 return new WikiDB_backend_ADODB_iter($this, $result);
511 function text_search($search = '', $fullsearch = false) {
513 extract($this->_table_names);
515 $table = "$nonempty_tbl, $page_tbl";
516 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
517 $fields = $this->page_tbl_fields;
518 $callback = new WikiMethodCb($this, '_sql_match_clause');
521 $table .= ", $recent_tbl";
522 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
524 $table .= ", $version_tbl";
525 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
527 $fields .= "," . $this->version_tbl_fields;
528 $callback = new WikiMethodCb($this, '_fullsearch_sql_match_clause');
531 $search_clause = $search->makeSqlClause($callback);
533 $result = $dbh->Execute("SELECT $fields FROM $table"
534 . " WHERE $join_clause"
535 . " AND ($search_clause)"
536 . " ORDER BY pagename");
538 return new WikiDB_backend_ADODB_iter($this, $result);
541 function _sql_match_clause($word) {
542 //not sure if we need this. ADODB may do it for us
543 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word);
545 // (we need it for at least % and _ --- they're the wildcard characters
546 // for the LIKE operator, and we need to quote them if we're searching
547 // for literal '%'s or '_'s. --- I'm not sure about \, but it seems to
549 $word = $this->_dbh->qstr("%$word%");
550 $page_tbl = $this->_table_names['page_tbl'];
551 return "LOWER($page_tbl.pagename) LIKE $word";
554 function _fullsearch_sql_match_clause($word) {
555 $word = preg_replace('/(?=[%_\\\\])/', "\\", $word); //not sure if we need this
557 $word = $this->_dbh->qstr("%$word%");
558 $page_tbl = $this->_table_names['page_tbl'];
559 return "LOWER($page_tbl.pagename) LIKE $word OR content LIKE $word";
563 * Find highest or lowest hit counts.
565 function most_popular($limit=20,$sortby = '') {
567 extract($this->_table_names);
573 if ($sortby) $orderby = 'ORDER BY ' . PageList::sortby($sortby,'db');
574 else $orderby = "ORDER BY hits $order";
575 $limit = $limit ? $limit : -1;
576 $result = $dbh->SelectLimit("SELECT "
577 . $this->page_tbl_fields
578 . " FROM $nonempty_tbl, $page_tbl"
579 . " WHERE $nonempty_tbl.id=$page_tbl.id"
583 return new WikiDB_backend_ADODB_iter($this, $result);
587 * Find recent changes.
589 function most_recent($params) {
592 $include_minor_revisions = false;
593 $exclude_major_revisions = false;
594 $include_all_revisions = false;
598 extract($this->_table_names);
602 $pick[] = "mtime >= $since";
604 if ($include_all_revisions) {
605 // Include all revisions of each page.
606 $table = "$page_tbl, $version_tbl";
607 $join_clause = "$page_tbl.id=$version_tbl.id";
609 if ($exclude_major_revisions) {
610 // Include only minor revisions
611 $pick[] = "minor_edit <> 0";
613 elseif (!$include_minor_revisions) {
614 // Include only major revisions
615 $pick[] = "minor_edit = 0";
619 $table = "$page_tbl, $recent_tbl";
620 $join_clause = "$page_tbl.id=$recent_tbl.id";
621 $table .= ", $version_tbl";
622 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
624 if ($exclude_major_revisions) {
625 // Include only most recent minor revision
626 $pick[] = 'version=latestminor';
628 elseif (!$include_minor_revisions) {
629 // Include only most recent major revision
630 $pick[] = 'version=latestmajor';
633 // Include only the latest revision (whether major or minor).
634 $pick[] ='version=latestversion';
642 $limit = $limit ? $limit : -1;
643 $where_clause = $join_clause;
645 $where_clause .= " AND " . join(" AND ", $pick);
647 // FIXME: use SQL_BUFFER_RESULT for mysql?
648 // Use SELECTLIMIT for portability
649 $result = $dbh->SelectLimit("SELECT "
650 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
652 . " WHERE $where_clause"
653 . " ORDER BY mtime $order",
656 return new WikiDB_backend_ADODB_iter($this, $result);
660 * Rename page in the database.
662 function rename_page($pagename, $to) {
664 extract($this->_table_names);
667 if ( ($id = $this->_get_pageid($pagename, false)) ) {
668 if ($new = $this->_get_pageid($to, false)) {
670 //this page does not exist (already verified before), but exists in the page table.
671 //so we delete this page.
672 $dbh->query(sprintf("DELETE FROM $page_tbl WHERE id=$id",
675 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
682 function _update_recent_table($pageid = false) {
684 extract($this->_table_names);
685 extract($this->_expressions);
687 $pageid = (int)$pageid;
691 $dbh->Execute("DELETE FROM $recent_tbl"
692 . ( $pageid ? " WHERE id=$pageid" : ""));
694 $dbh->Execute( "INSERT INTO $recent_tbl"
695 . " (id, latestversion, latestmajor, latestminor)"
696 . " SELECT id, $maxversion, $maxmajor, $maxminor"
697 . " FROM $version_tbl"
698 . ( $pageid ? " WHERE id=$pageid" : "")
703 function _update_nonempty_table($pageid = false) {
705 extract($this->_table_names);
707 $pageid = (int)$pageid;
711 $dbh->Execute("DELETE FROM $nonempty_tbl"
712 . ( $pageid ? " WHERE id=$pageid" : ""));
714 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
715 . " SELECT $recent_tbl.id"
716 . " FROM $recent_tbl, $version_tbl"
717 . " WHERE $recent_tbl.id=$version_tbl.id"
718 . " AND version=latestversion"
720 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
727 * Grab a write lock on the tables in the SQL database.
729 * Calls can be nested. The tables won't be unlocked until
730 * _unlock_database() is called as many times as _lock_database().
734 function lock($write_lock = true) {
735 if ($this->_lock_count++ == 0)
736 $this->_lock_tables($write_lock);
740 * Actually lock the required tables.
742 function _lock_tables($write_lock) {
743 trigger_error("virtual", E_USER_ERROR);
747 * Release a write lock on the tables in the SQL database.
751 * @param $force boolean Unlock even if not every call to lock() has been matched
752 * by a call to unlock().
754 * @see _lock_database
756 function unlock($force = false) {
757 if ($this->_lock_count == 0)
759 if (--$this->_lock_count <= 0 || $force) {
760 $this->_unlock_tables();
761 $this->_lock_count = 0;
766 * Actually unlock the required tables.
768 function _unlock_tables($write_lock) {
769 trigger_error("virtual", E_USER_ERROR);
773 class WikiDB_backend_ADODB_generic_iter
774 extends WikiDB_backend_iterator
776 function WikiDB_backend_ADODB_generic_iter(&$backend, &$query_result) {
777 $this->_backend = &$backend;
778 $this->_result = $query_result;
784 return $this->_result->numRows();
788 $result = &$this->_result;
789 if (!$result || $result->EOF) {
793 $backend = &$this->_backend;
795 // $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
796 $record = $result->fields;
802 if ($this->_result) {
803 // $this->_result->free();
804 $this->_result->Close();
805 $this->_result = false;
810 class WikiDB_backend_ADODB_iter
811 extends WikiDB_backend_ADODB_generic_iter
814 $result = &$this->_result;
815 if (!$result || $result->EOF) {
820 // $record = $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
821 $record = $result->fields;
824 $backend = &$this->_backend;
826 $pagedata = $backend->_extract_page_data($record);
827 $rec = array('pagename' => $record['pagename'],
828 'pagedata' => $pagedata);
830 if (!empty($record['version'])) {
831 $rec['versiondata'] = $backend->_extract_version_data($record);
832 $rec['version'] = $record['version'];
839 // Following function taken from adodb-pear.inc.php.
840 // Eventually, change index.php to provide the relevant information
843 * Parse a data source name
845 * @param $dsn string Data Source Name to be parsed
847 * @return array an associative array with the following keys:
849 * phptype: Database backend used in PHP (mysql, odbc etc.)
850 * dbsyntax: Database used with regards to SQL syntax etc.
851 * protocol: Communication protocol to use (tcp, unix etc.)
852 * hostspec: Host specification (hostname[:port])
853 * database: Database to use on the DBMS server
854 * username: User name for login
855 * password: Password for login
857 * The format of the supplied DSN is in its fullest form:
859 * phptype(dbsyntax)://username:password@protocol+hostspec/database
861 * Most variations are allowed:
863 * phptype://username:password@protocol+hostspec:110//usr/db_file.db
864 * phptype://username:password@hostspec/database_name
865 * phptype://username:password@hostspec
866 * phptype://username@hostspec
867 * phptype://hostspec/database
872 * @author Tomas V.V.Cox <cox@idecnet.com>
874 function parseDSN($dsn) {
875 if (is_array($dsn)) {
889 // Find phptype and dbsyntax
890 if (($pos = strpos($dsn, '://')) !== false) {
891 $str = substr($dsn, 0, $pos);
892 $dsn = substr($dsn, $pos + 3);
898 // Get phptype and dbsyntax
899 // $str => phptype(dbsyntax)
900 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
901 $parsed['phptype'] = $arr[1];
902 $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
904 $parsed['phptype'] = $str;
905 $parsed['dbsyntax'] = $str;
912 // Get (if found): username and password
913 // $dsn => username:password@protocol+hostspec/database
914 if (($at = strpos($dsn,'@')) !== false) {
915 $str = substr($dsn, 0, $at);
916 $dsn = substr($dsn, $at + 1);
917 if (($pos = strpos($str, ':')) !== false) {
918 $parsed['username'] = urldecode(substr($str, 0, $pos));
919 $parsed['password'] = urldecode(substr($str, $pos + 1));
921 $parsed['username'] = urldecode($str);
925 // Find protocol and hostspec
926 // $dsn => protocol+hostspec/database
927 if (($pos = strpos($dsn, '/')) !== false) {
928 $str = substr($dsn, 0, $pos);
929 $dsn = substr($dsn, $pos + 1);
935 // Get protocol + hostspec
936 // $str => protocol+hostspec
937 if (($pos = strpos($str, '+')) !== false) {
938 $parsed['protocol'] = substr($str, 0, $pos);
939 $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
941 $parsed['hostspec'] = urldecode($str);
947 $parsed['database'] = $dsn;
955 // (c-file-style: "gnu")
960 // c-hanging-comment-ender-p: nil
961 // indent-tabs-mode: nil