3 * Copyright © 2005 $ThePhpWikiProgrammingTeam
5 * This file is part of PhpWiki.
7 * PhpWiki is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * PhpWiki is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * SPDX-License-Identifier: GPL-2.0-or-later
26 * @author: Reini Urban
29 require_once 'lib/WikiDB/backend.php';
31 class WikiDB_backend_PDO
32 extends WikiDB_backend
34 function __construct($dbparams)
36 $this->_dbparams = $dbparams;
37 if (strstr($dbparams['dsn'], "://")) { // pear DB syntax
38 $parsed = parseDSN($dbparams['dsn']);
39 $this->_parsedDSN = $parsed;
40 /* Need to convert the DSN
41 * dbtype(dbsyntax)://username:password@protocol+hostspec/database?option=value&option2=value2
42 * to dbtype:option1=value1;option2=value2
43 * PDO passes the DSN verbatim to the driver. But we need to extract the username + password
44 * and cannot rely that the parseDSN keys have the same name as needed by the driver.
45 * e.g: odbc:DSN=SAMPLE;UID=db2inst1;PWD=ibmdb2, mysql:host=127.0.0.1;dbname=testdb
47 $driver = $parsed['phptype'];
48 if ($driver == "mysqli") {
51 unset($parsed['phptype']);
52 unset($parsed['dbsyntax']);
53 $dbparams['dsn'] = $driver . ":";
54 if (!isset($this->_dbh)) {
55 $this->_dbh = new stdClass();
57 $this->_dbh->database = $parsed['database'];
58 // mysql needs to map database=>dbname, hostspec=>host. TODO for the others.
59 $dsnmap = array('mysql' => array('database' => 'dbname', 'hostspec' => 'host'));
60 foreach (array('protocol', 'hostspec', 'port', 'socket', 'database') as $option) {
61 if (!empty($parsed[$option])) {
62 $optionname = (isset($dsnmap[$driver][$option]) and !isset($parsed[$optionname]))
63 ? $dsnmap[$driver][$option]
65 $dbparams['dsn'] .= ($optionname . "=" . $parsed[$option] . ";");
66 unset($parsed[$optionname]);
68 unset($parsed[$option]);
70 unset($parsed['username']);
71 unset($parsed['password']);
72 // pass the rest verbatim to the driver.
73 foreach ($parsed as $option => $value) {
74 $dbparams['dsn'] .= ($option . "=" . $value . ";");
77 list($driver, $dsn) = explode(":", $dbparams['dsn'], 2);
78 foreach (explode(";", trim($dsn)) as $pair) {
80 list($option, $value) = explode("=", $pair, 2);
81 $this->_parsedDSN[$option] = $value;
84 $this->_dbh->database = isset($this->_parsedDSN['database'])
85 ? $this->_parsedDSN['database']
86 : $this->_parsedDSN['dbname'];
88 if (empty($this->_parsedDSN['password'])) {
89 $this->_parsedDSN['password'] = '';
93 // persistent is defined as DSN option, or with a config value.
94 // phptype://username:password@hostspec/database?persistent=false
95 $this->_dbh = new PDO($dbparams['dsn'],
96 $this->_parsedDSN['username'],
97 $this->_parsedDSN['password'],
98 array(PDO::ATTR_AUTOCOMMIT => true,
99 PDO::ATTR_TIMEOUT => DATABASE_TIMEOUT,
100 PDO::ATTR_PERSISTENT => !empty($parsed['persistent'])
101 or DATABASE_PERSISTENT
103 } catch (PDOException $e) {
104 echo "<br>\nCan't connect to database: " . $e->getMessage();
105 if (DEBUG & _DEBUG_VERBOSE or DEBUG & _DEBUG_SQL) {
106 echo "<br>\nDSN: '", $dbparams['dsn'], "'";
107 echo "<br>\n_parsedDSN: '", print_r($this->_parsedDSN), "'";
108 echo "<br>\nparsed: '", print_r($parsed), "'";
110 if (isset($dbparams['_tryroot_from_upgrade']))
111 trigger_error(sprintf("Can't connect to database: %s", $e->getMessage()),
116 if (DEBUG & _DEBUG_SQL) { // not yet implemented
117 $this->_dbh->debug = true;
119 $this->_dsn = $dbparams['dsn'];
120 $this->_dbh->databaseType = $driver;
121 $this->_dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
122 // Use the faster FETCH_NUM, with some special ASSOC based exceptions.
124 $this->_hasTransactions = true;
126 $this->_dbh->beginTransaction();
127 } catch (PDOException $e) {
128 $this->_hasTransactions = false;
130 $sth = $this->_dbh->prepare("SELECT version()");
132 $this->_serverinfo['version'] = $sth->fetchColumn();
133 $this->commit(); // required to match the try catch block above!
135 $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
137 = array('page_tbl' => $prefix . 'page',
138 'version_tbl' => $prefix . 'version',
139 'link_tbl' => $prefix . 'link',
140 'recent_tbl' => $prefix . 'recent',
141 'nonempty_tbl' => $prefix . 'nonempty');
142 $page_tbl = $this->_table_names['page_tbl'];
143 $version_tbl = $this->_table_names['version_tbl'];
144 $this->page_tbl_fields = "$page_tbl.id AS id, $page_tbl.pagename AS pagename, "
145 . "$page_tbl.hits hits";
146 $this->page_tbl_field_list = array('id', 'pagename', 'hits');
147 $this->version_tbl_fields = "$version_tbl.version AS version, "
148 . "$version_tbl.mtime AS mtime, "
149 . "$version_tbl.minor_edit AS minor_edit, $version_tbl.content AS content, "
150 . "$version_tbl.versiondata AS versiondata";
151 $this->version_tbl_field_list = array('version', 'mtime', 'minor_edit', 'content',
155 = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)",
156 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)",
157 'maxversion' => "MAX(version)",
158 'notempty' => "<>''",
159 'iscontent' => "$version_tbl.content<>''");
160 $this->_lock_count = 0;
163 function beginTransaction()
165 if ($this->_hasTransactions)
166 $this->_dbh->beginTransaction();
171 if ($this->_hasTransactions)
172 $this->_dbh->commit();
177 if ($this->_hasTransactions)
178 $this->_dbh->rollBack();
184 $sth = $this->_dbh->prepare($sql);
185 return $sth->execute();
188 /* with one result row */
189 function getRow($sql)
191 $sth = $this->_dbh->prepare($sql);
193 return $sth->fetch(PDO::FETCH_BOTH);
199 * Close database connection.
206 if ($this->_lock_count) {
207 trigger_error("WARNING: database still locked " .
208 '(lock_count = $this->_lock_count)' . "\n<br />",
211 $this->unlock(array(), 'force');
217 * Fast test for wikipage.
219 function is_wiki_page($pagename)
222 extract($this->_table_names);
223 $sth = $dbh->prepare("SELECT $page_tbl.id AS id"
224 . " FROM $nonempty_tbl, $page_tbl"
225 . " WHERE $nonempty_tbl.id=$page_tbl.id"
226 . " AND pagename=?");
227 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
229 return $sth->fetchColumn();
234 function get_all_pagenames()
237 extract($this->_table_names);
238 $sth = $dbh->exec("SELECT pagename"
239 . " FROM $nonempty_tbl, $page_tbl"
240 . " WHERE $nonempty_tbl.id=$page_tbl.id"
242 return $sth->fetchAll(PDO::FETCH_NUM);
246 * filter (nonempty pages) currently ignored
248 function numPages($filter = false, $exclude = '')
251 extract($this->_table_names);
252 $sth = $dbh->query("SELECT count(*)"
253 . " FROM $nonempty_tbl, $page_tbl"
254 . " WHERE $nonempty_tbl.id=$page_tbl.id");
255 return $sth->fetchColumn();
258 function increaseHitCount($pagename)
261 $page_tbl = $this->_table_names['page_tbl'];
262 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=hits+1"
263 . " WHERE pagename=?"
265 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
270 * Read page information from database.
272 function get_pagedata($pagename)
275 $page_tbl = $this->_table_names['page_tbl'];
276 $sth = $dbh->prepare("SELECT id,pagename,hits,pagedata FROM $page_tbl"
277 . " WHERE pagename=? LIMIT 1");
278 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
280 $row = $sth->fetch(PDO::FETCH_NUM);
281 return $row ? $this->_extract_page_data($row[3], $row[2]) : false;
284 public function _extract_page_data($data, $hits)
287 return array('hits' => $hits);
289 return array_merge(array('hits' => $hits), $this->_unserialize($data));
292 function update_pagedata($pagename, $newdata)
295 $page_tbl = $this->_table_names['page_tbl'];
297 // Hits is the only thing we can update in a fast manner.
298 if (count($newdata) == 1 && isset($newdata['hits'])) {
299 // Note that this will fail silently if the page does not
300 // have a record in the page table. Since it's just the
301 // hit count, who cares?
302 $sth = $dbh->prepare("UPDATE $page_tbl SET hits=? WHERE pagename=? LIMIT 1");
303 $sth->bindParam(1, $newdata['hits'], PDO::PARAM_INT);
304 $sth->bindParam(2, $pagename, PDO::PARAM_STR, 100);
308 $this->beginTransaction();
309 $data = $this->get_pagedata($pagename);
312 $this->_get_pageid($pagename, true); // Creates page record
315 $hits = (empty($data['hits'])) ? 0 : (int)$data['hits'];
316 unset($data['hits']);
318 foreach ($newdata as $key => $val) {
321 else if (empty($val))
326 $sth = $dbh->prepare("UPDATE $page_tbl"
327 . " SET hits=?, pagedata=?"
328 . " WHERE pagename=?"
330 $sth->bindParam(1, $hits, PDO::PARAM_INT);
331 $serialized_data = $this->_serialize($data);
332 $sth->bindParam(2, $serialized_data, PDO::PARAM_LOB);
333 $sth->bindParam(3, $pagename, PDO::PARAM_STR, 100);
334 if ($sth->execute()) {
343 function get_cached_html($pagename)
346 $page_tbl = $this->_table_names['page_tbl'];
347 $sth = $dbh->prepare("SELECT cached_html FROM $page_tbl WHERE pagename=? LIMIT 1");
348 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
350 return $sth->fetchColumn(0);
353 function set_cached_html($pagename, $data)
356 $page_tbl = $this->_table_names['page_tbl'];
357 if (empty($data)) $data = '';
358 $sth = $dbh->prepare("UPDATE $page_tbl"
359 . " SET cached_html=?"
360 . " WHERE pagename=?"
362 $sth->bindParam(1, $data, PDO::PARAM_STR);
363 $sth->bindParam(2, $pagename, PDO::PARAM_STR, 100);
367 function _get_pageid($pagename, $create_if_missing = false)
371 $cache =& $request->_dbi->_cache->_id_cache;
372 if (isset($cache[$pagename])) {
373 if ($cache[$pagename] or !$create_if_missing) {
374 return $cache[$pagename];
378 // attributes play this game.
379 if ($pagename === '') return 0;
382 $page_tbl = $this->_table_names['page_tbl'];
383 $sth = $dbh->prepare("SELECT id FROM $page_tbl WHERE pagename=? LIMIT 1");
384 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
386 $id = $sth->fetchColumn();
387 if (!$create_if_missing) {
391 //mysql, mysqli or mysqlt
392 if (substr($dbh->databaseType, 0, 5) == 'mysql') {
393 // have auto-incrementing, atomic version
394 $sth = $dbh->prepare("INSERT INTO $page_tbl"
396 . " VALUES (NULL,?)");
397 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
399 $id = $dbh->lastInsertId();
401 $this->beginTransaction();
402 $sth = $dbh->prepare("SELECT MAX(id) FROM $page_tbl");
404 $id = $sth->fetchColumn();
405 $sth = $dbh->prepare("INSERT INTO $page_tbl"
406 . " (id,pagename,hits)"
407 . " VALUES (?,?,0)");
409 $sth->bindParam(1, $id, PDO::PARAM_INT);
410 $sth->bindParam(2, $pagename, PDO::PARAM_STR, 100);
421 function get_latest_version($pagename)
424 extract($this->_table_names);
425 $sth = $dbh->prepare("SELECT latestversion"
426 . " FROM $page_tbl, $recent_tbl"
427 . " WHERE $page_tbl.id=$recent_tbl.id"
430 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
432 return $sth->fetchColumn();
435 function get_previous_version($pagename, $version)
438 extract($this->_table_names);
439 $sth = $dbh->prepare("SELECT version"
440 . " FROM $version_tbl, $page_tbl"
441 . " WHERE $version_tbl.id=$page_tbl.id"
444 . " ORDER BY version DESC"
446 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
447 $sth->bindParam(2, $version, PDO::PARAM_INT);
449 return $sth->fetchColumn();
455 * @param string $pagename Name of the page
456 * @param int $version Which version to get
457 * @param bool $want_content Do we need content?
459 * @return array The version data, or false if specified version does not exist.
461 function get_versiondata($pagename, $version, $want_content = false)
464 extract($this->_table_names);
465 extract($this->_expressions);
467 assert(is_string($pagename) and $pagename != '');
468 assert($version > 0);
470 // FIXME: optimization: sometimes don't get page data?
472 $fields = $this->page_tbl_fields
473 . ",$page_tbl.pagedata AS pagedata,"
474 . $this->version_tbl_fields;
476 $fields = $this->page_tbl_fields . ", '' AS pagedata"
477 . ", $version_tbl.version AS version, $version_tbl.mtime AS mtime, "
478 . "$version_tbl.minor_edit AS minor_edit, $iscontent AS have_content, "
479 . "$version_tbl.versiondata as versiondata";
481 $sth = $dbh->prepare("SELECT $fields"
482 . " FROM $page_tbl, $version_tbl"
483 . " WHERE $page_tbl.id=$version_tbl.id"
487 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
488 $sth->bindParam(2, $version, PDO::PARAM_INT);
490 $row = $sth->fetch(PDO::FETCH_NUM);
491 return $row ? $this->_extract_version_data_num($row, $want_content) : false;
494 private function _extract_version_data_num($row, $want_content)
500 //$pagename &= $row[1];
501 $data = empty($row[8]) ? array() : $this->_unserialize($row[8]);
502 $data['mtime'] = $row[5];
503 $data['is_minor_edit'] = !empty($row[6]);
505 $data['%content'] = $row[7];
507 $data['%content'] = !empty($row[7]);
509 if (!empty($row[3])) {
510 $data['%pagedata'] = $this->_extract_page_data($row[3], $row[2]);
515 function _extract_version_data_assoc($row)
521 $data = empty($versiondata) ? array() : $this->_unserialize($versiondata);
522 $data['mtime'] = $mtime;
523 $data['is_minor_edit'] = !empty($minor_edit);
525 $data['%content'] = $content;
526 elseif ($have_content)
527 $data['%content'] = true; else
528 $data['%content'] = '';
529 if (!empty($pagedata)) {
530 $data['%pagedata'] = $this->_extract_page_data($pagedata, $hits);
536 * Create a new revision of a page.
538 function set_versiondata($pagename, $version, $data)
541 $version_tbl = $this->_table_names['version_tbl'];
543 $minor_edit = (int)!empty($data['is_minor_edit']);
544 unset($data['is_minor_edit']);
546 $mtime = (int)$data['mtime'];
547 unset($data['mtime']);
548 assert(!empty($mtime));
550 $content = isset($data['%content']) ? (string)$data['%content'] : '';
551 unset($data['%content']);
552 unset($data['%pagedata']);
554 $this->lock(array('page', 'recent', 'version', 'nonempty'));
555 $this->beginTransaction();
556 $id = $this->_get_pageid($pagename, true);
557 $backend_type = $this->backendType();
558 // optimize: mysql can do this with one REPLACE INTO.
559 if (substr($backend_type, 0, 5) == 'mysql') {
560 $sth = $dbh->prepare("REPLACE INTO $version_tbl"
561 . " (id,version,mtime,minor_edit,content,versiondata)"
562 . " VALUES(?,?,?,?,?,?)");
563 $sth->bindParam(1, $id, PDO::PARAM_INT);
564 $sth->bindParam(2, $version, PDO::PARAM_INT);
565 $sth->bindParam(3, $mtime, PDO::PARAM_INT);
566 $sth->bindParam(4, $minor_edit, PDO::PARAM_INT);
567 $sth->bindParam(5, $content, PDO::PARAM_STR, 100);
568 $serialized_data = $this->_serialize($data);
569 $sth->bindParam(6, $serialized_data, PDO::PARAM_STR, 100);
570 $rs = $sth->execute();
572 $sth = $dbh->prepare("DELETE FROM $version_tbl"
573 . " WHERE id=? AND version=?");
574 $sth->bindParam(1, $id, PDO::PARAM_INT);
575 $sth->bindParam(2, $version, PDO::PARAM_INT);
577 $sth = $dbh->prepare("INSERT INTO $version_tbl"
578 . " (id,version,mtime,minor_edit,content,versiondata)"
579 . " VALUES(?,?,?,?,?,?)");
580 $sth->bindParam(1, $id, PDO::PARAM_INT);
581 $sth->bindParam(2, $version, PDO::PARAM_INT);
582 $sth->bindParam(3, $mtime, PDO::PARAM_INT);
583 $sth->bindParam(4, $minor_edit, PDO::PARAM_INT);
584 $sth->bindParam(5, $content, PDO::PARAM_STR, 100);
585 $serialized_data = $this->_serialize($data);
586 $sth->bindParam(6, $serialized_data, PDO::PARAM_STR, 100);
587 $rs = $sth->execute();
589 $this->_update_recent_table($id);
590 $this->_update_nonempty_table($id);
596 $this->unlock(array('page', 'recent', 'version', 'nonempty'));
600 * Delete an old revision of a page.
602 function delete_versiondata($pagename, $version)
605 extract($this->_table_names);
607 $this->lock(array('version'));
608 if (($id = $this->_get_pageid($pagename))) {
609 $dbh->query("DELETE FROM $version_tbl"
610 . " WHERE id=$id AND version=$version");
611 $this->_update_recent_table($id);
612 // This shouldn't be needed (as long as the latestversion
613 // never gets deleted.) But, let's be safe.
614 $this->_update_nonempty_table($id);
616 $this->unlock(array('version'));
620 * Delete page from the database with backup possibility.
621 * i.e save_page('') and DELETE nonempty id
623 * deletePage increments latestversion in recent to a non-existent version,
624 * and removes the nonempty row,
625 * so that get_latest_version returns id+1 and get_previous_version returns prev id
626 * and page->exists returns false.
628 function delete_page($pagename)
631 * @var WikiRequest $request
636 extract($this->_table_names);
638 $this->beginTransaction();
639 //$dbh->CommitLock($recent_tbl);
640 if (($id = $this->_get_pageid($pagename, false)) === false) {
645 $user =& $request->_user;
646 $meta = array('author' => $user->getId(),
647 'author_id' => $user->getAuthenticatedId(),
649 $this->lock(array('version', 'recent', 'nonempty', 'page', 'link'));
650 $version = $this->get_latest_version($pagename);
651 if ($dbh->query("UPDATE $recent_tbl SET latestversion=latestversion+1,"
652 . "latestmajor=latestversion+1,latestminor=NULL WHERE id=$id")
654 $insert = $dbh->prepare("INSERT INTO $version_tbl"
655 . " (id,version,mtime,minor_edit,content,versiondata)"
656 . " VALUES(?,?,?,?,?,?)");
657 $version_plus_1 = $version + 1;
660 $insert->bindParam(1, $id, PDO::PARAM_INT);
661 $insert->bindParam(2, $version_plus_1, PDO::PARAM_INT);
662 $insert->bindParam(3, $mtime, PDO::PARAM_INT);
663 $insert->bindParam(4, $zero, PDO::PARAM_INT);
664 $insert->bindParam(5, $empty_string, PDO::PARAM_STR, 100);
665 $insert->bindParam(6, $this->_serialize($meta), PDO::PARAM_STR, 100);
666 if ($insert->execute()
667 and $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id")
668 and $this->set_links($pagename, array())
670 // need to keep perms and LOCKED, otherwise you can reset the perm
671 // by action=remove and re-create it with default perms
672 // keep hits but delete meta-data
673 //and $dbh->Execute("UPDATE $page_tbl SET pagedata='' WHERE id=$id")
674 $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
679 $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
687 * Delete page completely from the database.
689 function purge_page($pagename)
692 extract($this->_table_names);
694 $this->lock(array('version', 'recent', 'nonempty', 'page', 'link'));
695 if (($id = $this->_get_pageid($pagename, false))) {
696 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$id");
697 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id");
698 $dbh->query("DELETE FROM $version_tbl WHERE id=$id");
699 $this->set_links($pagename, array());
700 $sth = $dbh->prepare("SELECT COUNT(*) FROM $link_tbl WHERE linkto=$id");
702 if ($sth->fetchColumn()) {
703 // We're still in the link table (dangling link) so we can't delete this
705 $dbh->query("UPDATE $page_tbl SET hits=0, pagedata='' WHERE id=$id");
708 $dbh->query("DELETE FROM $page_tbl WHERE id=$id");
712 $result = -1; // already purged or not existing
714 $this->unlock(array('version', 'recent', 'nonempty', 'page', 'link'));
719 * Set links for page.
721 * @param string $pagename Page name
722 * @param array $links List of page(names) which page links to.
724 * on DEBUG: delete old, deleted links from page
726 function set_links($pagename, $links)
728 // Update link table.
729 // FIXME: optimize: mysql can do this all in one big INSERT/REPLACE.
732 extract($this->_table_names);
734 $this->lock(array('link'));
735 $pageid = $this->_get_pageid($pagename, true);
738 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
739 foreach ($links as $link) {
740 if (isset($linkseen[$link]))
742 $linkseen[$link] = true;
743 $linkid = $this->_get_pageid($link, true);
745 $dbh->query("INSERT INTO $link_tbl (linkfrom, linkto)"
746 . " VALUES ($pageid, $linkid)");
749 // purge page table: delete all non-referenced pages
750 // for all previously linked pages...
751 $sth = $dbh->prepare("SELECT $link_tbl.linkto as id FROM $link_tbl" .
752 " WHERE linkfrom=$pageid");
754 foreach ($sth->fetchAll(PDO::FETCH_NUM) as $id) {
755 // ...check if the page is empty and has no version
756 $sth1 = $dbh->prepare("SELECT $page_tbl.id FROM $page_tbl"
757 . " LEFT JOIN $nonempty_tbl USING (id) "
758 . " LEFT JOIN $version_tbl USING (id)"
759 . " WHERE ISNULL($nonempty_tbl.id) AND"
760 . " ISNULL($version_tbl.id) AND $page_tbl.id=$id");
762 if ($sth1->fetchColumn()) {
763 $dbh->query("DELETE FROM $page_tbl WHERE id=$id"); // this purges the link
764 $dbh->query("DELETE FROM $recent_tbl WHERE id=$id"); // may fail
767 $dbh->query("DELETE FROM $link_tbl WHERE linkfrom=$pageid");
769 $this->unlock(array('link'));
774 * Find pages which link to or are linked from a page.
776 * @param string $pagename Page name
777 * @param bool $reversed True to get backlinks
778 * @param bool $include_empty True to get empty pages
779 * @param string $sortby
780 * @param string $limit
781 * @param string $exclude Pages to exclude
782 * @param bool $want_relations
784 * FIXME: array or iterator?
785 * @return object A WikiDB_backend_iterator.
787 * Optimization: save request->_dbi->_iwpcache[] to avoid further iswikipage checks
788 * (linkExistingWikiWord or linkUnknownWikiWord)
789 * This is called on every page header GleanDescription, so we can store all the
792 function get_links($pagename, $reversed = true, $include_empty = false,
793 $sortby = '', $limit = '', $exclude = '',
794 $want_relations = false)
797 extract($this->_table_names);
800 list($have, $want) = array('linkee', 'linker');
802 list($have, $want) = array('linker', 'linkee');
803 $orderby = $this->sortby($sortby, 'db', array('pagename'));
804 if ($orderby) $orderby = " ORDER BY $want." . $orderby;
805 if ($exclude) // array of pagenames
806 $exclude = " AND $want.pagename NOT IN " . $this->_sql_set($exclude);
809 $limit = $this->_limit_sql($limit);
811 $sth = $dbh->prepare("SELECT $want.id AS id, $want.pagename AS pagename,"
812 . " $want.hits AS hits"
813 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee"
814 . (!$include_empty ? ", $nonempty_tbl" : '')
815 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
816 . " AND $have.pagename=?"
817 . (!$include_empty ? " AND $nonempty_tbl.id=$want.id" : "")
818 //. " GROUP BY $want.id"
822 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
824 $result = $sth->fetch(PDO::FETCH_BOTH);
825 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
829 * Find if a page links to another page
831 function exists_link($pagename, $link, $reversed = false)
834 extract($this->_table_names);
837 list($have, $want) = array('linkee', 'linker');
839 list($have, $want) = array('linker', 'linkee');
840 $sth = $dbh->prepare("SELECT CASE WHEN $want.pagename THEN 1 ELSE 0 END"
841 . " FROM $link_tbl, $page_tbl linker, $page_tbl linkee, $nonempty_tbl"
842 . " WHERE linkfrom=linker.id AND linkto=linkee.id"
843 . " AND $have.pagename=?"
844 . " AND $want.pagename=?");
845 $sth->bindParam(1, $pagename, PDO::PARAM_STR, 100);
846 $sth->bindParam(2, $link, PDO::PARAM_STR, 100);
848 return $sth->fetchColumn();
851 public function get_all_pages($include_empty = false,
852 $sortby = '', $limit = '', $exclude = '')
855 extract($this->_table_names);
856 $orderby = $this->sortby($sortby, 'db');
858 $orderby = ' ORDER BY ' . $orderby;
860 if ($exclude) { // array of pagenames
861 $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
865 $limit = $this->_limit_sql($limit);
867 if (strstr($orderby, 'mtime ')) { // multiple columns possible
868 if ($include_empty) {
870 . $this->page_tbl_fields
871 . " FROM $page_tbl, $recent_tbl, $version_tbl"
872 . " WHERE $page_tbl.id=$recent_tbl.id"
873 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
878 . $this->page_tbl_fields
879 . " FROM $nonempty_tbl, $page_tbl, $recent_tbl, $version_tbl"
880 . " WHERE $nonempty_tbl.id=$page_tbl.id"
881 . " AND $page_tbl.id=$recent_tbl.id"
882 . " AND $page_tbl.id=$version_tbl.id AND latestversion=version"
887 if ($include_empty) {
889 . $this->page_tbl_fields
891 . ($exclude ? " WHERE $exclude" : '')
895 . $this->page_tbl_fields
896 . " FROM $nonempty_tbl, $page_tbl"
897 . " WHERE $nonempty_tbl.id=$page_tbl.id"
902 $sth = $dbh->prepare($sql . $limit);
904 $result = $sth->fetch(PDO::FETCH_BOTH);
905 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
909 * Text search (title or full text)
911 public function text_search($search, $fulltext = false,
912 $sortby = '', $limit = '', $exclude = '')
915 extract($this->_table_names);
916 $orderby = $this->sortby($sortby, 'db');
918 $orderby = ' ORDER BY ' . $orderby;
920 $limit = $this->_limit_sql($limit);
922 $table = "$nonempty_tbl, $page_tbl";
923 $join_clause = "$nonempty_tbl.id=$page_tbl.id";
924 $fields = $this->page_tbl_fields;
925 $field_list = $this->page_tbl_field_list;
926 $searchobj = new WikiDB_backend_PDO_search($search, $dbh);
929 $table .= ", $recent_tbl";
930 $join_clause .= " AND $page_tbl.id=$recent_tbl.id";
932 $table .= ", $version_tbl";
933 $join_clause .= " AND $page_tbl.id=$version_tbl.id AND latestversion=version";
935 $fields .= ", $page_tbl.pagedata as pagedata, " . $this->version_tbl_fields;
936 $field_list = array_merge($field_list, array('pagedata'), $this->version_tbl_field_list);
937 $callback = new WikiMethodCb($searchobj, "_fulltext_match_clause");
939 $callback = new WikiMethodCb($searchobj, "_pagename_match_clause");
941 $search_clause = $search->makeSqlClauseObj($callback);
942 $sth = $dbh->prepare("SELECT $fields FROM $table"
943 . " WHERE $join_clause"
944 . " AND ($search_clause)"
948 $result = $sth->fetch(PDO::FETCH_NUM);
949 $iter = new WikiDB_backend_PDO_iter($this, $result, $field_list);
950 $iter->stoplisted = $searchobj->stoplisted;
955 * TODO: efficiently handle wildcards exclusion: exclude=Php* => 'Php%',
956 * not sets. See above, but the above methods find too much.
957 * This is only for already resolved wildcards:
958 * " WHERE $page_tbl.pagename NOT IN ".$this->_sql_set(array('page1','page2'));
960 function _sql_set(&$pagenames)
963 foreach ($pagenames as $p) {
964 $s .= ($this->_dbh->quote($p) . ",");
966 return substr($s, 0, -1) . ")";
970 * Find highest or lowest hit counts.
972 public function most_popular($limit = 20, $sortby = '-hits')
975 extract($this->_table_names);
982 $where = " AND hits > 0";
985 if ($sortby != '-hits') {
986 if ($order = $this->sortby($sortby, 'db'))
987 $orderby = " ORDER BY " . $order;
989 $orderby = " ORDER BY hits $order";
992 . $this->page_tbl_fields
993 . " FROM $nonempty_tbl, $page_tbl"
994 . " WHERE $nonempty_tbl.id=$page_tbl.id"
998 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1000 $sth = $dbh->prepare($sql);
1003 $result = $sth->fetch(PDO::FETCH_NUM);
1004 return new WikiDB_backend_PDO_iter($this, $result, $this->page_tbl_field_list);
1008 * Find recent changes.
1010 public function most_recent($params)
1014 $include_minor_revisions = false;
1015 $exclude_major_revisions = false;
1016 $include_all_revisions = false;
1019 $dbh = &$this->_dbh;
1020 extract($this->_table_names);
1024 $pick[] = "mtime >= $since";
1027 if ($include_all_revisions) {
1028 // Include all revisions of each page.
1029 $table = "$page_tbl, $version_tbl";
1030 $join_clause = "$page_tbl.id=$version_tbl.id";
1032 if ($exclude_major_revisions) {
1033 // Include only minor revisions
1034 $pick[] = "minor_edit <> 0";
1035 } elseif (!$include_minor_revisions) {
1036 // Include only major revisions
1037 $pick[] = "minor_edit = 0";
1040 $table = "$page_tbl, $recent_tbl";
1041 $join_clause = "$page_tbl.id=$recent_tbl.id";
1042 $table .= ", $version_tbl";
1043 $join_clause .= " AND $version_tbl.id=$page_tbl.id";
1045 if ($exclude_major_revisions) {
1046 // Include only most recent minor revision
1047 $pick[] = 'version=latestminor';
1048 } elseif (!$include_minor_revisions) {
1049 // Include only most recent major revision
1050 $pick[] = 'version=latestmajor';
1052 // Include only the latest revision (whether major or minor).
1053 $pick[] = 'version=latestversion';
1061 $where_clause = $join_clause;
1063 $where_clause .= " AND " . join(" AND ", $pick);
1066 . $this->page_tbl_fields . ", " . $this->version_tbl_fields
1068 . " WHERE $where_clause"
1069 . " ORDER BY mtime $order";
1071 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1073 $sth = $dbh->prepare($sql);
1076 $result = $sth->fetch(PDO::FETCH_NUM);
1077 return new WikiDB_backend_PDO_iter($this, $result,
1078 array_merge($this->page_tbl_field_list, $this->version_tbl_field_list));
1082 * Find referenced empty pages.
1084 function wanted_pages($exclude_from = '', $exclude = '', $sortby = '', $limit = '')
1086 $dbh = &$this->_dbh;
1087 extract($this->_table_names);
1088 if ($orderby = $this->sortby($sortby, 'db', array('pagename', 'wantedfrom')))
1089 $orderby = 'ORDER BY ' . $orderby;
1091 if ($exclude_from) { // array of pagenames
1092 $exclude_from = " AND linked.pagename NOT IN " . $this->_sql_set($exclude_from);
1094 if ($exclude) { // array of pagenames
1095 $exclude = " AND $page_tbl.pagename NOT IN " . $this->_sql_set($exclude);
1099 all empty pages, independent of linkstatus:
1100 select pagename as empty from page left join nonempty using(id) where isnull(nonempty.id);
1101 only all empty pages, which have a linkto:
1102 select page.pagename, linked.pagename as wantedfrom from link, page as linked
1103 left join page on(link.linkto=page.id) left join nonempty on(link.linkto=nonempty.id)
1104 where isnull(nonempty.id) and linked.id=link.linkfrom;
1106 $sql = "SELECT p.pagename, pp.pagename AS wantedfrom"
1107 . " FROM $page_tbl p JOIN $link_tbl linked"
1108 . " LEFT JOIN $page_tbl pp ON linked.linkto = pp.id"
1109 . " LEFT JOIN $nonempty_tbl ne ON linked.linkto = ne.id"
1110 . " WHERE ne.id IS NULL"
1111 . " AND p.id = linked.linkfrom"
1116 $sth = $dbh->prepare($sql . $this->_limit_sql($limit));
1118 $sth = $dbh->prepare($sql);
1121 $result = $sth->fetch(PDO::FETCH_NUM);
1122 return new WikiDB_backend_PDO_iter($this, $result, array('pagename', 'wantedfrom'));
1126 * Rename page in the database.
1128 * @param string $pagename Current page name
1129 * @param string $to Future page name
1132 function rename_page($pagename, $to)
1134 $dbh = &$this->_dbh;
1135 extract($this->_table_names);
1137 $this->lock(array('page', 'version', 'recent', 'nonempty', 'link'));
1138 if (($id = $this->_get_pageid($pagename, false))) {
1139 if ($new = $this->_get_pageid($to, false)) {
1141 // This page does not exist (already verified before), but exists in the page table.
1142 // So we delete this page.
1143 $dbh->query("DELETE FROM $nonempty_tbl WHERE id=$new");
1144 $dbh->query("DELETE FROM $recent_tbl WHERE id=$new");
1145 $dbh->query("DELETE FROM $version_tbl WHERE id=$new");
1146 // We have to fix all referring tables to the old id
1147 $dbh->query("UPDATE $link_tbl SET linkfrom=$id WHERE linkfrom=$new");
1148 $dbh->query("UPDATE $link_tbl SET linkto=$id WHERE linkto=$new");
1149 $dbh->query("DELETE FROM $page_tbl WHERE id=$new");
1151 $sth = $dbh->prepare("UPDATE $page_tbl SET pagename=? WHERE id=?");
1152 $sth->bindParam(1, $to, PDO::PARAM_STR, 100);
1153 $sth->bindParam(2, $id, PDO::PARAM_INT);
1156 $this->unlock(array('page'));
1160 function _update_recent_table($pageid = false)
1162 $dbh = &$this->_dbh;
1163 extract($this->_table_names);
1164 extract($this->_expressions);
1166 $pageid = (int)$pageid;
1168 // optimize: mysql can do this with one REPLACE INTO.
1169 $backend_type = $this->backendType();
1170 if (substr($backend_type, 0, 5) == 'mysql') {
1171 $sth = $dbh->prepare("REPLACE INTO $recent_tbl"
1172 . " (id, latestversion, latestmajor, latestminor)"
1173 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1174 . " FROM $version_tbl"
1175 . ($pageid ? " WHERE id=$pageid" : "")
1179 $this->lock(array('recent'));
1180 $sth = $dbh->prepare("DELETE FROM $recent_tbl"
1181 . ($pageid ? " WHERE id=$pageid" : ""));
1183 $sth = $dbh->prepare("INSERT INTO $recent_tbl"
1184 . " (id, latestversion, latestmajor, latestminor)"
1185 . " SELECT id, $maxversion, $maxmajor, $maxminor"
1186 . " FROM $version_tbl"
1187 . ($pageid ? " WHERE id=$pageid" : "")
1190 $this->unlock(array('recent'));
1194 function _update_nonempty_table($pageid = false)
1196 $dbh = &$this->_dbh;
1197 extract($this->_table_names);
1198 extract($this->_expressions);
1200 $pageid = (int)$pageid;
1202 extract($this->_expressions);
1203 $this->lock(array('nonempty'));
1204 $dbh->query("DELETE FROM $nonempty_tbl"
1205 . ($pageid ? " WHERE id=$pageid" : ""));
1206 $dbh->query("INSERT INTO $nonempty_tbl (id)"
1207 . " SELECT $recent_tbl.id"
1208 . " FROM $recent_tbl, $version_tbl"
1209 . " WHERE $recent_tbl.id=$version_tbl.id"
1210 . " AND version=latestversion"
1211 // We have some specifics here (Oracle)
1212 //. " AND content<>''"
1213 . " AND content $notempty" // On Oracle not just "<>''"
1214 . ($pageid ? " AND $recent_tbl.id=$pageid" : ""));
1215 $this->unlock(array('nonempty'));
1219 * Grab a write lock on the tables in the SQL database.
1221 * Calls can be nested. The tables won't be unlocked until
1222 * _unlock_database() is called as many times as _lock_database().
1224 public function lock($tables = array(), $write_lock = true)
1226 if ($this->_lock_count++ == 0) {
1227 $this->_current_lock = $tables;
1228 if (!$this->_hasTransactions)
1229 $this->_lock_tables($tables, $write_lock);
1234 * Overridden by non-transaction safe backends.
1236 protected function _lock_tables($tables, $write_lock = true)
1238 $lock_type = $write_lock ? "WRITE" : "READ";
1239 foreach ($this->_table_names as $key => $table) {
1240 $locks[] = "$table $lock_type";
1242 $this->_dbh->query("LOCK TABLES " . join(",", $locks));
1246 * Release a write lock on the tables in the SQL database.
1248 * @param array $tables
1249 * @param bool $force Unlock even if not every call to lock() has been matched
1250 * by a call to unlock().
1252 * @see _lock_database
1254 public function unlock($tables = array(), $force = false)
1256 if ($this->_lock_count == 0) {
1257 $this->_current_lock = false;
1260 if (--$this->_lock_count <= 0 || $force) {
1261 if (!$this->_hasTransactions)
1262 $this->_unlock_tables();
1263 $this->_current_lock = false;
1264 $this->_lock_count = 0;
1269 * overridden by non-transaction safe backends
1271 protected function _unlock_tables()
1273 $this->_dbh->query("UNLOCK TABLES");
1279 function _serialize($data)
1284 assert(is_array($data));
1285 return serialize($data);
1291 function _unserialize($data)
1293 return empty($data) ? array() : unserialize($data);
1296 /* some variables and functions for DB backend abstraction (action=upgrade) */
1299 return $this->_dbh->database;
1302 function backendType()
1304 return $this->_dbh->databaseType;
1307 function connection()
1309 trigger_error("PDO: connectionID unsupported", E_USER_ERROR);
1313 function listOfTables()
1315 trigger_error("PDO: virtual listOfTables", E_USER_ERROR);
1320 * LIMIT with OFFSET is not SQL specified.
1321 * mysql: LIMIT $offset, $count
1322 * pgsql,sqlite: LIMIT $count OFFSET $offset
1323 * InterBase,FireBird: ROWS $offset TO $last
1324 * mssql: TOP $rows => TOP $last
1326 * IBM DB2: FetchFirst
1327 * See http://search.cpan.org/dist/SQL-Abstract-Limit/lib/SQL/Abstract/Limit.pm
1329 SELECT field_list FROM $table X WHERE where_clause AND
1331 SELECT COUNT(*) FROM $table WHERE $pk > X.$pk
1333 BETWEEN $offset AND $last
1334 ORDER BY $pk $asc_desc
1336 function _limit_sql($limit = false)
1339 list($offset, $count) = $this->limit($limit);
1341 $limit = " LIMIT $count";
1342 trigger_error("unsupported OFFSET in SQL ignored", E_USER_WARNING);
1344 $limit = " LIMIT $count";
1350 function write_accesslog(&$entry)
1352 $dbh = &$this->_dbh;
1353 $log_tbl = $entry->_accesslog->logtable;
1354 $sth = $dbh->prepare("INSERT INTO $log_tbl"
1355 . " (time_stamp,remote_host,remote_user,request_method,request_line,request_args,"
1356 . "request_file,request_uri,request_time,status,bytes_sent,referer,agent,request_duration)"
1357 . " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
1358 // Either use unixtime as %d (long), or the native timestamp format.
1359 $sth->bindParam(1, $entry->time, PDO::PARAM_INT);
1360 $sth->bindParam(2, $entry->host, PDO::PARAM_STR, 100);
1361 $sth->bindParam(3, $entry->user, PDO::PARAM_STR, 50);
1362 $sth->bindParam(4, $entry->request_method, PDO::PARAM_STR, 10);
1363 $sth->bindParam(5, $entry->request, PDO::PARAM_STR, 255);
1364 $sth->bindParam(6, $entry->request_args, PDO::PARAM_STR, 255);
1365 $sth->bindParam(7, $entry->request_uri, PDO::PARAM_STR, 255);
1366 $ncsa_time = _ncsa_time($entry->time);
1367 $sth->bindParam(8, $ncsa_time, PDO::PARAM_STR, 28);
1368 $sth->bindParam(9, $entry->time, PDO::PARAM_INT);
1369 $sth->bindParam(10, $entry->status, PDO::PARAM_INT);
1370 $sth->bindParam(11, $entry->size, PDO::PARAM_INT);
1371 $sth->bindParam(12, $entry->referer, PDO::PARAM_STR, 255);
1372 $sth->bindParam(13, $entry->user_agent, PDO::PARAM_STR, 255);
1373 $sth->bindParam(14, $entry->duration, PDO::PARAM_STR);
1378 class WikiDB_backend_PDO_generic_iter
1379 extends WikiDB_backend_iterator
1381 function __construct($backend, $query_result, $field_list = NULL)
1383 $this->_backend = &$backend;
1384 $this->_result = $query_result;
1385 //$this->_fields = $field_list;
1390 if (!is_object($this->_result)) {
1393 $count = $this->_result->rowCount();
1399 $result = &$this->_result;
1400 if (!is_object($result)) {
1403 return $result->fetch(PDO::FETCH_BOTH);
1408 if ($this->_result) {
1409 unset($this->_result);
1414 class WikiDB_backend_PDO_iter
1415 extends WikiDB_backend_PDO_generic_iter
1419 $result = &$this->_result;
1420 if (!is_object($result)) {
1423 $this->_backend = &$backend;
1424 $rec = $result->fetch(PDO::FETCH_ASSOC);
1426 if (isset($rec['pagedata']))
1427 $rec['pagedata'] = $backend->_extract_page_data($rec['pagedata'], $rec['hits']);
1428 if (!empty($rec['version'])) {
1429 $rec['versiondata'] = $backend->_extract_version_data_assoc($rec);
1435 class WikiDB_backend_PDO_search extends WikiDB_backend_search_sql
1439 // Following function taken from Pear::DB (prev. from adodb-pear.inc.php).
1440 // Eventually, change index.php to provide the relevant information
1443 * Parse a data source name.
1445 * Additional keys can be added by appending a URI query string to the
1448 * The format of the supplied DSN is in its fullest form:
1450 * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
1453 * Most variations are allowed:
1455 * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
1456 * phptype://username:password@hostspec/database_name
1457 * phptype://username:password@hostspec
1458 * phptype://username@hostspec
1459 * phptype://hostspec/database
1460 * phptype://hostspec
1465 * @param string $dsn Data Source Name to be parsed
1467 * @return array an associative array with the following keys:
1468 * + phptype: Database backend used in PHP (mysql, odbc etc.)
1469 * + dbsyntax: Database used with regards to SQL syntax etc. (ignored with PDO)
1470 * + protocol: Communication protocol to use (tcp, unix, pipe etc.)
1471 * + hostspec: Host specification (hostname[:port])
1472 * + database: Database to use on the DBMS server
1473 * + username: User name for login
1474 * + password: Password for login
1476 * @author Tomas V.V.Cox <cox@idecnet.com>
1478 function parseDSN($dsn)
1482 'dbsyntax' => false,
1483 'username' => false,
1484 'password' => false,
1485 'protocol' => false,
1486 'hostspec' => false,
1489 'database' => false,
1492 if (is_array($dsn)) {
1493 $dsn = array_merge($parsed, $dsn);
1494 if (!$dsn['dbsyntax']) {
1495 $dsn['dbsyntax'] = $dsn['phptype'];
1500 // Find phptype and dbsyntax
1501 if (($pos = strpos($dsn, '://')) !== false) {
1502 $str = substr($dsn, 0, $pos);
1503 $dsn = substr($dsn, $pos + 3);
1509 // Get phptype and dbsyntax
1510 // $str => phptype(dbsyntax)
1511 if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
1512 $parsed['phptype'] = $arr[1];
1513 $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
1515 $parsed['phptype'] = $str;
1516 $parsed['dbsyntax'] = $str;
1523 // Get (if found): username and password
1524 // $dsn => username:password@protocol+hostspec/database
1525 if (($at = strrpos($dsn, '@')) !== false) {
1526 $str = substr($dsn, 0, $at);
1527 $dsn = substr($dsn, $at + 1);
1528 if (($pos = strpos($str, ':')) !== false) {
1529 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
1530 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
1532 $parsed['username'] = rawurldecode($str);
1536 // Find protocol and hostspec
1538 // $dsn => proto(proto_opts)/database
1539 if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
1541 $proto_opts = $match[2] ? $match[2] : false;
1544 // $dsn => protocol+hostspec/database (old format)
1546 if (strpos($dsn, '+') !== false) {
1547 list($proto, $dsn) = explode('+', $dsn, 2);
1549 if (strpos($dsn, '/') !== false) {
1550 list($proto_opts, $dsn) = explode('/', $dsn, 2);
1557 // process the different protocol options
1558 $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
1559 $proto_opts = rawurldecode($proto_opts);
1560 if ($parsed['protocol'] == 'tcp') {
1561 if (strpos($proto_opts, ':') !== false) {
1562 list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts);
1564 $parsed['hostspec'] = $proto_opts;
1566 } elseif ($parsed['protocol'] == 'unix') {
1567 $parsed['socket'] = $proto_opts;
1570 // Get database if any
1574 if (($pos = strpos($dsn, '?')) === false) {
1575 $parsed['database'] = $dsn;
1576 // /database?param1=value1¶m2=value2
1578 $parsed['database'] = substr($dsn, 0, $pos);
1579 $dsn = substr($dsn, $pos + 1);
1580 if (strpos($dsn, '&') !== false) {
1581 $opts = explode('&', $dsn);
1582 } else { // database?param1=value1
1583 $opts = array($dsn);
1585 foreach ($opts as $opt) {
1586 list($key, $value) = explode('=', $opt);
1587 if (!isset($parsed[$key])) {
1588 // don't allow params overwrite
1589 $parsed[$key] = rawurldecode($value);