PageRenderTime 67ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/fDatabase.php

https://bitbucket.org/ZilIsiltk/flourish
PHP | 3211 lines | 2016 code | 415 blank | 780 comment | 505 complexity | aa8866de51a13830825efd3031007590 MD5 | raw file
  1. <?php
  2. /**
  3. * Provides a common API for different databases - will automatically use any installed extension
  4. *
  5. * This class is implemented to use the UTF-8 character encoding. Please see
  6. * http://flourishlib.com/docs/UTF-8 for more information.
  7. *
  8. * The following databases are supported:
  9. *
  10. * - [http://ibm.com/db2 DB2]
  11. * - [http://microsoft.com/sql/ MSSQL]
  12. * - [http://mysql.com MySQL]
  13. * - [http://oracle.com Oracle]
  14. * - [http://postgresql.org PostgreSQL]
  15. * - [http://sqlite.org SQLite]
  16. *
  17. * The class will automatically use the first of the following extensions it finds:
  18. *
  19. * - DB2
  20. * - [http://php.net/ibm_db2 ibm_db2]
  21. * - [http://php.net/pdo_ibm pdo_ibm]
  22. * - MSSQL
  23. * - [http://msdn.microsoft.com/en-us/library/cc296221.aspx sqlsrv]
  24. * - [http://php.net/pdo_dblib pdo_dblib]
  25. * - [http://php.net/mssql mssql] (or [http://php.net/sybase sybase])
  26. * - MySQL
  27. * - [http://php.net/mysql mysql]
  28. * - [http://php.net/mysqli mysqli]
  29. * - [http://php.net/pdo_mysql pdo_mysql]
  30. * - Oracle
  31. * - [http://php.net/oci8 oci8]
  32. * - [http://php.net/pdo_oci pdo_oci]
  33. * - PostgreSQL
  34. * - [http://php.net/pgsql pgsql]
  35. * - [http://php.net/pdo_pgsql pdo_pgsql]
  36. * - SQLite
  37. * - [http://php.net/pdo_sqlite pdo_sqlite] (for v3.x)
  38. * - [http://php.net/sqlite sqlite] (for v2.x)
  39. *
  40. * The `odbc` and `pdo_odbc` extensions are not supported due to character
  41. * encoding and stability issues on Windows, and functionality on non-Windows
  42. * operating systems.
  43. *
  44. * @copyright Copyright (c) 2007-2010 Will Bond
  45. * @author Will Bond [wb] <will@flourishlib.com>
  46. * @license http://flourishlib.com/license
  47. *
  48. * @package Flourish
  49. * @link http://flourishlib.com/fDatabase
  50. *
  51. * @version 1.0.0b31
  52. * @changes 1.0.0b31 Fixed handling auto-incrementing values for MySQL when the `INTO` keyword is left out of an `INSERT` statement [wb, 2010-11-04]
  53. * @changes 1.0.0b30 Fixed the pgsql, mssql and mysql extensions to force a new connection instead of reusing an existing one [wb, 2010-08-17]
  54. * @changes 1.0.0b29 Backwards Compatibility Break - removed ::enableSlowQueryWarnings(), added ability to replicate via ::registerHookCallback() [wb, 2010-08-10]
  55. * @changes 1.0.0b28 Backwards Compatibility Break - removed ODBC support. Added support for the `pdo_ibm` extension. [wb, 2010-07-31]
  56. * @changes 1.0.0b27 Fixed a bug with running multiple copies of a SQL statement with string values through a single ::translatedQuery() call [wb, 2010-07-14]
  57. * @changes 1.0.0b26 Updated the class to use new fCore functionality [wb, 2010-07-05]
  58. * @changes 1.0.0b25 Added IBM DB2 support [wb, 2010-04-13]
  59. * @changes 1.0.0b24 Fixed an auto-incrementing transaction bug with Oracle and debugging issues with all databases [wb, 2010-03-17]
  60. * @changes 1.0.0b23 Resolved another bug with capturing auto-incrementing values for PostgreSQL and Oracle [wb, 2010-03-15]
  61. * @changes 1.0.0b22 Changed ::clearCache() to also clear the cache on the fSQLTranslation [wb, 2010-03-09]
  62. * @changes 1.0.0b21 Added ::execute() for result-less SQL queries, ::prepare() and ::translatedPrepare() to create fStatement objects for prepared statements, support for prepared statements in ::query() and ::unbufferedQuery(), fixed default caching key for ::enableCaching() [wb, 2010-03-02]
  63. * @changes 1.0.0b20 Added a parameter to ::enableCaching() to provide a key token that will allow cached values to be shared between multiple databases with the same schema [wb, 2009-10-28]
  64. * @changes 1.0.0b19 Added support for escaping identifiers (column and table names) to ::escape(), added support for database schemas, rewrote internal SQL string spliting [wb, 2009-10-22]
  65. * @changes 1.0.0b18 Updated the class for the new fResult and fUnbufferedResult APIs, fixed ::unescape() to not touch NULLs [wb, 2009-08-12]
  66. * @changes 1.0.0b17 Added the ability to pass an array of all values as a single parameter to ::escape() instead of one value per parameter [wb, 2009-08-11]
  67. * @changes 1.0.0b16 Fixed PostgreSQL and Oracle from trying to get auto-incrementing values on inserts when explicit values were given [wb, 2009-08-06]
  68. * @changes 1.0.0b15 Fixed a bug where auto-incremented values would not be detected when table names were quoted [wb, 2009-07-15]
  69. * @changes 1.0.0b14 Changed ::determineExtension() and ::determineCharacterSet() to be protected instead of private [wb, 2009-07-08]
  70. * @changes 1.0.0b13 Updated ::escape() to accept arrays of values for insertion into full SQL strings [wb, 2009-07-06]
  71. * @changes 1.0.0b12 Updates to ::unescape() to improve performance [wb, 2009-06-15]
  72. * @changes 1.0.0b11 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
  73. * @changes 1.0.0b10 Changed date/time/timestamp escaping from `strtotime()` to fDate/fTime/fTimestamp for better localization support [wb, 2009-06-01]
  74. * @changes 1.0.0b9 Fixed a bug with ::escape() where floats that start with a . were encoded as `NULL` [wb, 2009-05-09]
  75. * @changes 1.0.0b8 Added Oracle support, change PostgreSQL code to no longer cause lastval() warnings, added support for arrays of values to ::escape() [wb, 2009-05-03]
  76. * @changes 1.0.0b7 Updated for new fCore API [wb, 2009-02-16]
  77. * @changes 1.0.0b6 Fixed a bug with executing transaction queries when using the mysqli extension [wb, 2009-02-12]
  78. * @changes 1.0.0b5 Changed @ error suppression operator to `error_reporting()` calls [wb, 2009-01-26]
  79. * @changes 1.0.0b4 Added a few error suppression operators back in so that developers don't get errors and exceptions [wb, 2009-01-14]
  80. * @changes 1.0.0b3 Removed some unnecessary error suppresion operators [wb, 2008-12-11]
  81. * @changes 1.0.0b2 Fixed a bug with PostgreSQL when using the PDO extension and executing an INSERT statement [wb, 2008-12-11]
  82. * @changes 1.0.0b The initial implementation [wb, 2007-09-25]
  83. */
  84. class fDatabase
  85. {
  86. /**
  87. * Composes text using fText if loaded
  88. *
  89. * @param string $message The message to compose
  90. * @param mixed $component A string or number to insert into the message
  91. * @param mixed ...
  92. * @return string The composed and possible translated message
  93. */
  94. static protected function compose($message)
  95. {
  96. $args = array_slice(func_get_args(), 1);
  97. if (class_exists('fText', FALSE)) {
  98. return call_user_func_array(
  99. array('fText', 'compose'),
  100. array($message, $args)
  101. );
  102. } else {
  103. return vsprintf($message, $args);
  104. }
  105. }
  106. /**
  107. * An fCache object to cache the schema info to
  108. *
  109. * @var fCache
  110. */
  111. private $cache;
  112. /**
  113. * The cache prefix to use for cache entries
  114. *
  115. * @var string
  116. */
  117. private $cache_prefix;
  118. /**
  119. * Database connection resource or PDO object
  120. *
  121. * @var mixed
  122. */
  123. private $connection;
  124. /**
  125. * The database name
  126. *
  127. * @var string
  128. */
  129. private $database;
  130. /**
  131. * If debugging is enabled
  132. *
  133. * @var boolean
  134. */
  135. private $debug;
  136. /**
  137. * A temporary error holder for the mssql extension
  138. *
  139. * @var string
  140. */
  141. private $error;
  142. /**
  143. * The extension to use for the database specified
  144. *
  145. * Options include:
  146. *
  147. * - `'ibm_db2'`
  148. * - `'mssql'`
  149. * - `'mysql'`
  150. * - `'mysqli'`
  151. * - `'oci8'`
  152. * - `'pgsql'`
  153. * - `'sqlite'`
  154. * - `'sqlsrv'`
  155. * - `'pdo'`
  156. *
  157. * @var string
  158. */
  159. protected $extension;
  160. /**
  161. * Hooks callbacks to be used for accessing and modifying queries
  162. *
  163. * This array will have the structure:
  164. *
  165. * {{{
  166. * array(
  167. * 'unmodified' => array({callbacks}),
  168. * 'extracted' => array({callbacks}),
  169. * 'run' => array({callbacks})
  170. * )
  171. * }}}
  172. *
  173. * @var array
  174. */
  175. private $hook_callbacks;
  176. /**
  177. * The host the database server is located on
  178. *
  179. * @var string
  180. */
  181. private $host;
  182. /**
  183. * If a transaction is in progress
  184. *
  185. * @var boolean
  186. */
  187. private $inside_transaction;
  188. /**
  189. * The password for the user specified
  190. *
  191. * @var string
  192. */
  193. private $password;
  194. /**
  195. * The port number for the host
  196. *
  197. * @var string
  198. */
  199. private $port;
  200. /**
  201. * The total number of seconds spent executing queries
  202. *
  203. * @var float
  204. */
  205. private $query_time;
  206. /**
  207. * A cache of database-specific code
  208. *
  209. * @var array
  210. */
  211. protected $schema_info;
  212. /**
  213. * The last executed fStatement object
  214. *
  215. * @var fStatement
  216. */
  217. private $statement;
  218. /**
  219. * The fSQLTranslation object for this database
  220. *
  221. * @var object
  222. */
  223. private $translation;
  224. /**
  225. * The database type: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, or `'sqlite'`
  226. *
  227. * @var string
  228. */
  229. private $type;
  230. /**
  231. * The unbuffered query instance
  232. *
  233. * @var fUnbufferedResult
  234. */
  235. private $unbuffered_result;
  236. /**
  237. * The user to connect to the database as
  238. *
  239. * @var string
  240. */
  241. private $username;
  242. /**
  243. * Configures the connection to a database - connection is not made until the first query is executed
  244. *
  245. * @param string $type The type of the database: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, `'sqlite'`
  246. * @param string $database Name of the database. If SQLite the path to the database file.
  247. * @param string $username Database username - not used for SQLite
  248. * @param string $password The password for the username specified - not used for SQLite
  249. * @param string $host Database server host or IP, defaults to localhost - not used for SQLite. MySQL socket connection can be made by entering `'sock:'` followed by the socket path. PostgreSQL socket connection can be made by passing just `'sock:'`.
  250. * @param integer $port The port to connect to, defaults to the standard port for the database type specified - not used for SQLite
  251. * @return fDatabase
  252. */
  253. public function __construct($type, $database, $username=NULL, $password=NULL, $host=NULL, $port=NULL)
  254. {
  255. $valid_types = array('db2', 'mssql', 'mysql', 'oracle', 'postgresql', 'sqlite');
  256. if (!in_array($type, $valid_types)) {
  257. throw new fProgrammerException(
  258. 'The database type specified, %1$s, is invalid. Must be one of: %2$s.',
  259. $type,
  260. join(', ', $valid_types)
  261. );
  262. }
  263. if (empty($database)) {
  264. throw new fProgrammerException('No database was specified');
  265. }
  266. if ($host === NULL) {
  267. $host = 'localhost';
  268. }
  269. $this->type = $type;
  270. $this->database = $database;
  271. $this->username = $username;
  272. $this->password = $password;
  273. $this->host = $host;
  274. $this->port = $port;
  275. $this->hook_callbacks = array(
  276. 'unmodified' => array(),
  277. 'extracted' => array(),
  278. 'run' => array()
  279. );
  280. $this->schema_info = array();
  281. $this->determineExtension();
  282. }
  283. /**
  284. * Closes the open database connection
  285. *
  286. * @internal
  287. *
  288. * @return void
  289. */
  290. public function __destruct()
  291. {
  292. if (!$this->connection) { return; }
  293. fCore::debug('Total query time: ' . $this->query_time . ' seconds', $this->debug);
  294. if ($this->extension == 'ibm_db2') {
  295. db2_close($this->connection);
  296. } elseif ($this->extension == 'mssql') {
  297. mssql_close($this->connection);
  298. } elseif ($this->extension == 'mysql') {
  299. mysql_close($this->connection);
  300. } elseif ($this->extension == 'mysqli') {
  301. mysqli_close($this->connection);
  302. } elseif ($this->extension == 'oci8') {
  303. oci_close($this->connection);
  304. } elseif ($this->extension == 'pgsql') {
  305. pg_close($this->connection);
  306. } elseif ($this->extension == 'sqlite') {
  307. sqlite_close($this->connection);
  308. } elseif ($this->extension == 'sqlsrv') {
  309. sqlsrv_close($this->connection);
  310. } elseif ($this->extension == 'pdo') {
  311. // PDO objects close their own connections when destroyed
  312. }
  313. }
  314. /**
  315. * All requests that hit this method should be requests for callbacks
  316. *
  317. * @internal
  318. *
  319. * @param string $method The method to create a callback for
  320. * @return callback The callback for the method requested
  321. */
  322. public function __get($method)
  323. {
  324. return array($this, $method);
  325. }
  326. /**
  327. * Checks to see if an SQL error occured
  328. *
  329. * @param fResult|fUnbufferedResult|boolean $result The result object for the query
  330. * @param mixed $extra_info The sqlite extension will pass a string error message, the oci8 extension will pass the statement resource
  331. * @param string $sql The SQL that was executed
  332. * @return void
  333. */
  334. private function checkForError($result, $extra_info=NULL, $sql=NULL)
  335. {
  336. if ($result === FALSE || $result->getResult() === FALSE) {
  337. if ($this->extension == 'ibm_db2') {
  338. if (is_resource($extra_info)) {
  339. $message = db2_stmt_errormsg($extra_info);
  340. } else {
  341. $message = db2_stmt_errormsg();
  342. }
  343. } elseif ($this->extension == 'mssql') {
  344. $message = $this->error;
  345. unset($this->error);
  346. } elseif ($this->extension == 'mysql') {
  347. $message = mysql_error($this->connection);
  348. } elseif ($this->extension == 'mysqli') {
  349. if (is_object($extra_info)) {
  350. $message = $extra_info->error;
  351. } else {
  352. $message = mysqli_error($this->connection);
  353. }
  354. } elseif ($this->extension == 'oci8') {
  355. $error_info = oci_error($extra_info);
  356. $message = $error_info['message'];
  357. } elseif ($this->extension == 'pgsql') {
  358. $message = pg_last_error($this->connection);
  359. } elseif ($this->extension == 'sqlite') {
  360. $message = $extra_info;
  361. } elseif ($this->extension == 'sqlsrv') {
  362. $error_info = sqlsrv_errors(SQLSRV_ERR_ALL);
  363. $message = $error_info[0]['message'];
  364. } elseif ($this->extension == 'pdo') {
  365. if ($extra_info instanceof PDOStatement) {
  366. $error_info = $extra_info->errorInfo();
  367. } else {
  368. $error_info = $this->connection->errorInfo();
  369. }
  370. if (empty($error_info[2])) {
  371. $error_info[2] = 'Unknown error - this usually indicates a bug in the PDO driver';
  372. }
  373. $message = $error_info[2];
  374. }
  375. $db_type_map = array(
  376. 'db2' => 'DB2',
  377. 'mssql' => 'MSSQL',
  378. 'mysql' => 'MySQL',
  379. 'oracle' => 'Oracle',
  380. 'postgresql' => 'PostgreSQL',
  381. 'sqlite' => 'SQLite'
  382. );
  383. throw new fSQLException(
  384. '%1$s error (%2$s) in %3$s',
  385. $db_type_map[$this->type],
  386. $message,
  387. is_object($result) ? $result->getSQL() : $sql
  388. );
  389. }
  390. }
  391. /**
  392. * Clears all of the schema info out of the object and, if set, the fCache object
  393. *
  394. * @return void
  395. */
  396. public function clearCache()
  397. {
  398. $this->schema_info = array();
  399. if ($this->cache) {
  400. $this->cache->delete($this->makeCachePrefix() . 'schema_info');
  401. }
  402. if ($this->type == 'mssql') {
  403. $this->determineCharacterSet();
  404. }
  405. if ($this->translation) {
  406. $this->translation->clearCache();
  407. }
  408. }
  409. /**
  410. * Connects to the database specified if no connection exists
  411. *
  412. * @return void
  413. */
  414. private function connectToDatabase()
  415. {
  416. // Don't try to reconnect if we are already connected
  417. if ($this->connection) { return; }
  418. // Establish a connection to the database
  419. if ($this->extension == 'pdo') {
  420. $username = $this->username;
  421. $password = $this->password;
  422. if ($this->type == 'db2') {
  423. if ($this->host === NULL && $this->port === NULL) {
  424. $dsn = 'ibm:DSN:' . $this->database;
  425. } else {
  426. $dsn = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
  427. $dsn .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
  428. $dsn .= 'PROTOCOL=TCPIP;UID=' . $username . ';PWD=' . $password . ';';
  429. $username = NULL;
  430. $password = NULL;
  431. }
  432. } elseif ($this->type == 'mssql') {
  433. $separator = (fCore::checkOS('windows')) ? ',' : ':';
  434. $port = ($this->port) ? $separator . $this->port : '';
  435. $driver = (fCore::checkOs('windows')) ? 'mssql' : 'dblib';
  436. $dsn = $driver . ':host=' . $this->host . $port . ';dbname=' . $this->database;
  437. } elseif ($this->type == 'mysql') {
  438. if (substr($this->host, 0, 5) == 'sock:') {
  439. $dsn = 'mysql:unix_socket=' . substr($this->host, 5) . ';dbname=' . $this->database;
  440. } else {
  441. $port = ($this->port) ? ';port=' . $this->port : '';
  442. $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database . $port;
  443. }
  444. } elseif ($this->type == 'oracle') {
  445. $port = ($this->port) ? ':' . $this->port : '';
  446. $dsn = 'oci:dbname=' . $this->host . $port . '/' . $this->database . ';charset=AL32UTF8';
  447. } elseif ($this->type == 'postgresql') {
  448. $dsn = 'pgsql:dbname=' . $this->database;
  449. if ($this->host && $this->host != 'sock:') {
  450. $dsn .= ' host=' . $this->host;
  451. }
  452. if ($this->port) {
  453. $dsn .= ' port=' . $this->port;
  454. }
  455. } elseif ($this->type == 'sqlite') {
  456. $dsn = 'sqlite:' . $this->database;
  457. }
  458. try {
  459. $this->connection = new PDO($dsn, $username, $password);
  460. if ($this->type == 'mysql') {
  461. $this->connection->setAttribute(PDO::MYSQL_ATTR_DIRECT_QUERY, 1);
  462. }
  463. } catch (PDOException $e) {
  464. $this->connection = FALSE;
  465. }
  466. }
  467. if ($this->extension == 'sqlite') {
  468. $this->connection = sqlite_open($this->database);
  469. }
  470. if ($this->extension == 'ibm_db2') {
  471. $username = $this->username;
  472. $password = $this->password;
  473. if ($this->host === NULL && $this->port === NULL) {
  474. $connection_string = $this->database;
  475. } else {
  476. $connection_string = 'DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
  477. $connection_string .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
  478. $connection_string .= 'PROTOCOL=TCPIP;UID=' . $this->username . ';PWD=' . $this->password . ';';
  479. $username = NULL;
  480. $password = NULL;
  481. }
  482. $options = array(
  483. 'autocommit' => DB2_AUTOCOMMIT_ON,
  484. 'DB2_ATTR_CASE' => DB2_CASE_LOWER
  485. );
  486. $this->connection = db2_connect($connection_string, $username, $password, $options);
  487. }
  488. if ($this->extension == 'mssql') {
  489. $separator = (fCore::checkOS('windows')) ? ',' : ':';
  490. $this->connection = mssql_connect(($this->port) ? $this->host . $separator . $this->port : $this->host, $this->username, $this->password, TRUE);
  491. if ($this->connection !== FALSE && mssql_select_db($this->database, $this->connection) === FALSE) {
  492. $this->connection = FALSE;
  493. }
  494. }
  495. if ($this->extension == 'mysql') {
  496. if (substr($this->host, 0, 5) == 'sock:') {
  497. $host = substr($this->host, 4);
  498. } elseif ($this->port) {
  499. $host = $this->host . ':' . $this->port;
  500. } else {
  501. $host = $this->host;
  502. }
  503. $this->connection = mysql_connect($host, $this->username, $this->password, TRUE);
  504. if ($this->connection !== FALSE && mysql_select_db($this->database, $this->connection) === FALSE) {
  505. $this->connection = FALSE;
  506. }
  507. }
  508. if ($this->extension == 'mysqli') {
  509. if (substr($this->host, 0, 5) == 'sock:') {
  510. $this->connection = mysqli_connect('localhost', $this->username, $this->password, $this->database, $this->port, substr($this->host, 5));
  511. } elseif ($this->port) {
  512. $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database, $this->port);
  513. } else {
  514. $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
  515. }
  516. }
  517. if ($this->extension == 'oci8') {
  518. $this->connection = oci_connect($this->username, $this->password, $this->host . ($this->port ? ':' . $this->port : '') . '/' . $this->database, 'AL32UTF8');
  519. }
  520. if ($this->extension == 'pgsql') {
  521. $connection_string = "dbname='" . addslashes($this->database) . "'";
  522. if ($this->host && $this->host != 'sock:') {
  523. $connection_string .= " host='" . addslashes($this->host) . "'";
  524. }
  525. if ($this->username) {
  526. $connection_string .= " user='" . addslashes($this->username) . "'";
  527. }
  528. if ($this->password) {
  529. $connection_string .= " password='" . addslashes($this->password) . "'";
  530. }
  531. if ($this->port) {
  532. $connection_string .= " port='" . $this->port . "'";
  533. }
  534. $this->connection = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW);
  535. }
  536. if ($this->extension == 'sqlsrv') {
  537. $options = array(
  538. 'Database' => $this->database,
  539. 'UID' => $this->username,
  540. 'PWD' => $this->password
  541. );
  542. $this->connection = sqlsrv_connect($this->host . ',' . $this->port, $options);
  543. }
  544. // Ensure the connection was established
  545. if ($this->connection === FALSE) {
  546. throw new fConnectivityException(
  547. 'Unable to connect to database'
  548. );
  549. }
  550. // Make MySQL act more strict and use UTF-8
  551. if ($this->type == 'mysql') {
  552. $this->execute("SET SQL_MODE = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'");
  553. $this->execute("SET NAMES 'utf8'");
  554. $this->execute("SET CHARACTER SET utf8");
  555. }
  556. // Make SQLite behave like other DBs for assoc arrays
  557. if ($this->type == 'sqlite') {
  558. $this->execute('PRAGMA short_column_names = 1');
  559. }
  560. // Fix some issues with mssql
  561. if ($this->type == 'mssql') {
  562. if (!isset($this->schema_info['character_set'])) {
  563. $this->determineCharacterSet();
  564. }
  565. $this->execute('SET TEXTSIZE 65536');
  566. $this->execute('SET QUOTED_IDENTIFIER ON');
  567. }
  568. // Make PostgreSQL use UTF-8
  569. if ($this->type == 'postgresql') {
  570. $this->execute("SET NAMES 'UTF8'");
  571. }
  572. // Oracle has different date and timestamp defaults
  573. if ($this->type == 'oracle') {
  574. $this->execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
  575. $this->execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'");
  576. $this->execute("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS TZR'");
  577. $this->execute("ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS'");
  578. $this->execute("ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR'");
  579. }
  580. }
  581. /**
  582. * Determines the character set of a SQL Server database
  583. *
  584. * @return void
  585. */
  586. protected function determineCharacterSet()
  587. {
  588. $this->schema_info['character_set'] = 'WINDOWS-1252';
  589. $this->schema_info['character_set'] = $this->query("SELECT 'WINDOWS-' + CONVERT(VARCHAR, COLLATIONPROPERTY(CONVERT(NVARCHAR, DATABASEPROPERTYEX(DB_NAME(), 'Collation')), 'CodePage')) AS charset")->fetchScalar();
  590. if ($this->cache) {
  591. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  592. }
  593. }
  594. /**
  595. * Figures out which extension to use for the database type selected
  596. *
  597. * @return void
  598. */
  599. protected function determineExtension()
  600. {
  601. switch ($this->type) {
  602. case 'db2':
  603. if (extension_loaded('ibm_db2')) {
  604. $this->extension = 'ibm_db2';
  605. } elseif (class_exists('PDO', FALSE) && in_array('ibm', PDO::getAvailableDrivers())) {
  606. $this->extension = 'pdo';
  607. } else {
  608. $type = 'DB2';
  609. $exts = 'ibm_db2, pdo_ibm';
  610. }
  611. break;
  612. case 'mssql':
  613. if (extension_loaded('sqlsrv')) {
  614. $this->extension = 'sqlsrv';
  615. } elseif (extension_loaded('mssql')) {
  616. $this->extension = 'mssql';
  617. } elseif (class_exists('PDO', FALSE) && (in_array('dblib', PDO::getAvailableDrivers()) || in_array('mssql', PDO::getAvailableDrivers()))) {
  618. $this->extension = 'pdo';
  619. } else {
  620. $type = 'MSSQL';
  621. $exts = 'mssql, sqlsrv, pdo_dblib (linux), pdo_mssql (windows)';
  622. }
  623. break;
  624. case 'mysql':
  625. if (extension_loaded('mysqli')) {
  626. $this->extension = 'mysqli';
  627. } elseif (class_exists('PDO', FALSE) && in_array('mysql', PDO::getAvailableDrivers())) {
  628. $this->extension = 'pdo';
  629. } elseif (extension_loaded('mysql')) {
  630. $this->extension = 'mysql';
  631. } else {
  632. $type = 'MySQL';
  633. $exts = 'mysql, pdo_mysql, mysqli';
  634. }
  635. break;
  636. case 'oracle':
  637. if (extension_loaded('oci8')) {
  638. $this->extension = 'oci8';
  639. } elseif (class_exists('PDO', FALSE) && in_array('oci', PDO::getAvailableDrivers())) {
  640. $this->extension = 'pdo';
  641. } else {
  642. $type = 'Oracle';
  643. $exts = 'oci8, pdo_oci';
  644. }
  645. break;
  646. case 'postgresql':
  647. if (extension_loaded('pgsql')) {
  648. $this->extension = 'pgsql';
  649. } elseif (class_exists('PDO', FALSE) && in_array('pgsql', PDO::getAvailableDrivers())) {
  650. $this->extension = 'pdo';
  651. } else {
  652. $type = 'PostgreSQL';
  653. $exts = 'pgsql, pdo_pgsql';
  654. }
  655. break;
  656. case 'sqlite':
  657. $sqlite_version = 0;
  658. if (file_exists($this->database)) {
  659. $database_handle = fopen($this->database, 'r');
  660. $database_version = fread($database_handle, 64);
  661. fclose($database_handle);
  662. if (strpos($database_version, 'SQLite format 3') !== FALSE) {
  663. $sqlite_version = 3;
  664. } elseif (strpos($database_version, '** This file contains an SQLite 2.1 database **') !== FALSE) {
  665. $sqlite_version = 2;
  666. } else {
  667. throw new fConnectivityException(
  668. 'The database specified does not appear to be a valid %1$s or %2$s database',
  669. 'SQLite v2.1',
  670. 'v3'
  671. );
  672. }
  673. }
  674. if ((!$sqlite_version || $sqlite_version == 3) && class_exists('PDO', FALSE) && in_array('sqlite', PDO::getAvailableDrivers())) {
  675. $this->extension = 'pdo';
  676. } elseif ($sqlite_version == 3 && (!class_exists('PDO', FALSE) || !in_array('sqlite', PDO::getAvailableDrivers()))) {
  677. throw new fEnvironmentException(
  678. 'The database specified is an %1$s database and the %2$s extension is not installed',
  679. 'SQLite v3',
  680. 'pdo_sqlite'
  681. );
  682. } elseif ((!$sqlite_version || $sqlite_version == 2) && extension_loaded('sqlite')) {
  683. $this->extension = 'sqlite';
  684. } elseif ($sqlite_version == 2 && !extension_loaded('sqlite')) {
  685. throw new fEnvironmentException(
  686. 'The database specified is an %1$s database and the %2$s extension is not installed',
  687. 'SQLite v2.1',
  688. 'sqlite'
  689. );
  690. } else {
  691. $type = 'SQLite';
  692. $exts = 'pdo_sqlite, sqlite';
  693. }
  694. break;
  695. }
  696. if (!$this->extension) {
  697. throw new fEnvironmentException(
  698. 'The server does not have any of the following extensions for %2$s support: %2$s',
  699. $type,
  700. $exts
  701. );
  702. }
  703. }
  704. /**
  705. * Sets the schema info to be cached to the fCache object specified
  706. *
  707. * @param fCache $cache The cache to cache to
  708. * @param string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fDatabase object)
  709. * @return void
  710. */
  711. public function enableCaching($cache, $key_token=NULL)
  712. {
  713. $this->cache = $cache;
  714. if ($key_token !== NULL) {
  715. $this->cache_prefix = 'fDatabase::' . $this->type . '::' . $key_token . '::';
  716. }
  717. $this->schema_info = $this->cache->get($this->makeCachePrefix() . 'schema_info', array());
  718. }
  719. /**
  720. * Sets if debug messages should be shown
  721. *
  722. * @param boolean $flag If debugging messages should be shown
  723. * @return void
  724. */
  725. public function enableDebugging($flag)
  726. {
  727. $this->debug = (boolean) $flag;
  728. }
  729. /**
  730. * Escapes a value for insertion into SQL
  731. *
  732. * The valid data types are:
  733. *
  734. * - `'blob'`
  735. * - `'boolean'`
  736. * - `'date'`
  737. * - `'float'`
  738. * - `'identifier'`
  739. * - `'integer'`
  740. * - `'string'` (also varchar, char or text)
  741. * - `'varchar'`
  742. * - `'char'`
  743. * - `'text'`
  744. * - `'time'`
  745. * - `'timestamp'`
  746. *
  747. * In addition to being able to specify the data type, you can also pass
  748. * in an SQL statement with data type placeholders in the following form:
  749. *
  750. * - `%l` for a blob
  751. * - `%b` for a boolean
  752. * - `%d` for a date
  753. * - `%f` for a float
  754. * - `%r` for an indentifier (table or column name)
  755. * - `%i` for an integer
  756. * - `%s` for a string
  757. * - `%t` for a time
  758. * - `%p` for a timestamp
  759. *
  760. * Depending on what `$sql_or_type` and `$value` are, the output will be
  761. * slightly different. If `$sql_or_type` is a data type or a single
  762. * placeholder and `$value` is:
  763. *
  764. * - a scalar value - an escaped SQL string is returned
  765. * - an array - an array of escaped SQL strings is returned
  766. *
  767. * If `$sql_or_type` is a SQL string and `$value` is:
  768. *
  769. * - a scalar value - the escaped value is inserted into the SQL string
  770. * - an array - the escaped values are inserted into the SQL string separated by commas
  771. *
  772. * If `$sql_or_type` is a SQL string, it is also possible to pass an array
  773. * of all values as a single parameter instead of one value per parameter.
  774. * An example would look like the following:
  775. *
  776. * {{{
  777. * #!php
  778. * $db->escape(
  779. * "SELECT * FROM users WHERE status = %s AND authorization_level = %s",
  780. * array('Active', 'Admin')
  781. * );
  782. * }}}
  783. *
  784. * @param string $sql_or_type This can either be the data type to escape or an SQL string with a data type placeholder - see method description
  785. * @param mixed $value The value to escape - both single values and arrays of values are supported, see method description for details
  786. * @param mixed ...
  787. * @return mixed The escaped value/SQL or an array of the escaped values
  788. */
  789. public function escape($sql_or_type, $value)
  790. {
  791. $values = array_slice(func_get_args(), 1);
  792. if (sizeof($values) < 1) {
  793. throw new fProgrammerException(
  794. 'No value was specified to escape'
  795. );
  796. }
  797. // Convert all objects into strings
  798. $values = $this->scalarize($values);
  799. $value = array_shift($values);
  800. // Handle single value escaping
  801. $callback = NULL;
  802. switch ($sql_or_type) {
  803. case 'blob':
  804. case '%l':
  805. $callback = $this->escapeBlob;
  806. break;
  807. case 'boolean':
  808. case '%b':
  809. $callback = $this->escapeBoolean;
  810. break;
  811. case 'date':
  812. case '%d':
  813. $callback = $this->escapeDate;
  814. break;
  815. case 'float':
  816. case '%f':
  817. $callback = $this->escapeFloat;
  818. break;
  819. case 'identifier':
  820. case '%r':
  821. $callback = $this->escapeIdentifier;
  822. break;
  823. case 'integer':
  824. case '%i':
  825. $callback = $this->escapeInteger;
  826. break;
  827. case 'string':
  828. case 'varchar':
  829. case 'char':
  830. case 'text':
  831. case '%s':
  832. $callback = $this->escapeString;
  833. break;
  834. case 'time':
  835. case '%t':
  836. $callback = $this->escapeTime;
  837. break;
  838. case 'timestamp':
  839. case '%p':
  840. $callback = $this->escapeTimestamp;
  841. break;
  842. }
  843. if ($callback) {
  844. if (is_array($value)) {
  845. // If the values were passed as a single array, this handles that
  846. if (count($value) == 1 && is_array(current($value))) {
  847. $value = current($value);
  848. }
  849. return array_map($callback, $value);
  850. }
  851. return call_user_func($callback, $value);
  852. }
  853. // Fix \' in MySQL and PostgreSQL
  854. if(($this->type == 'mysql' || $this->type == 'postgresql') && strpos($sql_or_type, '\\') !== FALSE) {
  855. $sql_or_type = preg_replace("#(?<!\\\\)((\\\\{2})*)\\\\'#", "\\1''", $sql_or_type);
  856. }
  857. // Separate the SQL from quoted values
  858. $parts = $this->splitSQL($sql_or_type);
  859. $temp_sql = '';
  860. $strings = array();
  861. // Replace strings with a placeholder so they don't mess up the regex parsing
  862. foreach ($parts as $part) {
  863. if ($part[0] == "'") {
  864. $strings[] = $part;
  865. $part = ':string_' . (sizeof($strings)-1);
  866. }
  867. $temp_sql .= $part;
  868. }
  869. // If the values were passed as a single array, this handles that
  870. $placeholders = preg_match_all('#%[lbdfristp]\b#', $temp_sql, $trash);
  871. if (count($values) == 0 && is_array($value) && count($value) == $placeholders) {
  872. $values = $value;
  873. $value = array_shift($values);
  874. }
  875. array_unshift($values, $value);
  876. $sql = $this->escapeSQL($temp_sql, $values);
  877. $string_number = 0;
  878. foreach ($strings as $string) {
  879. $string = strtr($string, array('\\' => '\\\\', '$' => '\\$'));
  880. $sql = preg_replace('#:string_' . $string_number++ . '\b#', $string, $sql);
  881. }
  882. return $sql;
  883. }
  884. /**
  885. * Escapes a blob for use in SQL, includes surround quotes when appropriate
  886. *
  887. * A `NULL` value will be returned as `'NULL'`
  888. *
  889. * @param string $value The blob to escape
  890. * @return string The escaped blob
  891. */
  892. private function escapeBlob($value)
  893. {
  894. if ($value === NULL) {
  895. return 'NULL';
  896. }
  897. $this->connectToDatabase();
  898. if ($this->type == 'db2') {
  899. return "BLOB(X'" . bin2hex($value) . "')";
  900. } elseif ($this->type == 'mysql') {
  901. return "x'" . bin2hex($value) . "'";
  902. } elseif ($this->type == 'postgresql') {
  903. $output = '';
  904. for ($i=0; $i<strlen($value); $i++) {
  905. $output .= '\\\\' . str_pad(decoct(ord($value[$i])), 3, '0', STR_PAD_LEFT);
  906. }
  907. return "E'" . $output . "'";
  908. } elseif ($this->extension == 'sqlite') {
  909. return "'" . bin2hex($value) . "'";
  910. } elseif ($this->type == 'sqlite') {
  911. return "X'" . bin2hex($value) . "'";
  912. } elseif ($this->type == 'mssql') {
  913. return '0x' . bin2hex($value);
  914. } elseif ($this->type == 'oracle') {
  915. return "'" . bin2hex($value) . "'";
  916. }
  917. }
  918. /**
  919. * Escapes a boolean for use in SQL, includes surround quotes when appropriate
  920. *
  921. * A `NULL` value will be returned as `'NULL'`
  922. *
  923. * @param boolean $value The boolean to escape
  924. * @return string The database equivalent of the boolean passed
  925. */
  926. private function escapeBoolean($value)
  927. {
  928. if ($value === NULL) {
  929. return 'NULL';
  930. }
  931. if (in_array($this->type, array('postgresql', 'mysql'))) {
  932. return ($value) ? 'TRUE' : 'FALSE';
  933. } elseif (in_array($this->type, array('mssql', 'sqlite', 'db2'))) {
  934. return ($value) ? "'1'" : "'0'";
  935. } elseif ($this->type == 'oracle') {
  936. return ($value) ? '1' : '0';
  937. }
  938. }
  939. /**
  940. * Escapes a date for use in SQL, includes surrounding quotes
  941. *
  942. * A `NULL` or invalid value will be returned as `'NULL'`
  943. *
  944. * @param string $value The date to escape
  945. * @return string The escaped date
  946. */
  947. private function escapeDate($value)
  948. {
  949. if ($value === NULL) {
  950. return 'NULL';
  951. }
  952. try {
  953. $value = new fDate($value);
  954. return "'" . $value->format('Y-m-d') . "'";
  955. } catch (fValidationException $e) {
  956. return 'NULL';
  957. }
  958. }
  959. /**
  960. * Escapes a float for use in SQL
  961. *
  962. * A `NULL` value will be returned as `'NULL'`
  963. *
  964. * @param float $value The float to escape
  965. * @return string The escaped float
  966. */
  967. private function escapeFloat($value)
  968. {
  969. if ($value === NULL) {
  970. return 'NULL';
  971. }
  972. if (!strlen($value)) {
  973. return 'NULL';
  974. }
  975. if (!preg_match('#^[+\-]?([0-9]+(\.[0-9]+)?|(\.[0-9]+))$#D', $value)) {
  976. return 'NULL';
  977. }
  978. return (string) $value;
  979. }
  980. /**
  981. * Escapes an identifier for use in SQL, necessary for reserved words
  982. *
  983. * @param string $value The identifier to escape
  984. * @return string The escaped identifier
  985. */
  986. private function escapeIdentifier($value)
  987. {
  988. $value = '"' . str_replace(
  989. array('"', '.'),
  990. array('', '"."'),
  991. $value
  992. ) . '"';
  993. if (in_array($this->type, array('oracle', 'db2'))) {
  994. $value = strtoupper($value);
  995. }
  996. return $value;
  997. }
  998. /**
  999. * Escapes an integer for use in SQL
  1000. *
  1001. * A `NULL` or invalid value will be returned as `'NULL'`
  1002. *
  1003. * @param integer $value The integer to escape
  1004. * @return string The escaped integer
  1005. */
  1006. private function escapeInteger($value)
  1007. {
  1008. if ($value === NULL) {
  1009. return 'NULL';
  1010. }
  1011. if (!strlen($value)) {
  1012. return 'NULL';
  1013. }
  1014. if (!preg_match('#^([+\-]?[0-9]+)(\.[0-9]*)?$#D', $value, $matches)) {
  1015. return 'NULL';
  1016. }
  1017. return str_replace('+', '', $matches[1]);
  1018. }
  1019. /**
  1020. * Escapes a string for use in SQL, includes surrounding quotes
  1021. *
  1022. * A `NULL` value will be returned as `'NULL'`.
  1023. *
  1024. * @param string $value The string to escape
  1025. * @return string The escaped string
  1026. */
  1027. private function escapeString($value)
  1028. {
  1029. if ($value === NULL) {
  1030. return 'NULL';
  1031. }
  1032. $this->connectToDatabase();
  1033. if ($this->type == 'db2') {
  1034. return "'" . str_replace("'", "''", $value) . "'";
  1035. } elseif ($this->extension == 'mysql') {
  1036. return "'" . mysql_real_escape_string($value, $this->connection) . "'";
  1037. } elseif ($this->extension == 'mysqli') {
  1038. return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
  1039. } elseif ($this->extension == 'pgsql') {
  1040. return "'" . pg_escape_string($value) . "'";
  1041. } elseif ($this->extension == 'sqlite') {
  1042. return "'" . sqlite_escape_string($value) . "'";
  1043. } elseif ($this->type == 'oracle') {
  1044. return "'" . str_replace("'", "''", $value) . "'";
  1045. } elseif ($this->type == 'mssql') {
  1046. // If there are any non-ASCII characters, we need to escape
  1047. if (preg_match('#[^\x00-\x7F]#', $value)) {
  1048. preg_match_all('#.|^\z#us', $value, $characters);
  1049. $output = "";
  1050. $last_type = NULL;
  1051. foreach ($characters[0] as $character) {
  1052. if (strlen($character) > 1) {
  1053. $b = array_map('ord', str_split($character));
  1054. switch (strlen($character)) {
  1055. case 2:
  1056. $bin = substr(decbin($b[0]), 3) .
  1057. substr(decbin($b[1]), 2);
  1058. break;
  1059. case 3:
  1060. $bin = substr(decbin($b[0]), 4) .
  1061. substr(decbin($b[1]), 2) .
  1062. substr(decbin($b[2]), 2);
  1063. break;
  1064. // If it is a 4-byte character, MSSQL can't store it
  1065. // so instead store a ?
  1066. default:
  1067. $output .= '?';
  1068. continue;
  1069. }
  1070. if ($last_type == 'nchar') {
  1071. $output .= '+';
  1072. } elseif ($last_type == 'char') {
  1073. $output .= "'+";
  1074. }
  1075. $output .= "NCHAR(" . bindec($bin) . ")";
  1076. $last_type = 'nchar';
  1077. } else {
  1078. if (!$last_type) {
  1079. $output .= "'";
  1080. } elseif ($last_type == 'nchar') {
  1081. $output .= "+'";
  1082. }
  1083. $output .= $character;
  1084. // Escape single quotes
  1085. if ($character == "'") {
  1086. $output .= "'";
  1087. }
  1088. $last_type = 'char';
  1089. }
  1090. }
  1091. if ($last_type == 'char') {
  1092. $output .= "'";
  1093. } elseif (!$last_type) {
  1094. $output .= "''";
  1095. }
  1096. // ASCII text is normal
  1097. } else {
  1098. $output = "'" . str_replace("'", "''", $value) . "'";
  1099. }
  1100. # a \ before a \r\n has to be escaped with another \
  1101. return preg_replace('#(?<!\\\\)\\\\(?=\r\n)#', '\\\\\\\\', $output);
  1102. } elseif ($this->extension == 'pdo') {
  1103. return $this->connection->quote($value);
  1104. }
  1105. }
  1106. /**
  1107. * Takes a SQL string and an array of values and replaces the placeholders with the value
  1108. *
  1109. * @param string $sql The SQL string containing placeholders
  1110. * @param array $values An array of values to escape into the SQL
  1111. * @return string The SQL with the values escaped into it
  1112. */
  1113. private function escapeSQL($sql, $values)
  1114. {
  1115. $original_sql = $sql;
  1116. $pieces = preg_split('#(%[lbdfristp])\b#', $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  1117. $sql = '';
  1118. $value = array_shift($values);
  1119. $missing_values = -1;
  1120. foreach ($pieces as $piece) {
  1121. switch ($piece) {
  1122. case '%l':
  1123. $callback = $this->escapeBlob;
  1124. break;
  1125. case '%b':
  1126. $callback = $this->escapeBoolean;
  1127. break;
  1128. case '%d':
  1129. $callback = $this->escapeDate;
  1130. break;
  1131. case '%f':
  1132. $callback = $this->escapeFloat;
  1133. break;
  1134. case '%r':
  1135. $callback = $this->escapeIdentifier;
  1136. break;
  1137. case '%i':
  1138. $callback = $this->escapeInteger;
  1139. break;
  1140. case '%s':
  1141. $callback = $this->escapeString;
  1142. break;
  1143. case '%t':
  1144. $callback = $this->escapeTime;
  1145. break;
  1146. case '%p':
  1147. $callback = $this->escapeTimestamp;
  1148. break;
  1149. default:
  1150. $sql .= $piece;
  1151. continue 2;
  1152. }
  1153. if (is_array($value)) {
  1154. $sql .= join(', ', array_map($callback, $value));
  1155. } else {
  1156. $sql .= call_user_func($callback, $value);
  1157. }
  1158. if (sizeof($values)) {
  1159. $value = array_shift($values);
  1160. } else {
  1161. $value = NULL;
  1162. $missing_values++;
  1163. }
  1164. }
  1165. if ($missing_values > 0) {
  1166. throw new fProgrammerException(
  1167. '%1$s value(s) are missing for the placeholders in: %2$s',
  1168. $missing_values,
  1169. $original_sql
  1170. );
  1171. }
  1172. if (sizeof($values)) {
  1173. throw new fProgrammerException(
  1174. '%1$s extra value(s) were passed for the placeholders in: %2$s',
  1175. sizeof($values),
  1176. $original_sql
  1177. );
  1178. }
  1179. return $sql;
  1180. }
  1181. /**
  1182. * Escapes a time for use in SQL, includes surrounding quotes
  1183. *
  1184. * A `NULL` or invalid value will be returned as `'NULL'`
  1185. *
  1186. * @param string $value The time to escape
  1187. * @return string The escaped time
  1188. */
  1189. private function escapeTime($value)
  1190. {
  1191. if ($value === NULL) {
  1192. return 'NULL';
  1193. }
  1194. try {
  1195. $value = new fTime($value);
  1196. if ($this->type == 'mssql' || $this->type == 'oracle') {
  1197. return "'" . $value->format('1970-01-01 H:i:s') . "'";
  1198. }
  1199. return "'" . $value->format('H:i:s') . "'";
  1200. } catch (fValidationException $e) {
  1201. return 'NULL';
  1202. }
  1203. }
  1204. /**
  1205. * Escapes a timestamp for use in SQL, includes surrounding quotes
  1206. *
  1207. * A `NULL` or invalid value will be returned as `'NULL'`
  1208. *
  1209. * @param string $value The timestamp to escape
  1210. * @return string The escaped timestamp
  1211. */
  1212. private function escapeTimestamp($value)
  1213. {
  1214. if ($value === NULL) {
  1215. return 'NULL';
  1216. }
  1217. try {
  1218. $value = new fTimestamp($value);
  1219. return "'" . $value->format('Y-m-d H:i:s') . "'";
  1220. } catch (fValidationException $e) {
  1221. return 'NULL';
  1222. }
  1223. }
  1224. /**
  1225. * Executes one or more SQL queries without returning any results
  1226. *
  1227. * @param string|fStatement $statement One or more SQL statements in a string or an fStatement prepared statement
  1228. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  1229. * @param mixed ...
  1230. * @return void
  1231. */
  1232. public function execute($statement)
  1233. {
  1234. $args = func_get_args();
  1235. $params = array_slice($args, 1);
  1236. if (is_object($statement)) {
  1237. return $this->run($statement, NULL, $params);
  1238. }
  1239. $queries = $this->prepareSQL($statement, $params, FALSE);
  1240. $output = array();
  1241. foreach ($queries as $query) {
  1242. $this->run($query);
  1243. }
  1244. }
  1245. /**
  1246. * Takes in a string of SQL that contains multiple queries and returns any array of them
  1247. *
  1248. * @param string $sql The string of SQL to parse for queries
  1249. * @return array The individual SQL queries
  1250. */
  1251. private function explodeQueries($sql)
  1252. {
  1253. $sql_queries = array();
  1254. // Separate the SQL from quoted values
  1255. preg_match_all("#(?:'([^']*(?:'')*)*?')|(?:[^']+)#", $sql, $matches);
  1256. $cur_sql = '';
  1257. foreach ($matches[0] as $match) {
  1258. // This is a quoted string value, don't do anything to it
  1259. if ($match[0] == "'") {
  1260. $cur_sql .= $match;
  1261. // Handle the SQL, exploding on any ; that isn't escaped with a \
  1262. } else {
  1263. $sql_strings = preg_split('#(?<!\\\\);#', $match);
  1264. $cur_sql .= $sql_strings[0];
  1265. for ($i=1; $i < sizeof($sql_strings); $i++) {
  1266. $cur_sql = trim($cur_sql);
  1267. if ($cur_sql) {
  1268. $sql_queries[] = $cur_sql;
  1269. }
  1270. $cur_sql = $sql_strings[$i];
  1271. }
  1272. }
  1273. }
  1274. if (trim($cur_sql)) {
  1275. $sql_queries[] = $cur_sql;
  1276. }
  1277. return $sql_queries;
  1278. }
  1279. /**
  1280. * Returns the database connection resource or object
  1281. *
  1282. * @return mixed The database connection
  1283. */
  1284. public function getConnection()
  1285. {
  1286. $this->connectToDatabase();
  1287. return $this->connection;
  1288. }
  1289. /**
  1290. * Gets the name of the database currently connected to
  1291. *
  1292. * @return string The name of the database currently connected to
  1293. */
  1294. public function getDatabase()
  1295. {
  1296. return $this->database;
  1297. }
  1298. /**
  1299. * Gets the php extension being used
  1300. *
  1301. * @internal
  1302. *
  1303. * @return string The php extension used for database interaction
  1304. */
  1305. public function getExtension()
  1306. {
  1307. return $this->extension;
  1308. }
  1309. /**
  1310. * Gets the host for this database
  1311. *
  1312. * @return string The host
  1313. */
  1314. public function getHost()
  1315. {
  1316. return $this->host;
  1317. }
  1318. /**
  1319. * Gets the port for this database
  1320. *
  1321. * @return string The port
  1322. */
  1323. public function getPort()
  1324. {
  1325. return $this->port;
  1326. }
  1327. /**
  1328. * Gets the fSQLTranslation object used for translated queries
  1329. *
  1330. * @return fSQLTranslation The SQL translation object
  1331. */
  1332. public function getSQLTranslation()
  1333. {
  1334. if (!$this->translation) { new fSQLTranslation($this); }
  1335. return $this->translation;
  1336. }
  1337. /**
  1338. * Gets the database type
  1339. *
  1340. * @return string The database type: `'mssql'`, `'mysql'`, `'postgresql'` or `'sqlite'`
  1341. */
  1342. public function getType()
  1343. {
  1344. return $this->type;
  1345. }
  1346. /**
  1347. * Gets the username for this database
  1348. *
  1349. * @return string The username
  1350. */
  1351. public function getUsername()
  1352. {
  1353. return $this->username;
  1354. }
  1355. /**
  1356. * Will grab the auto incremented value from the last query (if one exists)
  1357. *
  1358. * @param fResult $result The result object for the query
  1359. * @param mixed $resource Only applicable for `pdo`, `oci8` and `sqlsrv` extentions or `mysqli` prepared statements - this is either the `PDOStatement` object, `mysqli_stmt` object or the `oci8` or `sqlsrv` resource
  1360. * @return void
  1361. */
  1362. private function handleAutoIncrementedValue($result, $resource=NULL)
  1363. {
  1364. if (!preg_match('#^\s*INSERT\s+(?:INTO\s+)?(?:`|"|\[)?(["\w.]+)(?:`|"|\])?#i', $result->getSQL(), $table_match)) {
  1365. $result->setAutoIncrementedValue(NULL);
  1366. return;
  1367. }
  1368. $quoted_table = $table_match[1];
  1369. $table = str_replace('"', '', strtolower($table_match[1]));
  1370. $insert_id = NULL;
  1371. if ($this->type == 'oracle') {
  1372. if (!isset($this->schema_info['sequences'])) {
  1373. $sql = "SELECT
  1374. LOWER(OWNER) AS \"SCHEMA\",
  1375. LOWER(TABLE_NAME) AS \"TABLE\",
  1376. TRIGGER_BODY
  1377. FROM
  1378. ALL_TRIGGERS
  1379. WHERE
  1380. TRIGGERING_EVENT = 'INSERT' AND
  1381. STATUS = 'ENABLED' AND
  1382. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  1383. OWNER NOT IN (
  1384. 'SYS',
  1385. 'SYSTEM',
  1386. 'OUTLN',
  1387. 'ANONYMOUS',
  1388. 'AURORA\$ORB\$UNAUTHENTICATED',
  1389. 'AWR_STAGE',
  1390. 'CSMIG',
  1391. 'CTXSYS',
  1392. 'DBSNMP',
  1393. 'DIP',
  1394. 'DMSYS',
  1395. 'DSSYS',
  1396. 'EXFSYS',
  1397. 'FLOWS_020100',
  1398. 'FLOWS_FILES',
  1399. 'LBACSYS',
  1400. 'MDSYS',
  1401. 'ORACLE_OCM',
  1402. 'ORDPLUGINS',
  1403. 'ORDSYS',
  1404. 'PERFSTAT',
  1405. 'TRACESVR',
  1406. 'TSMSYS',
  1407. 'XDB'
  1408. )";
  1409. $this->schema_info['sequences'] = array();
  1410. foreach ($this->query($sql) as $row) {
  1411. if (preg_match('#SELECT\s+(["\w.]+).nextval\s+INTO\s+:new\.(\w+)\s+FROM\s+dual#i', $row['trigger_body'], $matches)) {
  1412. $table_name = $row['table'];
  1413. if ($row['schema'] != strtolower($this->username)) {
  1414. $table_name = $row['schema'] . '.' . $table_name;
  1415. }
  1416. $this->schema_info['sequences'][$table_name] = array('sequence' => $matches[1], 'column' => str_replace('"', '', $matches[2]));
  1417. }
  1418. }
  1419. if ($this->cache) {
  1420. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  1421. }
  1422. }
  1423. if (!isset($this->schema_info['sequences'][$table]) || preg_match('#INSERT\s+INTO\s+"?' . preg_quote($quoted_table, '#') . '"?\s+\([^\)]*?(\b|")' . preg_quote($this->schema_info['sequences'][$table]['column'], '#') . '(\b|")#i', $result->getSQL())) {
  1424. return;
  1425. }
  1426. $insert_id_sql = "SELECT " . $this->schema_info['sequences'][$table]['sequence'] . ".currval AS INSERT_ID FROM dual";
  1427. }
  1428. if ($this->type == 'postgresql') {
  1429. if (!isset($this->schema_info['sequences'])) {
  1430. $sql = "SELECT
  1431. pg_namespace.nspname AS \"schema\",
  1432. pg_class.relname AS \"table\",
  1433. pg_attribute.attname AS column
  1434. FROM
  1435. pg_attribute INNER JOIN
  1436. pg_class ON pg_attribute.attrelid = pg_class.oid INNER JOIN
  1437. pg_namespace ON pg_class.relnamespace = pg_namespace.oid INNER JOIN
  1438. pg_attrdef ON pg_class.oid = pg_attrdef.adrelid AND pg_attribute.attnum = pg_attrdef.adnum
  1439. WHERE
  1440. NOT pg_attribute.attisdropped AND
  1441. pg_attrdef.adsrc LIKE 'nextval(%'";
  1442. $this->schema_info['sequences'] = array();
  1443. foreach ($this->query($sql) as $row) {
  1444. $table_name = strtolower($row['table']);
  1445. if ($row['schema'] != 'public') {
  1446. $table_name = $row['schema'] . '.' . $table_name;
  1447. }
  1448. $this->schema_info['sequences'][$table_name] = $row['column'];
  1449. }
  1450. if ($this->cache) {
  1451. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  1452. }
  1453. }
  1454. if (!isset($this->schema_info['sequences'][$table]) || preg_match('#INSERT\s+INTO\s+"?' . preg_quote($quoted_table, '#') . '"?\s+\([^\)]*?(\b|")' . preg_quote($this->schema_info['sequences'][$table], '#') . '(\b|")#i', $result->getSQL())) {
  1455. return;
  1456. }
  1457. }
  1458. if ($this->extension == 'ibm_db2') {
  1459. $insert_id_res = db2_exec($this->connection, "SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1");
  1460. $insert_id_row = db2_fetch_assoc($insert_id_res);
  1461. $insert_id = current($insert_id_row);
  1462. db2_free_result($insert_id_res);
  1463. } elseif ($this->extension == 'mssql') {
  1464. $insert_id_res = mssql_query("SELECT @@IDENTITY AS insert_id", $this->connection);
  1465. $insert_id = mssql_result($insert_id_res, 0, 'insert_id');
  1466. mssql_free_result($insert_id_res);
  1467. } elseif ($this->extension == 'mysql') {
  1468. $insert_id = mysql_insert_id($this->connection);
  1469. } elseif ($this->extension == 'mysqli') {
  1470. if (is_object($resource)) {
  1471. $insert_id = mysqli_stmt_insert_id($resource);
  1472. } else {
  1473. $insert_id = mysqli_insert_id($this->connection);
  1474. }
  1475. } elseif ($this->extension == 'oci8') {
  1476. $oci_statement = oci_parse($this->connection, $insert_id_sql);
  1477. oci_execute($oci_statement, $this->inside_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS);
  1478. $insert_id_row = oci_fetch_array($oci_statement, OCI_ASSOC);
  1479. $insert_id = $insert_id_row['INSERT_ID'];
  1480. oci_free_statement($oci_statement);
  1481. } elseif ($this->extension == 'pgsql') {
  1482. $insert_id_res = pg_query($this->connection, "SELECT lastval()");
  1483. $insert_id_row = pg_fetch_assoc($insert_id_res);
  1484. $insert_id = array_shift($insert_id_row);
  1485. pg_free_result($insert_id_res);
  1486. } elseif ($this->extension == 'sqlite') {
  1487. $insert_id = sqlite_last_insert_rowid($this->connection);
  1488. } elseif ($this->extension == 'sqlsrv') {
  1489. $insert_id_res = sqlsrv_query($this->connection, "SELECT @@IDENTITY AS insert_id");
  1490. $insert_id_row = sqlsrv_fetch_array($insert_id_res, SQLSRV_FETCH_ASSOC);
  1491. $insert_id = $insert_id_row['insert_id'];
  1492. sqlsrv_free_stmt($insert_id_res);
  1493. } elseif ($this->extension == 'pdo') {
  1494. switch ($this->type) {
  1495. case 'db2':
  1496. $insert_id_statement = $this->connection->query("SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1");
  1497. $insert_id_row = $insert_id_statement->fetch(PDO::FETCH_ASSOC);
  1498. $insert_id = array_shift($insert_id_row);
  1499. $insert_id_statement->closeCursor();
  1500. unset($insert_id_statement);
  1501. break;
  1502. case 'mssql':
  1503. try {
  1504. $insert_id_statement = $this->connection->query("SELECT @@IDENTITY AS insert_id");
  1505. if (!$insert_id_statement) {
  1506. throw new Exception();
  1507. }
  1508. $insert_id_row = $insert_id_statement->fetch(PDO::FETCH_ASSOC);
  1509. $insert_id = array_shift($insert_id_row);
  1510. } catch (Exception $e) {
  1511. // If there was an error we don't have an insert id
  1512. }
  1513. break;
  1514. case 'oracle':
  1515. try {
  1516. $insert_id_statement = $this->connection->query($insert_id_sql);
  1517. if (!$insert_id_statement) {
  1518. throw new Exception();
  1519. }
  1520. $insert_id_row = $insert_id_statement->fetch(PDO::FETCH_ASSOC);
  1521. $insert_id = array_shift($insert_id_row);
  1522. } catch (Exception $e) {
  1523. // If there was an error we don't have an insert id
  1524. }
  1525. break;
  1526. case 'postgresql':
  1527. $insert_id_statement = $this->connection->query("SELECT lastval()");
  1528. $insert_id_row = $insert_id_statement->fetch(PDO::FETCH_ASSOC);
  1529. $insert_id = array_shift($insert_id_row);
  1530. $insert_id_statement->closeCursor();
  1531. unset($insert_id_statement);
  1532. break;
  1533. case 'mysql':
  1534. $insert_id = $this->connection->lastInsertId();
  1535. break;
  1536. case 'sqlite':
  1537. $insert_id = $this->connection->lastInsertId();
  1538. break;
  1539. }
  1540. }
  1541. $result->setAutoIncrementedValue($insert_id);
  1542. }
  1543. /**
  1544. * Handles a PHP error to extract error information for the mssql extension
  1545. *
  1546. * @param array $errors An array of error information from fCore::stopErrorCapture()
  1547. * @return void
  1548. */
  1549. private function handleErrors($errors)
  1550. {
  1551. if ($this->extension != 'mssql') {
  1552. return;
  1553. }
  1554. foreach ($errors as $error) {
  1555. if (substr($error['string'], 0, 14) == 'mssql_query():') {
  1556. if ($this->error) {
  1557. $this->error .= " ";
  1558. }
  1559. $this->error .= preg_replace('#^mssql_query\(\): ([^:]+: )?#', '', $error['string']);
  1560. }
  1561. }
  1562. }
  1563. /**
  1564. * Makes sure each database and extension handles BEGIN, COMMIT and ROLLBACK
  1565. *
  1566. * @param string &$sql The SQL to check for a transaction query
  1567. * @param string $result_class The type of result object to create
  1568. * @return mixed `FALSE` if normal processing should continue, otherwise an object of the type $result_class
  1569. */
  1570. private function handleTransactionQueries(&$sql, $result_class)
  1571. {
  1572. // SQL Server supports transactions, but starts then with BEGIN TRANSACTION
  1573. if ($this->type == 'mssql' && preg_match('#^\s*(begin|start(\s+transaction)?)\s*#i', $sql)) {
  1574. $sql = 'BEGIN TRANSACTION';
  1575. }
  1576. $begin = FALSE;
  1577. $commit = FALSE;
  1578. $rollback = FALSE;
  1579. // Track transactions since most databases don't support nesting
  1580. if (preg_match('#^\s*(begin|start)(\s+(transaction|work))?\s*$#iD', $sql)) {
  1581. if ($this->inside_transaction) {
  1582. throw new fProgrammerException('A transaction is already in progress');
  1583. }
  1584. $this->inside_transaction = TRUE;
  1585. $begin = TRUE;
  1586. } elseif (preg_match('#^\s*(commit)(\s+(transaction|work))?\s*$#iD', $sql)) {
  1587. if (!$this->inside_transaction) {
  1588. throw new fProgrammerException('There is no transaction in progress');
  1589. }
  1590. $this->inside_transaction = FALSE;
  1591. $commit = TRUE;
  1592. } elseif (preg_match('#^\s*(rollback)(\s+(transaction|work))?\s*$#iD', $sql)) {
  1593. if (!$this->inside_transaction) {
  1594. throw new fProgrammerException('There is no transaction in progress');
  1595. }
  1596. $this->inside_transaction = FALSE;
  1597. $rollback = TRUE;
  1598. }
  1599. if (!$begin && !$commit && !$rollback) {
  1600. return FALSE;
  1601. }
  1602. // The PDO, OCI8 and SQLSRV extensions require special handling through methods and functions
  1603. $is_pdo = $this->extension == 'pdo';
  1604. $is_oci = $this->extension == 'oci8';
  1605. $is_sqlsrv = $this->extension == 'sqlsrv';
  1606. $is_ibm_db2 = $this->extension == 'ibm_db2';
  1607. if (!$is_pdo && !$is_oci && !$is_sqlsrv && !$is_ibm_db2) {
  1608. return FALSE;
  1609. }
  1610. $this->statement = $sql;
  1611. // PDO seems to act weird if you try to start transactions through a normal query call
  1612. if ($is_pdo) {
  1613. try {
  1614. $is_mssql = $this->type == 'mssql' && substr($this->database, 0, 4) != 'dsn:';
  1615. $is_oracle = $this->type == 'oracle' && substr($this->database, 0, 4) != 'dsn:';
  1616. if ($begin) {
  1617. // The SQL Server PDO object hasn't implemented transactions
  1618. if ($is_mssql) {
  1619. $this->connection->exec('BEGIN TRANSACTION');
  1620. } elseif ($is_oracle) {
  1621. $this->connection->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
  1622. } else {
  1623. $this->connection->beginTransaction();
  1624. }
  1625. } elseif ($commit) {
  1626. if ($is_mssql) {
  1627. $this->connection->exec('COMMIT');
  1628. } elseif ($is_oracle) {
  1629. $this->connection->exec('COMMIT');
  1630. $this->connection->setAttribute(PDO::ATTR_AUTOCOMMIT, TRUE);
  1631. } else {
  1632. $this->connection->commit();
  1633. }
  1634. } elseif ($rollback) {
  1635. if ($is_mssql) {
  1636. $this->connection->exec('ROLLBACK');
  1637. } elseif ($is_oracle) {
  1638. $this->connection->exec('ROLLBACK');
  1639. $this->connection->setAttribute(PDO::ATTR_AUTOCOMMIT, TRUE);
  1640. } else {
  1641. $this->connection->rollBack();
  1642. }
  1643. }
  1644. } catch (Exception $e) {
  1645. $db_type_map = array(
  1646. 'db2' => 'DB2',
  1647. 'mssql' => 'MSSQL',
  1648. 'mysql' => 'MySQL',
  1649. 'oracle' => 'Oracle',
  1650. 'postgresql' => 'PostgreSQL',
  1651. 'sqlite' => 'SQLite'
  1652. );
  1653. throw new fSQLException(
  1654. '%1$s error (%2$s) in %3$s',
  1655. $db_type_map[$this->type],
  1656. $e->getMessage(),
  1657. $sql
  1658. );
  1659. }
  1660. } elseif ($is_oci) {
  1661. if ($commit) {
  1662. oci_commit($this->connection);
  1663. } elseif ($rollback) {
  1664. oci_rollback($this->connection);
  1665. }
  1666. } elseif ($is_sqlsrv) {
  1667. if ($begin) {
  1668. sqlsrv_begin_transaction($this->connection);
  1669. } elseif ($commit) {
  1670. sqlsrv_commit($this->connection);
  1671. } elseif ($rollback) {
  1672. sqlsrv_rollback($this->connection);
  1673. }
  1674. } elseif ($is_ibm_db2) {
  1675. if ($begin) {
  1676. db2_autocommit($this->connection, FALSE);
  1677. } elseif ($commit) {
  1678. db2_commit($this->connection);
  1679. db2_autocommit($this->connection, TRUE);
  1680. } elseif ($rollback) {
  1681. db2_rollback($this->connection);
  1682. db2_autocommit($this->connection, TRUE);
  1683. }
  1684. }
  1685. if ($result_class) {
  1686. $result = new $result_class($this);
  1687. $result->setSQL($sql);
  1688. $result->setResult(TRUE);
  1689. return $result;
  1690. }
  1691. return TRUE;
  1692. }
  1693. /**
  1694. * Injects an fSQLTranslation object to handle translation
  1695. *
  1696. * @internal
  1697. *
  1698. * @param fSQLTranslation $sql_translation The SQL translation object
  1699. * @return void
  1700. */
  1701. public function inject($sql_translation)
  1702. {
  1703. $this->translation = $sql_translation;
  1704. }
  1705. /**
  1706. * Will indicate if a transaction is currently in progress
  1707. *
  1708. * @return boolean If a transaction has been started and not yet rolled back or committed
  1709. */
  1710. public function isInsideTransaction()
  1711. {
  1712. return $this->inside_transaction;
  1713. }
  1714. /**
  1715. * Creates a unique cache prefix to help prevent cache conflicts
  1716. *
  1717. * @return string The cache prefix to use
  1718. */
  1719. private function makeCachePrefix()
  1720. {
  1721. if (!$this->cache_prefix) {
  1722. $prefix = 'fDatabase::' . $this->type . '::';
  1723. if ($this->host) {
  1724. $prefix .= $this->host . '::';
  1725. }
  1726. if ($this->port) {
  1727. $prefix .= $this->port . '::';
  1728. }
  1729. $prefix .= $this->database . '::';
  1730. if ($this->username) {
  1731. $prefix .= $this->username . '::';
  1732. }
  1733. $this->cache_prefix = $prefix;
  1734. }
  1735. return $this->cache_prefix;
  1736. }
  1737. /**
  1738. * Executes a SQL statement
  1739. *
  1740. * @param string|fStatement $statement The statement to perform
  1741. * @param array $params The parameters for prepared statements
  1742. * @return void
  1743. */
  1744. private function perform($statement, $params)
  1745. {
  1746. fCore::startErrorCapture();
  1747. $extra = NULL;
  1748. if (is_object($statement)) {
  1749. $result = $statement->execute($params, $extra, $statement != $this->statement);
  1750. } elseif ($this->extension == 'ibm_db2') {
  1751. $result = db2_exec($this->connection, $statement, array('cursor' => DB2_FORWARD_ONLY));
  1752. } elseif ($this->extension == 'mssql') {
  1753. $result = mssql_query($statement, $this->connection);
  1754. } elseif ($this->extension == 'mysql') {
  1755. $result = mysql_unbuffered_query($statement, $this->connection);
  1756. } elseif ($this->extension == 'mysqli') {
  1757. $result = mysqli_query($this->connection, $statement, MYSQLI_USE_RESULT);
  1758. } elseif ($this->extension == 'oci8') {
  1759. $extra = oci_parse($this->connection, $statement);
  1760. $result = oci_execute($extra, $this->inside_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS);
  1761. } elseif ($this->extension == 'pgsql') {
  1762. $result = pg_query($this->connection, $statement);
  1763. } elseif ($this->extension == 'sqlite') {
  1764. $result = sqlite_exec($this->connection, $statement, $extra);
  1765. } elseif ($this->extension == 'sqlsrv') {
  1766. $result = sqlsrv_query($this->connection, $statement);
  1767. } elseif ($this->extension == 'pdo') {
  1768. if ($this->type == 'mssql' && !fCore::checkOS('windows')) {
  1769. $result = $this->connection->query($statement);
  1770. if ($result instanceof PDOStatement) {
  1771. $result->closeCursor();
  1772. }
  1773. } else {
  1774. $result = $this->connection->exec($statement);
  1775. }
  1776. }
  1777. $this->statement = $statement;
  1778. $this->handleErrors(fCore::stopErrorCapture());
  1779. if ($result === FALSE) {
  1780. $this->checkForError($result, $extra, is_object($statement) ? $statement->getSQL() : $statement);
  1781. } elseif (!is_bool($result) && $result !== NULL) {
  1782. if ($this->extension == 'ibm_db2') {
  1783. db2_free_result($result);
  1784. } elseif ($this->extension == 'mssql') {
  1785. mssql_free_result($result);
  1786. } elseif ($this->extension == 'mysql') {
  1787. mysql_free_result($result);
  1788. } elseif ($this->extension == 'mysqli') {
  1789. mysqli_free_result($result);
  1790. } elseif ($this->extension == 'oci8') {
  1791. oci_free_statement($oci_statement);
  1792. } elseif ($this->extension == 'pgsql') {
  1793. pg_free_result($result);
  1794. } elseif ($this->extension == 'sqlsrv') {
  1795. sqlsrv_free_stmt($result);
  1796. }
  1797. }
  1798. }
  1799. /**
  1800. * Executes an SQL query
  1801. *
  1802. * @param string|fStatement $statement The statement to perform
  1803. * @param fResult $result The result object for the query
  1804. * @param array $params The parameters for prepared statements
  1805. * @return void
  1806. */
  1807. private function performQuery($statement, $result, $params)
  1808. {
  1809. fCore::startErrorCapture();
  1810. $extra = NULL;
  1811. if (is_object($statement)) {
  1812. $statement->executeQuery($result, $params, $extra, $statement != $this->statement);
  1813. } elseif ($this->extension == 'ibm_db2') {
  1814. $extra = db2_exec($this->connection, $statement, array('cursor' => DB2_FORWARD_ONLY));
  1815. if (is_resource($extra)) {
  1816. $rows = array();
  1817. while ($row = db2_fetch_assoc($extra)) {
  1818. $rows[] = $row;
  1819. }
  1820. $result->setResult($rows);
  1821. unset($rows);
  1822. } else {
  1823. $result->setResult($extra);
  1824. }
  1825. } elseif ($this->extension == 'mssql') {
  1826. $result->setResult(mssql_query($result->getSQL(), $this->connection));
  1827. } elseif ($this->extension == 'mysql') {
  1828. $result->setResult(mysql_query($result->getSQL(), $this->connection));
  1829. } elseif ($this->extension == 'mysqli') {
  1830. $result->setResult(mysqli_query($this->connection, $result->getSQL()));
  1831. } elseif ($this->extension == 'oci8') {
  1832. $extra = oci_parse($this->connection, $result->getSQL());
  1833. if (oci_execute($extra, $this->inside_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS)) {
  1834. oci_fetch_all($extra, $rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
  1835. $result->setResult($rows);
  1836. unset($rows);
  1837. } else {
  1838. $result->setResult(FALSE);
  1839. }
  1840. } elseif ($this->extension == 'pgsql') {
  1841. $result->setResult(pg_query($this->connection, $result->getSQL()));
  1842. } elseif ($this->extension == 'sqlite') {
  1843. $result->setResult(sqlite_query($this->connection, $result->getSQL(), SQLITE_ASSOC, $extra));
  1844. } elseif ($this->extension == 'sqlsrv') {
  1845. $extra = sqlsrv_query($this->connection, $result->getSQL());
  1846. if (is_resource($extra)) {
  1847. $rows = array();
  1848. while ($row = sqlsrv_fetch_array($extra, SQLSRV_FETCH_ASSOC)) {
  1849. $rows[] = $row;
  1850. }
  1851. $result->setResult($rows);
  1852. unset($rows);
  1853. } else {
  1854. $result->setResult($extra);
  1855. }
  1856. } elseif ($this->extension == 'pdo') {
  1857. if (preg_match('#^\s*CREATE(\s+OR\s+REPLACE)?\s+TRIGGER#i', $result->getSQL())) {
  1858. $this->connection->exec($result->getSQL());
  1859. $extra = FALSE;
  1860. $returned_rows = array();
  1861. } else {
  1862. $extra = $this->connection->query($result->getSQL());
  1863. if (is_object($extra)) {
  1864. // This fixes a segfault issue with blobs and fetchAll() for pdo_ibm
  1865. if ($this->type == 'db2') {
  1866. $returned_rows = array();
  1867. $scanned_for_blobs = FALSE;
  1868. $blob_columns = array();
  1869. while (($row = $extra->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
  1870. if (!$scanned_for_blobs) {
  1871. foreach ($row as $key => $value) {
  1872. if (is_resource($value)) {
  1873. $blob_columns[] = $key;
  1874. }
  1875. }
  1876. }
  1877. foreach ($blob_columns as $blob_column) {
  1878. $row[$blob_column] = stream_get_contents($row[$blob_column]);
  1879. }
  1880. $returned_rows[] = $row;
  1881. }
  1882. } else {
  1883. $returned_rows = $extra->fetchAll(PDO::FETCH_ASSOC);
  1884. }
  1885. } else {
  1886. $returned_rows = $extra;
  1887. }
  1888. // The pdo_pgsql driver likes to return empty rows equal to the number of affected rows for insert and deletes
  1889. if ($this->type == 'postgresql' && $returned_rows && $returned_rows[0] == array()) {
  1890. $returned_rows = array();
  1891. }
  1892. }
  1893. $result->setResult($returned_rows);
  1894. }
  1895. $this->statement = $statement;
  1896. $this->handleErrors(fCore::stopErrorCapture());
  1897. $this->checkForError($result, $extra);
  1898. if ($this->extension == 'ibm_db2') {
  1899. $this->setAffectedRows($result, $extra);
  1900. if ($extra && !is_object($statement)) {
  1901. db2_free_result($extra);
  1902. }
  1903. } elseif ($this->extension == 'pdo') {
  1904. $this->setAffectedRows($result, $extra);
  1905. if ($extra && !is_object($statement)) {
  1906. $extra->closeCursor();
  1907. }
  1908. } elseif ($this->extension == 'oci8') {
  1909. $this->setAffectedRows($result, $extra);
  1910. if ($extra && !is_object($statement)) {
  1911. oci_free_statement($extra);
  1912. }
  1913. } elseif ($this->extension == 'sqlsrv') {
  1914. $this->setAffectedRows($result, $extra);
  1915. if ($extra && !is_object($statement)) {
  1916. sqlsrv_free_stmt($extra);
  1917. }
  1918. } else {
  1919. $this->setAffectedRows($result, $extra);
  1920. }
  1921. $this->setReturnedRows($result);
  1922. $this->handleAutoIncrementedValue($result, $extra);
  1923. }
  1924. /**
  1925. * Executes an unbuffered SQL query
  1926. *
  1927. * @param string|fStatement $statement The statement to perform
  1928. * @param fUnbufferedResult $result The result object for the query
  1929. * @param array $params The parameters for prepared statements
  1930. * @return void
  1931. */
  1932. private function performUnbufferedQuery($statement, $result, $params)
  1933. {
  1934. fCore::startErrorCapture();
  1935. $extra = NULL;
  1936. if (is_object($statement)) {
  1937. $statement->executeUnbufferedQuery($result, $params, $extra, $statement != $this->statement);
  1938. } elseif ($this->extension == 'ibm_db2') {
  1939. $result->setResult(db2_exec($this->connection, $statement, array('cursor' => DB2_FORWARD_ONLY)));
  1940. } elseif ($this->extension == 'mssql') {
  1941. $result->setResult(mssql_query($result->getSQL(), $this->connection, 20));
  1942. } elseif ($this->extension == 'mysql') {
  1943. $result->setResult(mysql_unbuffered_query($result->getSQL(), $this->connection));
  1944. } elseif ($this->extension == 'mysqli') {
  1945. $result->setResult(mysqli_query($this->connection, $result->getSQL(), MYSQLI_USE_RESULT));
  1946. } elseif ($this->extension == 'oci8') {
  1947. $extra = oci_parse($this->connection, $result->getSQL());
  1948. if (oci_execute($extra, $this->inside_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS)) {
  1949. $result->setResult($extra);
  1950. } else {
  1951. $result->setResult(FALSE);
  1952. }
  1953. } elseif ($this->extension == 'pgsql') {
  1954. $result->setResult(pg_query($this->connection, $result->getSQL()));
  1955. } elseif ($this->extension == 'sqlite') {
  1956. $result->setResult(sqlite_unbuffered_query($this->connection, $result->getSQL(), SQLITE_ASSOC, $extra));
  1957. } elseif ($this->extension == 'sqlsrv') {
  1958. $result->setResult(sqlsrv_query($this->connection, $result->getSQL()));
  1959. } elseif ($this->extension == 'pdo') {
  1960. $result->setResult($this->connection->query($result->getSQL()));
  1961. }
  1962. $this->statement = $statement;
  1963. $this->handleErrors(fCore::stopErrorCapture());
  1964. $this->checkForError($result, $extra);
  1965. }
  1966. /**
  1967. * Prepares a single fStatement object to execute prepared statements
  1968. *
  1969. * Identifier placeholders (%r) are not supported with prepared statements.
  1970. * In addition, multiple values can not be escaped by a placeholder - only
  1971. * a single value can be provided.
  1972. *
  1973. * @param string $sql The SQL to prepare
  1974. * @return fStatement A prepared statement object that can be passed to ::query(), ::unbufferedQuery() or ::execute()
  1975. */
  1976. public function prepare($sql)
  1977. {
  1978. return $this->prepareStatement($sql);
  1979. }
  1980. /**
  1981. * Prepares a single fStatement object to execute prepared statements
  1982. *
  1983. * Identifier placeholders (%r) are not supported with prepared statements.
  1984. * In addition, multiple values can not be escaped by a placeholder - only
  1985. * a single value can be provided.
  1986. *
  1987. * @param string $sql The SQL to prepare
  1988. * @param boolean $translate If the SQL should be translated using fSQLTranslation
  1989. * @return fStatement A prepare statement object that can be passed to ::query(), ::unbufferedQuery() or ::execute()
  1990. */
  1991. private function prepareStatement($sql, $translate=FALSE)
  1992. {
  1993. // Ensure an SQL statement was passed
  1994. if (empty($sql)) {
  1995. throw new fProgrammerException('No SQL statement passed');
  1996. }
  1997. // This is just to keep the callback method signature consistent
  1998. $values = array();
  1999. if ($this->hook_callbacks['unmodified']) {
  2000. foreach ($this->hook_callbacks['unmodified'] as $callback) {
  2001. $params = array(
  2002. $this,
  2003. &$sql,
  2004. &$values
  2005. );
  2006. call_user_func_array($callback, $params);
  2007. }
  2008. }
  2009. // Fix \' in MySQL and PostgreSQL
  2010. if(($this->type == 'mysql' || $this->type == 'postgresql') && strpos($sql, '\\') !== FALSE) {
  2011. $sql = preg_replace("#(?<!\\\\)((\\\\{2})*)\\\\'#", "\\1''", $sql);
  2012. }
  2013. // Separate the SQL from quoted values
  2014. $parts = $this->splitSQL($sql);
  2015. $query = '';
  2016. $strings = array();
  2017. foreach ($parts as $part) {
  2018. // We split out all strings except for empty ones because Oracle
  2019. // has to translate empty strings to NULL
  2020. if ($part[0] == "'" && $part != "''") {
  2021. $query .= ':string_' . sizeof($strings);
  2022. $strings[] = $part;
  2023. } else {
  2024. $query .= $part;
  2025. }
  2026. }
  2027. if ($this->hook_callbacks['extracted']) {
  2028. foreach ($this->hook_callbacks['extracted'] as $callback) {
  2029. $params = array(
  2030. $this,
  2031. &$query,
  2032. &$values,
  2033. &$strings
  2034. );
  2035. call_user_func_array($callback, $params);
  2036. }
  2037. }
  2038. $pieces = preg_split('#(%[lbdfistp])\b#', $query, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  2039. $placeholders = array();
  2040. $new_query = '';
  2041. foreach ($pieces as $piece) {
  2042. if (strlen($piece) == 2 && $piece[0] == '%') {
  2043. $placeholders[] = $piece;
  2044. $new_query .= '%s';
  2045. } else {
  2046. $new_query .= $piece;
  2047. }
  2048. }
  2049. $query = $new_query;
  2050. $untranslated_sql = NULL;
  2051. if ($translate) {
  2052. list($query) = $t->gethisSQLTranslation()->translate(array($query));
  2053. $untranslated_sql = $sql;
  2054. }
  2055. // Unescape literal semicolons in the queries
  2056. $query = preg_replace('#(?<!\\\\)\\\\;#', ';', $query);
  2057. // Put the strings back into the SQL
  2058. foreach ($strings as $index => $string) {
  2059. $string = strtr($string, array('\\' => '\\\\', '$' => '\\$'));
  2060. $query = preg_replace('#:string_' . $index . '\b#', $string, $query, 1);
  2061. }
  2062. return new fStatement($this, $query, $placeholders, $untranslated_sql);
  2063. }
  2064. /**
  2065. * Prepares the SQL by escaping values, spliting queries, cleaning escaped semicolons, fixing backslashed single quotes and translating
  2066. *
  2067. * @param string $sql The SQL to prepare
  2068. * @param array $values Literal values to escape into the SQL
  2069. * @param boolean $translate If the SQL should be translated
  2070. * @return array The split out SQL queries, queries that have been translated will have a string key of a number, `:` and the original SQL, non-translated SQL will have a numeric key
  2071. */
  2072. private function prepareSQL($sql, $values, $translate)
  2073. {
  2074. $this->connectToDatabase();
  2075. // Ensure an SQL statement was passed
  2076. if (empty($sql)) {
  2077. throw new fProgrammerException('No SQL statement passed');
  2078. }
  2079. if ($this->hook_callbacks['unmodified']) {
  2080. foreach ($this->hook_callbacks['unmodified'] as $callback) {
  2081. $params = array(
  2082. $this,
  2083. &$sql,
  2084. &$values
  2085. );
  2086. call_user_func_array($callback, $params);
  2087. }
  2088. }
  2089. // Fix \' in MySQL and PostgreSQL
  2090. if(($this->type == 'mysql' || $this->type == 'postgresql') && strpos($sql, '\\') !== FALSE) {
  2091. $sql = preg_replace("#(?<!\\\\)((\\\\{2})*)\\\\'#", "\\1''", $sql);
  2092. }
  2093. $strings = array(array());
  2094. $queries = array('');
  2095. $number = 0;
  2096. // Separate the SQL from quoted values
  2097. $parts = $this->splitSQL($sql);
  2098. foreach ($parts as $part) {
  2099. // We split out all strings except for empty ones because Oracle
  2100. // has to translate empty strings to NULL
  2101. if ($part[0] == "'" && $part != "''") {
  2102. $queries[$number] .= ':string_' . sizeof($strings[$number]);
  2103. $strings[$number][] = $part;
  2104. } else {
  2105. $split_queries = preg_split('#(?<!\\\\);#', $part);
  2106. $queries[$number] .= $split_queries[0];
  2107. for ($i=1; $i < sizeof($split_queries); $i++) {
  2108. $queries[$number] = trim($queries[$number]);
  2109. $number++;
  2110. $strings[$number] = array();
  2111. $queries[$number] = $split_queries[$i];
  2112. }
  2113. }
  2114. }
  2115. if (!trim($queries[$number])) {
  2116. unset($queries[$number]);
  2117. unset($strings[$number]);
  2118. } else {
  2119. $queries[$number] = trim($queries[$number]);
  2120. }
  2121. // If the values were passed as a single array, this handles that
  2122. $placeholders = preg_match_all('#%[lbdfristp]\b#', join(';', $queries), $trash);
  2123. if (count($values) == 1 && is_array($values[0]) && count($values[0]) == $placeholders) {
  2124. $values = array_shift($values);
  2125. }
  2126. // Loop through the queries, chunk the values and add blank strings back in
  2127. $chunked_values = array();
  2128. $value_number = 0;
  2129. foreach (array_keys($queries) as $number) {
  2130. $pieces = preg_split('#(%[lbdfristp])\b#', $queries[$number], -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  2131. $placeholders = 0;
  2132. $new_sql = '';
  2133. $chunked_values[$number] = array();
  2134. foreach ($pieces as $piece) {
  2135. // A placeholder
  2136. if (strlen($piece) == 2 && $piece[0] == '%') {
  2137. $value = $values[$value_number];
  2138. // Here we put blank strings back into the SQL so they can be translated for Oracle
  2139. if ($piece == '%s' && $value !== NULL && ((string) $value) == '') {
  2140. $new_sql .= "''";
  2141. $value_number++;
  2142. } elseif ($piece == '%r') {
  2143. if (is_array($value)) {
  2144. $new_sql .= join(', ', array_map($this->escapeIdentifier, $value));
  2145. } else {
  2146. $new_sql .= $this->escapeIdentifier($value);
  2147. }
  2148. $value_number++;
  2149. // Other placeholder/value combos just get added
  2150. } else {
  2151. $placeholders++;
  2152. $value_number++;
  2153. $new_sql .= $piece;
  2154. $chunked_values[$number][] = $value;
  2155. }
  2156. // A piece of SQL
  2157. } else {
  2158. $new_sql .= $piece;
  2159. }
  2160. }
  2161. $queries[$number] = $new_sql;
  2162. }
  2163. if ($this->hook_callbacks['extracted']) {
  2164. foreach (array_keys($queries) as $number) {
  2165. foreach ($this->hook_callbacks['extracted'] as $callback) {
  2166. if (!isset($chunked_values[$number])) {
  2167. $chunked_values[$number] = array();
  2168. }
  2169. $params = array(
  2170. $this,
  2171. &$queries[$number],
  2172. &$chunked_values[$number],
  2173. &$strings[$number]
  2174. );
  2175. call_user_func_array($callback, $params);
  2176. }
  2177. }
  2178. }
  2179. // Translate the SQL queries
  2180. if ($translate) {
  2181. $queries = $this->getSQLTranslation()->translate($queries);
  2182. }
  2183. $output = array();
  2184. foreach (array_keys($queries) as $key) {
  2185. $query = $queries[$key];
  2186. $parts = explode(':', $key, 2);
  2187. $number = $parts[0];
  2188. // Escape the values into the SQL
  2189. if (!empty($chunked_values[$number])) {
  2190. $query = $this->escapeSQL($query, $chunked_values[$number]);
  2191. }
  2192. // Unescape literal semicolons in the queries
  2193. $query = preg_replace('#(?<!\\\\)\\\\;#', ';', $query);
  2194. // Put the strings back into the SQL
  2195. if (isset($strings[$number])) {
  2196. foreach ($strings[$number] as $index => $string) {
  2197. $string = strtr($string, array('\\' => '\\\\', '$' => '\\$'));
  2198. $query = preg_replace('#:string_' . $index . '\b#', $string, $query, 1);
  2199. }
  2200. }
  2201. $output[$key] = $query;
  2202. }
  2203. return $output;
  2204. }
  2205. /**
  2206. * Executes one or more SQL queries and returns the result(s)
  2207. *
  2208. * @param string|fStatement $statement One or more SQL statements in a string or a single fStatement prepared statement
  2209. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  2210. * @param mixed ...
  2211. * @return fResult|array The fResult object(s) for the query
  2212. */
  2213. public function query($statement)
  2214. {
  2215. $args = func_get_args();
  2216. $params = array_slice($args, 1);
  2217. if (is_object($statement)) {
  2218. return $this->run($statement, 'fResult', $params);
  2219. }
  2220. $queries = $this->prepareSQL($statement, $params, FALSE);
  2221. $output = array();
  2222. foreach ($queries as $query) {
  2223. $output[] = $this->run($query, 'fResult');
  2224. }
  2225. return sizeof($output) == 1 ? $output[0] : $output;
  2226. }
  2227. /**
  2228. * Registers a callback for one of the various query hooks - multiple callbacks can be registered for each hook
  2229. *
  2230. * The following hooks are available:
  2231. * - `'unmodified'`: The original SQL passed to fDatabase, for prepared statements this is called just once before the fStatement object is created
  2232. * - `'extracted'`: The SQL after all non-empty strings have been extracted and replaced with `:string_{number}` placeholders
  2233. * - `'run'`: After the SQL has been run
  2234. *
  2235. * Methods for the `'unmodified'` hook should have the following signature:
  2236. *
  2237. * - **`$database`**: The fDatabase instance
  2238. * - **`&$sql`**: The original, unedited SQL
  2239. * - **`&$values`**: The values to be escaped into the placeholders in the SQL - this will be empty for prepared statements
  2240. *
  2241. * Methods for the `'extracted'` hook should have the following signature:
  2242. *
  2243. * - **`$database`**: The fDatabase instance
  2244. * - **`&$sql`**: The original, unedited SQL
  2245. * - **`&$values`**: The values to be escaped into the placeholders in the SQL - this will be empty for prepared statements
  2246. * - **`&$strings`** The literal strings that were extracted from the SQL
  2247. *
  2248. * The `extracted` hook is the best place to modify the SQL since there is
  2249. * no risk of breaking string literals. Please note that there may be empty
  2250. * strings (`''`) present in the SQL since some database treat those as
  2251. * `NULL`.
  2252. *
  2253. * Methods for the `'run'` hook should have the following signature:
  2254. *
  2255. * - **`$database`**: The fDatabase instance
  2256. * - **`$query`**: The (string) SQL or `array(0 => {fStatement object}, 1 => {values array})`
  2257. * - **`$query_time`**: The (float) number of seconds the query took
  2258. * - **`$result`** The fResult or fUnbufferedResult object, or `FALSE` if no result
  2259. *
  2260. * @param string $hook The hook to register for
  2261. * @param callback $callback The callback to register - see the method description for details about the method signature
  2262. * @return void
  2263. */
  2264. public function registerHookCallback($hook, $callback)
  2265. {
  2266. $valid_hooks = array(
  2267. 'unmodified',
  2268. 'extracted',
  2269. 'run'
  2270. );
  2271. if (!in_array($hook, $valid_hooks)) {
  2272. throw new fProgrammerException(
  2273. 'The hook specified, %1$s, should be one of: %2$s.',
  2274. $hook,
  2275. join(', ', $valid_hooks)
  2276. );
  2277. }
  2278. $this->hook_callbacks[$hook][] = $callback;
  2279. }
  2280. /**
  2281. * Runs a single statement and times it, removes any old unbuffered queries before starting
  2282. *
  2283. * @param string|fStatement $statement The SQL statement or prepared statement to execute
  2284. * @param string $result_type The type of result object to return, fResult or fUnbufferedResult
  2285. * @return fResult|fUnbufferedResult The result for the query
  2286. */
  2287. private function run($statement, $result_type=NULL, $params=array())
  2288. {
  2289. if ($this->unbuffered_result) {
  2290. $this->unbuffered_result->__destruct();
  2291. $this->unbuffered_result = NULL;
  2292. }
  2293. $start_time = microtime(TRUE);
  2294. if (is_object($statement)) {
  2295. $sql = $statement->getSQL();
  2296. } else {
  2297. $sql = $statement;
  2298. }
  2299. if (!$result = $this->handleTransactionQueries($sql, $result_type)) {
  2300. if ($result_type) {
  2301. $result = new $result_type($this, $this->type == 'mssql' ? $this->schema_info['character_set'] : NULL);
  2302. $result->setSQL($sql);
  2303. if ($result_type == 'fResult') {
  2304. $this->performQuery($statement, $result, $params);
  2305. } else {
  2306. $this->performUnbufferedQuery($statement, $result, $params);
  2307. }
  2308. } else {
  2309. $this->perform($statement, $params);
  2310. }
  2311. }
  2312. // Write some debugging info
  2313. $query_time = microtime(TRUE) - $start_time;
  2314. $this->query_time += $query_time;
  2315. if (fCore::getDebug($this->debug)) {
  2316. fCore::debug(
  2317. self::compose(
  2318. 'Query time was %1$s seconds for:%2$s',
  2319. $query_time,
  2320. "\n" . $sql
  2321. ),
  2322. $this->debug
  2323. );
  2324. }
  2325. if ($this->hook_callbacks['run']) {
  2326. foreach ($this->hook_callbacks['run'] as $callback) {
  2327. $callback_params = array(
  2328. $this,
  2329. is_object($statement) ? array($statement, $params) : $sql,
  2330. $query_time,
  2331. $result
  2332. );
  2333. call_user_func_array($callback, $callback_params);
  2334. }
  2335. }
  2336. if ($result_type) {
  2337. return $result;
  2338. }
  2339. }
  2340. /**
  2341. * Turns an array possibly containing objects into an array of all strings
  2342. *
  2343. * @param array $values The array of values to scalarize
  2344. * @return array The scalarized values
  2345. */
  2346. private function scalarize($values)
  2347. {
  2348. $new_values = array();
  2349. foreach ($values as $value) {
  2350. if (is_object($value) && is_callable(array($value, '__toString'))) {
  2351. $value = $value->__toString();
  2352. } elseif (is_object($value)) {
  2353. $value = (string) $value;
  2354. } elseif (is_array($value)) {
  2355. $value = $this->scalarize($value);
  2356. }
  2357. $new_values[] = $value;
  2358. }
  2359. return $new_values;
  2360. }
  2361. /**
  2362. * Sets the number of rows affected by the query
  2363. *
  2364. * @param fResult $result The result object for the query
  2365. * @param mixed $resource Only applicable for `ibm_db2`, `pdo`, `oci8` and `sqlsrv` extentions or `mysqli` prepared statements - this is either the `PDOStatement` object, `mysqli_stmt` object or the `oci8` or `sqlsrv` resource
  2366. * @return void
  2367. */
  2368. private function setAffectedRows($result, $resource=NULL)
  2369. {
  2370. if ($this->extension == 'ibm_db2') {
  2371. $insert_update_delete = preg_match('#^\s*(INSERT|UPDATE|DELETE)\b#i', $result->getSQL());
  2372. $result->setAffectedRows(!$insert_update_delete ? 0 : db2_num_rows($resource));
  2373. } elseif ($this->extension == 'mssql') {
  2374. $affected_rows_result = mssql_query('SELECT @@ROWCOUNT AS rows', $this->connection);
  2375. $result->setAffectedRows((int) mssql_result($affected_rows_result, 0, 'rows'));
  2376. } elseif ($this->extension == 'mysql') {
  2377. $result->setAffectedRows(mysql_affected_rows($this->connection));
  2378. } elseif ($this->extension == 'mysqli') {
  2379. if (is_object($resource)) {
  2380. $result->setAffectedRows($resource->affected_rows);
  2381. } else {
  2382. $result->setAffectedRows(mysqli_affected_rows($this->connection));
  2383. }
  2384. } elseif ($this->extension == 'oci8') {
  2385. $result->setAffectedRows(oci_num_rows($resource));
  2386. } elseif ($this->extension == 'pgsql') {
  2387. $result->setAffectedRows(pg_affected_rows($result->getResult()));
  2388. } elseif ($this->extension == 'sqlite') {
  2389. $result->setAffectedRows(sqlite_changes($this->connection));
  2390. } elseif ($this->extension == 'sqlsrv') {
  2391. $result->setAffectedRows(sqlsrv_rows_affected($resource));
  2392. } elseif ($this->extension == 'pdo') {
  2393. // This fixes the fact that rowCount is not reset for non INSERT/UPDATE/DELETE statements
  2394. try {
  2395. if (!$resource || !$resource->fetch()) {
  2396. throw new PDOException();
  2397. }
  2398. $result->setAffectedRows(0);
  2399. } catch (PDOException $e) {
  2400. // The SQLite PDO driver seems to return 1 when no rows are returned from a SELECT statement
  2401. if ($this->type == 'sqlite' && $this->extension == 'pdo' && preg_match('#^\s*SELECT#i', $result->getSQL())) {
  2402. $result->setAffectedRows(0);
  2403. } elseif (!$resource) {
  2404. $result->setAffectedRows(0);
  2405. } else {
  2406. $result->setAffectedRows($resource->rowCount());
  2407. }
  2408. }
  2409. }
  2410. }
  2411. /**
  2412. * Sets the number of rows returned by the query
  2413. *
  2414. * @param fResult $result The result object for the query
  2415. * @return void
  2416. */
  2417. private function setReturnedRows($result)
  2418. {
  2419. if (is_resource($result->getResult()) || is_object($result->getResult())) {
  2420. if ($this->extension == 'mssql') {
  2421. $result->setReturnedRows(mssql_num_rows($result->getResult()));
  2422. } elseif ($this->extension == 'mysql') {
  2423. $result->setReturnedRows(mysql_num_rows($result->getResult()));
  2424. } elseif ($this->extension == 'mysqli') {
  2425. $result->setReturnedRows(mysqli_num_rows($result->getResult()));
  2426. } elseif ($this->extension == 'pgsql') {
  2427. $result->setReturnedRows(pg_num_rows($result->getResult()));
  2428. } elseif ($this->extension == 'sqlite') {
  2429. $result->setReturnedRows(sqlite_num_rows($result->getResult()));
  2430. }
  2431. } elseif (is_array($result->getResult())) {
  2432. $result->setReturnedRows(sizeof($result->getResult()));
  2433. }
  2434. }
  2435. /**
  2436. * Splits SQL into pieces of SQL and quoted strings
  2437. *
  2438. * @param string $sql The SQL to split
  2439. * @return array The pieces
  2440. */
  2441. private function splitSQL($sql)
  2442. {
  2443. $parts = array();
  2444. $temp_sql = $sql;
  2445. $start_pos = 0;
  2446. $inside_string = FALSE;
  2447. do {
  2448. $pos = strpos($temp_sql, "'", $start_pos);
  2449. if ($pos !== FALSE) {
  2450. if (!$inside_string) {
  2451. $parts[] = substr($temp_sql, 0, $pos);
  2452. $temp_sql = substr($temp_sql, $pos);
  2453. $start_pos = 1;
  2454. $inside_string = TRUE;
  2455. } elseif ($pos == strlen($temp_sql)) {
  2456. $parts[] = $temp_sql;
  2457. $temp_sql = '';
  2458. $pos = FALSE;
  2459. } elseif (strlen($temp_sql) > $pos+1 && $temp_sql[$pos+1] == "'") {
  2460. $start_pos = $pos+2;
  2461. } else {
  2462. $parts[] = substr($temp_sql, 0, $pos+1);
  2463. $temp_sql = substr($temp_sql, $pos+1);
  2464. $start_pos = 0;
  2465. $inside_string = FALSE;
  2466. }
  2467. }
  2468. } while ($pos !== FALSE);
  2469. if ($temp_sql) {
  2470. $parts[] = $temp_sql;
  2471. }
  2472. return $parts;
  2473. }
  2474. /**
  2475. * Translates one or more SQL statements using fSQLTranslation and executes them without returning any results
  2476. *
  2477. * @param string $sql One or more SQL statements
  2478. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  2479. * @param mixed ...
  2480. * @return void
  2481. */
  2482. public function translatedExecute($sql)
  2483. {
  2484. $args = func_get_args();
  2485. $queries = $this->prepareSQL(
  2486. $sql,
  2487. array_slice($args, 1),
  2488. TRUE
  2489. );
  2490. $output = array();
  2491. foreach ($queries as $query) {
  2492. $this->run($query);
  2493. }
  2494. }
  2495. /**
  2496. * Translates a SQL statement and creates an fStatement object from it
  2497. *
  2498. * Identifier placeholders (%r) are not supported with prepared statements.
  2499. * In addition, multiple values can not be escaped by a placeholder - only
  2500. * a single value can be provided.
  2501. *
  2502. * @param string $sql The SQL to prepare
  2503. * @return fStatement A prepared statement object that can be passed to ::query(), ::unbufferedQuery() or ::execute()
  2504. */
  2505. public function translatedPrepare($sql)
  2506. {
  2507. return $this->prepareStatement($sql, TRUE);
  2508. }
  2509. /**
  2510. * Translates one or more SQL statements using fSQLTranslation and executes them
  2511. *
  2512. * @param string $sql One or more SQL statements
  2513. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  2514. * @param mixed ...
  2515. * @return fResult|array The fResult object(s) for the query
  2516. */
  2517. public function translatedQuery($sql)
  2518. {
  2519. $args = func_get_args();
  2520. $queries = $this->prepareSQL(
  2521. $sql,
  2522. array_slice($args, 1),
  2523. TRUE
  2524. );
  2525. $output = array();
  2526. foreach ($queries as $key => $query) {
  2527. $result = $this->run($query, 'fResult');
  2528. if (!is_numeric($key)) {
  2529. list($number, $original_query) = explode(':', $key, 2);
  2530. $result->setUntranslatedSQL($original_query);
  2531. }
  2532. $output[] = $result;
  2533. }
  2534. return sizeof($output) == 1 ? $output[0] : $output;
  2535. }
  2536. /**
  2537. * Executes a single SQL statement in unbuffered mode. This is optimal for
  2538. * large results sets since it does not load the whole result set into
  2539. * memory first. The gotcha is that only one unbuffered result can exist at
  2540. * one time. If another unbuffered query is executed, the old result will
  2541. * be deleted.
  2542. *
  2543. * @param string|fStatement $statement A single SQL statement
  2544. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  2545. * @param mixed ...
  2546. * @return fUnbufferedResult The result object for the unbuffered query
  2547. */
  2548. public function unbufferedQuery($statement)
  2549. {
  2550. $args = func_get_args();
  2551. $params = array_slice($args, 1);
  2552. if (is_object($statement)) {
  2553. $result = $this->run($statement, 'fUnbufferedResult', $params);
  2554. } else {
  2555. $queries = $this->prepareSQL($statement, $params, FALSE);
  2556. if (sizeof($queries) > 1) {
  2557. throw new fProgrammerException(
  2558. 'Only a single unbuffered query can be run at a time, however %d were passed',
  2559. sizeof($queries)
  2560. );
  2561. }
  2562. $result = $this->run($queries[0], 'fUnbufferedResult');
  2563. }
  2564. $this->unbuffered_result = $result;
  2565. return $result;
  2566. }
  2567. /**
  2568. * Translates the SQL statement using fSQLTranslation and then executes it
  2569. * in unbuffered mode. This is optimal for large results sets since it does
  2570. * not load the whole result set into memory first. The gotcha is that only
  2571. * one unbuffered result can exist at one time. If another unbuffered query
  2572. * is executed, the old result will be deleted.
  2573. *
  2574. * @param string $sql A single SQL statement
  2575. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  2576. * @param mixed ...
  2577. * @return fUnbufferedResult The result object for the unbuffered query
  2578. */
  2579. public function unbufferedTranslatedQuery($sql)
  2580. {
  2581. $args = func_get_args();
  2582. $queries = $this->prepareSQL(
  2583. $sql,
  2584. array_slice($args, 1),
  2585. TRUE
  2586. );
  2587. if (sizeof($queries) > 1) {
  2588. throw new fProgrammerException(
  2589. 'Only a single unbuffered query can be run at a time, however %d were passed',
  2590. sizeof($queries)
  2591. );
  2592. }
  2593. $query_keys = array_keys($queries);
  2594. $key = $query_keys[0];
  2595. list($number, $original_query) = explode(':', $key, 2);
  2596. $result = $this->run($queries[$key], 'fUnbufferedResult');
  2597. $result->setUntranslatedSQL($original_query);
  2598. $this->unbuffered_result = $result;
  2599. return $result;
  2600. }
  2601. /**
  2602. * Unescapes a value coming out of a database based on its data type
  2603. *
  2604. * The valid data types are:
  2605. *
  2606. * - `'blob'` (or `'%l'`)
  2607. * - `'boolean'` (or `'%b'`)
  2608. * - `'date'` (or `'%d'`)
  2609. * - `'float'` (or `'%f'`)
  2610. * - `'integer'` (or `'%i'`)
  2611. * - `'string'` (also `'%s'`, `'varchar'`, `'char'` or `'text'`)
  2612. * - `'time'` (or `'%t'`)
  2613. * - `'timestamp'` (or `'%p'`)
  2614. *
  2615. * @param string $data_type The data type being unescaped - see method description for valid values
  2616. * @param mixed $value The value or array of values to unescape
  2617. * @return mixed The unescaped value
  2618. */
  2619. public function unescape($data_type, $value)
  2620. {
  2621. if ($value === NULL) {
  2622. return $value;
  2623. }
  2624. $callback = NULL;
  2625. switch ($data_type) {
  2626. // Testing showed that strings tend to be most common,
  2627. // and moving this to the top of the switch statement
  2628. // improved performance on read-heavy pages
  2629. case 'string':
  2630. case 'varchar':
  2631. case 'char':
  2632. case 'text':
  2633. case '%s':
  2634. return $value;
  2635. case 'boolean':
  2636. case '%b':
  2637. $callback = $this->unescapeBoolean;
  2638. break;
  2639. case 'date':
  2640. case '%d':
  2641. $callback = $this->unescapeDate;
  2642. break;
  2643. case 'float':
  2644. case '%f':
  2645. return $value;
  2646. case 'integer':
  2647. case '%i':
  2648. return $value;
  2649. case 'time':
  2650. case '%t':
  2651. $callback = $this->unescapeTime;
  2652. break;
  2653. case 'timestamp':
  2654. case '%p':
  2655. $callback = $this->unescapeTimestamp;
  2656. break;
  2657. case 'blob':
  2658. case '%l':
  2659. $callback = $this->unescapeBlob;
  2660. break;
  2661. }
  2662. if ($callback) {
  2663. if (is_array($value)) {
  2664. return array_map($callback, $value);
  2665. }
  2666. return call_user_func($callback, $value);
  2667. }
  2668. throw new fProgrammerException(
  2669. 'Unknown data type, %1$s, specified. Must be one of: %2$s.',
  2670. $data_type,
  2671. 'blob, %l, boolean, %b, date, %d, float, %f, integer, %i, string, %s, time, %t, timestamp, %p'
  2672. );
  2673. }
  2674. /**
  2675. * Unescapes a blob coming out of the database
  2676. *
  2677. * @param string $value The value to unescape
  2678. * @return binary The binary data
  2679. */
  2680. private function unescapeBlob($value)
  2681. {
  2682. $this->connectToDatabase();
  2683. if ($this->extension == 'pgsql') {
  2684. return pg_unescape_bytea($value);
  2685. } elseif ($this->extension == 'pdo' && is_resource($value)) {
  2686. return stream_get_contents($value);
  2687. } elseif ($this->extension == 'sqlite') {
  2688. return pack('H*', $value);
  2689. } else {
  2690. return $value;
  2691. }
  2692. }
  2693. /**
  2694. * Unescapes a boolean coming out of the database
  2695. *
  2696. * @param string $value The value to unescape
  2697. * @return boolean The boolean
  2698. */
  2699. private function unescapeBoolean($value)
  2700. {
  2701. return ($value === 'f' || !$value) ? FALSE : TRUE;
  2702. }
  2703. /**
  2704. * Unescapes a date coming out of the database
  2705. *
  2706. * @param string $value The value to unescape
  2707. * @return string The date in YYYY-MM-DD format
  2708. */
  2709. private function unescapeDate($value)
  2710. {
  2711. if ($this->extension == 'sqlsrv' && $value instanceof DateTime) {
  2712. return $value->format('Y-m-d');
  2713. } elseif ($this->type == 'mssql') {
  2714. $value = preg_replace('#:\d{3}#', '', $value);
  2715. }
  2716. return date('Y-m-d', strtotime($value));
  2717. }
  2718. /**
  2719. * Unescapes a time coming out of the database
  2720. *
  2721. * @param string $value The value to unescape
  2722. * @return string The time in `HH:MM:SS` format
  2723. */
  2724. private function unescapeTime($value)
  2725. {
  2726. if ($this->extension == 'sqlsrv' && $value instanceof DateTime) {
  2727. return $value->format('H:i:s');
  2728. } elseif ($this->type == 'mssql') {
  2729. $value = preg_replace('#:\d{3}#', '', $value);
  2730. }
  2731. return date('H:i:s', strtotime($value));
  2732. }
  2733. /**
  2734. * Unescapes a timestamp coming out of the database
  2735. *
  2736. * @param string $value The value to unescape
  2737. * @return string The timestamp in `YYYY-MM-DD HH:MM:SS` format
  2738. */
  2739. private function unescapeTimestamp($value)
  2740. {
  2741. if ($this->extension == 'sqlsrv' && $value instanceof DateTime) {
  2742. return $value->format('Y-m-d H:i:s');
  2743. } elseif ($this->type == 'mssql') {
  2744. $value = preg_replace('#:\d{3}#', '', $value);
  2745. }
  2746. return date('Y-m-d H:i:s', strtotime($value));
  2747. }
  2748. }
  2749. /**
  2750. * Copyright (c) 2007-2010 Will Bond <will@flourishlib.com>
  2751. *
  2752. * Permission is hereby granted, free of charge, to any person obtaining a copy
  2753. * of this software and associated documentation files (the "Software"), to deal
  2754. * in the Software without restriction, including without limitation the rights
  2755. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  2756. * copies of the Software, and to permit persons to whom the Software is
  2757. * furnished to do so, subject to the following conditions:
  2758. *
  2759. * The above copyright notice and this permission notice shall be included in
  2760. * all copies or substantial portions of the Software.
  2761. *
  2762. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2763. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2764. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2765. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2766. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  2767. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  2768. * THE SOFTWARE.
  2769. */