PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/sites/all/modules/activitystream/activitystream_flickr/PEAR/DB.php

https://github.com/jiva-technology/smcuk
PHP | 1388 lines | 496 code | 170 blank | 722 comment | 90 complexity | 8ee5e9d07356d9b2982993ce38ed5261 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-2005 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.1 2008/03/26 00:46:11 akalsey 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-2005 The PHP Group
  348. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  349. * @version Release: @package_version@
  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. $err->addUserInfo($dsn);
  464. return $err;
  465. }
  466. return $obj;
  467. }
  468. // }}}
  469. // {{{ apiVersion()
  470. /**
  471. * Return the DB API version
  472. *
  473. * @return string the DB API version number
  474. */
  475. function apiVersion()
  476. {
  477. return '@package_version@';
  478. }
  479. // }}}
  480. // {{{ isError()
  481. /**
  482. * Determines if a variable is a DB_Error object
  483. *
  484. * @param mixed $value the variable to check
  485. *
  486. * @return bool whether $value is DB_Error object
  487. */
  488. function isError($value)
  489. {
  490. return is_a($value, 'DB_Error');
  491. }
  492. // }}}
  493. // {{{ isConnection()
  494. /**
  495. * Determines if a value is a DB_<driver> object
  496. *
  497. * @param mixed $value the value to test
  498. *
  499. * @return bool whether $value is a DB_<driver> object
  500. */
  501. function isConnection($value)
  502. {
  503. return (is_object($value) &&
  504. is_subclass_of($value, 'db_common') &&
  505. method_exists($value, 'simpleQuery'));
  506. }
  507. // }}}
  508. // {{{ isManip()
  509. /**
  510. * Tell whether a query is a data manipulation or data definition query
  511. *
  512. * Examples of data manipulation queries are INSERT, UPDATE and DELETE.
  513. * Examples of data definition queries are CREATE, DROP, ALTER, GRANT,
  514. * REVOKE.
  515. *
  516. * @param string $query the query
  517. *
  518. * @return boolean whether $query is a data manipulation query
  519. */
  520. function isManip($query)
  521. {
  522. $manips = 'INSERT|UPDATE|DELETE|REPLACE|'
  523. . 'CREATE|DROP|'
  524. . 'LOAD DATA|SELECT .* INTO|COPY|'
  525. . 'ALTER|GRANT|REVOKE|'
  526. . 'LOCK|UNLOCK';
  527. if (preg_match('/^\s*"?(' . $manips . ')\s+/i', $query)) {
  528. return true;
  529. }
  530. return false;
  531. }
  532. // }}}
  533. // {{{ errorMessage()
  534. /**
  535. * Return a textual error message for a DB error code
  536. *
  537. * @param integer $value the DB error code
  538. *
  539. * @return string the error message or false if the error code was
  540. * not recognized
  541. */
  542. function errorMessage($value)
  543. {
  544. static $errorMessages;
  545. if (!isset($errorMessages)) {
  546. $errorMessages = array(
  547. DB_ERROR => 'unknown error',
  548. DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
  549. DB_ERROR_ALREADY_EXISTS => 'already exists',
  550. DB_ERROR_CANNOT_CREATE => 'can not create',
  551. DB_ERROR_CANNOT_DROP => 'can not drop',
  552. DB_ERROR_CONNECT_FAILED => 'connect failed',
  553. DB_ERROR_CONSTRAINT => 'constraint violation',
  554. DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
  555. DB_ERROR_DIVZERO => 'division by zero',
  556. DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  557. DB_ERROR_INVALID => 'invalid',
  558. DB_ERROR_INVALID_DATE => 'invalid date or time',
  559. DB_ERROR_INVALID_DSN => 'invalid DSN',
  560. DB_ERROR_INVALID_NUMBER => 'invalid number',
  561. DB_ERROR_MISMATCH => 'mismatch',
  562. DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
  563. DB_ERROR_NODBSELECTED => 'no database selected',
  564. DB_ERROR_NOSUCHDB => 'no such database',
  565. DB_ERROR_NOSUCHFIELD => 'no such field',
  566. DB_ERROR_NOSUCHTABLE => 'no such table',
  567. DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
  568. DB_ERROR_NOT_FOUND => 'not found',
  569. DB_ERROR_NOT_LOCKED => 'not locked',
  570. DB_ERROR_SYNTAX => 'syntax error',
  571. DB_ERROR_UNSUPPORTED => 'not supported',
  572. DB_ERROR_TRUNCATED => 'truncated',
  573. DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  574. DB_OK => 'no error',
  575. );
  576. }
  577. if (DB::isError($value)) {
  578. $value = $value->getCode();
  579. }
  580. return isset($errorMessages[$value]) ? $errorMessages[$value]
  581. : $errorMessages[DB_ERROR];
  582. }
  583. // }}}
  584. // {{{ parseDSN()
  585. /**
  586. * Parse a data source name
  587. *
  588. * Additional keys can be added by appending a URI query string to the
  589. * end of the DSN.
  590. *
  591. * The format of the supplied DSN is in its fullest form:
  592. * <code>
  593. * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
  594. * </code>
  595. *
  596. * Most variations are allowed:
  597. * <code>
  598. * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
  599. * phptype://username:password@hostspec/database_name
  600. * phptype://username:password@hostspec
  601. * phptype://username@hostspec
  602. * phptype://hostspec/database
  603. * phptype://hostspec
  604. * phptype(dbsyntax)
  605. * phptype
  606. * </code>
  607. *
  608. * @param string $dsn Data Source Name to be parsed
  609. *
  610. * @return array an associative array with the following keys:
  611. * + phptype: Database backend used in PHP (mysql, odbc etc.)
  612. * + dbsyntax: Database used with regards to SQL syntax etc.
  613. * + protocol: Communication protocol to use (tcp, unix etc.)
  614. * + hostspec: Host specification (hostname[:port])
  615. * + database: Database to use on the DBMS server
  616. * + username: User name for login
  617. * + password: Password for login
  618. */
  619. function parseDSN($dsn)
  620. {
  621. $parsed = array(
  622. 'phptype' => false,
  623. 'dbsyntax' => false,
  624. 'username' => false,
  625. 'password' => false,
  626. 'protocol' => false,
  627. 'hostspec' => false,
  628. 'port' => false,
  629. 'socket' => false,
  630. 'database' => false,
  631. );
  632. if (is_array($dsn)) {
  633. $dsn = array_merge($parsed, $dsn);
  634. if (!$dsn['dbsyntax']) {
  635. $dsn['dbsyntax'] = $dsn['phptype'];
  636. }
  637. return $dsn;
  638. }
  639. // Find phptype and dbsyntax
  640. if (($pos = strpos($dsn, '://')) !== false) {
  641. $str = substr($dsn, 0, $pos);
  642. $dsn = substr($dsn, $pos + 3);
  643. } else {
  644. $str = $dsn;
  645. $dsn = null;
  646. }
  647. // Get phptype and dbsyntax
  648. // $str => phptype(dbsyntax)
  649. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  650. $parsed['phptype'] = $arr[1];
  651. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  652. } else {
  653. $parsed['phptype'] = $str;
  654. $parsed['dbsyntax'] = $str;
  655. }
  656. if (!count($dsn)) {
  657. return $parsed;
  658. }
  659. // Get (if found): username and password
  660. // $dsn => username:password@protocol+hostspec/database
  661. if (($at = strrpos($dsn,'@')) !== false) {
  662. $str = substr($dsn, 0, $at);
  663. $dsn = substr($dsn, $at + 1);
  664. if (($pos = strpos($str, ':')) !== false) {
  665. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  666. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  667. } else {
  668. $parsed['username'] = rawurldecode($str);
  669. }
  670. }
  671. // Find protocol and hostspec
  672. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  673. // $dsn => proto(proto_opts)/database
  674. $proto = $match[1];
  675. $proto_opts = $match[2] ? $match[2] : false;
  676. $dsn = $match[3];
  677. } else {
  678. // $dsn => protocol+hostspec/database (old format)
  679. if (strpos($dsn, '+') !== false) {
  680. list($proto, $dsn) = explode('+', $dsn, 2);
  681. }
  682. if (strpos($dsn, '/') !== false) {
  683. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  684. } else {
  685. $proto_opts = $dsn;
  686. $dsn = null;
  687. }
  688. }
  689. // process the different protocol options
  690. $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  691. $proto_opts = rawurldecode($proto_opts);
  692. if ($parsed['protocol'] == 'tcp') {
  693. if (strpos($proto_opts, ':') !== false) {
  694. list($parsed['hostspec'],
  695. $parsed['port']) = explode(':', $proto_opts);
  696. } else {
  697. $parsed['hostspec'] = $proto_opts;
  698. }
  699. } elseif ($parsed['protocol'] == 'unix') {
  700. $parsed['socket'] = $proto_opts;
  701. }
  702. // Get dabase if any
  703. // $dsn => database
  704. if ($dsn) {
  705. if (($pos = strpos($dsn, '?')) === false) {
  706. // /database
  707. $parsed['database'] = rawurldecode($dsn);
  708. } else {
  709. // /database?param1=value1&param2=value2
  710. $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
  711. $dsn = substr($dsn, $pos + 1);
  712. if (strpos($dsn, '&') !== false) {
  713. $opts = explode('&', $dsn);
  714. } else { // database?param1=value1
  715. $opts = array($dsn);
  716. }
  717. foreach ($opts as $opt) {
  718. list($key, $value) = explode('=', $opt);
  719. if (!isset($parsed[$key])) {
  720. // don't allow params overwrite
  721. $parsed[$key] = rawurldecode($value);
  722. }
  723. }
  724. }
  725. }
  726. return $parsed;
  727. }
  728. // }}}
  729. }
  730. // }}}
  731. // {{{ class DB_Error
  732. /**
  733. * DB_Error implements a class for reporting portable database error
  734. * messages
  735. *
  736. * @category Database
  737. * @package DB
  738. * @author Stig Bakken <ssb@php.net>
  739. * @copyright 1997-2005 The PHP Group
  740. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  741. * @version Release: @package_version@
  742. * @link http://pear.php.net/package/DB
  743. */
  744. class DB_Error extends PEAR_Error
  745. {
  746. // {{{ constructor
  747. /**
  748. * DB_Error constructor
  749. *
  750. * @param mixed $code DB error code, or string with error message
  751. * @param int $mode what "error mode" to operate in
  752. * @param int $level what error level to use for $mode &
  753. * PEAR_ERROR_TRIGGER
  754. * @param mixed $debuginfo additional debug info, such as the last query
  755. *
  756. * @see PEAR_Error
  757. */
  758. function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN,
  759. $level = E_USER_NOTICE, $debuginfo = null)
  760. {
  761. if (is_int($code)) {
  762. $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code,
  763. $mode, $level, $debuginfo);
  764. } else {
  765. $this->PEAR_Error("DB Error: $code", DB_ERROR,
  766. $mode, $level, $debuginfo);
  767. }
  768. }
  769. // }}}
  770. }
  771. // }}}
  772. // {{{ class DB_result
  773. /**
  774. * This class implements a wrapper for a DB result set
  775. *
  776. * A new instance of this class will be returned by the DB implementation
  777. * after processing a query that returns data.
  778. *
  779. * @category Database
  780. * @package DB
  781. * @author Stig Bakken <ssb@php.net>
  782. * @copyright 1997-2005 The PHP Group
  783. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  784. * @version Release: @package_version@
  785. * @link http://pear.php.net/package/DB
  786. */
  787. class DB_result
  788. {
  789. // {{{ properties
  790. /**
  791. * Should results be freed automatically when there are no more rows?
  792. * @var boolean
  793. * @see DB_common::$options
  794. */
  795. var $autofree;
  796. /**
  797. * A reference to the DB_<driver> object
  798. * @var object
  799. */
  800. var $dbh;
  801. /**
  802. * The current default fetch mode
  803. * @var integer
  804. * @see DB_common::$fetchmode
  805. */
  806. var $fetchmode;
  807. /**
  808. * The name of the class into which results should be fetched when
  809. * DB_FETCHMODE_OBJECT is in effect
  810. *
  811. * @var string
  812. * @see DB_common::$fetchmode_object_class
  813. */
  814. var $fetchmode_object_class;
  815. /**
  816. * The number of rows to fetch from a limit query
  817. * @var integer
  818. */
  819. var $limit_count = null;
  820. /**
  821. * The row to start fetching from in limit queries
  822. * @var integer
  823. */
  824. var $limit_from = null;
  825. /**
  826. * The execute parameters that created this result
  827. * @var array
  828. * @since Property available since Release 1.7.0
  829. */
  830. var $parameters;
  831. /**
  832. * The query string that created this result
  833. *
  834. * Copied here incase it changes in $dbh, which is referenced
  835. *
  836. * @var string
  837. * @since Property available since Release 1.7.0
  838. */
  839. var $query;
  840. /**
  841. * The query result resource id created by PHP
  842. * @var resource
  843. */
  844. var $result;
  845. /**
  846. * The present row being dealt with
  847. * @var integer
  848. */
  849. var $row_counter = null;
  850. /**
  851. * The prepared statement resource id created by PHP in $dbh
  852. *
  853. * This resource is only available when the result set was created using
  854. * a driver's native execute() method, not PEAR DB's emulated one.
  855. *
  856. * Copied here incase it changes in $dbh, which is referenced
  857. *
  858. * {@internal Mainly here because the InterBase/Firebird API is only
  859. * able to retrieve data from result sets if the statemnt handle is
  860. * still in scope.}}
  861. *
  862. * @var resource
  863. * @since Property available since Release 1.7.0
  864. */
  865. var $statement;
  866. // }}}
  867. // {{{ constructor
  868. /**
  869. * This constructor sets the object's properties
  870. *
  871. * @param object &$dbh the DB object reference
  872. * @param resource $result the result resource id
  873. * @param array $options an associative array with result options
  874. *
  875. * @return void
  876. */
  877. function DB_result(&$dbh, $result, $options = array())
  878. {
  879. $this->autofree = $dbh->options['autofree'];
  880. $this->dbh = &$dbh;
  881. $this->fetchmode = $dbh->fetchmode;
  882. $this->fetchmode_object_class = $dbh->fetchmode_object_class;
  883. $this->parameters = $dbh->last_parameters;
  884. $this->query = $dbh->last_query;
  885. $this->result = $result;
  886. $this->statement = empty($dbh->last_stmt) ? null : $dbh->last_stmt;
  887. foreach ($options as $key => $value) {
  888. $this->setOption($key, $value);
  889. }
  890. }
  891. /**
  892. * Set options for the DB_result object
  893. *
  894. * @param string $key the option to set
  895. * @param mixed $value the value to set the option to
  896. *
  897. * @return void
  898. */
  899. function setOption($key, $value = null)
  900. {
  901. switch ($key) {
  902. case 'limit_from':
  903. $this->limit_from = $value;
  904. break;
  905. case 'limit_count':
  906. $this->limit_count = $value;
  907. }
  908. }
  909. // }}}
  910. // {{{ fetchRow()
  911. /**
  912. * Fetch a row of data and return it by reference into an array
  913. *
  914. * The type of array returned can be controlled either by setting this
  915. * method's <var>$fetchmode</var> parameter or by changing the default
  916. * fetch mode setFetchMode() before calling this method.
  917. *
  918. * There are two options for standardizing the information returned
  919. * from databases, ensuring their values are consistent when changing
  920. * DBMS's. These portability options can be turned on when creating a
  921. * new DB object or by using setOption().
  922. *
  923. * + <var>DB_PORTABILITY_LOWERCASE</var>
  924. * convert names of fields to lower case
  925. *
  926. * + <var>DB_PORTABILITY_RTRIM</var>
  927. * right trim the data
  928. *
  929. * @param int $fetchmode the constant indicating how to format the data
  930. * @param int $rownum the row number to fetch (index starts at 0)
  931. *
  932. * @return mixed an array or object containing the row's data,
  933. * NULL when the end of the result set is reached
  934. * or a DB_Error object on failure.
  935. *
  936. * @see DB_common::setOption(), DB_common::setFetchMode()
  937. */
  938. function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
  939. {
  940. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  941. $fetchmode = $this->fetchmode;
  942. }
  943. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  944. $fetchmode = DB_FETCHMODE_ASSOC;
  945. $object_class = $this->fetchmode_object_class;
  946. }
  947. if ($this->limit_from !== null) {
  948. if ($this->row_counter === null) {
  949. $this->row_counter = $this->limit_from;
  950. // Skip rows
  951. if ($this->dbh->features['limit'] === false) {
  952. $i = 0;
  953. while ($i++ < $this->limit_from) {
  954. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  955. }
  956. }
  957. }
  958. if ($this->row_counter >= ($this->limit_from + $this->limit_count))
  959. {
  960. if ($this->autofree) {
  961. $this->free();
  962. }
  963. $tmp = null;
  964. return $tmp;
  965. }
  966. if ($this->dbh->features['limit'] === 'emulate') {
  967. $rownum = $this->row_counter;
  968. }
  969. $this->row_counter++;
  970. }
  971. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  972. if ($res === DB_OK) {
  973. if (isset($object_class)) {
  974. // The default mode is specified in the
  975. // DB_common::fetchmode_object_class property
  976. if ($object_class == 'stdClass') {
  977. $arr = (object) $arr;
  978. } else {
  979. $arr = &new $object_class($arr);
  980. }
  981. }
  982. return $arr;
  983. }
  984. if ($res == null && $this->autofree) {
  985. $this->free();
  986. }
  987. return $res;
  988. }
  989. // }}}
  990. // {{{ fetchInto()
  991. /**
  992. * Fetch a row of data into an array which is passed by reference
  993. *
  994. * The type of array returned can be controlled either by setting this
  995. * method's <var>$fetchmode</var> parameter or by changing the default
  996. * fetch mode setFetchMode() before calling this method.
  997. *
  998. * There are two options for standardizing the information returned
  999. * from databases, ensuring their values are consistent when changing
  1000. * DBMS's. These portability options can be turned on when creating a
  1001. * new DB object or by using setOption().
  1002. *
  1003. * + <var>DB_PORTABILITY_LOWERCASE</var>
  1004. * convert names of fields to lower case
  1005. *
  1006. * + <var>DB_PORTABILITY_RTRIM</var>
  1007. * right trim the data
  1008. *
  1009. * @param array &$arr the variable where the data should be placed
  1010. * @param int $fetchmode the constant indicating how to format the data
  1011. * @param int $rownum the row number to fetch (index starts at 0)
  1012. *
  1013. * @return mixed DB_OK if a row is processed, NULL when the end of the
  1014. * result set is reached or a DB_Error object on failure
  1015. *
  1016. * @see DB_common::setOption(), DB_common::setFetchMode()
  1017. */
  1018. function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum = null)
  1019. {
  1020. if ($fetchmode === DB_FETCHMODE_DEFAULT) {
  1021. $fetchmode = $this->fetchmode;
  1022. }
  1023. if ($fetchmode === DB_FETCHMODE_OBJECT) {
  1024. $fetchmode = DB_FETCHMODE_ASSOC;
  1025. $object_class = $this->fetchmode_object_class;
  1026. }
  1027. if ($this->limit_from !== null) {
  1028. if ($this->row_counter === null) {
  1029. $this->row_counter = $this->limit_from;
  1030. // Skip rows
  1031. if ($this->dbh->features['limit'] === false) {
  1032. $i = 0;
  1033. while ($i++ < $this->limit_from) {
  1034. $this->dbh->fetchInto($this->result, $arr, $fetchmode);
  1035. }
  1036. }
  1037. }
  1038. if ($this->row_counter >= (
  1039. $this->limit_from + $this->limit_count))
  1040. {
  1041. if ($this->autofree) {
  1042. $this->free();
  1043. }
  1044. return null;
  1045. }
  1046. if ($this->dbh->features['limit'] === 'emulate') {
  1047. $rownum = $this->row_counter;
  1048. }
  1049. $this->row_counter++;
  1050. }
  1051. $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum);
  1052. if ($res === DB_OK) {
  1053. if (isset($object_class)) {
  1054. // default mode specified in the
  1055. // DB_common::fetchmode_object_class property
  1056. if ($object_class == 'stdClass') {
  1057. $arr = (object) $arr;
  1058. } else {
  1059. $arr = new $object_class($arr);
  1060. }
  1061. }
  1062. return DB_OK;
  1063. }
  1064. if ($res == null && $this->autofree) {
  1065. $this->free();
  1066. }
  1067. return $res;
  1068. }
  1069. // }}}
  1070. // {{{ numCols()
  1071. /**
  1072. * Get the the number of columns in a result set
  1073. *
  1074. * @return int the number of columns. A DB_Error object on failure.
  1075. */
  1076. function numCols()
  1077. {
  1078. return $this->dbh->numCols($this->result);
  1079. }
  1080. // }}}
  1081. // {{{ numRows()
  1082. /**
  1083. * Get the number of rows in a result set
  1084. *
  1085. * @return int the number of rows. A DB_Error object on failure.
  1086. */
  1087. function numRows()
  1088. {
  1089. if ($this->dbh->features['numrows'] === 'emulate'
  1090. && $this->dbh->options['portability'] & DB_PORTABILITY_NUMROWS)
  1091. {
  1092. if ($this->dbh->features['prepare']) {
  1093. $res = $this->dbh->query($this->query, $this->parameters);
  1094. } else {
  1095. $res = $this->dbh->query($this->query);
  1096. }
  1097. if (DB::isError($res)) {
  1098. return $res;
  1099. }
  1100. $i = 0;
  1101. while ($res->fetchInto($tmp, DB_FETCHMODE_ORDERED)) {
  1102. $i++;
  1103. }
  1104. return $i;
  1105. } else {
  1106. return $this->dbh->numRows($this->result);
  1107. }
  1108. }
  1109. // }}}
  1110. // {{{ nextResult()
  1111. /**
  1112. * Get the next result if a batch of queries was executed
  1113. *
  1114. * @return bool true if a new result is available or false if not
  1115. */
  1116. function nextResult()
  1117. {
  1118. return $this->dbh->nextResult($this->result);
  1119. }
  1120. // }}}
  1121. // {{{ free()
  1122. /**
  1123. * Frees the resources allocated for this result set
  1124. *
  1125. * @return bool true on success. A DB_Error object on failure.
  1126. */
  1127. function free()
  1128. {
  1129. $err = $this->dbh->freeResult($this->result);
  1130. if (DB::isError($err)) {
  1131. return $err;
  1132. }
  1133. $this->result = false;
  1134. $this->statement = false;
  1135. return true;
  1136. }
  1137. // }}}
  1138. // {{{ tableInfo()
  1139. /**
  1140. * @see DB_common::tableInfo()
  1141. * @deprecated Method deprecated some time before Release 1.2
  1142. */
  1143. function tableInfo($mode = null)
  1144. {
  1145. if (is_string($mode)) {
  1146. return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA);
  1147. }
  1148. return $this->dbh->tableInfo($this, $mode);
  1149. }
  1150. // }}}
  1151. // {{{ getQuery()
  1152. /**
  1153. * Determine the query string that created this result
  1154. *
  1155. * @return string the query string
  1156. *
  1157. * @since Method available since Release 1.7.0
  1158. */
  1159. function getQuery()
  1160. {
  1161. return $this->query;
  1162. }
  1163. // }}}
  1164. // {{{ getRowCounter()
  1165. /**
  1166. * Tells which row number is currently being processed
  1167. *
  1168. * @return integer the current row being looked at. Starts at 1.
  1169. */
  1170. function getRowCounter()
  1171. {
  1172. return $this->row_counter;
  1173. }
  1174. // }}}
  1175. }
  1176. // }}}
  1177. // {{{ class DB_row
  1178. /**
  1179. * PEAR DB Row Object
  1180. *
  1181. * The object contains a row of data from a result set. Each column's data
  1182. * is placed in a property named for the column.
  1183. *
  1184. * @category Database
  1185. * @package DB
  1186. * @author Stig Bakken <ssb@php.net>
  1187. * @copyright 1997-2005 The PHP Group
  1188. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  1189. * @version Release: @package_version@
  1190. * @link http://pear.php.net/package/DB
  1191. * @see DB_common::setFetchMode()
  1192. */
  1193. class DB_row
  1194. {
  1195. // {{{ constructor
  1196. /**
  1197. * The constructor places a row's data into properties of this object
  1198. *
  1199. * @param array the array containing the row's data
  1200. *
  1201. * @return void
  1202. */
  1203. function DB_row(&$arr)
  1204. {
  1205. foreach ($arr as $key => $value) {
  1206. $this->$key = &$arr[$key];
  1207. }
  1208. }
  1209. // }}}
  1210. }
  1211. // }}}
  1212. /*
  1213. * Local variables:
  1214. * tab-width: 4
  1215. * c-basic-offset: 4
  1216. * End:
  1217. */
  1218. ?>