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

/system/database/DB_driver.php

https://bitbucket.org/inflex13/inkedgirls
PHP | 1406 lines | 713 code | 204 blank | 489 comment | 123 complexity | 910f80c23a57510a3db64b5035e9fcd0 MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * NOTICE OF LICENSE
  8. *
  9. * Licensed under the Open Software License version 3.0
  10. *
  11. * This source file is subject to the Open Software License (OSL 3.0) that is
  12. * bundled with this package in the files license.txt / license.rst. It is
  13. * also available through the world wide web at this URL:
  14. * http://opensource.org/licenses/OSL-3.0
  15. * If you did not receive a copy of the license and are unable to obtain it
  16. * through the world wide web, please send an email to
  17. * licensing@ellislab.com so we can send you a copy immediately.
  18. *
  19. * @package CodeIgniter
  20. * @author EllisLab Dev Team
  21. * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. (http://ellislab.com/)
  22. * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
  23. * @link http://codeigniter.com
  24. * @since Version 1.0
  25. * @filesource
  26. */
  27. // ------------------------------------------------------------------------
  28. /**
  29. * Database Driver Class
  30. *
  31. * This is the platform-independent base DB implementation class.
  32. * This class will not be called directly. Rather, the adapter
  33. * class for the specific database will extend and instantiate it.
  34. *
  35. * @package CodeIgniter
  36. * @subpackage Drivers
  37. * @category Database
  38. * @author EllisLab Dev Team
  39. * @link http://codeigniter.com/user_guide/database/
  40. */
  41. class CI_DB_driver {
  42. var $username;
  43. var $password;
  44. var $hostname;
  45. var $database;
  46. var $dbdriver = 'mysql';
  47. var $dbprefix = '';
  48. var $char_set = 'utf8';
  49. var $dbcollat = 'utf8_general_ci';
  50. var $autoinit = TRUE; // Whether to automatically initialize the DB
  51. var $swap_pre = '';
  52. var $port = '';
  53. var $pconnect = FALSE;
  54. var $conn_id = FALSE;
  55. var $result_id = FALSE;
  56. var $db_debug = FALSE;
  57. var $benchmark = 0;
  58. var $query_count = 0;
  59. var $bind_marker = '?';
  60. var $save_queries = TRUE;
  61. var $queries = array();
  62. var $query_times = array();
  63. var $data_cache = array();
  64. var $trans_enabled = TRUE;
  65. var $trans_strict = TRUE;
  66. var $_trans_depth = 0;
  67. var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur
  68. var $cache_on = FALSE;
  69. var $cachedir = '';
  70. var $cache_autodel = FALSE;
  71. var $CACHE; // The cache class object
  72. // Private variables
  73. var $_protect_identifiers = TRUE;
  74. var $_reserved_identifiers = array('*'); // Identifiers that should NOT be escaped
  75. // These are use with Oracle
  76. var $stmt_id;
  77. var $curs_id;
  78. var $limit_used;
  79. /**
  80. * Constructor. Accepts one parameter containing the database
  81. * connection settings.
  82. *
  83. * @param array
  84. */
  85. function __construct($params)
  86. {
  87. if (is_array($params))
  88. {
  89. foreach ($params as $key => $val)
  90. {
  91. $this->$key = $val;
  92. }
  93. }
  94. log_message('debug', 'Database Driver Class Initialized');
  95. }
  96. // --------------------------------------------------------------------
  97. /**
  98. * Initialize Database Settings
  99. *
  100. * @access private Called by the constructor
  101. * @param mixed
  102. * @return void
  103. */
  104. function initialize()
  105. {
  106. // If an existing connection resource is available
  107. // there is no need to connect and select the database
  108. if (is_resource($this->conn_id) OR is_object($this->conn_id))
  109. {
  110. return TRUE;
  111. }
  112. // ----------------------------------------------------------------
  113. // Connect to the database and set the connection ID
  114. $this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
  115. // No connection resource? Throw an error
  116. if ( ! $this->conn_id)
  117. {
  118. log_message('error', 'Unable to connect to the database');
  119. if ($this->db_debug)
  120. {
  121. $this->display_error('db_unable_to_connect');
  122. }
  123. return FALSE;
  124. }
  125. // ----------------------------------------------------------------
  126. // Select the DB... assuming a database name is specified in the config file
  127. if ($this->database != '')
  128. {
  129. if ( ! $this->db_select())
  130. {
  131. log_message('error', 'Unable to select database: '.$this->database);
  132. if ($this->db_debug)
  133. {
  134. $this->display_error('db_unable_to_select', $this->database);
  135. }
  136. return FALSE;
  137. }
  138. else
  139. {
  140. // We've selected the DB. Now we set the character set
  141. if ( ! $this->db_set_charset($this->char_set, $this->dbcollat))
  142. {
  143. return FALSE;
  144. }
  145. return TRUE;
  146. }
  147. }
  148. return TRUE;
  149. }
  150. // --------------------------------------------------------------------
  151. /**
  152. * Set client character set
  153. *
  154. * @access public
  155. * @param string
  156. * @param string
  157. * @return resource
  158. */
  159. function db_set_charset($charset, $collation)
  160. {
  161. if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat))
  162. {
  163. log_message('error', 'Unable to set database connection charset: '.$this->char_set);
  164. if ($this->db_debug)
  165. {
  166. $this->display_error('db_unable_to_set_charset', $this->char_set);
  167. }
  168. return FALSE;
  169. }
  170. return TRUE;
  171. }
  172. // --------------------------------------------------------------------
  173. /**
  174. * The name of the platform in use (mysql, mssql, etc...)
  175. *
  176. * @access public
  177. * @return string
  178. */
  179. function platform()
  180. {
  181. return $this->dbdriver;
  182. }
  183. // --------------------------------------------------------------------
  184. /**
  185. * Database Version Number. Returns a string containing the
  186. * version of the database being used
  187. *
  188. * @access public
  189. * @return string
  190. */
  191. function version()
  192. {
  193. if (FALSE === ($sql = $this->_version()))
  194. {
  195. if ($this->db_debug)
  196. {
  197. return $this->display_error('db_unsupported_function');
  198. }
  199. return FALSE;
  200. }
  201. // Some DBs have functions that return the version, and don't run special
  202. // SQL queries per se. In these instances, just return the result.
  203. $driver_version_exceptions = array('oci8', 'sqlite', 'cubrid', 'pdo');
  204. if (in_array($this->dbdriver, $driver_version_exceptions))
  205. {
  206. return $sql;
  207. }
  208. else
  209. {
  210. $query = $this->query($sql);
  211. return $query->row('ver');
  212. }
  213. }
  214. // --------------------------------------------------------------------
  215. /**
  216. * Execute the query
  217. *
  218. * Accepts an SQL string as input and returns a result object upon
  219. * successful execution of a "read" type query. Returns boolean TRUE
  220. * upon successful execution of a "write" type query. Returns boolean
  221. * FALSE upon failure, and if the $db_debug variable is set to TRUE
  222. * will raise an error.
  223. *
  224. * @access public
  225. * @param string An SQL query string
  226. * @param array An array of binding data
  227. * @return mixed
  228. */
  229. function query($sql, $binds = FALSE, $return_object = TRUE)
  230. {
  231. if ($sql == '')
  232. {
  233. log_message('error', 'Invalid query: '.$sql);
  234. if ($this->db_debug)
  235. {
  236. return $this->display_error('db_invalid_query');
  237. }
  238. return FALSE;
  239. }
  240. // Verify table prefix and replace if necessary
  241. if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
  242. {
  243. $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
  244. }
  245. // Is query caching enabled? If the query is a "read type"
  246. // we will load the caching class and return the previously
  247. // cached query if it exists
  248. if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
  249. {
  250. if ($this->_cache_init())
  251. {
  252. $this->load_rdriver();
  253. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  254. {
  255. return $cache;
  256. }
  257. }
  258. }
  259. // Compile binds if needed
  260. if ($binds !== FALSE)
  261. {
  262. $sql = $this->compile_binds($sql, $binds);
  263. }
  264. // Save the query for debugging
  265. if ($this->save_queries == TRUE)
  266. {
  267. $this->queries[] = $sql;
  268. }
  269. // Start the Query Timer
  270. $time_start = list($sm, $ss) = explode(' ', microtime());
  271. // Run the Query
  272. if (FALSE === ($this->result_id = $this->simple_query($sql)))
  273. {
  274. if ($this->save_queries == TRUE)
  275. {
  276. $this->query_times[] = 0;
  277. }
  278. // This will trigger a rollback if transactions are being used
  279. $this->_trans_status = FALSE;
  280. // Grab the error number and message now, as we might run some
  281. // additional queries before displaying the error
  282. $error_no = $this->_error_number();
  283. $error_msg = $this->_error_message();
  284. // Log errors
  285. log_message('error', 'Query error: '.$error_msg);
  286. if ($this->db_debug)
  287. {
  288. // We call this function in order to roll-back queries
  289. // if transactions are enabled. If we don't call this here
  290. // the error message will trigger an exit, causing the
  291. // transactions to remain in limbo.
  292. $this->trans_complete();
  293. // Display errors
  294. return $this->display_error(
  295. array(
  296. 'Error Number: '.$error_no,
  297. $error_msg,
  298. $sql
  299. )
  300. );
  301. }
  302. return FALSE;
  303. }
  304. // Stop and aggregate the query time results
  305. $time_end = list($em, $es) = explode(' ', microtime());
  306. $this->benchmark += ($em + $es) - ($sm + $ss);
  307. if ($this->save_queries == TRUE)
  308. {
  309. $this->query_times[] = ($em + $es) - ($sm + $ss);
  310. }
  311. // Increment the query counter
  312. $this->query_count++;
  313. // Was the query a "write" type?
  314. // If so we'll simply return true
  315. if ($this->is_write_type($sql) === TRUE)
  316. {
  317. // If caching is enabled we'll auto-cleanup any
  318. // existing files related to this particular URI
  319. if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
  320. {
  321. $this->CACHE->delete();
  322. }
  323. return TRUE;
  324. }
  325. // Return TRUE if we don't need to create a result object
  326. // Currently only the Oracle driver uses this when stored
  327. // procedures are used
  328. if ($return_object !== TRUE)
  329. {
  330. return TRUE;
  331. }
  332. // Load and instantiate the result driver
  333. $driver = $this->load_rdriver();
  334. $RES = new $driver();
  335. $RES->conn_id = $this->conn_id;
  336. $RES->result_id = $this->result_id;
  337. if ($this->dbdriver == 'oci8')
  338. {
  339. $RES->stmt_id = $this->stmt_id;
  340. $RES->curs_id = NULL;
  341. $RES->limit_used = $this->limit_used;
  342. $this->stmt_id = FALSE;
  343. }
  344. // oci8 vars must be set before calling this
  345. $RES->num_rows = $RES->num_rows();
  346. // Is query caching enabled? If so, we'll serialize the
  347. // result object and save it to a cache file.
  348. if ($this->cache_on == TRUE AND $this->_cache_init())
  349. {
  350. // We'll create a new instance of the result object
  351. // only without the platform specific driver since
  352. // we can't use it with cached data (the query result
  353. // resource ID won't be any good once we've cached the
  354. // result object, so we'll have to compile the data
  355. // and save it)
  356. $CR = new CI_DB_result();
  357. $CR->num_rows = $RES->num_rows();
  358. $CR->result_object = $RES->result_object();
  359. $CR->result_array = $RES->result_array();
  360. // Reset these since cached objects can not utilize resource IDs.
  361. $CR->conn_id = NULL;
  362. $CR->result_id = NULL;
  363. $this->CACHE->write($sql, $CR);
  364. }
  365. return $RES;
  366. }
  367. // --------------------------------------------------------------------
  368. /**
  369. * Load the result drivers
  370. *
  371. * @access public
  372. * @return string the name of the result class
  373. */
  374. function load_rdriver()
  375. {
  376. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  377. if ( ! class_exists($driver))
  378. {
  379. include_once(BASEPATH.'database/DB_result.php');
  380. include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  381. }
  382. return $driver;
  383. }
  384. // --------------------------------------------------------------------
  385. /**
  386. * Simple Query
  387. * This is a simplified version of the query() function. Internally
  388. * we only use it when running transaction commands since they do
  389. * not require all the features of the main query() function.
  390. *
  391. * @access public
  392. * @param string the sql query
  393. * @return mixed
  394. */
  395. function simple_query($sql)
  396. {
  397. if ( ! $this->conn_id)
  398. {
  399. $this->initialize();
  400. }
  401. return $this->_execute($sql);
  402. }
  403. // --------------------------------------------------------------------
  404. /**
  405. * Disable Transactions
  406. * This permits transactions to be disabled at run-time.
  407. *
  408. * @access public
  409. * @return void
  410. */
  411. function trans_off()
  412. {
  413. $this->trans_enabled = FALSE;
  414. }
  415. // --------------------------------------------------------------------
  416. /**
  417. * Enable/disable Transaction Strict Mode
  418. * When strict mode is enabled, if you are running multiple groups of
  419. * transactions, if one group fails all groups will be rolled back.
  420. * If strict mode is disabled, each group is treated autonomously, meaning
  421. * a failure of one group will not affect any others
  422. *
  423. * @access public
  424. * @return void
  425. */
  426. function trans_strict($mode = TRUE)
  427. {
  428. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  429. }
  430. // --------------------------------------------------------------------
  431. /**
  432. * Start Transaction
  433. *
  434. * @access public
  435. * @return void
  436. */
  437. function trans_start($test_mode = FALSE)
  438. {
  439. if ( ! $this->trans_enabled)
  440. {
  441. return FALSE;
  442. }
  443. // When transactions are nested we only begin/commit/rollback the outermost ones
  444. if ($this->_trans_depth > 0)
  445. {
  446. $this->_trans_depth += 1;
  447. return;
  448. }
  449. $this->trans_begin($test_mode);
  450. }
  451. // --------------------------------------------------------------------
  452. /**
  453. * Complete Transaction
  454. *
  455. * @access public
  456. * @return bool
  457. */
  458. function trans_complete()
  459. {
  460. if ( ! $this->trans_enabled)
  461. {
  462. return FALSE;
  463. }
  464. // When transactions are nested we only begin/commit/rollback the outermost ones
  465. if ($this->_trans_depth > 1)
  466. {
  467. $this->_trans_depth -= 1;
  468. return TRUE;
  469. }
  470. // The query() function will set this flag to FALSE in the event that a query failed
  471. if ($this->_trans_status === FALSE)
  472. {
  473. $this->trans_rollback();
  474. // If we are NOT running in strict mode, we will reset
  475. // the _trans_status flag so that subsequent groups of transactions
  476. // will be permitted.
  477. if ($this->trans_strict === FALSE)
  478. {
  479. $this->_trans_status = TRUE;
  480. }
  481. log_message('debug', 'DB Transaction Failure');
  482. return FALSE;
  483. }
  484. $this->trans_commit();
  485. return TRUE;
  486. }
  487. // --------------------------------------------------------------------
  488. /**
  489. * Lets you retrieve the transaction flag to determine if it has failed
  490. *
  491. * @access public
  492. * @return bool
  493. */
  494. function trans_status()
  495. {
  496. return $this->_trans_status;
  497. }
  498. // --------------------------------------------------------------------
  499. /**
  500. * Compile Bindings
  501. *
  502. * @access public
  503. * @param string the sql statement
  504. * @param array an array of bind data
  505. * @return string
  506. */
  507. function compile_binds($sql, $binds)
  508. {
  509. if (strpos($sql, $this->bind_marker) === FALSE)
  510. {
  511. return $sql;
  512. }
  513. if ( ! is_array($binds))
  514. {
  515. $binds = array($binds);
  516. }
  517. // Get the sql segments around the bind markers
  518. $segments = explode($this->bind_marker, $sql);
  519. // The count of bind should be 1 less then the count of segments
  520. // If there are more bind arguments trim it down
  521. if (count($binds) >= count($segments)) {
  522. $binds = array_slice($binds, 0, count($segments)-1);
  523. }
  524. // Construct the binded query
  525. $result = $segments[0];
  526. $i = 0;
  527. foreach ($binds as $bind)
  528. {
  529. $result .= $this->escape($bind);
  530. $result .= $segments[++$i];
  531. }
  532. return $result;
  533. }
  534. // --------------------------------------------------------------------
  535. /**
  536. * Determines if a query is a "write" type.
  537. *
  538. * @access public
  539. * @param string An SQL query string
  540. * @return boolean
  541. */
  542. function is_write_type($sql)
  543. {
  544. if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
  545. {
  546. return FALSE;
  547. }
  548. return TRUE;
  549. }
  550. // --------------------------------------------------------------------
  551. /**
  552. * Calculate the aggregate query elapsed time
  553. *
  554. * @access public
  555. * @param integer The number of decimal places
  556. * @return integer
  557. */
  558. function elapsed_time($decimals = 6)
  559. {
  560. return number_format($this->benchmark, $decimals);
  561. }
  562. // --------------------------------------------------------------------
  563. /**
  564. * Returns the total number of queries
  565. *
  566. * @access public
  567. * @return integer
  568. */
  569. function total_queries()
  570. {
  571. return $this->query_count;
  572. }
  573. // --------------------------------------------------------------------
  574. /**
  575. * Returns the last query that was executed
  576. *
  577. * @access public
  578. * @return void
  579. */
  580. function last_query()
  581. {
  582. return end($this->queries);
  583. }
  584. // --------------------------------------------------------------------
  585. /**
  586. * "Smart" Escape String
  587. *
  588. * Escapes data based on type
  589. * Sets boolean and null types
  590. *
  591. * @access public
  592. * @param string
  593. * @return mixed
  594. */
  595. function escape($str)
  596. {
  597. if (is_string($str))
  598. {
  599. $str = "'".$this->escape_str($str)."'";
  600. }
  601. elseif (is_bool($str))
  602. {
  603. $str = ($str === FALSE) ? 0 : 1;
  604. }
  605. elseif (is_null($str))
  606. {
  607. $str = 'NULL';
  608. }
  609. return $str;
  610. }
  611. // --------------------------------------------------------------------
  612. /**
  613. * Escape LIKE String
  614. *
  615. * Calls the individual driver for platform
  616. * specific escaping for LIKE conditions
  617. *
  618. * @access public
  619. * @param string
  620. * @return mixed
  621. */
  622. function escape_like_str($str)
  623. {
  624. return $this->escape_str($str, TRUE);
  625. }
  626. // --------------------------------------------------------------------
  627. /**
  628. * Primary
  629. *
  630. * Retrieves the primary key. It assumes that the row in the first
  631. * position is the primary key
  632. *
  633. * @access public
  634. * @param string the table name
  635. * @return string
  636. */
  637. function primary($table = '')
  638. {
  639. $fields = $this->list_fields($table);
  640. if ( ! is_array($fields))
  641. {
  642. return FALSE;
  643. }
  644. return current($fields);
  645. }
  646. // --------------------------------------------------------------------
  647. /**
  648. * Returns an array of table names
  649. *
  650. * @access public
  651. * @return array
  652. */
  653. function list_tables($constrain_by_prefix = FALSE)
  654. {
  655. // Is there a cached result?
  656. if (isset($this->data_cache['table_names']))
  657. {
  658. return $this->data_cache['table_names'];
  659. }
  660. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  661. {
  662. if ($this->db_debug)
  663. {
  664. return $this->display_error('db_unsupported_function');
  665. }
  666. return FALSE;
  667. }
  668. $retval = array();
  669. $query = $this->query($sql);
  670. if ($query->num_rows() > 0)
  671. {
  672. foreach ($query->result_array() as $row)
  673. {
  674. if (isset($row['TABLE_NAME']))
  675. {
  676. $retval[] = $row['TABLE_NAME'];
  677. }
  678. else
  679. {
  680. $retval[] = array_shift($row);
  681. }
  682. }
  683. }
  684. $this->data_cache['table_names'] = $retval;
  685. return $this->data_cache['table_names'];
  686. }
  687. // --------------------------------------------------------------------
  688. /**
  689. * Determine if a particular table exists
  690. * @access public
  691. * @return boolean
  692. */
  693. function table_exists($table_name)
  694. {
  695. return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
  696. }
  697. // --------------------------------------------------------------------
  698. /**
  699. * Fetch MySQL Field Names
  700. *
  701. * @access public
  702. * @param string the table name
  703. * @return array
  704. */
  705. function list_fields($table = '')
  706. {
  707. // Is there a cached result?
  708. if (isset($this->data_cache['field_names'][$table]))
  709. {
  710. return $this->data_cache['field_names'][$table];
  711. }
  712. if ($table == '')
  713. {
  714. if ($this->db_debug)
  715. {
  716. return $this->display_error('db_field_param_missing');
  717. }
  718. return FALSE;
  719. }
  720. if (FALSE === ($sql = $this->_list_columns($table)))
  721. {
  722. if ($this->db_debug)
  723. {
  724. return $this->display_error('db_unsupported_function');
  725. }
  726. return FALSE;
  727. }
  728. $query = $this->query($sql);
  729. $retval = array();
  730. foreach ($query->result_array() as $row)
  731. {
  732. if (isset($row['COLUMN_NAME']))
  733. {
  734. $retval[] = $row['COLUMN_NAME'];
  735. }
  736. else
  737. {
  738. $retval[] = current($row);
  739. }
  740. }
  741. $this->data_cache['field_names'][$table] = $retval;
  742. return $this->data_cache['field_names'][$table];
  743. }
  744. // --------------------------------------------------------------------
  745. /**
  746. * Determine if a particular field exists
  747. * @access public
  748. * @param string
  749. * @param string
  750. * @return boolean
  751. */
  752. function field_exists($field_name, $table_name)
  753. {
  754. return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
  755. }
  756. // --------------------------------------------------------------------
  757. /**
  758. * Returns an object with field data
  759. *
  760. * @access public
  761. * @param string the table name
  762. * @return object
  763. */
  764. function field_data($table = '')
  765. {
  766. if ($table == '')
  767. {
  768. if ($this->db_debug)
  769. {
  770. return $this->display_error('db_field_param_missing');
  771. }
  772. return FALSE;
  773. }
  774. $query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
  775. return $query->field_data();
  776. }
  777. // --------------------------------------------------------------------
  778. /**
  779. * Generate an insert string
  780. *
  781. * @access public
  782. * @param string the table upon which the query will be performed
  783. * @param array an associative array data of key/values
  784. * @return string
  785. */
  786. function insert_string($table, $data)
  787. {
  788. $fields = array();
  789. $values = array();
  790. foreach ($data as $key => $val)
  791. {
  792. $fields[] = $this->_escape_identifiers($key);
  793. $values[] = $this->escape($val);
  794. }
  795. return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  796. }
  797. // --------------------------------------------------------------------
  798. /**
  799. * Generate an update string
  800. *
  801. * @access public
  802. * @param string the table upon which the query will be performed
  803. * @param array an associative array data of key/values
  804. * @param mixed the "where" statement
  805. * @return string
  806. */
  807. function update_string($table, $data, $where)
  808. {
  809. if ($where == '')
  810. {
  811. return false;
  812. }
  813. $fields = array();
  814. foreach ($data as $key => $val)
  815. {
  816. $fields[$this->_protect_identifiers($key)] = $this->escape($val);
  817. }
  818. if ( ! is_array($where))
  819. {
  820. $dest = array($where);
  821. }
  822. else
  823. {
  824. $dest = array();
  825. foreach ($where as $key => $val)
  826. {
  827. $prefix = (count($dest) == 0) ? '' : ' AND ';
  828. $key = $this->_protect_identifiers($key);
  829. if ($val !== '')
  830. {
  831. if ( ! $this->_has_operator($key))
  832. {
  833. $key .= ' =';
  834. }
  835. $val = ' '.$this->escape($val);
  836. }
  837. $dest[] = $prefix.$key.$val;
  838. }
  839. }
  840. return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
  841. }
  842. // --------------------------------------------------------------------
  843. /**
  844. * Tests whether the string has an SQL operator
  845. *
  846. * @access private
  847. * @param string
  848. * @return bool
  849. */
  850. function _has_operator($str)
  851. {
  852. $str = trim($str);
  853. if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
  854. {
  855. return FALSE;
  856. }
  857. return TRUE;
  858. }
  859. // --------------------------------------------------------------------
  860. /**
  861. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  862. *
  863. * @access public
  864. * @param string the function name
  865. * @param mixed any parameters needed by the function
  866. * @return mixed
  867. */
  868. function call_function($function)
  869. {
  870. $driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
  871. if (FALSE === strpos($driver, $function))
  872. {
  873. $function = $driver.$function;
  874. }
  875. if ( ! function_exists($function))
  876. {
  877. if ($this->db_debug)
  878. {
  879. return $this->display_error('db_unsupported_function');
  880. }
  881. return FALSE;
  882. }
  883. else
  884. {
  885. $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
  886. return call_user_func_array($function, $args);
  887. }
  888. }
  889. // --------------------------------------------------------------------
  890. /**
  891. * Set Cache Directory Path
  892. *
  893. * @access public
  894. * @param string the path to the cache directory
  895. * @return void
  896. */
  897. function cache_set_path($path = '')
  898. {
  899. $this->cachedir = $path;
  900. }
  901. // --------------------------------------------------------------------
  902. /**
  903. * Enable Query Caching
  904. *
  905. * @access public
  906. * @return void
  907. */
  908. function cache_on()
  909. {
  910. $this->cache_on = TRUE;
  911. return TRUE;
  912. }
  913. // --------------------------------------------------------------------
  914. /**
  915. * Disable Query Caching
  916. *
  917. * @access public
  918. * @return void
  919. */
  920. function cache_off()
  921. {
  922. $this->cache_on = FALSE;
  923. return FALSE;
  924. }
  925. // --------------------------------------------------------------------
  926. /**
  927. * Delete the cache files associated with a particular URI
  928. *
  929. * @access public
  930. * @return void
  931. */
  932. function cache_delete($segment_one = '', $segment_two = '')
  933. {
  934. if ( ! $this->_cache_init())
  935. {
  936. return FALSE;
  937. }
  938. return $this->CACHE->delete($segment_one, $segment_two);
  939. }
  940. // --------------------------------------------------------------------
  941. /**
  942. * Delete All cache files
  943. *
  944. * @access public
  945. * @return void
  946. */
  947. function cache_delete_all()
  948. {
  949. if ( ! $this->_cache_init())
  950. {
  951. return FALSE;
  952. }
  953. return $this->CACHE->delete_all();
  954. }
  955. // --------------------------------------------------------------------
  956. /**
  957. * Initialize the Cache Class
  958. *
  959. * @access private
  960. * @return void
  961. */
  962. function _cache_init()
  963. {
  964. if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
  965. {
  966. return TRUE;
  967. }
  968. if ( ! class_exists('CI_DB_Cache'))
  969. {
  970. if ( ! @include(BASEPATH.'database/DB_cache.php'))
  971. {
  972. return $this->cache_off();
  973. }
  974. }
  975. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  976. return TRUE;
  977. }
  978. // --------------------------------------------------------------------
  979. /**
  980. * Close DB Connection
  981. *
  982. * @access public
  983. * @return void
  984. */
  985. function close()
  986. {
  987. if (is_resource($this->conn_id) OR is_object($this->conn_id))
  988. {
  989. $this->_close($this->conn_id);
  990. }
  991. $this->conn_id = FALSE;
  992. }
  993. // --------------------------------------------------------------------
  994. /**
  995. * Display an error message
  996. *
  997. * @access public
  998. * @param string the error message
  999. * @param string any "swap" values
  1000. * @param boolean whether to localize the message
  1001. * @return string sends the application/error_db.php template
  1002. */
  1003. function display_error($error = '', $swap = '', $native = FALSE)
  1004. {
  1005. $LANG =& load_class('Lang', 'core');
  1006. $LANG->load('db');
  1007. $heading = $LANG->line('db_error_heading');
  1008. if ($native == TRUE)
  1009. {
  1010. $message = (array) $error;
  1011. }
  1012. else
  1013. {
  1014. $message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
  1015. }
  1016. // Find the most likely culprit of the error by going through
  1017. // the backtrace until the source file is no longer in the
  1018. // database folder.
  1019. $trace = debug_backtrace();
  1020. foreach ($trace as $call)
  1021. {
  1022. if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
  1023. {
  1024. // Found it - use a relative path for safety
  1025. $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
  1026. $message[] = 'Line Number: '.$call['line'];
  1027. break;
  1028. }
  1029. }
  1030. $error =& load_class('Exceptions', 'core');
  1031. echo $error->show_error($heading, $message, 'error_db');
  1032. exit;
  1033. }
  1034. // --------------------------------------------------------------------
  1035. /**
  1036. * Protect Identifiers
  1037. *
  1038. * This function adds backticks if appropriate based on db type
  1039. *
  1040. * @access private
  1041. * @param mixed the item to escape
  1042. * @return mixed the item with backticks
  1043. */
  1044. function protect_identifiers($item, $prefix_single = FALSE)
  1045. {
  1046. return $this->_protect_identifiers($item, $prefix_single);
  1047. }
  1048. // --------------------------------------------------------------------
  1049. /**
  1050. * Protect Identifiers
  1051. *
  1052. * This function is used extensively by the Active Record class, and by
  1053. * a couple functions in this class.
  1054. * It takes a column or table name (optionally with an alias) and inserts
  1055. * the table prefix onto it. Some logic is necessary in order to deal with
  1056. * column names that include the path. Consider a query like this:
  1057. *
  1058. * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
  1059. *
  1060. * Or a query with aliasing:
  1061. *
  1062. * SELECT m.member_id, m.member_name FROM members AS m
  1063. *
  1064. * Since the column name can include up to four segments (host, DB, table, column)
  1065. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1066. * insert the table prefix (if it exists) in the proper position, and escape only
  1067. * the correct identifiers.
  1068. *
  1069. * @access private
  1070. * @param string
  1071. * @param bool
  1072. * @param mixed
  1073. * @param bool
  1074. * @return string
  1075. */
  1076. function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1077. {
  1078. if ( ! is_bool($protect_identifiers))
  1079. {
  1080. $protect_identifiers = $this->_protect_identifiers;
  1081. }
  1082. if (is_array($item))
  1083. {
  1084. $escaped_array = array();
  1085. foreach ($item as $k => $v)
  1086. {
  1087. $escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
  1088. }
  1089. return $escaped_array;
  1090. }
  1091. // Convert tabs or multiple spaces into single spaces
  1092. $item = preg_replace('/[\t ]+/', ' ', $item);
  1093. // If the item has an alias declaration we remove it and set it aside.
  1094. // Basically we remove everything to the right of the first space
  1095. $alias = '';
  1096. if (strpos($item, ' ') !== FALSE)
  1097. {
  1098. $alias = strstr($item, " ");
  1099. $item = substr($item, 0, - strlen($alias));
  1100. }
  1101. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1102. // If a parenthesis is found we know that we do not need to
  1103. // escape the data or add a prefix. There's probably a more graceful
  1104. // way to deal with this, but I'm not thinking of it -- Rick
  1105. if (strpos($item, '(') !== FALSE)
  1106. {
  1107. return $item.$alias;
  1108. }
  1109. // Break the string apart if it contains periods, then insert the table prefix
  1110. // in the correct location, assuming the period doesn't indicate that we're dealing
  1111. // with an alias. While we're at it, we will escape the components
  1112. if (strpos($item, '.') !== FALSE)
  1113. {
  1114. $parts = explode('.', $item);
  1115. // Does the first segment of the exploded item match
  1116. // one of the aliases previously identified? If so,
  1117. // we have nothing more to do other than escape the item
  1118. if (in_array($parts[0], $this->ar_aliased_tables))
  1119. {
  1120. if ($protect_identifiers === TRUE)
  1121. {
  1122. foreach ($parts as $key => $val)
  1123. {
  1124. if ( ! in_array($val, $this->_reserved_identifiers))
  1125. {
  1126. $parts[$key] = $this->_escape_identifiers($val);
  1127. }
  1128. }
  1129. $item = implode('.', $parts);
  1130. }
  1131. return $item.$alias;
  1132. }
  1133. // Is there a table prefix defined in the config file? If not, no need to do anything
  1134. if ($this->dbprefix != '')
  1135. {
  1136. // We now add the table prefix based on some logic.
  1137. // Do we have 4 segments (hostname.database.table.column)?
  1138. // If so, we add the table prefix to the column name in the 3rd segment.
  1139. if (isset($parts[3]))
  1140. {
  1141. $i = 2;
  1142. }
  1143. // Do we have 3 segments (database.table.column)?
  1144. // If so, we add the table prefix to the column name in 2nd position
  1145. elseif (isset($parts[2]))
  1146. {
  1147. $i = 1;
  1148. }
  1149. // Do we have 2 segments (table.column)?
  1150. // If so, we add the table prefix to the column name in 1st segment
  1151. else
  1152. {
  1153. $i = 0;
  1154. }
  1155. // This flag is set when the supplied $item does not contain a field name.
  1156. // This can happen when this function is being called from a JOIN.
  1157. if ($field_exists == FALSE)
  1158. {
  1159. $i++;
  1160. }
  1161. // Verify table prefix and replace if necessary
  1162. if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
  1163. {
  1164. $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
  1165. }
  1166. // We only add the table prefix if it does not already exist
  1167. if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
  1168. {
  1169. $parts[$i] = $this->dbprefix.$parts[$i];
  1170. }
  1171. // Put the parts back together
  1172. $item = implode('.', $parts);
  1173. }
  1174. if ($protect_identifiers === TRUE)
  1175. {
  1176. $item = $this->_escape_identifiers($item);
  1177. }
  1178. return $item.$alias;
  1179. }
  1180. // Is there a table prefix? If not, no need to insert it
  1181. if ($this->dbprefix != '')
  1182. {
  1183. // Verify table prefix and replace if necessary
  1184. if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
  1185. {
  1186. $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
  1187. }
  1188. // Do we prefix an item with no segments?
  1189. if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
  1190. {
  1191. $item = $this->dbprefix.$item;
  1192. }
  1193. }
  1194. if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
  1195. {
  1196. $item = $this->_escape_identifiers($item);
  1197. }
  1198. return $item.$alias;
  1199. }
  1200. }
  1201. /* End of file DB_driver.php */
  1202. /* Location: ./system/database/DB_driver.php */