PageRenderTime 78ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/PHP-server-1.1/src/DB.php

https://github.com/Mercedes/openid-server
PHP | 1489 lines | 562 code | 179 blank | 748 comment | 111 complexity | 66425aadd9e12aef76d80dc60fb1949e MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Database independent query interface
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: This source file is subject to version 3.0 of the PHP license
  9. * that is available through the world-wide-web at the following URI:
  10. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  11. * the PHP License and are unable to obtain it through the web, please
  12. * send a note to license@php.net so we can mail you a copy immediately.
  13. *
  14. * @category Database
  15. * @package DB
  16. * @author Stig Bakken <ssb@php.net>
  17. * @author Tomas V.V.Cox <cox@idecnet.com>
  18. * @author Daniel Convissor <danielc@php.net>
  19. * @copyright 1997-2007 The PHP Group
  20. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  21. * @version CVS: $Id: DB.php,v 1.88 2007/08/12 05:27:25 aharvey Exp $
  22. * @link http://pear.php.net/package/DB
  23. */
  24. /**
  25. * Obtain the PEAR class so it can be extended from
  26. */
  27. require_once 'PEAR.php';
  28. // {{{ constants
  29. // {{{ error codes
  30. /**#@+
  31. * One of PEAR DB's portable error codes.
  32. * @see DB_common::errorCode(), DB::errorMessage()
  33. *
  34. * {@internal If you add an error code here, make sure you also add a textual
  35. * version of it in DB::errorMessage().}}
  36. */
  37. /**
  38. * The code returned by many methods upon success
  39. */
  40. define('DB_OK', 1);
  41. /**
  42. * Unkown error
  43. */
  44. define('DB_ERROR', -1);
  45. /**
  46. * Syntax error
  47. */
  48. define('DB_ERROR_SYNTAX', -2);
  49. /**
  50. * Tried to insert a duplicate value into a primary or unique index
  51. */
  52. define('DB_ERROR_CONSTRAINT', -3);
  53. /**
  54. * An identifier in the query refers to a non-existant object
  55. */
  56. define('DB_ERROR_NOT_FOUND', -4);
  57. /**
  58. * Tried to create a duplicate object
  59. */
  60. define('DB_ERROR_ALREADY_EXISTS', -5);
  61. /**
  62. * The current driver does not support the action you attempted
  63. */
  64. define('DB_ERROR_UNSUPPORTED', -6);
  65. /**
  66. * The number of parameters does not match the number of placeholders
  67. */
  68. define('DB_ERROR_MISMATCH', -7);
  69. /**
  70. * A literal submitted did not match the data type expected
  71. */
  72. define('DB_ERROR_INVALID', -8);
  73. /**
  74. * The current DBMS does not support the action you attempted
  75. */
  76. define('DB_ERROR_NOT_CAPABLE', -9);
  77. /**
  78. * A literal submitted was too long so the end of it was removed
  79. */
  80. define('DB_ERROR_TRUNCATED', -10);
  81. /**
  82. * A literal number submitted did not match the data type expected
  83. */
  84. define('DB_ERROR_INVALID_NUMBER', -11);
  85. /**
  86. * A literal date submitted did not match the data type expected
  87. */
  88. define('DB_ERROR_INVALID_DATE', -12);
  89. /**
  90. * Attempt to divide something by zero
  91. */
  92. define('DB_ERROR_DIVZERO', -13);
  93. /**
  94. * A database needs to be selected
  95. */
  96. define('DB_ERROR_NODBSELECTED', -14);
  97. /**
  98. * Could not create the object requested
  99. */
  100. define('DB_ERROR_CANNOT_CREATE', -15);
  101. /**
  102. * Could not drop the database requested because it does not exist
  103. */
  104. define('DB_ERROR_CANNOT_DROP', -17);
  105. /**
  106. * An identifier in the query refers to a non-existant table
  107. */
  108. define('DB_ERROR_NOSUCHTABLE', -18);
  109. /**
  110. * An identifier in the query refers to a non-existant column
  111. */
  112. define('DB_ERROR_NOSUCHFIELD', -19);
  113. /**
  114. * The data submitted to the method was inappropriate
  115. */
  116. define('DB_ERROR_NEED_MORE_DATA', -20);
  117. /**
  118. * The attempt to lock the table failed
  119. */
  120. define('DB_ERROR_NOT_LOCKED', -21);
  121. /**
  122. * The number of columns doesn't match the number of values
  123. */
  124. define('DB_ERROR_VALUE_COUNT_ON_ROW', -22);
  125. /**
  126. * The DSN submitted has problems
  127. */
  128. define('DB_ERROR_INVALID_DSN', -23);
  129. /**
  130. * Could not connect to the database
  131. */
  132. define('DB_ERROR_CONNECT_FAILED', -24);
  133. /**
  134. * The PHP extension needed for this DBMS could not be found
  135. */
  136. define('DB_ERROR_EXTENSION_NOT_FOUND',-25);
  137. /**
  138. * The present user has inadequate permissions to perform the task requestd
  139. */
  140. define('DB_ERROR_ACCESS_VIOLATION', -26);
  141. /**
  142. * The database requested does not exist
  143. */
  144. define('DB_ERROR_NOSUCHDB', -27);
  145. /**
  146. * Tried to insert a null value into a column that doesn't allow nulls
  147. */
  148. define('DB_ERROR_CONSTRAINT_NOT_NULL',-29);
  149. /**#@-*/
  150. // }}}
  151. // {{{ prepared statement-related
  152. /**#@+
  153. * Identifiers for the placeholders used in prepared statements.
  154. * @see DB_common::prepare()
  155. */
  156. /**
  157. * Indicates a scalar (<kbd>?</kbd>) placeholder was used
  158. *
  159. * Quote and escape the value as necessary.
  160. */
  161. define('DB_PARAM_SCALAR', 1);
  162. /**
  163. * Indicates an opaque (<kbd>&</kbd>) placeholder was used
  164. *
  165. * The value presented is a file name. Extract the contents of that file
  166. * and place them in this column.
  167. */
  168. define('DB_PARAM_OPAQUE', 2);
  169. /**
  170. * Indicates a misc (<kbd>!</kbd>) placeholder was used
  171. *
  172. * The value should not be quoted or escaped.
  173. */
  174. define('DB_PARAM_MISC', 3);
  175. /**#@-*/
  176. // }}}
  177. // {{{ binary data-related
  178. /**#@+
  179. * The different ways of returning binary data from queries.
  180. */
  181. /**
  182. * Sends the fetched data straight through to output
  183. */
  184. define('DB_BINMODE_PASSTHRU', 1);
  185. /**
  186. * Lets you return data as usual
  187. */
  188. define('DB_BINMODE_RETURN', 2);
  189. /**
  190. * Converts the data to hex format before returning it
  191. *
  192. * For example the string "123" would become "313233".
  193. */
  194. define('DB_BINMODE_CONVERT', 3);
  195. /**#@-*/
  196. // }}}
  197. // {{{ fetch modes
  198. /**#@+
  199. * Fetch Modes.
  200. * @see DB_common::setFetchMode()
  201. */
  202. /**
  203. * Indicates the current default fetch mode should be used
  204. * @see DB_common::$fetchmode
  205. */
  206. define('DB_FETCHMODE_DEFAULT', 0);
  207. /**
  208. * Column data indexed by numbers, ordered from 0 and up
  209. */
  210. define('DB_FETCHMODE_ORDERED', 1);
  211. /**
  212. * Column data indexed by column names
  213. */
  214. define('DB_FETCHMODE_ASSOC', 2);
  215. /**
  216. * Column data as object properties
  217. */
  218. define('DB_FETCHMODE_OBJECT', 3);
  219. /**
  220. * For multi-dimensional results, make the column name the first level
  221. * of the array and put the row number in the second level of the array
  222. *
  223. * This is flipped from the normal behavior, which puts the row numbers
  224. * in the first level of the array and the column names in the second level.
  225. */
  226. define('DB_FETCHMODE_FLIPPED', 4);
  227. /**#@-*/
  228. /**#@+
  229. * Old fetch modes. Left here for compatibility.
  230. */
  231. define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
  232. define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
  233. define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED);
  234. /**#@-*/
  235. // }}}
  236. // {{{ tableInfo() && autoPrepare()-related
  237. /**#@+
  238. * The type of information to return from the tableInfo() method.
  239. *
  240. * Bitwised constants, so they can be combined using <kbd>|</kbd>
  241. * and removed using <kbd>^</kbd>.
  242. *
  243. * @see DB_common::tableInfo()
  244. *
  245. * {@internal Since the TABLEINFO constants are bitwised, if more of them are
  246. * added in the future, make sure to adjust DB_TABLEINFO_FULL accordingly.}}
  247. */
  248. define('DB_TABLEINFO_ORDER', 1);
  249. define('DB_TABLEINFO_ORDERTABLE', 2);
  250. define('DB_TABLEINFO_FULL', 3);
  251. /**#@-*/
  252. /**#@+
  253. * The type of query to create with the automatic query building methods.
  254. * @see DB_common::autoPrepare(), DB_common::autoExecute()
  255. */
  256. define('DB_AUTOQUERY_INSERT', 1);
  257. define('DB_AUTOQUERY_UPDATE', 2);
  258. /**#@-*/
  259. // }}}
  260. // {{{ portability modes
  261. /**#@+
  262. * Portability Modes.
  263. *
  264. * Bitwised constants, so they can be combined using <kbd>|</kbd>
  265. * and removed using <kbd>^</kbd>.
  266. *
  267. * @see DB_common::setOption()
  268. *
  269. * {@internal Since the PORTABILITY constants are bitwised, if more of them are
  270. * added in the future, make sure to adjust DB_PORTABILITY_ALL accordingly.}}
  271. */
  272. /**
  273. * Turn off all portability features
  274. */
  275. define('DB_PORTABILITY_NONE', 0);
  276. /**
  277. * Convert names of tables and fields to lower case
  278. * when using the get*(), fetch*() and tableInfo() methods
  279. */
  280. define('DB_PORTABILITY_LOWERCASE', 1);
  281. /**
  282. * Right trim the data output by get*() and fetch*()
  283. */
  284. define('DB_PORTABILITY_RTRIM', 2);
  285. /**
  286. * Force reporting the number of rows deleted
  287. */
  288. define('DB_PORTABILITY_DELETE_COUNT', 4);
  289. /**
  290. * Enable hack that makes numRows() work in Oracle
  291. */
  292. define('DB_PORTABILITY_NUMROWS', 8);
  293. /**
  294. * Makes certain error messages in certain drivers compatible
  295. * with those from other DBMS's
  296. *
  297. * + mysql, mysqli: change unique/primary key constraints
  298. * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
  299. *
  300. * + odbc(access): MS's ODBC driver reports 'no such field' as code
  301. * 07001, which means 'too few parameters.' When this option is on
  302. * that code gets mapped to DB_ERROR_NOSUCHFIELD.
  303. */
  304. define('DB_PORTABILITY_ERRORS', 16);
  305. /**
  306. * Convert null values to empty strings in data output by
  307. * get*() and fetch*()
  308. */
  309. define('DB_PORTABILITY_NULL_TO_EMPTY', 32);
  310. /**
  311. * Turn on all portability features
  312. */
  313. define('DB_PORTABILITY_ALL', 63);
  314. /**#@-*/
  315. // }}}
  316. // }}}
  317. // {{{ class DB
  318. /**
  319. * Database independent query interface
  320. *
  321. * The main "DB" class is simply a container class with some static
  322. * methods for creating DB objects as well as some utility functions
  323. * common to all parts of DB.
  324. *
  325. * The object model of DB is as follows (indentation means inheritance):
  326. * <pre>
  327. * DB The main DB class. This is simply a utility class
  328. * with some "static" methods for creating DB objects as
  329. * well as common utility functions for other DB classes.
  330. *
  331. * DB_common The base for each DB implementation. Provides default
  332. * | implementations (in OO lingo virtual methods) for
  333. * | the actual DB implementations as well as a bunch of
  334. * | query utility functions.
  335. * |
  336. * +-DB_mysql The DB implementation for MySQL. Inherits DB_common.
  337. * When calling DB::factory or DB::connect for MySQL
  338. * connections, the object returned is an instance of this
  339. * class.
  340. * </pre>
  341. *
  342. * @category Database
  343. * @package DB
  344. * @author Stig Bakken <ssb@php.net>
  345. * @author Tomas V.V.Cox <cox@idecnet.com>
  346. * @author Daniel Convissor <danielc@php.net>
  347. * @copyright 1997-2007 The PHP Group
  348. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  349. * @version Release: 1.7.14RC1
  350. * @link http://pear.php.net/package/DB
  351. */
  352. class DB
  353. {
  354. // {{{ &factory()
  355. /**
  356. * Create a new DB object for the specified database type but don't
  357. * connect to the database
  358. *
  359. * @param string $type the database type (eg "mysql")
  360. * @param array $options an associative array of option names and values
  361. *
  362. * @return object a new DB object. A DB_Error object on failure.
  363. *
  364. * @see DB_common::setOption()
  365. */
  366. function &factory($type, $options = false)
  367. {
  368. if (!is_array($options)) {
  369. $options = array('persistent' => $options);
  370. }
  371. if (isset($options['debug']) && $options['debug'] >= 2) {
  372. // expose php errors with sufficient debug level
  373. include_once "DB/{$type}.php";
  374. } else {
  375. @include_once "DB/{$type}.php";
  376. }
  377. $classname = "DB_${type}";
  378. if (!class_exists($classname)) {
  379. $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
  380. "Unable to include the DB/{$type}.php"
  381. . " file for '$dsn'",
  382. 'DB_Error', true);
  383. return $tmp;
  384. }
  385. @$obj = new $classname;
  386. foreach ($options as $option => $value) {
  387. $test = $obj->setOption($option, $value);
  388. if (DB::isError($test)) {
  389. return $test;
  390. }
  391. }
  392. return $obj;
  393. }
  394. // }}}
  395. // {{{ &connect()
  396. /**
  397. * Create a new DB object including a connection to the specified database
  398. *
  399. * Example 1.
  400. * <code>
  401. * require_once 'DB.php';
  402. *
  403. * $dsn = 'pgsql://user:password@host/database';
  404. * $options = array(
  405. * 'debug' => 2,
  406. * 'portability' => DB_PORTABILITY_ALL,
  407. * );
  408. *
  409. * $db =& DB::connect($dsn, $options);
  410. * if (PEAR::isError($db)) {
  411. * die($db->getMessage());
  412. * }
  413. * </code>
  414. *
  415. * @param mixed $dsn the string "data source name" or array in the
  416. * format returned by DB::parseDSN()
  417. * @param array $options an associative array of option names and values
  418. *
  419. * @return object a new DB object. A DB_Error object on failure.
  420. *
  421. * @uses DB_dbase::connect(), DB_fbsql::connect(), DB_ibase::connect(),
  422. * DB_ifx::connect(), DB_msql::connect(), DB_mssql::connect(),
  423. * DB_mysql::connect(), DB_mysqli::connect(), DB_oci8::connect(),
  424. * DB_odbc::connect(), DB_pgsql::connect(), DB_sqlite::connect(),
  425. * DB_sybase::connect()
  426. *
  427. * @uses DB::parseDSN(), DB_common::setOption(), PEAR::isError()
  428. */
  429. function &connect($dsn, $options = array())
  430. {
  431. $dsninfo = DB::parseDSN($dsn);
  432. $type = $dsninfo['phptype'];
  433. if (!is_array($options)) {
  434. /*
  435. * For backwards compatibility. $options used to be boolean,
  436. * indicating whether the connection should be persistent.
  437. */
  438. $options = array('persistent' => $options);
  439. }
  440. if (isset($options['debug']) && $options['debug'] >= 2) {
  441. // expose php errors with sufficient debug level
  442. include_once "DB/${type}.php";
  443. } else {
  444. @include_once "DB/${type}.php";
  445. }
  446. $classname = "DB_${type}";
  447. if (!class_exists($classname)) {
  448. $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null,
  449. "Unable to include the DB/{$type}.php"
  450. . " file for '$dsn'",
  451. 'DB_Error', true);
  452. return $tmp;
  453. }
  454. @$obj = new $classname;
  455. foreach ($options as $option => $value) {
  456. $test = $obj->setOption($option, $value);
  457. if (DB::isError($test)) {
  458. return $test;
  459. }
  460. }
  461. $err = $obj->connect($dsninfo, $obj->getOption('persistent'));
  462. if (DB::isError($err)) {
  463. if (is_array($dsn)) {
  464. $err->addUserInfo(DB::getDSNString($dsn, true));
  465. } else {
  466. $err->addUserInfo($dsn);
  467. }
  468. return $err;
  469. }
  470. return $obj;
  471. }
  472. // }}}
  473. // {{{ apiVersion()
  474. /**
  475. * Return the DB API version
  476. *
  477. * @return string the DB API version number
  478. */
  479. function apiVersion()
  480. {
  481. return '1.7.14RC1';
  482. }
  483. // }}}
  484. // {{{ isError()
  485. /**
  486. * Determines if a variable is a DB_Error object
  487. *
  488. * @param mixed $value the variable to check
  489. *
  490. * @return bool whether $value is DB_Error object
  491. */
  492. function isError($value)
  493. {
  494. return is_a($value, 'DB_Error');
  495. }
  496. // }}}
  497. // {{{ isConnection()
  498. /**
  499. * Determines if a value is a DB_<driver> object
  500. *
  501. * @param mixed $value the value to test
  502. *
  503. * @return bool whether $value is a DB_<driver> object
  504. */
  505. function isConnection($value)
  506. {
  507. return (is_object($value) &&
  508. is_subclass_of($value, 'db_common') &&
  509. method_exists($value, 'simpleQuery'));
  510. }
  511. // }}}
  512. // {{{ isManip()
  513. /**
  514. * Tell whether a query is a data manipulation or data definition query
  515. *
  516. * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
  517. * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
  518. * REVOKE.
  519. *
  520. * @param string $query the query
  521. *
  522. * @return boolean whether $query is a data manipulation query
  523. */
  524. function isManip($query)
  525. {
  526. $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
  527. . 'CREATE|DROP|'
  528. . 'LOAD DATA|SELECT .* INTO .* FROM|COPY|'
  529. . 'ALTER|GRANT|REVOKE|'
  530. . 'LOCK|UNLOCK';
  531. if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
  532. return true;
  533. }
  534. return false;
  535. }
  536. // }}}
  537. // {{{ errorMessage()
  538. /**
  539. * Return a textual error message for a DB error code
  540. *
  541. * @param integer $value the DB error code
  542. *
  543. * @return string the error message or false if the error code was
  544. * not recognized
  545. */
  546. function errorMessage($value)
  547. {
  548. static $errorMessages;
  549. if (!isset($errorMessages)) {
  550. $errorMessages = array(
  551. DB_ERROR => 'unknown error',
  552. DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
  553. DB_ERROR_ALREADY_EXISTS => 'already exists',
  554. DB_ERROR_CANNOT_CREATE => 'can not create',
  555. DB_ERROR_CANNOT_DROP => 'can not drop',
  556. DB_ERROR_CONNECT_FAILED => 'connect failed',
  557. DB_ERROR_CONSTRAINT => 'constraint violation',
  558. DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
  559. DB_ERROR_DIVZERO => 'division by zero',
  560. DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  561. DB_ERROR_INVALID => 'invalid',
  562. DB_ERROR_INVALID_DATE => 'invalid date or time',
  563. DB_ERROR_INVALID_DSN => 'invalid DSN',
  564. DB_ERROR_INVALID_NUMBER => 'invalid number',
  565. DB_ERROR_MISMATCH => 'mismatch',
  566. DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
  567. DB_ERROR_NODBSELECTED => 'no database selected',
  568. DB_ERROR_NOSUCHDB => 'no such database',
  569. DB_ERROR_NOSUCHFIELD => 'no such field',
  570. DB_ERROR_NOSUCHTABLE => 'no such table',
  571. DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
  572. DB_ERROR_NOT_FOUND => 'not found',
  573. DB_ERROR_NOT_LOCKED => 'not locked',
  574. DB_ERROR_SYNTAX => 'syntax error',
  575. DB_ERROR_UNSUPPORTED => 'not supported',
  576. DB_ERROR_TRUNCATED => 'truncated',
  577. DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  578. DB_OK => 'no error',
  579. );
  580. }
  581. if (DB::isError($value)) {
  582. $value = $value->getCode();
  583. }
  584. return isset($errorMessages[$value]) ? $errorMessages[$value]
  585. : $errorMessages[DB_ERROR];
  586. }
  587. // }}}
  588. // {{{ parseDSN()
  589. /**
  590. * Parse a data source name
  591. *
  592. * Additional keys can be added by appending a URI query string to the
  593. * end of the DSN.
  594. *
  595. * The format of the supplied DSN is in its fullest form:
  596. * <code>
  597. * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
  598. * </code>
  599. *
  600. * Most variations are allowed:
  601. * <code>
  602. * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
  603. * phptype://username:password@hostspec/database_name
  604. * phptype://username:password@hostspec
  605. * phptype://username@hostspec
  606. * phptype://hostspec/database
  607. * phptype://hostspec
  608. * phptype(dbsyntax)
  609. * phptype
  610. * </code>
  611. *
  612. * @param string $dsn Data Source Name to be parsed
  613. *
  614. * @return array an associative array with the following keys:
  615. * + phptype: Database backend used in PHP (mysql, odbc etc.)
  616. * + dbsyntax: Database used with regards to SQL syntax etc.
  617. * + protocol: Communication protocol to use (tcp, unix etc.)
  618. * + hostspec: Host specification (hostname[:port])
  619. * + database: Database to use on the DBMS server
  620. * + username: User name for login
  621. * + password: Password for login
  622. */
  623. function parseDSN($dsn)
  624. {
  625. $parsed = array(
  626. 'phptype' => false,
  627. 'dbsyntax' => false,
  628. 'username' => false,
  629. 'password' => false,
  630. 'protocol' => false,
  631. 'hostspec' => false,
  632. 'port' => false,
  633. 'socket' => false,
  634. 'database' => false,
  635. );
  636. if (is_array($dsn)) {
  637. $dsn = array_merge($parsed, $dsn);
  638. if (!$dsn['dbsyntax']) {
  639. $dsn['dbsyntax'] = $dsn['phptype'];
  640. }
  641. return $dsn;
  642. }
  643. // Find phptype and dbsyntax
  644. if (($pos = strpos($dsn, '://')) !== false) {
  645. $str = substr($dsn, 0, $pos);
  646. $dsn = substr($dsn, $pos + 3);
  647. } else {
  648. $str = $dsn;
  649. $dsn = null;
  650. }
  651. // Get phptype and dbsyntax
  652. // $str => phptype(dbsyntax)
  653. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  654. $parsed['phptype'] = $arr[1];
  655. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  656. } else {
  657. $parsed['phptype'] = $str;
  658. $parsed['dbsyntax'] = $str;
  659. }
  660. if (!count($dsn)) {
  661. return $parsed;
  662. }
  663. // Get (if found): username and password
  664. // $dsn => username:password@protocol+hostspec/database
  665. if (($at = strrpos($dsn,'@')) !== false) {
  666. $str = substr($dsn, 0, $at);
  667. $dsn = substr($dsn, $at + 1);
  668. if (($pos = strpos($str, ':')) !== false) {
  669. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  670. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  671. } else {
  672. $parsed['username'] = rawurldecode($str);
  673. }
  674. }
  675. // Find protocol and hostspec
  676. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  677. // $dsn => proto(proto_opts)/database
  678. $proto = $match[1];
  679. $proto_opts = $match[2] ? $match[2] : false;
  680. $dsn = $match[3];
  681. } else {
  682. // $dsn => protocol+hostspec/database (old format)
  683. if (strpos($dsn, '+') !== false) {
  684. list($proto, $dsn) = explode('+', $dsn, 2);
  685. }
  686. if (strpos($dsn, '/') !== false) {
  687. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  688. } else {
  689. $proto_opts = $dsn;
  690. $dsn = null;
  691. }
  692. }
  693. // process the different protocol options
  694. $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  695. $proto_opts = rawurldecode($proto_opts);
  696. if (strpos($proto_opts, ':') !== false) {
  697. list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
  698. }
  699. if ($parsed['protocol'] == 'tcp') {
  700. $parsed['hostspec'] = $proto_opts;
  701. } elseif ($parsed['protocol'] == 'unix') {
  702. $parsed['socket'] = $proto_opts;
  703. }
  704. // Get dabase if any
  705. // $dsn => database
  706. if ($dsn) {
  707. if (($pos = strpos($dsn, '?')) === false) {
  708. // /database
  709. $parsed['database'] = rawurldecode($dsn);
  710. } else {
  711. // /database?param1=value1&param2=value2
  712. $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
  713. $dsn = substr($dsn, $pos + 1);
  714. if (strpos($dsn, '&') !== false) {
  715. $opts = explode('&', $dsn);
  716. } else { // database?param1=value1
  717. $opts = array($dsn);
  718. }
  719. foreach ($opts as $opt) {
  720. list($key, $value) = explode('=', $opt);
  721. if (!isset($parsed[$key])) {
  722. // don't allow params overwrite
  723. $parsed[$key] = rawurldecode($value);
  724. }
  725. }
  726. }
  727. }
  728. return $parsed;
  729. }
  730. // }}}
  731. // {{{ getDSNString()
  732. /**
  733. * Returns the given DSN in a string format suitable for output.
  734. *
  735. * @param array|string the DSN to parse and format
  736. * @param boolean true to hide the password, false to include it
  737. * @return string
  738. */
  739. function getDSNString($dsn, $hidePassword) {
  740. /* Calling parseDSN will ensure that we have all the array elements
  741. * defined, and means that we deal with strings and array in the same
  742. * manner. */
  743. $dsnArray = DB::parseDSN($dsn);
  744. if ($hidePassword) {
  745. $dsnArray['password'] = 'PASSWORD';
  746. }
  747. /* Protocol is special-cased, as using the default "tcp" along with an
  748. * Oracle TNS connection string fails. */
  749. if (is_string($dsn) && strpos($dsn, 'tcp') === false && $dsnArray['protocol'] == 'tcp') {
  750. $dsnArray['protocol'] = false;
  751. }
  752. // Now we just have to construct the actual string. This is ugly.
  753. $dsnString = $dsnArray['phptype'];
  754. if ($dsnArray['dbsyntax']) {
  755. $dsnString .= '('.$dsnArray['dbsyntax'].')';
  756. }
  757. $dsnString .= '://'
  758. .$dsnArray['username']
  759. .':'
  760. .$dsnArray['password']
  761. .'@'
  762. .$dsnArray['protocol'];
  763. if ($dsnArray['socket']) {
  764. $dsnString .= '('.$dsnArray['socket'].')';
  765. }
  766. if ($dsnArray['protocol'] && $dsnArray['hostspec']) {
  767. $dsnString .= '+';
  768. }
  769. $dsnString .= $dsnArray['hostspec'];
  770. if ($dsnArray['port']) {
  771. $dsnString .= ':'.$dsnArray['port'];
  772. }
  773. $dsnString .= '/'.$dsnArray['database'];
  774. /* Option handling. Unfortunately, parseDSN simply places options into
  775. * the top-level array, so we'll first get rid of the fields defined by
  776. * DB and see what's left. */
  777. unset($dsnArray['phptype'],
  778. $dsnArray['dbsyntax'],
  779. $dsnArray['username'],
  780. $dsnArray['password'],
  781. $dsnArray['protocol'],
  782. $dsnArray['socket'],
  783. $dsnArray['hostspec'],
  784. $dsnArray['port'],
  785. $dsnArray['database']
  786. );
  787. if (count($dsnArray) > 0) {
  788. $dsnString .= '?';
  789. $i = 0;
  790. foreach ($dsnArray as $key => $value) {
  791. if (++$i > 1) {
  792. $dsnString .= '&';
  793. }
  794. $dsnString .= $key.'='.$value;
  795. }
  796. }
  797. return $dsnString;
  798. }
  799. // }}}
  800. }
  801. // }}}
  802. // {{{ class DB_Error
  803. /**
  804. * DB_Error implements a class for reporting portable database error
  805. * messages
  806. *
  807. * @category Database
  808. * @package DB
  809. * @author Stig Bakken <ssb@php.net>
  810. * @copyright 1997-2007 The PHP Group
  811. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  812. * @version Release: 1.7.14RC1
  813. * @link http://pear.php.net/package/DB
  814. */
  815. class DB_Error extends PEAR_Error
  816. {
  817. // {{{ constructor
  818. /**
  819. * DB_Error constructor
  820. *
  821. * @param mixed $code DB error code, or string with error message
  822. * @param int $mode what "error mode" to operate in
  823. * @param int $level what error level to use for $mode &
  824. * PEAR_ERROR_TRIGGER
  825. * @param mixed $debuginfo additional debug info, such as the last query
  826. *
  827. * @see PEAR_Error
  828. */
  829. function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
  830. $level = E_USER_ERROR, $debuginfo = null)
  831. {
  832. if (is_int($code)) {
  833. $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code,
  834. $mode, $level, $debuginfo);
  835. } else {
  836. $this->PEAR_Error("DB Error: $code", DB_ERROR,
  837. $mode, $level, $debuginfo);
  838. }
  839. }
  840. // }}}
  841. }
  842. // }}}
  843. // {{{ class DB_result
  844. /**
  845. * This class implements a wrapper for a DB result set
  846. *
  847. * A new instance of this class will be returned by the DB implementation
  848. * after processing a query that returns data.
  849. *
  850. * @category Database
  851. * @package DB
  852. * @author Stig Bakken <ssb@php.net>
  853. * @copyright 1997-2007 The PHP Group
  854. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  855. * @version Release: 1.7.14RC1
  856. * @link http://pear.php.net/package/DB
  857. */
  858. class DB_result
  859. {
  860. // {{{ properties
  861. /**
  862. * Should results be freed automatically when there are no more rows?
  863. * @var boolean
  864. * @see DB_common::$options
  865. */
  866. var $autofree;
  867. /**
  868. * A reference to the DB_<driver> object
  869. * @var object
  870. */
  871. var $dbh;
  872. /**
  873. * The current default fetch mode
  874. * @var integer
  875. * @see DB_common::$fetchmode
  876. */
  877. var $fetchmode;
  878. /**
  879. * The name of the class into which results should be fetched when
  880. * DB_FETCHMODE_OBJECT is in effect
  881. *
  882. * @var string
  883. * @see DB_common::$fetchmode_object_class
  884. */
  885. var $fetchmode_object_class;
  886. /**
  887. * The number of rows to fetch from a limit query
  888. * @var integer
  889. */
  890. var $limit_count = null;
  891. /**
  892. * The row to start fetching from in limit queries
  893. * @var integer
  894. */
  895. var $limit_from = null;
  896. /**
  897. * The execute parameters that created this result
  898. * @var array
  899. * @since Property available since Release 1.7.0
  900. */
  901. var $parameters;
  902. /**
  903. * The query string that created this result
  904. *
  905. * Copied here incase it changes in $dbh, which is referenced
  906. *
  907. * @var string
  908. * @since Property available since Release 1.7.0
  909. */
  910. var $query;
  911. /**
  912. * The query result resource id created by PHP
  913. * @var resource
  914. */
  915. var $result;
  916. /**
  917. * The present row being dealt with
  918. * @var integer
  919. */
  920. var $row_counter = null;
  921. /**
  922. * The prepared statement resource id created by PHP in $dbh
  923. *
  924. * This resource is only available when the result set was created using
  925. * a driver's native execute() method, not PEAR DB's emulated one.
  926. *
  927. * Copied here incase it changes in $dbh, which is referenced
  928. *
  929. * {@internal Mainly here because the InterBase/Firebird API is only
  930. * able to retrieve data from result sets if the statemnt handle is
  931. * still in scope.}}
  932. *
  933. * @var resource
  934. * @since Property available since Release 1.7.0
  935. */
  936. var $statement;
  937. // }}}
  938. // {{{ constructor
  939. /**
  940. * This constructor sets the object's properties
  941. *
  942. * @param object &$dbh the DB object reference
  943. * @param resource $result the result resource id
  944. * @param array $options an associative array with result options
  945. *
  946. * @return void
  947. */
  948. function DB_result(&$dbh, $result, $options = array())
  949. {
  950. $this->autofree = $dbh->options['autofree'];
  951. $this->dbh = &$dbh;
  952. $this->fetchmode = $dbh->fetchmode;
  953. $this->fetchmode_object_class = $dbh->fetchmode_object_class;
  954. $this->parameters = $dbh->last_parameters;
  955. $this->query = $dbh->last_query;
  956. $this->result = $result;
  957. $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
  958. foreach ($options as $key => $value) {
  959. $this->setOption($key, $value);
  960. }
  961. }
  962. /**
  963. * Set options for the DB_result object
  964. *
  965. * @param string $key the option to set
  966. * @param mixed $value the value to set the option to
  967. *
  968. * @return void
  969. */
  970. function setOption($key, $value = null)
  971. {
  972. switch ($key) {
  973. case 'limit_from':
  974. $this->limit_from = $value;
  975. break;
  976. case 'limit_count':
  977. $this->limit_count = $value;
  978. }
  979. }
  980. // }}}
  981. // {{{ fetchRow()
  982. /**
  983. * Fetch a row of data and return it by reference into an array
  984. *
  985. * The type of array returned can be controlled either by setting this
  986. * method's <var>$fetchmode</var> parameter or by changing the default
  987. * fetch mode setFetchMode() before calling this method.
  988. *
  989. * There are two options for standardizing the information returned
  990. * from databases, ensuring their values are consistent when changing
  991. * DBMS's. These portability options can be turned on when creating a
  992. * new DB object or by using setOption().
  993. *
  994. * + <var>DB_PORTABILITY_LOWERCASE</var>
  995. * convert names of fields to lower case
  996. *
  997. * + <var>DB_PORTABILITY_RTRIM</var>
  998. * right trim the data
  999. *
  1000. * @param int $fetchmode the constant indicating how to format the data
  1001. * @param int $rownum the row number to fetch (index starts at 0)
  1002. *
  1003. * @return mixed an array or object containing the row's data,
  1004. * NULL when the end of the result set is reached
  1005. * or a DB_Error object on failure.
  1006. *
  1007. * @see DB_common::setOption(), DB_common::setFetchMode()
  1008. */
  1009. function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
  1010. {
  1011. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  1012. $fetchmode = $this->fetchmode;
  1013. }
  1014. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  1015. $fetchmode = DB_FETCHMODE_ASSOC;
  1016. $object_class = $this->fetchmode_object_class;
  1017. }
  1018. if (is_null($rownum) && $this->limit_from !== null) {
  1019. if ($this->row_counter === null) {
  1020. $this->row_counter = $this->limit_from;
  1021. // Skip rows
  1022. if ($this->dbh->features['limit'] === false) {
  1023. $i = 0;
  1024. while ($i++ < $this->limit_from) {
  1025. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  1026. }
  1027. }
  1028. }
  1029. if ($this->row_counter >= ($this->limit_from + $this->limit_count))
  1030. {
  1031. if ($this->autofree) {
  1032. $this->free();
  1033. }
  1034. $tmp = null;
  1035. return $tmp;
  1036. }
  1037. if ($this->dbh->features['limit'] === 'emulate') {
  1038. $rownum = $this->row_counter;
  1039. }
  1040. $this->row_counter++;
  1041. }
  1042. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  1043. if ($res === DB_OK) {
  1044. if (isset($object_class)) {
  1045. // The default mode is specified in the
  1046. // DB_common::fetchmode_object_class property
  1047. if ($object_class == 'stdClass') {
  1048. $arr = (object) $arr;
  1049. } else {
  1050. $arr = new $object_class($arr);
  1051. }
  1052. }
  1053. return $arr;
  1054. }
  1055. if ($res == null && $this->autofree) {
  1056. $this->free();
  1057. }
  1058. return $res;
  1059. }
  1060. // }}}
  1061. // {{{ fetchInto()
  1062. /**
  1063. * Fetch a row of data into an array which is passed by reference
  1064. *
  1065. * The type of array returned can be controlled either by setting this
  1066. * method's <var>$fetchmode</var> parameter or by changing the default
  1067. * fetch mode setFetchMode() before calling this method.
  1068. *
  1069. * There are two options for standardizing the information returned
  1070. * from databases, ensuring their values are consistent when changing
  1071. * DBMS's. These portability options can be turned on when creating a
  1072. * new DB object or by using setOption().
  1073. *
  1074. * + <var>DB_PORTABILITY_LOWERCASE</var>
  1075. * convert names of fields to lower case
  1076. *
  1077. * + <var>DB_PORTABILITY_RTRIM</var>
  1078. * right trim the data
  1079. *
  1080. * @param array &$arr the variable where the data should be placed
  1081. * @param int $fetchmode the constant indicating how to format the data
  1082. * @param int $rownum the row number to fetch (index starts at 0)
  1083. *
  1084. * @return mixed DB_OK if a row is processed, NULL when the end of the
  1085. * result set is reached or a DB_Error object on failure
  1086. *
  1087. * @see DB_common::setOption(), DB_common::setFetchMode()
  1088. */
  1089. function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
  1090. {
  1091. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  1092. $fetchmode = $this->fetchmode;
  1093. }
  1094. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  1095. $fetchmode = DB_FETCHMODE_ASSOC;
  1096. $object_class = $this->fetchmode_object_class;
  1097. }
  1098. if (is_null($rownum) && $this->limit_from !== null) {
  1099. if ($this->row_counter === null) {
  1100. $this->row_counter = $this->limit_from;
  1101. // Skip rows
  1102. if ($this->dbh->features['limit'] === false) {
  1103. $i = 0;
  1104. while ($i++ < $this->limit_from) {
  1105. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  1106. }
  1107. }
  1108. }
  1109. if ($this->row_counter >= (
  1110. $this->limit_from + $this->limit_count))
  1111. {
  1112. if ($this->autofree) {
  1113. $this->free();
  1114. }
  1115. return null;
  1116. }
  1117. if ($this->dbh->features['limit'] === 'emulate') {
  1118. $rownum = $this->row_counter;
  1119. }
  1120. $this->row_counter++;
  1121. }
  1122. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  1123. if ($res === DB_OK) {
  1124. if (isset($object_class)) {
  1125. // default mode specified in the
  1126. // DB_common::fetchmode_object_class property
  1127. if ($object_class == 'stdClass') {
  1128. $arr = (object) $arr;
  1129. } else {
  1130. $arr = new $object_class($arr);
  1131. }
  1132. }
  1133. return DB_OK;
  1134. }
  1135. if ($res == null && $this->autofree) {
  1136. $this->free();
  1137. }
  1138. return $res;
  1139. }
  1140. // }}}
  1141. // {{{ numCols()
  1142. /**
  1143. * Get the the number of columns in a result set
  1144. *
  1145. * @return int the number of columns. A DB_Error object on failure.
  1146. */
  1147. function numCols()
  1148. {
  1149. return $this->dbh->numCols($this->result);
  1150. }
  1151. // }}}
  1152. // {{{ numRows()
  1153. /**
  1154. * Get the number of rows in a result set
  1155. *
  1156. * @return int the number of rows. A DB_Error object on failure.
  1157. */
  1158. function numRows()
  1159. {
  1160. if ($this->dbh->features['numrows'] === 'emulate'
  1161. && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
  1162. {
  1163. if ($this->dbh->features['prepare']) {
  1164. $res = $this->dbh->query($this->query, $this->parameters);
  1165. } else {
  1166. $res = $this->dbh->query($this->query);
  1167. }
  1168. if (DB::isError($res)) {
  1169. return $res;
  1170. }
  1171. $i = 0;
  1172. while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
  1173. $i++;
  1174. }
  1175. $count = $i;
  1176. } else {
  1177. $count = $this->dbh->numRows($this->result);
  1178. }
  1179. /* fbsql is checked for here because limit queries are implemented
  1180. * using a TOP() function, which results in fbsql_num_rows still
  1181. * returning the total number of rows that would have been returned,
  1182. * rather than the real number. As a result, we'll just do the limit
  1183. * calculations for fbsql in the same way as a database with emulated
  1184. * limits. Unfortunately, we can't just do this in DB_fbsql::numRows()
  1185. * because that only gets the result resource, rather than the full
  1186. * DB_Result object. */
  1187. if (($this->dbh->features['limit'] === 'emulate'
  1188. && $this->limit_from !== null)
  1189. || $this->dbh->phptype == 'fbsql') {
  1190. $limit_count = is_null($this->limit_count) ? $count : $this->limit_count;
  1191. if ($count < $this->limit_from) {
  1192. $count = 0;
  1193. } elseif ($count < ($this->limit_from + $limit_count)) {
  1194. $count -= $this->limit_from;
  1195. } else {
  1196. $count = $limit_count;
  1197. }
  1198. }
  1199. return $count;
  1200. }
  1201. // }}}
  1202. // {{{ nextResult()
  1203. /**
  1204. * Get the next result if a batch of queries was executed
  1205. *
  1206. * @return bool true if a new result is available or false if not
  1207. */
  1208. function nextResult()
  1209. {
  1210. return $this->dbh->nextResult($this->result);
  1211. }
  1212. // }}}
  1213. // {{{ free()
  1214. /**
  1215. * Frees the resources allocated for this result set
  1216. *
  1217. * @return bool true on success. A DB_Error object on failure.
  1218. */
  1219. function free()
  1220. {
  1221. $err = $this->dbh->freeResult($this->result);
  1222. if (DB::isError($err)) {
  1223. return $err;
  1224. }
  1225. $this->result = false;
  1226. $this->statement = false;
  1227. return true;
  1228. }
  1229. // }}}
  1230. // {{{ tableInfo()
  1231. /**
  1232. * @see DB_common::tableInfo()
  1233. * @deprecated Method deprecated some time before Release 1.2
  1234. */
  1235. function tableInfo($mode = null)
  1236. {
  1237. if (is_string($mode)) {
  1238. return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
  1239. }
  1240. return $this->dbh->tableInfo($this, $mode);
  1241. }
  1242. // }}}
  1243. // {{{ getQuery()
  1244. /**
  1245. * Determine the query string that created this result
  1246. *
  1247. * @return string the query string
  1248. *
  1249. * @since Method available since Release 1.7.0
  1250. */
  1251. function getQuery()
  1252. {
  1253. return $this->query;
  1254. }
  1255. // }}}
  1256. // {{{ getRowCounter()
  1257. /**
  1258. * Tells which row number is currently being processed
  1259. *
  1260. * @return integer the current row being looked at. Starts at 1.
  1261. */
  1262. function getRowCounter()
  1263. {
  1264. return $this->row_counter;
  1265. }
  1266. // }}}
  1267. }
  1268. // }}}
  1269. // {{{ class DB_row
  1270. /**
  1271. * PEAR DB Row Object
  1272. *
  1273. * The object contains a row of data from a result set. Each column's data
  1274. * is placed in a property named for the column.
  1275. *
  1276. * @category Database
  1277. * @package DB
  1278. * @author Stig Bakken <ssb@php.net>
  1279. * @copyright 1997-2007 The PHP Group
  1280. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  1281. * @version Release: 1.7.14RC1
  1282. * @link http://pear.php.net/package/DB
  1283. * @see DB_common::setFetchMode()
  1284. */
  1285. class DB_row
  1286. {
  1287. // {{{ constructor
  1288. /**
  1289. * The constructor places a row's data into properties of this object
  1290. *
  1291. * @param array the array containing the row's data
  1292. *
  1293. * @return void
  1294. */
  1295. function DB_row(&$arr)
  1296. {
  1297. foreach ($arr as $key => $value) {
  1298. $this->$key = &$arr[$key];
  1299. }
  1300. }
  1301. // }}}
  1302. }
  1303. // }}}
  1304. /*
  1305. * Local variables:
  1306. * tab-width: 4
  1307. * c-basic-offset: 4
  1308. * End:
  1309. */
  1310. ?>