PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/base/lib/flourishlib/fDatabase.php

https://bitbucket.org/thanhtungnguyenphp/monitos
PHP | 3242 lines | 2035 code | 420 blank | 787 comment | 515 complexity | 074f964f1e623036c3a68457a94dff53 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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-2011 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.0b37
  52. * @changes 1.0.0b37 Fixed usage of the mysqli extension to only call mysqli_set_charset() if it exists [wb, 2011-03-04]
  53. * @changes 1.0.0b36 Updated ::escape() and methods that use ::escape() to handle float values that don't contain a digit before or after the . [wb, 2011-02-01]
  54. * @changes 1.0.0b35 Updated the class to replace `LIMIT` and `OFFSET` value placeholders in the SQL with their values before translating since most databases that translate `LIMIT` statements need to move or add values together [wb, 2011-01-11]
  55. * @changes 1.0.0b34 Fixed a bug with creating translated prepared statements [wb, 2011-01-09]
  56. * @changes 1.0.0b33 Added code to explicitly set the connection encoding for the mysql and mysqli extensions since some PHP installs don't see to fully respect `SET NAMES` [wb, 2010-12-06]
  57. * @changes 1.0.0b32 Fixed handling auto-incrementing values for Oracle when the trigger was on `INSERT OR UPDATE` instead of just `INSERT` [wb, 2010-12-04]
  58. * @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]
  59. * @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]
  60. * @changes 1.0.0b29 Backwards Compatibility Break - removed ::enableSlowQueryWarnings(), added ability to replicate via ::registerHookCallback() [wb, 2010-08-10]
  61. * @changes 1.0.0b28 Backwards Compatibility Break - removed ODBC support. Added support for the `pdo_ibm` extension. [wb, 2010-07-31]
  62. * @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]
  63. * @changes 1.0.0b26 Updated the class to use new fCore functionality [wb, 2010-07-05]
  64. * @changes 1.0.0b25 Added IBM DB2 support [wb, 2010-04-13]
  65. * @changes 1.0.0b24 Fixed an auto-incrementing transaction bug with Oracle and debugging issues with all databases [wb, 2010-03-17]
  66. * @changes 1.0.0b23 Resolved another bug with capturing auto-incrementing values for PostgreSQL and Oracle [wb, 2010-03-15]
  67. * @changes 1.0.0b22 Changed ::clearCache() to also clear the cache on the fSQLTranslation [wb, 2010-03-09]
  68. * @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]
  69. * @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]
  70. * @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]
  71. * @changes 1.0.0b18 Updated the class for the new fResult and fUnbufferedResult APIs, fixed ::unescape() to not touch NULLs [wb, 2009-08-12]
  72. * @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]
  73. * @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]
  74. * @changes 1.0.0b15 Fixed a bug where auto-incremented values would not be detected when table names were quoted [wb, 2009-07-15]
  75. * @changes 1.0.0b14 Changed ::determineExtension() and ::determineCharacterSet() to be protected instead of private [wb, 2009-07-08]
  76. * @changes 1.0.0b13 Updated ::escape() to accept arrays of values for insertion into full SQL strings [wb, 2009-07-06]
  77. * @changes 1.0.0b12 Updates to ::unescape() to improve performance [wb, 2009-06-15]
  78. * @changes 1.0.0b11 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
  79. * @changes 1.0.0b10 Changed date/time/timestamp escaping from `strtotime()` to fDate/fTime/fTimestamp for better localization support [wb, 2009-06-01]
  80. * @changes 1.0.0b9 Fixed a bug with ::escape() where floats that start with a . were encoded as `NULL` [wb, 2009-05-09]
  81. * @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]
  82. * @changes 1.0.0b7 Updated for new fCore API [wb, 2009-02-16]
  83. * @changes 1.0.0b6 Fixed a bug with executing transaction queries when using the mysqli extension [wb, 2009-02-12]
  84. * @changes 1.0.0b5 Changed @ error suppression operator to `error_reporting()` calls [wb, 2009-01-26]
  85. * @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]
  86. * @changes 1.0.0b3 Removed some unnecessary error suppresion operators [wb, 2008-12-11]
  87. * @changes 1.0.0b2 Fixed a bug with PostgreSQL when using the PDO extension and executing an INSERT statement [wb, 2008-12-11]
  88. * @changes 1.0.0b The initial implementation [wb, 2007-09-25]
  89. */
  90. class fDatabase
  91. {
  92. /**
  93. * Composes text using fText if loaded
  94. *
  95. * @param string $message The message to compose
  96. * @param mixed $component A string or number to insert into the message
  97. * @param mixed ...
  98. * @return string The composed and possible translated message
  99. */
  100. static protected function compose($message)
  101. {
  102. $args = array_slice(func_get_args(), 1);
  103. if (class_exists('fText', FALSE)) {
  104. return call_user_func_array(
  105. array('fText', 'compose'),
  106. array($message, $args)
  107. );
  108. } else {
  109. return vsprintf($message, $args);
  110. }
  111. }
  112. /**
  113. * An fCache object to cache the schema info to
  114. *
  115. * @var fCache
  116. */
  117. private $cache;
  118. /**
  119. * The cache prefix to use for cache entries
  120. *
  121. * @var string
  122. */
  123. private $cache_prefix;
  124. /**
  125. * Database connection resource or PDO object
  126. *
  127. * @var mixed
  128. */
  129. private $connection;
  130. /**
  131. * The database name
  132. *
  133. * @var string
  134. */
  135. private $database;
  136. /**
  137. * If debugging is enabled
  138. *
  139. * @var boolean
  140. */
  141. private $debug;
  142. /**
  143. * A temporary error holder for the mssql extension
  144. *
  145. * @var string
  146. */
  147. private $error;
  148. /**
  149. * The extension to use for the database specified
  150. *
  151. * Options include:
  152. *
  153. * - `'ibm_db2'`
  154. * - `'mssql'`
  155. * - `'mysql'`
  156. * - `'mysqli'`
  157. * - `'oci8'`
  158. * - `'pgsql'`
  159. * - `'sqlite'`
  160. * - `'sqlsrv'`
  161. * - `'pdo'`
  162. *
  163. * @var string
  164. */
  165. protected $extension;
  166. /**
  167. * Hooks callbacks to be used for accessing and modifying queries
  168. *
  169. * This array will have the structure:
  170. *
  171. * {{{
  172. * array(
  173. * 'unmodified' => array({callbacks}),
  174. * 'extracted' => array({callbacks}),
  175. * 'run' => array({callbacks})
  176. * )
  177. * }}}
  178. *
  179. * @var array
  180. */
  181. private $hook_callbacks;
  182. /**
  183. * The host the database server is located on
  184. *
  185. * @var string
  186. */
  187. private $host;
  188. /**
  189. * If a transaction is in progress
  190. *
  191. * @var boolean
  192. */
  193. private $inside_transaction;
  194. /**
  195. * The password for the user specified
  196. *
  197. * @var string
  198. */
  199. private $password;
  200. /**
  201. * The port number for the host
  202. *
  203. * @var string
  204. */
  205. private $port;
  206. /**
  207. * The total number of seconds spent executing queries
  208. *
  209. * @var float
  210. */
  211. private $query_time;
  212. /**
  213. * A cache of database-specific code
  214. *
  215. * @var array
  216. */
  217. protected $schema_info;
  218. /**
  219. * The last executed fStatement object
  220. *
  221. * @var fStatement
  222. */
  223. private $statement;
  224. /**
  225. * The fSQLTranslation object for this database
  226. *
  227. * @var object
  228. */
  229. private $translation;
  230. /**
  231. * The database type: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, or `'sqlite'`
  232. *
  233. * @var string
  234. */
  235. private $type;
  236. /**
  237. * The unbuffered query instance
  238. *
  239. * @var fUnbufferedResult
  240. */
  241. private $unbuffered_result;
  242. /**
  243. * The user to connect to the database as
  244. *
  245. * @var string
  246. */
  247. private $username;
  248. /**
  249. * Configures the connection to a database - connection is not made until the first query is executed
  250. *
  251. * @param string $type The type of the database: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, `'sqlite'`
  252. * @param string $database Name of the database. If SQLite the path to the database file.
  253. * @param string $username Database username - not used for SQLite
  254. * @param string $password The password for the username specified - not used for SQLite
  255. * @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:'`.
  256. * @param integer $port The port to connect to, defaults to the standard port for the database type specified - not used for SQLite
  257. * @return fDatabase
  258. */
  259. public function __construct($type, $database, $username=NULL, $password=NULL, $host=NULL, $port=NULL)
  260. {
  261. $valid_types = array('db2', 'mssql', 'mysql', 'oracle', 'postgresql', 'sqlite');
  262. if (!in_array($type, $valid_types)) {
  263. throw new fProgrammerException(
  264. 'The database type specified, %1$s, is invalid. Must be one of: %2$s.',
  265. $type,
  266. join(', ', $valid_types)
  267. );
  268. }
  269. if (empty($database)) {
  270. throw new fProgrammerException('No database was specified');
  271. }
  272. if ($host === NULL) {
  273. $host = 'localhost';
  274. }
  275. $this->type = $type;
  276. $this->database = $database;
  277. $this->username = $username;
  278. $this->password = $password;
  279. $this->host = $host;
  280. $this->port = $port;
  281. $this->hook_callbacks = array(
  282. 'unmodified' => array(),
  283. 'extracted' => array(),
  284. 'run' => array()
  285. );
  286. $this->schema_info = array();
  287. $this->determineExtension();
  288. }
  289. /**
  290. * Closes the open database connection
  291. *
  292. * @internal
  293. *
  294. * @return void
  295. */
  296. public function __destruct()
  297. {
  298. if (!$this->connection) { return; }
  299. fCore::debug('Total query time: ' . $this->query_time . ' seconds', $this->debug);
  300. if ($this->extension == 'ibm_db2') {
  301. db2_close($this->connection);
  302. } elseif ($this->extension == 'mssql') {
  303. mssql_close($this->connection);
  304. } elseif ($this->extension == 'mysql') {
  305. mysql_close($this->connection);
  306. } elseif ($this->extension == 'mysqli') {
  307. mysqli_close($this->connection);
  308. } elseif ($this->extension == 'oci8') {
  309. oci_close($this->connection);
  310. } elseif ($this->extension == 'pgsql') {
  311. pg_close($this->connection);
  312. } elseif ($this->extension == 'sqlite') {
  313. sqlite_close($this->connection);
  314. } elseif ($this->extension == 'sqlsrv') {
  315. sqlsrv_close($this->connection);
  316. } elseif ($this->extension == 'pdo') {
  317. // PDO objects close their own connections when destroyed
  318. }
  319. }
  320. /**
  321. * All requests that hit this method should be requests for callbacks
  322. *
  323. * @internal
  324. *
  325. * @param string $method The method to create a callback for
  326. * @return callback The callback for the method requested
  327. */
  328. public function __get($method)
  329. {
  330. return array($this, $method);
  331. }
  332. /**
  333. * Checks to see if an SQL error occured
  334. *
  335. * @param fResult|fUnbufferedResult|boolean $result The result object for the query
  336. * @param mixed $extra_info The sqlite extension will pass a string error message, the oci8 extension will pass the statement resource
  337. * @param string $sql The SQL that was executed
  338. * @return void
  339. */
  340. private function checkForError($result, $extra_info=NULL, $sql=NULL)
  341. {
  342. if ($result === FALSE || $result->getResult() === FALSE) {
  343. if ($this->extension == 'ibm_db2') {
  344. if (is_resource($extra_info)) {
  345. $message = db2_stmt_errormsg($extra_info);
  346. } else {
  347. $message = db2_stmt_errormsg();
  348. }
  349. } elseif ($this->extension == 'mssql') {
  350. $message = $this->error;
  351. unset($this->error);
  352. } elseif ($this->extension == 'mysql') {
  353. $message = mysql_error($this->connection);
  354. } elseif ($this->extension == 'mysqli') {
  355. if (is_object($extra_info)) {
  356. $message = $extra_info->error;
  357. } else {
  358. $message = mysqli_error($this->connection);
  359. }
  360. } elseif ($this->extension == 'oci8') {
  361. $error_info = oci_error($extra_info);
  362. $message = $error_info['message'];
  363. } elseif ($this->extension == 'pgsql') {
  364. $message = pg_last_error($this->connection);
  365. } elseif ($this->extension == 'sqlite') {
  366. $message = $extra_info;
  367. } elseif ($this->extension == 'sqlsrv') {
  368. $error_info = sqlsrv_errors(SQLSRV_ERR_ALL);
  369. $message = $error_info[0]['message'];
  370. } elseif ($this->extension == 'pdo') {
  371. if ($extra_info instanceof PDOStatement) {
  372. $error_info = $extra_info->errorInfo();
  373. } else {
  374. $error_info = $this->connection->errorInfo();
  375. }
  376. if (empty($error_info[2])) {
  377. $error_info[2] = 'Unknown error - this usually indicates a bug in the PDO driver';
  378. }
  379. $message = $error_info[2];
  380. }
  381. $db_type_map = array(
  382. 'db2' => 'DB2',
  383. 'mssql' => 'MSSQL',
  384. 'mysql' => 'MySQL',
  385. 'oracle' => 'Oracle',
  386. 'postgresql' => 'PostgreSQL',
  387. 'sqlite' => 'SQLite'
  388. );
  389. throw new fSQLException(
  390. '%1$s error (%2$s) in %3$s',
  391. $db_type_map[$this->type],
  392. $message,
  393. is_object($result) ? $result->getSQL() : $sql
  394. );
  395. }
  396. }
  397. /**
  398. * Clears all of the schema info out of the object and, if set, the fCache object
  399. *
  400. * @return void
  401. */
  402. public function clearCache()
  403. {
  404. $this->schema_info = array();
  405. if ($this->cache) {
  406. $this->cache->delete($this->makeCachePrefix() . 'schema_info');
  407. }
  408. if ($this->type == 'mssql') {
  409. $this->determineCharacterSet();
  410. }
  411. if ($this->translation) {
  412. $this->translation->clearCache();
  413. }
  414. }
  415. /**
  416. * Connects to the database specified if no connection exists
  417. *
  418. * @return void
  419. */
  420. private function connectToDatabase()
  421. {
  422. // Don't try to reconnect if we are already connected
  423. if ($this->connection) { return; }
  424. // Establish a connection to the database
  425. if ($this->extension == 'pdo') {
  426. $username = $this->username;
  427. $password = $this->password;
  428. if ($this->type == 'db2') {
  429. if ($this->host === NULL && $this->port === NULL) {
  430. $dsn = 'ibm:DSN:' . $this->database;
  431. } else {
  432. $dsn = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
  433. $dsn .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
  434. $dsn .= 'PROTOCOL=TCPIP;UID=' . $username . ';PWD=' . $password . ';';
  435. $username = NULL;
  436. $password = NULL;
  437. }
  438. } elseif ($this->type == 'mssql') {
  439. $separator = (fCore::checkOS('windows')) ? ',' : ':';
  440. $port = ($this->port) ? $separator . $this->port : '';
  441. $driver = (fCore::checkOs('windows')) ? 'mssql' : 'dblib';
  442. $dsn = $driver . ':host=' . $this->host . $port . ';dbname=' . $this->database;
  443. } elseif ($this->type == 'mysql') {
  444. if (substr($this->host, 0, 5) == 'sock:') {
  445. $dsn = 'mysql:unix_socket=' . substr($this->host, 5) . ';dbname=' . $this->database;
  446. } else {
  447. $port = ($this->port) ? ';port=' . $this->port : '';
  448. $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database . $port;
  449. }
  450. } elseif ($this->type == 'oracle') {
  451. $port = ($this->port) ? ':' . $this->port : '';
  452. $dsn = 'oci:dbname=' . $this->host . $port . '/' . $this->database . ';charset=AL32UTF8';
  453. } elseif ($this->type == 'postgresql') {
  454. $dsn = 'pgsql:dbname=' . $this->database;
  455. if ($this->host && $this->host != 'sock:') {
  456. $dsn .= ' host=' . $this->host;
  457. }
  458. if ($this->port) {
  459. $dsn .= ' port=' . $this->port;
  460. }
  461. } elseif ($this->type == 'sqlite') {
  462. $dsn = 'sqlite:' . $this->database;
  463. }
  464. try {
  465. $this->connection = new PDO($dsn, $username, $password);
  466. if ($this->type == 'mysql') {
  467. $this->connection->setAttribute(PDO::MYSQL_ATTR_DIRECT_QUERY, 1);
  468. }
  469. } catch (PDOException $e) {
  470. $this->connection = FALSE;
  471. }
  472. }
  473. if ($this->extension == 'sqlite') {
  474. $this->connection = sqlite_open($this->database);
  475. }
  476. if ($this->extension == 'ibm_db2') {
  477. $username = $this->username;
  478. $password = $this->password;
  479. if ($this->host === NULL && $this->port === NULL) {
  480. $connection_string = $this->database;
  481. } else {
  482. $connection_string = 'DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
  483. $connection_string .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
  484. $connection_string .= 'PROTOCOL=TCPIP;UID=' . $this->username . ';PWD=' . $this->password . ';';
  485. $username = NULL;
  486. $password = NULL;
  487. }
  488. $options = array(
  489. 'autocommit' => DB2_AUTOCOMMIT_ON,
  490. 'DB2_ATTR_CASE' => DB2_CASE_LOWER
  491. );
  492. $this->connection = db2_connect($connection_string, $username, $password, $options);
  493. }
  494. if ($this->extension == 'mssql') {
  495. $separator = (fCore::checkOS('windows')) ? ',' : ':';
  496. $this->connection = mssql_connect(($this->port) ? $this->host . $separator . $this->port : $this->host, $this->username, $this->password, TRUE);
  497. if ($this->connection !== FALSE && mssql_select_db($this->database, $this->connection) === FALSE) {
  498. $this->connection = FALSE;
  499. }
  500. }
  501. if ($this->extension == 'mysql') {
  502. if (substr($this->host, 0, 5) == 'sock:') {
  503. $host = substr($this->host, 4);
  504. } elseif ($this->port) {
  505. $host = $this->host . ':' . $this->port;
  506. } else {
  507. $host = $this->host;
  508. }
  509. $this->connection = mysql_connect($host, $this->username, $this->password, TRUE);
  510. if ($this->connection !== FALSE && mysql_select_db($this->database, $this->connection) === FALSE) {
  511. $this->connection = FALSE;
  512. }
  513. if ($this->connection && function_exists('mysql_set_charset') && !mysql_set_charset('utf8', $this->connection)) {
  514. throw new fConnectivityException(
  515. 'There was an error setting the database connection to use UTF-8'
  516. );
  517. }
  518. }
  519. if ($this->extension == 'mysqli') {
  520. if (substr($this->host, 0, 5) == 'sock:') {
  521. $this->connection = mysqli_connect('localhost', $this->username, $this->password, $this->database, $this->port, substr($this->host, 5));
  522. } elseif ($this->port) {
  523. $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database, $this->port);
  524. } else {
  525. $this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
  526. }
  527. if ($this->connection && function_exists('mysqli_set_charset') && !mysqli_set_charset($this->connection, 'utf8')) {
  528. throw new fConnectivityException(
  529. 'There was an error setting the database connection to use UTF-8'
  530. );
  531. }
  532. }
  533. if ($this->extension == 'oci8') {
  534. $this->connection = oci_connect($this->username, $this->password, $this->host . ($this->port ? ':' . $this->port : '') . '/' . $this->database, 'AL32UTF8');
  535. }
  536. if ($this->extension == 'pgsql') {
  537. $connection_string = "dbname='" . addslashes($this->database) . "'";
  538. if ($this->host && $this->host != 'sock:') {
  539. $connection_string .= " host='" . addslashes($this->host) . "'";
  540. }
  541. if ($this->username) {
  542. $connection_string .= " user='" . addslashes($this->username) . "'";
  543. }
  544. if ($this->password) {
  545. $connection_string .= " password='" . addslashes($this->password) . "'";
  546. }
  547. if ($this->port) {
  548. $connection_string .= " port='" . $this->port . "'";
  549. }
  550. $this->connection = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW);
  551. }
  552. if ($this->extension == 'sqlsrv') {
  553. $options = array(
  554. 'Database' => $this->database,
  555. 'UID' => $this->username,
  556. 'PWD' => $this->password
  557. );
  558. $this->connection = sqlsrv_connect($this->host . ',' . $this->port, $options);
  559. }
  560. // Ensure the connection was established
  561. if ($this->connection === FALSE) {
  562. throw new fConnectivityException(
  563. 'Unable to connect to database'
  564. );
  565. }
  566. // Make MySQL act more strict and use UTF-8
  567. if ($this->type == 'mysql') {
  568. $this->execute("SET SQL_MODE = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'");
  569. $this->execute("SET NAMES 'utf8'");
  570. $this->execute("SET CHARACTER SET utf8");
  571. }
  572. // Make SQLite behave like other DBs for assoc arrays
  573. if ($this->type == 'sqlite') {
  574. $this->execute('PRAGMA short_column_names = 1');
  575. }
  576. // Fix some issues with mssql
  577. if ($this->type == 'mssql') {
  578. if (!isset($this->schema_info['character_set'])) {
  579. $this->determineCharacterSet();
  580. }
  581. $this->execute('SET TEXTSIZE 65536');
  582. $this->execute('SET QUOTED_IDENTIFIER ON');
  583. }
  584. // Make PostgreSQL use UTF-8
  585. if ($this->type == 'postgresql') {
  586. $this->execute("SET NAMES 'UTF8'");
  587. }
  588. // Oracle has different date and timestamp defaults
  589. if ($this->type == 'oracle') {
  590. $this->execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
  591. $this->execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'");
  592. $this->execute("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS TZR'");
  593. $this->execute("ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS'");
  594. $this->execute("ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR'");
  595. }
  596. }
  597. /**
  598. * Determines the character set of a SQL Server database
  599. *
  600. * @return void
  601. */
  602. protected function determineCharacterSet()
  603. {
  604. $this->schema_info['character_set'] = 'WINDOWS-1252';
  605. $this->schema_info['character_set'] = $this->query("SELECT 'WINDOWS-' + CONVERT(VARCHAR, COLLATIONPROPERTY(CONVERT(NVARCHAR, DATABASEPROPERTYEX(DB_NAME(), 'Collation')), 'CodePage')) AS charset")->fetchScalar();
  606. if ($this->cache) {
  607. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  608. }
  609. }
  610. /**
  611. * Figures out which extension to use for the database type selected
  612. *
  613. * @return void
  614. */
  615. protected function determineExtension()
  616. {
  617. switch ($this->type) {
  618. case 'db2':
  619. if (extension_loaded('ibm_db2')) {
  620. $this->extension = 'ibm_db2';
  621. } elseif (class_exists('PDO', FALSE) && in_array('ibm', PDO::getAvailableDrivers())) {
  622. $this->extension = 'pdo';
  623. } else {
  624. $type = 'DB2';
  625. $exts = 'ibm_db2, pdo_ibm';
  626. }
  627. break;
  628. case 'mssql':
  629. if (extension_loaded('sqlsrv')) {
  630. $this->extension = 'sqlsrv';
  631. } elseif (extension_loaded('mssql')) {
  632. $this->extension = 'mssql';
  633. } elseif (class_exists('PDO', FALSE) && (in_array('dblib', PDO::getAvailableDrivers()) || in_array('mssql', PDO::getAvailableDrivers()))) {
  634. $this->extension = 'pdo';
  635. } else {
  636. $type = 'MSSQL';
  637. $exts = 'mssql, sqlsrv, pdo_dblib (linux), pdo_mssql (windows)';
  638. }
  639. break;
  640. case 'mysql':
  641. if (extension_loaded('mysqli')) {
  642. $this->extension = 'mysqli';
  643. } elseif (class_exists('PDO', FALSE) && in_array('mysql', PDO::getAvailableDrivers())) {
  644. $this->extension = 'pdo';
  645. } elseif (extension_loaded('mysql')) {
  646. $this->extension = 'mysql';
  647. } else {
  648. $type = 'MySQL';
  649. $exts = 'mysql, pdo_mysql, mysqli';
  650. }
  651. break;
  652. case 'oracle':
  653. if (extension_loaded('oci8')) {
  654. $this->extension = 'oci8';
  655. } elseif (class_exists('PDO', FALSE) && in_array('oci', PDO::getAvailableDrivers())) {
  656. $this->extension = 'pdo';
  657. } else {
  658. $type = 'Oracle';
  659. $exts = 'oci8, pdo_oci';
  660. }
  661. break;
  662. case 'postgresql':
  663. if (extension_loaded('pgsql')) {
  664. $this->extension = 'pgsql';
  665. } elseif (class_exists('PDO', FALSE) && in_array('pgsql', PDO::getAvailableDrivers())) {
  666. $this->extension = 'pdo';
  667. } else {
  668. $type = 'PostgreSQL';
  669. $exts = 'pgsql, pdo_pgsql';
  670. }
  671. break;
  672. case 'sqlite':
  673. $sqlite_version = 0;
  674. if (file_exists($this->database)) {
  675. $database_handle = fopen($this->database, 'r');
  676. $database_version = fread($database_handle, 64);
  677. fclose($database_handle);
  678. if (strpos($database_version, 'SQLite format 3') !== FALSE) {
  679. $sqlite_version = 3;
  680. } elseif (strpos($database_version, '** This file contains an SQLite 2.1 database **') !== FALSE) {
  681. $sqlite_version = 2;
  682. } else {
  683. throw new fConnectivityException(
  684. 'The database specified does not appear to be a valid %1$s or %2$s database',
  685. 'SQLite v2.1',
  686. 'v3'
  687. );
  688. }
  689. }
  690. if ((!$sqlite_version || $sqlite_version == 3) && class_exists('PDO', FALSE) && in_array('sqlite', PDO::getAvailableDrivers())) {
  691. $this->extension = 'pdo';
  692. } elseif ($sqlite_version == 3 && (!class_exists('PDO', FALSE) || !in_array('sqlite', PDO::getAvailableDrivers()))) {
  693. throw new fEnvironmentException(
  694. 'The database specified is an %1$s database and the %2$s extension is not installed',
  695. 'SQLite v3',
  696. 'pdo_sqlite'
  697. );
  698. } elseif ((!$sqlite_version || $sqlite_version == 2) && extension_loaded('sqlite')) {
  699. $this->extension = 'sqlite';
  700. } elseif ($sqlite_version == 2 && !extension_loaded('sqlite')) {
  701. throw new fEnvironmentException(
  702. 'The database specified is an %1$s database and the %2$s extension is not installed',
  703. 'SQLite v2.1',
  704. 'sqlite'
  705. );
  706. } else {
  707. $type = 'SQLite';
  708. $exts = 'pdo_sqlite, sqlite';
  709. }
  710. break;
  711. }
  712. if (!$this->extension) {
  713. throw new fEnvironmentException(
  714. 'The server does not have any of the following extensions for %2$s support: %2$s',
  715. $type,
  716. $exts
  717. );
  718. }
  719. }
  720. /**
  721. * Sets the schema info to be cached to the fCache object specified
  722. *
  723. * @param fCache $cache The cache to cache to
  724. * @param string $key_token Internal use only! (this will be used in the cache key to uniquely identify the cache for this fDatabase object)
  725. * @return void
  726. */
  727. public function enableCaching($cache, $key_token=NULL)
  728. {
  729. $this->cache = $cache;
  730. if ($key_token !== NULL) {
  731. $this->cache_prefix = 'fDatabase::' . $this->type . '::' . $key_token . '::';
  732. }
  733. $this->schema_info = $this->cache->get($this->makeCachePrefix() . 'schema_info', array());
  734. }
  735. /**
  736. * Sets if debug messages should be shown
  737. *
  738. * @param boolean $flag If debugging messages should be shown
  739. * @return void
  740. */
  741. public function enableDebugging($flag)
  742. {
  743. $this->debug = (boolean) $flag;
  744. }
  745. /**
  746. * Escapes a value for insertion into SQL
  747. *
  748. * The valid data types are:
  749. *
  750. * - `'blob'`
  751. * - `'boolean'`
  752. * - `'date'`
  753. * - `'float'`
  754. * - `'identifier'`
  755. * - `'integer'`
  756. * - `'string'` (also varchar, char or text)
  757. * - `'varchar'`
  758. * - `'char'`
  759. * - `'text'`
  760. * - `'time'`
  761. * - `'timestamp'`
  762. *
  763. * In addition to being able to specify the data type, you can also pass
  764. * in an SQL statement with data type placeholders in the following form:
  765. *
  766. * - `%l` for a blob
  767. * - `%b` for a boolean
  768. * - `%d` for a date
  769. * - `%f` for a float
  770. * - `%r` for an indentifier (table or column name)
  771. * - `%i` for an integer
  772. * - `%s` for a string
  773. * - `%t` for a time
  774. * - `%p` for a timestamp
  775. *
  776. * Depending on what `$sql_or_type` and `$value` are, the output will be
  777. * slightly different. If `$sql_or_type` is a data type or a single
  778. * placeholder and `$value` is:
  779. *
  780. * - a scalar value - an escaped SQL string is returned
  781. * - an array - an array of escaped SQL strings is returned
  782. *
  783. * If `$sql_or_type` is a SQL string and `$value` is:
  784. *
  785. * - a scalar value - the escaped value is inserted into the SQL string
  786. * - an array - the escaped values are inserted into the SQL string separated by commas
  787. *
  788. * If `$sql_or_type` is a SQL string, it is also possible to pass an array
  789. * of all values as a single parameter instead of one value per parameter.
  790. * An example would look like the following:
  791. *
  792. * {{{
  793. * #!php
  794. * $db->escape(
  795. * "SELECT * FROM users WHERE status = %s AND authorization_level = %s",
  796. * array('Active', 'Admin')
  797. * );
  798. * }}}
  799. *
  800. * @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
  801. * @param mixed $value The value to escape - both single values and arrays of values are supported, see method description for details
  802. * @param mixed ...
  803. * @return mixed The escaped value/SQL or an array of the escaped values
  804. */
  805. public function escape($sql_or_type, $value)
  806. {
  807. $values = array_slice(func_get_args(), 1);
  808. if (sizeof($values) < 1) {
  809. throw new fProgrammerException(
  810. 'No value was specified to escape'
  811. );
  812. }
  813. // Convert all objects into strings
  814. $values = $this->scalarize($values);
  815. $value = array_shift($values);
  816. // Handle single value escaping
  817. $callback = NULL;
  818. switch ($sql_or_type) {
  819. case 'blob':
  820. case '%l':
  821. $callback = $this->escapeBlob;
  822. break;
  823. case 'boolean':
  824. case '%b':
  825. $callback = $this->escapeBoolean;
  826. break;
  827. case 'date':
  828. case '%d':
  829. $callback = $this->escapeDate;
  830. break;
  831. case 'float':
  832. case '%f':
  833. $callback = $this->escapeFloat;
  834. break;
  835. case 'identifier':
  836. case '%r':
  837. $callback = $this->escapeIdentifier;
  838. break;
  839. case 'integer':
  840. case '%i':
  841. $callback = $this->escapeInteger;
  842. break;
  843. case 'string':
  844. case 'varchar':
  845. case 'char':
  846. case 'text':
  847. case '%s':
  848. $callback = $this->escapeString;
  849. break;
  850. case 'time':
  851. case '%t':
  852. $callback = $this->escapeTime;
  853. break;
  854. case 'timestamp':
  855. case '%p':
  856. $callback = $this->escapeTimestamp;
  857. break;
  858. }
  859. if ($callback) {
  860. if (is_array($value)) {
  861. // If the values were passed as a single array, this handles that
  862. if (count($value) == 1 && is_array(current($value))) {
  863. $value = current($value);
  864. }
  865. return array_map($callback, $value);
  866. }
  867. return call_user_func($callback, $value);
  868. }
  869. // Fix \' in MySQL and PostgreSQL
  870. if(($this->type == 'mysql' || $this->type == 'postgresql') && strpos($sql_or_type, '\\') !== FALSE) {
  871. $sql_or_type = preg_replace("#(?<!\\\\)((\\\\{2})*)\\\\'#", "\\1''", $sql_or_type);
  872. }
  873. // Separate the SQL from quoted values
  874. $parts = $this->splitSQL($sql_or_type);
  875. $temp_sql = '';
  876. $strings = array();
  877. // Replace strings with a placeholder so they don't mess up the regex parsing
  878. foreach ($parts as $part) {
  879. if ($part[0] == "'") {
  880. $strings[] = $part;
  881. $part = ':string_' . (sizeof($strings)-1);
  882. }
  883. $temp_sql .= $part;
  884. }
  885. // If the values were passed as a single array, this handles that
  886. $placeholders = preg_match_all('#%[lbdfristp]\b#', $temp_sql, $trash);
  887. if (count($values) == 0 && is_array($value) && count($value) == $placeholders) {
  888. $values = $value;
  889. $value = array_shift($values);
  890. }
  891. array_unshift($values, $value);
  892. $sql = $this->escapeSQL($temp_sql, $values);
  893. $string_number = 0;
  894. foreach ($strings as $string) {
  895. $string = strtr($string, array('\\' => '\\\\', '$' => '\\$'));
  896. $sql = preg_replace('#:string_' . $string_number++ . '\b#', $string, $sql);
  897. }
  898. return $sql;
  899. }
  900. /**
  901. * Escapes a blob for use in SQL, includes surround quotes when appropriate
  902. *
  903. * A `NULL` value will be returned as `'NULL'`
  904. *
  905. * @param string $value The blob to escape
  906. * @return string The escaped blob
  907. */
  908. private function escapeBlob($value)
  909. {
  910. if ($value === NULL) {
  911. return 'NULL';
  912. }
  913. $this->connectToDatabase();
  914. if ($this->type == 'db2') {
  915. return "BLOB(X'" . bin2hex($value) . "')";
  916. } elseif ($this->type == 'mysql') {
  917. return "x'" . bin2hex($value) . "'";
  918. } elseif ($this->type == 'postgresql') {
  919. $output = '';
  920. for ($i=0; $i<strlen($value); $i++) {
  921. $output .= '\\\\' . str_pad(decoct(ord($value[$i])), 3, '0', STR_PAD_LEFT);
  922. }
  923. return "E'" . $output . "'";
  924. } elseif ($this->extension == 'sqlite') {
  925. return "'" . bin2hex($value) . "'";
  926. } elseif ($this->type == 'sqlite') {
  927. return "X'" . bin2hex($value) . "'";
  928. } elseif ($this->type == 'mssql') {
  929. return '0x' . bin2hex($value);
  930. } elseif ($this->type == 'oracle') {
  931. return "'" . bin2hex($value) . "'";
  932. }
  933. }
  934. /**
  935. * Escapes a boolean for use in SQL, includes surround quotes when appropriate
  936. *
  937. * A `NULL` value will be returned as `'NULL'`
  938. *
  939. * @param boolean $value The boolean to escape
  940. * @return string The database equivalent of the boolean passed
  941. */
  942. private function escapeBoolean($value)
  943. {
  944. if ($value === NULL) {
  945. return 'NULL';
  946. }
  947. if (in_array($this->type, array('postgresql', 'mysql'))) {
  948. return ($value) ? 'TRUE' : 'FALSE';
  949. } elseif (in_array($this->type, array('mssql', 'sqlite', 'db2'))) {
  950. return ($value) ? "'1'" : "'0'";
  951. } elseif ($this->type == 'oracle') {
  952. return ($value) ? '1' : '0';
  953. }
  954. }
  955. /**
  956. * Escapes a date for use in SQL, includes surrounding quotes
  957. *
  958. * A `NULL` or invalid value will be returned as `'NULL'`
  959. *
  960. * @param string $value The date to escape
  961. * @return string The escaped date
  962. */
  963. private function escapeDate($value)
  964. {
  965. if ($value === NULL) {
  966. return 'NULL';
  967. }
  968. try {
  969. $value = new fDate($value);
  970. return "'" . $value->format('Y-m-d') . "'";
  971. } catch (fValidationException $e) {
  972. return 'NULL';
  973. }
  974. }
  975. /**
  976. * Escapes a float for use in SQL
  977. *
  978. * A `NULL` value will be returned as `'NULL'`
  979. *
  980. * @param float $value The float to escape
  981. * @return string The escaped float
  982. */
  983. private function escapeFloat($value)
  984. {
  985. if ($value === NULL) {
  986. return 'NULL';
  987. }
  988. if (!strlen($value)) {
  989. return 'NULL';
  990. }
  991. if (!preg_match('#^[+\-]?([0-9]+(\.([0-9]+)?)?|(\.[0-9]+))$#D', $value)) {
  992. return 'NULL';
  993. }
  994. $value = rtrim($value, '.');
  995. $value = preg_replace('#(?<![0-9])\.#', '0.', $value);
  996. return (string) $value;
  997. }
  998. /**
  999. * Escapes an identifier for use in SQL, necessary for reserved words
  1000. *
  1001. * @param string $value The identifier to escape
  1002. * @return string The escaped identifier
  1003. */
  1004. private function escapeIdentifier($value)
  1005. {
  1006. $value = '"' . str_replace(
  1007. array('"', '.'),
  1008. array('', '"."'),
  1009. $value
  1010. ) . '"';
  1011. if (in_array($this->type, array('oracle', 'db2'))) {
  1012. $value = strtoupper($value);
  1013. }
  1014. return $value;
  1015. }
  1016. /**
  1017. * Escapes an integer for use in SQL
  1018. *
  1019. * A `NULL` or invalid value will be returned as `'NULL'`
  1020. *
  1021. * @param integer $value The integer to escape
  1022. * @return string The escaped integer
  1023. */
  1024. private function escapeInteger($value)
  1025. {
  1026. if ($value === NULL) {
  1027. return 'NULL';
  1028. }
  1029. if (!strlen($value)) {
  1030. return 'NULL';
  1031. }
  1032. if (!preg_match('#^([+\-]?[0-9]+)(\.[0-9]*)?$#D', $value, $matches)) {
  1033. return 'NULL';
  1034. }
  1035. return str_replace('+', '', $matches[1]);
  1036. }
  1037. /**
  1038. * Escapes a string for use in SQL, includes surrounding quotes
  1039. *
  1040. * A `NULL` value will be returned as `'NULL'`.
  1041. *
  1042. * @param string $value The string to escape
  1043. * @return string The escaped string
  1044. */
  1045. private function escapeString($value)
  1046. {
  1047. if ($value === NULL) {
  1048. return 'NULL';
  1049. }
  1050. $this->connectToDatabase();
  1051. if ($this->type == 'db2') {
  1052. return "'" . str_replace("'", "''", $value) . "'";
  1053. } elseif ($this->extension == 'mysql') {
  1054. return "'" . mysql_real_escape_string($value, $this->connection) . "'";
  1055. } elseif ($this->extension == 'mysqli') {
  1056. return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
  1057. } elseif ($this->extension == 'pgsql') {
  1058. return "'" . pg_escape_string($value) . "'";
  1059. } elseif ($this->extension == 'sqlite') {
  1060. return "'" . sqlite_escape_string($value) . "'";
  1061. } elseif ($this->type == 'oracle') {
  1062. return "'" . str_replace("'", "''", $value) . "'";
  1063. } elseif ($this->type == 'mssql') {
  1064. // If there are any non-ASCII characters, we need to escape
  1065. if (preg_match('#[^\x00-\x7F]#', $value)) {
  1066. preg_match_all('#.|^\z#us', $value, $characters);
  1067. $output = "";
  1068. $last_type = NULL;
  1069. foreach ($characters[0] as $character) {
  1070. if (strlen($character) > 1) {
  1071. $b = array_map('ord', str_split($character));
  1072. switch (strlen($character)) {
  1073. case 2:
  1074. $bin = substr(decbin($b[0]), 3) .
  1075. substr(decbin($b[1]), 2);
  1076. break;
  1077. case 3:
  1078. $bin = substr(decbin($b[0]), 4) .
  1079. substr(decbin($b[1]), 2) .
  1080. substr(decbin($b[2]), 2);
  1081. break;
  1082. // If it is a 4-byte character, MSSQL can't store it
  1083. // so instead store a ?
  1084. default:
  1085. $output .= '?';
  1086. continue;
  1087. }
  1088. if ($last_type == 'nchar') {
  1089. $output .= '+';
  1090. } elseif ($last_type == 'char') {
  1091. $output .= "'+";
  1092. }
  1093. $output .= "NCHAR(" . bindec($bin) . ")";
  1094. $last_type = 'nchar';
  1095. } else {
  1096. if (!$last_type) {
  1097. $output .= "'";
  1098. } elseif ($last_type == 'nchar') {
  1099. $output .= "+'";
  1100. }
  1101. $output .= $character;
  1102. // Escape single quotes
  1103. if ($character == "'") {
  1104. $output .= "'";
  1105. }
  1106. $last_type = 'char';
  1107. }
  1108. }
  1109. if ($last_type == 'char') {
  1110. $output .= "'";
  1111. } elseif (!$last_type) {
  1112. $output .= "''";
  1113. }
  1114. // ASCII text is normal
  1115. } else {
  1116. $output = "'" . str_replace("'", "''", $value) . "'";
  1117. }
  1118. # a \ before a \r\n has to be escaped with another \
  1119. return preg_replace('#(?<!\\\\)\\\\(?=\r\n)#', '\\\\\\\\', $output);
  1120. } elseif ($this->extension == 'pdo') {
  1121. return $this->connection->quote($value);
  1122. }
  1123. }
  1124. /**
  1125. * Takes a SQL string and an array of values and replaces the placeholders with the value
  1126. *
  1127. * @param string $sql The SQL string containing placeholders
  1128. * @param array $values An array of values to escape into the SQL
  1129. * @return string The SQL with the values escaped into it
  1130. */
  1131. private function escapeSQL($sql, $values)
  1132. {
  1133. $original_sql = $sql;
  1134. $pieces = preg_split('#(%[lbdfristp])\b#', $sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  1135. $sql = '';
  1136. $value = array_shift($values);
  1137. $missing_values = -1;
  1138. foreach ($pieces as $piece) {
  1139. switch ($piece) {
  1140. case '%l':
  1141. $callback = $this->escapeBlob;
  1142. break;
  1143. case '%b':
  1144. $callback = $this->escapeBoolean;
  1145. break;
  1146. case '%d':
  1147. $callback = $this->escapeDate;
  1148. break;
  1149. case '%f':
  1150. $callback = $this->escapeFloat;
  1151. break;
  1152. case '%r':
  1153. $callback = $this->escapeIdentifier;
  1154. break;
  1155. case '%i':
  1156. $callback = $this->escapeInteger;
  1157. break;
  1158. case '%s':
  1159. $callback = $this->escapeString;
  1160. break;
  1161. case '%t':
  1162. $callback = $this->escapeTime;
  1163. break;
  1164. case '%p':
  1165. $callback = $this->escapeTimestamp;
  1166. break;
  1167. default:
  1168. $sql .= $piece;
  1169. continue 2;
  1170. }
  1171. if (is_array($value)) {
  1172. $sql .= join(', ', array_map($callback, $value));
  1173. } else {
  1174. $sql .= call_user_func($callback, $value);
  1175. }
  1176. if (sizeof($values)) {
  1177. $value = array_shift($values);
  1178. } else {
  1179. $value = NULL;
  1180. $missing_values++;
  1181. }
  1182. }
  1183. if ($missing_values > 0) {
  1184. throw new fProgrammerException(
  1185. '%1$s value(s) are missing for the placeholders in: %2$s',
  1186. $missing_values,
  1187. $original_sql
  1188. );
  1189. }
  1190. if (sizeof($values)) {
  1191. throw new fProgrammerException(
  1192. '%1$s extra value(s) were passed for the placeholders in: %2$s',
  1193. sizeof($values),
  1194. $original_sql
  1195. );
  1196. }
  1197. return $sql;
  1198. }
  1199. /**
  1200. * Escapes a time for use in SQL, includes surrounding quotes
  1201. *
  1202. * A `NULL` or invalid value will be returned as `'NULL'`
  1203. *
  1204. * @param string $value The time to escape
  1205. * @return string The escaped time
  1206. */
  1207. private function escapeTime($value)
  1208. {
  1209. if ($value === NULL) {
  1210. return 'NULL';
  1211. }
  1212. try {
  1213. $value = new fTime($value);
  1214. if ($this->type == 'mssql' || $this->type == 'oracle') {
  1215. return "'" . $value->format('1970-01-01 H:i:s') . "'";
  1216. }
  1217. return "'" . $value->format('H:i:s') . "'";
  1218. } catch (fValidationException $e) {
  1219. return 'NULL';
  1220. }
  1221. }
  1222. /**
  1223. * Escapes a timestamp for use in SQL, includes surrounding quotes
  1224. *
  1225. * A `NULL` or invalid value will be returned as `'NULL'`
  1226. *
  1227. * @param string $value The timestamp to escape
  1228. * @return string The escaped timestamp
  1229. */
  1230. private function escapeTimestamp($value)
  1231. {
  1232. if ($value === NULL) {
  1233. return 'NULL';
  1234. }
  1235. try {
  1236. $value = new fTimestamp($value);
  1237. return "'" . $value->format('Y-m-d H:i:s') . "'";
  1238. } catch (fValidationException $e) {
  1239. return 'NULL';
  1240. }
  1241. }
  1242. /**
  1243. * Executes one or more SQL queries without returning any results
  1244. *
  1245. * @param string|fStatement $statement One or more SQL statements in a string or an fStatement prepared statement
  1246. * @param mixed $value The optional value(s) to place into any placeholders in the SQL - see ::escape() for details
  1247. * @param mixed ...
  1248. * @return void
  1249. */
  1250. public function execute($statement)
  1251. {
  1252. $args = func_get_args();
  1253. $params = array_slice($args, 1);
  1254. if (is_object($statement)) {
  1255. return $this->run($statement, NULL, $params);
  1256. }
  1257. $queries = $this->prepareSQL($statement, $params, FALSE);
  1258. $output = array();
  1259. foreach ($queries as $query) {
  1260. $this->run($query);
  1261. }
  1262. }
  1263. /**
  1264. * Takes in a string of SQL that contains multiple queries and returns any array of them
  1265. *
  1266. * @param string $sql The string of SQL to parse for queries
  1267. * @return array The individual SQL queries
  1268. */
  1269. private function explodeQueries($sql)
  1270. {
  1271. $sql_queries = array();
  1272. // Separate the SQL from quoted values
  1273. preg_match_all("#(?:'([^']*(?:'')*)*?')|(?:[^']+)#", $sql, $matches);
  1274. $cur_sql = '';
  1275. foreach ($matches[0] as $match) {
  1276. // This is a quoted string value, don't do anything to it
  1277. if ($match[0] == "'") {
  1278. $cur_sql .= $match;
  1279. // Handle the SQL, exploding on any ; that isn't escaped with a \
  1280. } else {
  1281. $sql_strings = preg_split('#(?<!\\\\);#', $match);
  1282. $cur_sql .= $sql_strings[0];
  1283. for ($i=1; $i < sizeof($sql_strings); $i++) {
  1284. $cur_sql = trim($cur_sql);
  1285. if ($cur_sql) {
  1286. $sql_queries[] = $cur_sql;
  1287. }
  1288. $cur_sql = $sql_strings[$i];
  1289. }
  1290. }
  1291. }
  1292. if (trim($cur_sql)) {
  1293. $sql_queries[] = $cur_sql;
  1294. }
  1295. return $sql_queries;
  1296. }
  1297. /**
  1298. * Returns the database connection resource or object
  1299. *
  1300. * @return mixed The database connection
  1301. */
  1302. public function getConnection()
  1303. {
  1304. $this->connectToDatabase();
  1305. return $this->connection;
  1306. }
  1307. /**
  1308. * Gets the name of the database currently connected to
  1309. *
  1310. * @return string The name of the database currently connected to
  1311. */
  1312. public function getDatabase()
  1313. {
  1314. return $this->database;
  1315. }
  1316. /**
  1317. * Gets the php extension being used
  1318. *
  1319. * @internal
  1320. *
  1321. * @return string The php extension used for database interaction
  1322. */
  1323. public function getExtension()
  1324. {
  1325. return $this->extension;
  1326. }
  1327. /**
  1328. * Gets the host for this database
  1329. *
  1330. * @return string The host
  1331. */
  1332. public function getHost()
  1333. {
  1334. return $this->host;
  1335. }
  1336. /**
  1337. * Gets the port for this database
  1338. *
  1339. * @return string The port
  1340. */
  1341. public function getPort()
  1342. {
  1343. return $this->port;
  1344. }
  1345. /**
  1346. * Gets the fSQLTranslation object used for translated queries
  1347. *
  1348. * @return fSQLTranslation The SQL translation object
  1349. */
  1350. public function getSQLTranslation()
  1351. {
  1352. if (!$this->translation) { new fSQLTranslation($this); }
  1353. return $this->translation;
  1354. }
  1355. /**
  1356. * Gets the database type
  1357. *
  1358. * @return string The database type: `'mssql'`, `'mysql'`, `'postgresql'` or `'sqlite'`
  1359. */
  1360. public function getType()
  1361. {
  1362. return $this->type;
  1363. }
  1364. /**
  1365. * Gets the username for this database
  1366. *
  1367. * @return string The username
  1368. */
  1369. public function getUsername()
  1370. {
  1371. return $this->username;
  1372. }
  1373. /**
  1374. * Will grab the auto incremented value from the last query (if one exists)
  1375. *
  1376. * @param fResult $result The result object for the query
  1377. * @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
  1378. * @return void
  1379. */
  1380. private function handleAutoIncrementedValue($result, $resource=NULL)
  1381. {
  1382. if (!preg_match('#^\s*INSERT\s+(?:INTO\s+)?(?:`|"|\[)?(["\w.]+)(?:`|"|\])?#i', $result->getSQL(), $table_match)) {
  1383. $result->setAutoIncrementedValue(NULL);
  1384. return;
  1385. }
  1386. $quoted_table = $table_match[1];
  1387. $table = str_replace('"', '', strtolower($table_match[1]));
  1388. $insert_id = NULL;
  1389. if ($this->type == 'oracle') {
  1390. if (!isset($this->schema_info['sequences'])) {
  1391. $sql = "SELECT
  1392. LOWER(OWNER) AS \"SCHEMA\",
  1393. LOWER(TABLE_NAME) AS \"TABLE\",
  1394. TRIGGER_BODY
  1395. FROM
  1396. ALL_TRIGGERS
  1397. WHERE
  1398. TRIGGERING_EVENT LIKE 'INSERT%' AND
  1399. STATUS = 'ENABLED' AND
  1400. TRIGGER_NAME NOT LIKE 'BIN\$%' AND
  1401. OWNER NOT IN (
  1402. 'SYS',
  1403. 'SYSTEM',
  1404. 'OUTLN',
  1405. 'ANONYMOUS',
  1406. 'AURORA\$ORB\$UNAUTHENTICATED',
  1407. 'AWR_STAGE',
  1408. 'CSMIG',
  1409. 'CTXSYS',
  1410. 'DBSNMP',
  1411. 'DIP',
  1412. 'DMSYS',
  1413. 'DSSYS',
  1414. 'EXFSYS',
  1415. 'FLOWS_020100',
  1416. 'FLOWS_FILES',
  1417. 'LBACSYS',
  1418. 'MDSYS',
  1419. 'ORACLE_OCM',
  1420. 'ORDPLUGINS',
  1421. 'ORDSYS',
  1422. 'PERFSTAT',
  1423. 'TRACESVR',
  1424. 'TSMSYS',
  1425. 'XDB'
  1426. )";
  1427. $this->schema_info['sequences'] = array();
  1428. foreach ($this->query($sql) as $row) {
  1429. if (preg_match('#SELECT\s+(["\w.]+).nextval\s+INTO\s+:new\.(\w+)\s+FROM\s+dual#i', $row['trigger_body'], $matches)) {
  1430. $table_name = $row['table'];
  1431. if ($row['schema'] != strtolower($this->username)) {
  1432. $table_name = $row['schema'] . '.' . $table_name;
  1433. }
  1434. $this->schema_info['sequences'][$table_name] = array('sequence' => $matches[1], 'column' => str_replace('"', '', $matches[2]));
  1435. }
  1436. }
  1437. if ($this->cache) {
  1438. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  1439. }
  1440. }
  1441. 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())) {
  1442. return;
  1443. }
  1444. $insert_id_sql = "SELECT " . $this->schema_info['sequences'][$table]['sequence'] . ".currval AS INSERT_ID FROM dual";
  1445. }
  1446. if ($this->type == 'postgresql') {
  1447. if (!isset($this->schema_info['sequences'])) {
  1448. $sql = "SELECT
  1449. pg_namespace.nspname AS \"schema\",
  1450. pg_class.relname AS \"table\",
  1451. pg_attribute.attname AS column
  1452. FROM
  1453. pg_attribute INNER JOIN
  1454. pg_class ON pg_attribute.attrelid = pg_class.oid INNER JOIN
  1455. pg_namespace ON pg_class.relnamespace = pg_namespace.oid INNER JOIN
  1456. pg_attrdef ON pg_class.oid = pg_attrdef.adrelid AND pg_attribute.attnum = pg_attrdef.adnum
  1457. WHERE
  1458. NOT pg_attribute.attisdropped AND
  1459. pg_attrdef.adsrc LIKE 'nextval(%'";
  1460. $this->schema_info['sequences'] = array();
  1461. foreach ($this->query($sql) as $row) {
  1462. $table_name = strtolower($row['table']);
  1463. if ($row['schema'] != 'public') {
  1464. $table_name = $row['schema'] . '.' . $table_name;
  1465. }
  1466. $this->schema_info['sequences'][$table_name] = $row['column'];
  1467. }
  1468. if ($this->cache) {
  1469. $this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
  1470. }
  1471. }
  1472. if (!isset($this->schema_info['sequences'][$table]) || preg_match('#INSERT\s+INTO\s+"?' . preg_quote($quoted_table, '#') . '"?\s+\([^\)]*?(\b|")' . preg_quote($this->schema_i

Large files files are truncated, but you can click here to view the full file