2 // $Id: ADODB.php 8071 2011-05-18 14:56:14Z vargenau $
5 * Copyright 2002,2004,2005,2006 $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 along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * Based on PearDB.php.
26 * @author: Lawrence Akka, Reini Urban
28 * Now (since phpwiki-1.3.10) with adodb-4.22, by Reini Urban:
29 * 1) Extended to use all available database backends, not only mysql.
30 * 2) It uses the ultra-fast binary adodb extension if loaded.
31 * 3) We use FETCH_NUM instead of FETCH_ASSOC (faster and more generic)
32 * 4) To support generic iterators which return ASSOC fields, and to support queries with
33 * variable columns, some trickery was needed to use recordset specific fetchMode.
34 * The first Execute uses the global fetchMode (ASSOC), then it's resetted back to NUM
35 * and the recordset fetchmode is set to ASSOC.
36 * 5) Transaction support, and locking as fallback.
37 * 6) 2004-12-10 added extra page.cached_html
39 * phpwiki-1.3.11, by Philippe Vanhaesendonck
40 * - pass column list to iterators so we can FETCH_NUM in all cases
41 * phpwiki-1.3.12: get rid of ISNULL
42 * phpwiki-1.3.13: tsearch2 and stored procedures
44 * ADODB basic differences to PearDB: It pre-fetches the first row into fields,
45 * is dirtier in style, layout and more low-level ("worse is better").
46 * It has less needed basic features (modifyQuery, locks, ...), but some more
47 * unneeded features included: paging, monitoring and sessions, and much more drivers.
48 * No locking (which PearDB supports in some backends), and sequences are very
49 * bad compared to PearDB.
51 * Old Comments, by Lawrence Akka:
52 * 1) ADODB's GetRow() is slightly different from that in PEAR. It does not
53 * accept a fetchmode parameter
54 * That doesn't matter too much here, since we only ever use FETCHMODE_ASSOC
55 * 2) No need for ''s around strings in sprintf arguments - qstr puts them
57 * 3) ADODB has a version of GetOne, but it is difficult to use it when
58 * FETCH_ASSOC is in effect.
59 * Instead, use $rs = Execute($query); $value = $rs->fields["$colname"]
60 * 4) No error handling yet - could use ADOConnection->raiseErrorFn
61 * 5) It used to be faster then PEAR/DB at the beginning of 2002.
62 * Now at August 2002 PEAR/DB with our own page cache added,
63 * performance is comparable.
66 require_once 'lib/WikiDB/backend.php';
67 // Error handling - calls trigger_error. NB - does not close the connection. Does it need to?
68 include_once 'lib/WikiDB/adodb/adodb-errorhandler.inc.php';
69 // include the main adodb file
70 require_once 'lib/WikiDB/adodb/adodb.inc.php';
72 class WikiDB_backend_ADODB
73 extends WikiDB_backend
76 function WikiDB_backend_ADODB ($dbparams) {
77 $parsed = parseDSN($dbparams['dsn']);
78 $this->_dbparams = $dbparams;
79 $this->_parsedDSN =& $parsed;
80 $this->_dbh = &ADONewConnection($parsed['phptype']);
81 if (DEBUG & _DEBUG_SQL) {
82 $this->_dbh->debug = true;
83 $GLOBALS['ADODB_OUTP'] = '_sql_debuglog';
85 $this->_dsn = $parsed;
86 // persistent is defined as DSN option, or with a config value.
87 // phptype://username:password@hostspec/database?persistent=false
89 //FIXME: how to catch connection errors for dbamin_user?
90 if (!empty($parsed['persistent']) or DATABASE_PERSISTENT)
91 $conn = $this->_dbh->PConnect($parsed['hostspec'],$parsed['username'],
92 $parsed['password'], $parsed['database']);
94 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
95 $parsed['password'], $parsed['database']);
98 // Since 1.3.10 we use the faster ADODB_FETCH_NUM,
99 // with some ASSOC based recordsets.
100 $GLOBALS['ADODB_FETCH_MODE'] = ADODB_FETCH_NUM;
101 $this->_dbh->SetFetchMode(ADODB_FETCH_NUM);
102 $GLOBALS['ADODB_COUNTRECS'] = false;
104 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
106 = array('page_tbl' => $prefix . 'page',
107 'version_tbl' => $prefix . 'version',
108 'link_tbl' => $prefix . 'link',
109 'recent_tbl' => $prefix . 'recent',
110 'nonempty_tbl' => $prefix . 'nonempty');
111 $page_tbl = $this->_table_names['page_tbl'];
112 $version_tbl = $this->_table_names['version_tbl'];
113 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
114 . "$page_tbl.hits AS hits";
115 $this->links_field_list = array('id', 'pagename');
116 $this->page_tbl_field_list = array('id', 'pagename', 'hits');
117 $this->version_tbl_fields = "$version_tbl.version AS version, "
118 . "$version_tbl.mtime AS mtime, "
119 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
120 . "$version_tbl.versiondata AS versiondata";
121 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
125 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
126 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
127 'maxversion' => "MAX(version)",
128 'notempty' => "<>''",
129 'iscontent' => "$version_tbl.content<>''");
130 $this->_lock_count = 0;
134 * Close database connection.
139 if ($this->_lock_count) {
140 trigger_error("WARNING: database still locked " .
141 '(lock_count = $this->_lock_count)' . "\n<br />",
144 // $this->_dbh->setErrorHandling(PEAR_ERROR_PRINT); // prevent recursive loops.
145 $this->unlock(false,'force');
147 $this->_dbh->close();
152 * Fast test for wikipage.
154 function is_wiki_page($pagename) {
156 extract($this->_table_names);
157 $row = $dbh->GetRow(sprintf("SELECT $page_tbl.id AS id"
158 . " FROM $nonempty_tbl, $page_tbl"
159 . " WHERE $nonempty_tbl.id=$page_tbl.id"
160 . " AND pagename=%s",
161 $dbh->qstr($pagename)));
162 return $row ? $row[0] : false;
165 function get_all_pagenames() {
167 extract($this->_table_names);
168 $result = $dbh->Execute("SELECT pagename"
169 . " FROM $nonempty_tbl, $page_tbl"
170 . " WHERE $nonempty_tbl.id=$page_tbl.id");
171 return $result->GetArray();
175 * filter (nonempty pages) currently ignored
177 function numPages($filter=false, $exclude='') {
179 extract($this->_table_names);
180 $result = $dbh->getRow("SELECT count(*)"
181 . " FROM $nonempty_tbl, $page_tbl"
182 . " WHERE $nonempty_tbl.id=$page_tbl.id");
186 function increaseHitCount($pagename) {
188 // Hits is the only thing we can update in a fast manner.
189 // Note that this will fail silently if the page does not
190 // have a record in the page table. Since it's just the
191 // hit count, who cares?
192 $dbh->Execute(sprintf("UPDATE %s SET hits=hits+1 WHERE pagename=%s",
193 $this->_table_names['page_tbl'],
194 $dbh->qstr($pagename)));
199 * Read page information from database.
201 function get_pagedata($pagename) {
203 $row = $dbh->GetRow(sprintf("SELECT id,pagename,hits,pagedata FROM %s WHERE pagename=%s",
204 $this->_table_names['page_tbl'],
205 $dbh->qstr($pagename)));
206 return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
209 function _extract_page_data($data, $hits) {
211 return array('hits' => $hits);
213 return array_merge(array('hits' => $hits), $this->_unserialize($data));
216 function update_pagedata($pagename, $newdata) {
218 $page_tbl = $this->_table_names['page_tbl'];
220 // Hits is the only thing we can update in a fast manner.
221 if (count($newdata) == 1 && isset($newdata['hits'])) {
222 // Note that this will fail silently if the page does not
223 // have a record in the page table. Since it's just the
224 // hit count, who cares?
225 $dbh->Execute(sprintf("UPDATE $page_tbl SET hits=%d WHERE pagename=%s",
226 $newdata['hits'], $dbh->qstr($pagename)));
229 $where = sprintf("pagename=%s", $dbh->qstr($pagename));
231 $dbh->RowLock($page_tbl,$where);
233 $data = $this->get_pagedata($pagename);
236 $this->_get_pageid($pagename, true); // Creates page record
239 $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
240 unset($data['hits']);
242 foreach ($newdata as $key => $val) {
245 else if (empty($val))
250 if ($dbh->Execute("UPDATE $page_tbl"
251 . " SET hits=?, pagedata=?"
252 . " WHERE pagename=?",
253 array($hits, $this->_serialize($data), $pagename))) {
254 $dbh->CommitTrans( );
257 $dbh->RollbackTrans( );
262 function get_cached_html($pagename) {
264 $page_tbl = $this->_table_names['page_tbl'];
265 $row = $dbh->GetRow(sprintf("SELECT cached_html FROM $page_tbl WHERE pagename=%s",
266 $dbh->qstr($pagename)));
267 return $row ? $row[0] : false;
270 function set_cached_html($pagename, $data) {
272 $page_tbl = $this->_table_names['page_tbl'];
273 if (empty($data)) $data = '';
274 $rs = $dbh->Execute("UPDATE $page_tbl"
275 . " SET cached_html=?"
276 . " WHERE pagename=?",
277 array($data, $pagename));
280 function _get_pageid($pagename, $create_if_missing = false) {
284 $cache =& $request->_dbi->_cache->_id_cache;
285 if (isset($cache[$pagename])) {
286 if ($cache[$pagename] or !$create_if_missing) {
287 return $cache[$pagename];
290 // attributes play this game.
291 if ($pagename === '') return 0;
294 $page_tbl = $this->_table_names['page_tbl'];
295 $query = sprintf("SELECT id FROM $page_tbl WHERE pagename=%s",
296 $dbh->qstr($pagename));
297 if (! $create_if_missing ) {
298 $row = $dbh->GetRow($query);
299 return $row ? $row[0] : false;
301 $row = $dbh->GetRow($query);
303 //TODO: Does the DBM has subselects? Then we can do it with select max(id)+1
304 // $this->lock(array('page'));
306 $dbh->CommitLock($page_tbl);
307 if (0 and $dbh->hasGenID) {
308 // requires create permissions
309 $id = $dbh->GenID($page_tbl."_id");
311 // Better generic version than with adodb::genID
312 $row = $dbh->GetRow("SELECT MAX(id) FROM $page_tbl");
315 $rs = $dbh->Execute(sprintf("INSERT INTO $page_tbl"
316 . " (id,pagename,hits)"
317 . " VALUES (%d,%s,0)",
318 $id, $dbh->qstr($pagename)));
319 if ($rs) $dbh->CommitTrans( );
320 else $dbh->RollbackTrans( );
321 // $this->unlock(array('page'));
329 function get_latest_version($pagename) {
331 extract($this->_table_names);
332 $row = $dbh->GetRow(sprintf("SELECT latestversion"
333 . " FROM $page_tbl, $recent_tbl"
334 . " WHERE $page_tbl.id=$recent_tbl.id"
335 . " AND pagename=%s",
336 $dbh->qstr($pagename)));
337 return $row ? (int)$row[0] : false;
340 function get_previous_version($pagename, $version) {
342 extract($this->_table_names);
343 // Use SELECTLIMIT for maximum portability
344 $rs = $dbh->SelectLimit(sprintf("SELECT version"
345 . " FROM $version_tbl, $page_tbl"
346 . " WHERE $version_tbl.id=$page_tbl.id"
348 . " AND version < %d"
349 . " ORDER BY version DESC",
350 $dbh->qstr($pagename),
353 return $rs->fields ? (int)$rs->fields[0] : false;
359 * @param $version int Which version to get.
361 * @return hash The version data, or false if specified version does not
364 function get_versiondata($pagename, $version, $want_content = false) {
366 extract($this->_table_names);
367 extract($this->_expressions);
369 assert(is_string($pagename) and $pagename != '');
370 assert($version > 0);
372 // FIXME: optimization: sometimes don't get page data?
374 $fields = $this->page_tbl_fields . ", $page_tbl.pagedata AS pagedata"
375 . ', ' . $this->version_tbl_fields;
377 $fields = $this->page_tbl_fields . ", '' AS pagedata"
378 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
379 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
380 . "$version_tbl.versiondata as versiondata";
382 $row = $dbh->GetRow(sprintf("SELECT $fields"
383 . " FROM $page_tbl, $version_tbl"
384 . " WHERE $page_tbl.id=$version_tbl.id"
387 $dbh->qstr($pagename), $version));
388 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
391 function _extract_version_data_num($row, $want_content) {
396 //$pagename &= $row[1];
397 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
398 $data['mtime'] = $row[5];
399 $data['is_minor_edit'] = !empty($row[6]);
401 $data['%content'] = $row[7];
403 $data['%content'] = !empty($row[7]);
405 if (!empty($row[3])) {
406 $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
411 function _extract_version_data_assoc($row) {
416 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
417 $data['mtime'] = $mtime;
418 $data['is_minor_edit'] = !empty($minor_edit);
420 $data['%content'] = $content;
421 elseif ($have_content)
422 $data['%content'] = true;
424 $data['%content'] = '';
425 if (!empty($pagedata)) {
426 // hmm, $pagedata = is already extracted by WikiDB_backend_ADODB_iter
427 //$data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
428 $data['%pagedata'] = $pagedata;
434 * Create a new revision of a page.
436 function set_versiondata($pagename, $version, $data) {
438 $version_tbl = $this->_table_names['version_tbl'];
440 $minor_edit = (int) !empty($data['is_minor_edit']);
441 unset($data['is_minor_edit']);
443 $mtime = (int)$data['mtime'];
444 unset($data['mtime']);
445 assert(!empty($mtime));
447 @$content = (string) $data['%content'];
448 unset($data['%content']);
449 unset($data['%pagedata']);
451 $this->lock(array('page','recent','version','nonempty'));
453 $dbh->CommitLock($version_tbl);
454 $id = $this->_get_pageid($pagename, true);
455 $backend_type = $this->backendType();
456 $dbh->Execute(sprintf("DELETE FROM $version_tbl"
457 . " WHERE id=%d AND version=%d",
459 $rs = $dbh->Execute("INSERT INTO $version_tbl"
460 . " (id,version,mtime,minor_edit,content,versiondata)"
461 . " VALUES(?,?,?,?,?,?)",
462 array($id, $version, $mtime, $minor_edit,
463 $content, $this->_serialize($data)));
464 $this->_update_recent_table($id);
465 $this->_update_nonempty_table($id);
466 if ($rs) $dbh->CommitTrans( );
467 else $dbh->RollbackTrans( );
468 $this->unlock(array('page','recent','version','nonempty'));
472 * Delete an old revision of a page.
474 function delete_versiondata($pagename, $version) {
476 extract($this->_table_names);
478 $this->lock(array('version'));
479 if ( ($id = $this->_get_pageid($pagename)) ) {
480 $dbh->Execute("DELETE FROM $version_tbl"
481 . " WHERE id=$id AND version=$version");
482 $this->_update_recent_table($id);
483 // This shouldn't be needed (as long as the latestversion
484 // never gets deleted.) But, let's be safe.
485 $this->_update_nonempty_table($id);
487 $this->unlock(array('version'));
491 * Delete page from the database with backup possibility.
492 * i.e save_page('') and DELETE nonempty id
494 * deletePage increments latestversion in recent to a non-existent version,
495 * and removes the nonempty row,
496 * so that get_latest_version returns id+1 and get_previous_version returns prev id
497 * and page->exists returns false.
499 function delete_page($pagename) {
501 extract($this->_table_names);
504 $dbh->CommitLock($recent_tbl);
505 if (($id = $this->_get_pageid($pagename, false)) === false) {
506 $dbh->RollbackTrans( );
510 $user =& $GLOBALS['request']->_user;
511 $meta = array('author' => $user->getId(),
512 'author_id' => $user->getAuthenticatedId(),
514 $this->lock(array('version','recent','nonempty','page','link'));
515 $version = $this->get_latest_version($pagename);
516 if ($dbh->Execute("UPDATE $recent_tbl SET latestversion=latestversion+1,"
517 . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id")
518 and $dbh->Execute("INSERT INTO $version_tbl"
519 . " (id,version,mtime,minor_edit,content,versiondata)"
520 . " VALUES(?,?,?,?,?,?)",
521 array($id, $version+1, $mtime, 0,
522 '', $this->_serialize($meta)))
523 and $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id")
524 and $this->set_links($pagename, false)
525 // need to keep perms and LOCKED, otherwise you can reset the perm
526 // by action=remove and re-create it with default perms
527 // keep hits but delete meta-data
528 //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id")
531 $this->unlock(array('version','recent','nonempty','page','link'));
532 $dbh->CommitTrans( );
535 $this->unlock(array('version','recent','nonempty','page','link'));
536 $dbh->RollbackTrans( );
541 function purge_page($pagename) {
543 extract($this->_table_names);
545 $this->lock(array('version','recent','nonempty','page','link'));
546 if ( ($id = $this->_get_pageid($pagename, false)) ) {
547 $dbh->Execute("DELETE FROM $nonempty_tbl WHERE id=$id");
548 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id");
549 $dbh->Execute("DELETE FROM $version_tbl WHERE id=$id");
550 $this->set_links($pagename, false);
551 $row = $dbh->GetRow("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
552 if ($row and $row[0]) {
553 // We're still in the link table (dangling link) so we can't delete this
555 $dbh->Execute("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
559 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id");
563 $result = -1; // already purged or not existing
565 $this->unlock(array('version','recent','nonempty','page','link'));
570 // The only thing we might be interested in updating which we can
571 // do fast in the flags (minor_edit). I think the default
572 // update_versiondata will work fine...
573 //function update_versiondata($pagename, $version, $data) {
578 * on DEBUG: delete old, deleted links from page
580 function set_links($pagename, $links) {
581 // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
584 extract($this->_table_names);
586 $this->lock(array('link'));
587 $pageid = $this->_get_pageid($pagename, true);
589 $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as id, page.pagename FROM $link_tbl"
590 ." JOIN page ON ($link_tbl.linkto = page.id)"
591 ." WHERE linkfrom=$pageid");
592 // Delete current links,
593 $dbh->Execute("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
594 // and insert new links. Faster than checking for all single links
596 foreach ($links as $link) {
597 $linkto = $link['linkto'];
598 if (isset($link['relation']))
599 $relation = $this->_get_pageid($link['relation'], true);
602 if ($linkto === "") { // ignore attributes
606 if (isset($linkseen[$linkto]) and !$relation) {
610 $linkseen[$linkto] = true;
612 $linkid = $this->_get_pageid($linkto, true);
615 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
616 . " VALUES ($pageid, $linkid, $relation)");
618 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
619 . " VALUES ($pageid, $linkid)");
621 if ($oldlinks and array_key_exists($linkid, $oldlinks)) {
622 // This was also in the previous page
623 unset($oldlinks[$linkid]);
627 // purge page table: delete all non-referenced pages
628 // for all previously linked pages, which have no other linkto links
629 if (DEBUG and $oldlinks) {
630 // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE);
631 foreach ($oldlinks as $id => $name) {
632 // ...check if the page is empty and has no version
633 $result = $dbh->getRow("SELECT $page_tbl.id FROM $page_tbl"
634 . " LEFT JOIN $nonempty_tbl USING (id) "
635 . " LEFT JOIN $version_tbl USING (id)"
636 . " WHERE $nonempty_tbl.id is NULL"
637 . " AND $version_tbl.id is NULL"
638 . " AND $page_tbl.id=$id");
639 $linkto = $dbh->getRow("SELECT linkfrom FROM $link_tbl WHERE linkto=$id");
640 if ($result and empty($linkto))
642 trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE);
643 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
644 $dbh->Execute("DELETE FROM $link_tbl WHERE linkto=$id");
645 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
649 $this->unlock(array('link'));
653 /* get all oldlinks in hash => id, relation
654 check for all new links
656 function set_links1($pagename, $links) {
659 extract($this->_table_names);
661 $this->lock(array('link'));
662 $pageid = $this->_get_pageid($pagename, true);
664 $oldlinks = $dbh->getAssoc("SELECT $link_tbl.linkto as linkto, $link_tbl.relation, page.pagename"
666 ." JOIN page ON ($link_tbl.linkto = page.id)"
667 ." WHERE linkfrom=$pageid");
669 * X => [1,0 2,0 1,1] X => [1,1 3,0]
670 * => delete 1,0 2,0 + insert 3,0
673 foreach ($links as $link) {
674 $linkto = $link['linkto'];
675 if ($link['relation'])
676 $relation = $this->_get_pageid($link['relation'], true);
680 if (isset($linkseen[$linkto]) and !$relation) {
684 $linkseen[$linkto] = true;
686 $linkid = $this->_get_pageid($linkto, true);
689 // find linkfrom,linkto,relation triple in oldlinks
690 foreach ($oldlinks as $l) {
691 if ($relation) { // relation NOT NULL
692 if ($l['linkto'] == $linkid and $l['relation'] == $relation) {
702 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto, relation)"
703 . " VALUES ($pageid, $linkid, $relation)");
705 $dbh->Execute("INSERT INTO $link_tbl (linkfrom, linkto)"
706 . " VALUES ($pageid, $linkid)");
710 if (array_key_exists($linkid, $oldlinks)) {
711 // This was also in the previous page
712 unset($oldlinks[$linkid]);
716 // purge page table: delete all non-referenced pages
717 // for all previously linked pages...
718 if (DEBUG and $oldlinks) {
719 // trigger_error("purge page table: delete all non-referenced pages...", E_USER_NOTICE);
720 foreach ($oldlinks as $id => $name) {
721 // ...check if the page is empty and has no version
722 if ($dbh->getRow("SELECT $page_tbl.id FROM $page_tbl"
723 . " LEFT JOIN $nonempty_tbl USING (id) "
724 . " LEFT JOIN $version_tbl USING (id)"
725 . " WHERE $nonempty_tbl.id is NULL"
726 . " AND $version_tbl.id is NULL"
727 . " AND $page_tbl.id=$id"))
729 trigger_error("delete empty and non-referenced link $name ($id)", E_USER_NOTICE);
730 $dbh->Execute("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
731 $dbh->Execute("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
735 $this->unlock(array('link'));
740 * Find pages which link to or are linked from a page.
742 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
743 * (linkExistingWikiWord or linkUnknownWikiWord)
744 * This is called on every page header GleanDescription, so we can store all the
747 * relations: $backend->get_links is responsible to add the relation to the pagehash
748 * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next
749 * if (isset($next['linkrelation']))
751 function get_links($pagename, $reversed=true, $include_empty=false,
752 $sortby='', $limit='', $exclude='',
753 $want_relations = false)
756 extract($this->_table_names);
759 list($have,$want) = array('linkee', 'linker');
761 list($have,$want) = array('linker', 'linkee');
762 $orderby = $this->sortby($sortby, 'db', array('pagename'));
763 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
764 if ($exclude) // array of pagenames
765 $exclude = " AND $want.pagename NOT IN ".$this->_sql_set($exclude);
769 $qpagename = $dbh->qstr($pagename);
770 // removed ref to FETCH_MODE in next line
771 $sql = "SELECT $want.id AS id, $want.pagename AS pagename, "
772 . ($want_relations ? " related.pagename as linkrelation" : " $want.hits AS hits")
774 . (!$include_empty ? "$nonempty_tbl, " : '')
775 . " $page_tbl linkee, $page_tbl linker, $link_tbl "
776 . ($want_relations ? " JOIN $page_tbl related ON ($link_tbl.relation=related.id)" : '')
777 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
778 . " AND $have.pagename=$qpagename"
779 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
780 //. " GROUP BY $want.id"
784 echo "SELECT linkee.id AS id, linkee.pagename AS pagename, related.pagename as linkrelation FROM link, page linkee, page linker JOIN page related ON (link.relation=related.id) WHERE linkfrom=linker.id AND linkto=linkee.id AND linker.pagename='SanDiego'" | mysql phpwiki
785 id pagename linkrelation
786 2268 California located_in
789 // extract from,count from limit
790 list($offset,$count) = $this->limit($limit);
791 $result = $dbh->SelectLimit($sql, $count, $offset);
793 $result = $dbh->Execute($sql);
795 $fields = $this->links_field_list;
796 if ($want_relations) // instead of hits
797 $fields[2] = 'linkrelation';
798 return new WikiDB_backend_ADODB_iter($this, $result, $fields);
802 * Find if a page links to another page
804 function exists_link($pagename, $link, $reversed=false) {
806 extract($this->_table_names);
809 list($have, $want) = array('linkee', 'linker');
811 list($have, $want) = array('linker', 'linkee');
812 $qpagename = $dbh->qstr($pagename);
813 $qlink = $dbh->qstr($link);
814 $row = $dbh->GetRow("SELECT CASE WHEN $want.pagename=$qlink THEN 1 ELSE 0 END"
815 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
816 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
817 . " AND $have.pagename=$qpagename"
818 . " AND $want.pagename=$qlink");
825 function get_all_pages($include_empty=false, $sortby='', $limit='', $exclude='') {
827 extract($this->_table_names);
828 $orderby = $this->sortby($sortby, 'db');
829 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
831 if ($exclude) {// array of pagenames
833 $exclude = " $page_tbl.pagename NOT IN ".$this->_sql_set($exclude);
838 //$dbh->SetFetchMode(ADODB_FETCH_ASSOC);
839 if (strstr($orderby, 'mtime ')) { // was ' mtime'
840 if ($include_empty) {
842 . $this->page_tbl_fields
843 ." FROM $page_tbl, $recent_tbl, $version_tbl"
844 . " WHERE $page_tbl.id=$recent_tbl.id"
845 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
851 . $this->page_tbl_fields
852 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
853 . " WHERE $nonempty_tbl.id=$page_tbl.id"
854 . " AND $page_tbl.id=$recent_tbl.id"
855 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
860 if ($include_empty) {
862 . $this->page_tbl_fields
864 . ($exclude ? " WHERE $exclude" : '')
868 . $this->page_tbl_fields
869 . " FROM $nonempty_tbl, $page_tbl"
870 . " WHERE $nonempty_tbl.id=$page_tbl.id"
876 // extract from,count from limit
877 list($offset,$count) = $this->limit($limit);
878 $result = $dbh->SelectLimit($sql, $count, $offset);
880 $result = $dbh->Execute($sql);
882 //$dbh->SetFetchMode(ADODB_FETCH_NUM);
883 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
887 * Title and fulltext search.
889 function text_search($search, $fullsearch=false,
890 $sortby='', $limit='', $exclude='')
893 extract($this->_table_names);
894 $orderby = $this->sortby($sortby, 'db');
895 if ($orderby) $orderby = ' ORDER BY ' . $orderby;
897 $table = "$nonempty_tbl, $page_tbl";
898 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
899 $fields = $this->page_tbl_fields;
900 $field_list = $this->page_tbl_field_list;
901 $searchobj = new WikiDB_backend_ADODB_search($search, $dbh);
904 $table .= ", $recent_tbl";
905 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
907 $table .= ", $version_tbl";
908 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
910 $fields .= ",$page_tbl.pagedata as pagedata," . $this->version_tbl_fields;
911 $field_list = array_merge($field_list, array('pagedata'),
912 $this->version_tbl_field_list);
913 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
915 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
918 $search_clause = $search->makeSqlClauseObj($callback);
919 $sql = "SELECT $fields FROM $table"
920 . " WHERE $join_clause"
921 . " AND ($search_clause)"
924 // extract from,count from limit
925 list($offset,$count) = $this->limit($limit);
926 $result = $dbh->SelectLimit($sql, $count, $offset);
928 $result = $dbh->Execute($sql);
930 $iter = new WikiDB_backend_ADODB_iter($this, $result, $field_list);
932 $iter->stoplisted = $searchobj->stoplisted;
937 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
938 * not sets. See above, but the above methods find too much.
939 * This is only for already resolved wildcards:
940 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
942 function _sql_set(&$pagenames) {
944 foreach ($pagenames as $p) {
945 $s .= ($this->_dbh->qstr($p).",");
947 return substr($s,0,-1).")";
951 * Find highest or lowest hit counts.
953 function most_popular($limit=20, $sortby='-hits') {
955 extract($this->_table_names);
962 $where = " AND hits > 0";
964 if ($sortby != '-hits') {
965 if ($order = $this->sortby($sortby, 'db')) $orderby = " ORDER BY " . $order;
968 $orderby = " ORDER BY hits $order";
970 . $this->page_tbl_fields
971 . " FROM $nonempty_tbl, $page_tbl"
972 . " WHERE $nonempty_tbl.id=$page_tbl.id"
976 // extract from,count from limit
977 list($offset,$count) = $this->limit($limit);
978 $result = $dbh->SelectLimit($sql, $count, $offset);
980 $result = $dbh->Execute($sql);
982 return new WikiDB_backend_ADODB_iter($this, $result, $this->page_tbl_field_list);
986 * Find recent changes.
988 function most_recent($params) {
991 $include_minor_revisions = false;
992 $exclude_major_revisions = false;
993 $include_all_revisions = false;
997 extract($this->_table_names);
1001 $pick[] = "mtime >= $since";
1003 if ($include_all_revisions) {
1004 // Include all revisions of each page.
1005 $table = "$page_tbl, $version_tbl";
1006 $join_clause = "$page_tbl.id=$version_tbl.id";
1008 if ($exclude_major_revisions) {
1009 // Include only minor revisions
1010 $pick[] = "minor_edit <> 0";
1012 elseif (!$include_minor_revisions) {
1013 // Include only major revisions
1014 $pick[] = "minor_edit = 0";
1018 $table = "$page_tbl, $recent_tbl";
1019 $join_clause = "$page_tbl.id=$recent_tbl.id";
1020 $table .= ", $version_tbl";
1021 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
1023 if ($exclude_major_revisions) {
1024 // Include only most recent minor revision
1025 $pick[] = 'version=latestminor';
1027 elseif (!$include_minor_revisions) {
1028 // Include only most recent major revision
1029 $pick[] = 'version=latestmajor';
1032 // Include only the latest revision (whether major or minor).
1033 $pick[] ='version=latestversion';
1041 $where_clause = $join_clause;
1043 $where_clause .= " AND " . join(" AND ", $pick);
1045 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
1047 . " WHERE $where_clause"
1048 . " ORDER BY mtime $order";
1049 // FIXME: use SQL_BUFFER_RESULT for mysql?
1051 // extract from,count from limit
1052 list($offset,$count) = $this->limit($limit);
1053 $result = $dbh->SelectLimit($sql, $count, $offset);
1055 $result = $dbh->Execute($sql);
1057 //$result->fields['version'] = $result->fields[6];
1058 return new WikiDB_backend_ADODB_iter($this, $result,
1059 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1063 * Find referenced empty pages.
1065 function wanted_pages($exclude_from='', $exclude='', $sortby='', $limit='') {
1066 $dbh = &$this->_dbh;
1067 extract($this->_table_names);
1068 if ($orderby = $this->sortby($sortby, 'db', array('pagename','wantedfrom')))
1069 $orderby = 'ORDER BY ' . $orderby;
1071 if ($exclude_from) // array of pagenames
1072 $exclude_from = " AND pp.pagename NOT IN ".$this->_sql_set($exclude_from);
1073 if ($exclude) // array of pagenames
1074 $exclude = " AND p.pagename NOT IN ".$this->_sql_set($exclude);
1077 all empty pages, independent of linkstatus:
1078 select pagename as empty from page left join nonempty using(id) where is null(nonempty.id);
1079 only all empty pages, which have a linkto:
1080 select page.pagename, linked.pagename as wantedfrom from link, page linked
1081 left join page on link.linkto=page.id left join nonempty on link.linkto=nonempty.id
1082 where nonempty.id is null and linked.id=link.linkfrom;
1084 $sql = "SELECT p.pagename, pp.pagename as wantedfrom"
1085 . " FROM $page_tbl p, $link_tbl linked"
1086 . " LEFT JOIN $page_tbl pp ON (linked.linkto = pp.id)"
1087 . " LEFT JOIN $nonempty_tbl ne ON (linked.linkto = ne.id)"
1088 . " WHERE ne.id is NULL"
1089 . " AND (p.id = linked.linkfrom)"
1094 // extract from,count from limit
1095 list($offset,$count) = $this->limit($limit);
1096 $result = $dbh->SelectLimit($sql, $count, $offset);
1098 $result = $dbh->Execute($sql);
1100 return new WikiDB_backend_ADODB_iter($this, $result, array('pagename','wantedfrom'));
1104 * Rename page in the database.
1106 function rename_page($pagename, $to) {
1107 $dbh = &$this->_dbh;
1108 extract($this->_table_names);
1110 $this->lock(array('page','version','recent','nonempty','link'));
1111 if ( ($id = $this->_get_pageid($pagename, false)) ) {
1112 if ($new = $this->_get_pageid($to, false)) {
1114 // This page does not exist (already verified before), but exists in the page table.
1115 // So we delete this page.
1116 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1117 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1118 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1119 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1120 // We have to fix all referring tables to the old id
1121 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1122 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1124 $dbh->query(sprintf("UPDATE $page_tbl SET pagename=%s WHERE id=$id",
1127 $this->unlock(array('page'));
1131 function _update_recent_table($pageid = false) {
1132 $dbh = &$this->_dbh;
1133 extract($this->_table_names);
1134 extract($this->_expressions);
1136 $pageid = (int)$pageid;
1138 // optimize: mysql can do this with one REPLACE INTO.
1139 $backend_type = $this->backendType();
1140 if (substr($backend_type,0,5) == 'mysql') {
1141 $dbh->Execute("REPLACE INTO $recent_tbl"
1142 . " (id, latestversion, latestmajor, latestminor)"
1143 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1144 . " FROM $version_tbl"
1145 . ( $pageid ? " WHERE id=$pageid" : "")
1148 $this->lock(array('recent'));
1149 $dbh->Execute("DELETE FROM $recent_tbl"
1150 . ( $pageid ? " WHERE id=$pageid" : ""));
1151 $dbh->Execute( "INSERT INTO $recent_tbl"
1152 . " (id, latestversion, latestmajor, latestminor)"
1153 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1154 . " FROM $version_tbl"
1155 . ( $pageid ? " WHERE id=$pageid" : "")
1157 $this->unlock(array('recent'));
1161 function _update_nonempty_table($pageid = false) {
1162 $dbh = &$this->_dbh;
1163 extract($this->_table_names);
1164 extract($this->_expressions);
1166 $pageid = (int)$pageid;
1168 extract($this->_expressions);
1169 $this->lock(array('nonempty'));
1170 $dbh->Execute("DELETE FROM $nonempty_tbl"
1171 . ( $pageid ? " WHERE id=$pageid" : ""));
1172 $dbh->Execute("INSERT INTO $nonempty_tbl (id)"
1173 . " SELECT $recent_tbl.id"
1174 . " FROM $recent_tbl, $version_tbl"
1175 . " WHERE $recent_tbl.id=$version_tbl.id"
1176 . " AND version=latestversion"
1177 // We have some specifics here (Oracle)
1178 //. " AND content<>''"
1179 . " AND content $notempty" // On Oracle not just "<>''"
1180 . ( $pageid ? " AND $recent_tbl.id=$pageid" : ""));
1181 $this->unlock(array('nonempty'));
1185 * Grab a write lock on the tables in the SQL database.
1187 * Calls can be nested. The tables won't be unlocked until
1188 * _unlock_database() is called as many times as _lock_database().
1192 function lock($tables, $write_lock = true) {
1193 $this->_dbh->StartTrans();
1194 if ($this->_lock_count++ == 0) {
1195 $this->_current_lock = $tables;
1196 $this->_lock_tables($tables, $write_lock);
1201 * Overridden by non-transaction safe backends.
1203 function _lock_tables($tables, $write_lock) {
1204 return $this->_current_lock;
1208 * Release a write lock on the tables in the SQL database.
1212 * @param $force boolean Unlock even if not every call to lock() has been matched
1213 * by a call to unlock().
1215 * @see _lock_database
1217 function unlock($tables = false, $force = false) {
1218 if ($this->_lock_count == 0) {
1219 $this->_current_lock = false;
1222 if (--$this->_lock_count <= 0 || $force) {
1223 $this->_unlock_tables($tables, $force);
1224 $this->_current_lock = false;
1225 $this->_lock_count = 0;
1227 $this->_dbh->CompleteTrans(! $force);
1231 * overridden by non-transaction safe backends
1233 function _unlock_tables($tables, $write_lock=false) {
1240 function _serialize($data) {
1243 assert(is_array($data));
1244 return serialize($data);
1250 function _unserialize($data) {
1251 return empty($data) ? array() : unserialize($data);
1254 /* some variables and functions for DB backend abstraction (action=upgrade) */
1255 function database () {
1256 return $this->_dbh->database;
1258 function backendType() {
1259 return $this->_dbh->databaseType;
1261 function connection() {
1262 return $this->_dbh->_connectionID;
1264 function getRow($query) {
1265 return $this->_dbh->getRow($query);
1268 function listOfTables() {
1269 return $this->_dbh->MetaTables();
1272 // other database needs another connection and other privileges.
1273 function listOfFields($database, $table) {
1274 $field_list = array();
1275 $old_db = $this->database();
1276 if ($database != $old_db) {
1277 $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'],
1278 DBADMIN_USER ? DBADMIN_USER : $this->_parsedDSN['username'],
1279 DBADMIN_PASSWD ? DBADMIN_PASSWD : $this->_parsedDSN['password'],
1282 foreach ($this->_dbh->MetaColumns($table, false) as $field) {
1283 $field_list[] = $field->name;
1285 if ($database != $old_db) {
1286 $this->_dbh->close();
1287 $conn = $this->_dbh->Connect($this->_parsedDSN['hostspec'],
1288 $this->_parsedDSN['username'],
1289 $this->_parsedDSN['password'],
1297 class WikiDB_backend_ADODB_generic_iter
1298 extends WikiDB_backend_iterator
1300 function WikiDB_backend_ADODB_generic_iter($backend, $query_result, $field_list = NULL) {
1301 $this->_backend = &$backend;
1302 $this->_result = $query_result;
1304 if (is_null($field_list)) {
1305 // No field list passed, retrieve from DB
1306 // WikiLens is using the iterator behind the scene
1307 $field_list = array();
1308 $fields = $query_result->FieldCount();
1309 for ($i = 0; $i < $fields ; $i++) {
1310 $field_info = $query_result->FetchField($i);
1311 array_push($field_list, $field_info->name);
1315 $this->_fields = $field_list;
1319 if (!$this->_result) {
1322 $count = $this->_result->numRows();
1323 //$this->_result->Close();
1328 $result = &$this->_result;
1329 $backend = &$this->_backend;
1330 if (!$result || $result->EOF) {
1335 // Convert array to hash
1337 $rec_num = $result->fields;
1338 foreach ($this->_fields as $field) {
1339 $rec_assoc[$field] = $rec_num[$i++];
1341 // check if the cache can be populated here?
1343 $result->MoveNext();
1348 if ($this->_result) {
1349 $this->_result->MoveFirst();
1352 function asArray () {
1354 while ($page = $this->next())
1360 if ($this->_result) {
1361 /* call mysql_free_result($this->_queryID) */
1362 $this->_result->Close();
1363 $this->_result = false;
1368 class WikiDB_backend_ADODB_iter
1369 extends WikiDB_backend_ADODB_generic_iter
1372 $result = &$this->_result;
1373 $backend = &$this->_backend;
1374 if (!$result || $result->EOF) {
1379 // Convert array to hash
1381 $rec_num = $result->fields;
1382 foreach ($this->_fields as $field) {
1383 $rec_assoc[$field] = $rec_num[$i++];
1386 $result->MoveNext();
1387 if (isset($rec_assoc['pagedata']))
1388 $rec_assoc['pagedata'] = $backend->_extract_page_data($rec_assoc['pagedata'], $rec_assoc['hits']);
1389 if (!empty($rec_assoc['version'])) {
1390 $rec_assoc['versiondata'] = $backend->_extract_version_data_assoc($rec_assoc);
1392 if (!empty($rec_assoc['linkrelation'])) {
1393 $rec_assoc['linkrelation'] = $rec_assoc['linkrelation']; // pagename enough?
1399 class WikiDB_backend_ADODB_search extends WikiDB_backend_search_sql
1401 // no surrounding quotes because we know it's a string
1402 // function _quote($word) { return $this->_dbh->escapeSimple($word); }
1405 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1406 // Eventually, change index.php to provide the relevant information
1409 * Parse a data source name.
1411 * Additional keys can be added by appending a URI query string to the
1414 * The format of the supplied DSN is in its fullest form:
1416 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1419 * Most variations are allowed:
1421 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1422 * phptype://username:password@hostspec/database_name
1423 * phptype://username:password@hostspec
1424 * phptype://username@hostspec
1425 * phptype://hostspec/database
1426 * phptype://hostspec
1431 * @param string $dsn Data Source Name to be parsed
1433 * @return array an associative array with the following keys:
1434 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1435 * + dbsyntax: Database used with regards to SQL syntax etc.
1436 * + protocol: Communication protocol to use (tcp, unix etc.)
1437 * + hostspec: Host specification (hostname[:port])
1438 * + database: Database to use on the DBMS server
1439 * + username: User name for login
1440 * + password: Password for login
1442 * @author Tomas V.V.Cox <cox@idecnet.com>
1444 function parseDSN($dsn)
1448 'dbsyntax' => false,
1449 'username' => false,
1450 'password' => false,
1451 'protocol' => false,
1452 'hostspec' => false,
1455 'database' => false,
1458 if (is_array($dsn)) {
1459 $dsn = array_merge($parsed, $dsn);
1460 if (!$dsn['dbsyntax']) {
1461 $dsn['dbsyntax'] = $dsn['phptype'];
1466 // Find phptype and dbsyntax
1467 if (($pos = strpos($dsn, '://')) !== false) {
1468 $str = substr($dsn, 0, $pos);
1469 $dsn = substr($dsn, $pos + 3);
1475 // Get phptype and dbsyntax
1476 // $str => phptype(dbsyntax)
1477 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1478 $parsed['phptype'] = $arr[1];
1479 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1481 $parsed['phptype'] = $str;
1482 $parsed['dbsyntax'] = $str;
1489 // Get (if found): username and password
1490 // $dsn => username:password@protocol+hostspec/database
1491 if (($at = strrpos($dsn,'@')) !== false) {
1492 $str = substr($dsn, 0, $at);
1493 $dsn = substr($dsn, $at + 1);
1494 if (($pos = strpos($str, ':')) !== false) {
1495 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1496 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1498 $parsed['username'] = rawurldecode($str);
1502 // Find protocol and hostspec
1504 // $dsn => proto(proto_opts)/database
1505 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1507 $proto_opts = $match[2] ? $match[2] : false;
1510 // $dsn => protocol+hostspec/database (old format)
1512 if (strpos($dsn, '+') !== false) {
1513 list($proto, $dsn) = explode('+', $dsn, 2);
1515 if (strpos($dsn, '/') !== false) {
1516 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1523 // process the different protocol options
1524 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1525 $proto_opts = rawurldecode($proto_opts);
1526 if ($parsed['protocol'] == 'tcp') {
1527 if (strpos($proto_opts, ':') !== false) {
1528 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1530 $parsed['hostspec'] = $proto_opts;
1532 } elseif ($parsed['protocol'] == 'unix') {
1533 $parsed['socket'] = $proto_opts;
1536 // Get dabase if any
1540 if (($pos = strpos($dsn, '?')) === false) {
1541 $parsed['database'] = $dsn;
1542 // /database?param1=value1¶m2=value2
1544 $parsed['database'] = substr($dsn, 0, $pos);
1545 $dsn = substr($dsn, $pos + 1);
1546 if (strpos($dsn, '&') !== false) {
1547 $opts = explode('&', $dsn);
1548 } else { // database?param1=value1
1549 $opts = array($dsn);
1551 foreach ($opts as $opt) {
1552 list($key, $value) = explode('=', $opt);
1553 if (!isset($parsed[$key])) {
1554 // don't allow params overwrite
1555 $parsed[$key] = rawurldecode($value);
1567 // c-basic-offset: 4
1568 // c-hanging-comment-ender-p: nil
1569 // indent-tabs-mode: nil