You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1986 lines
45 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Database Driver Class
  41. *
  42. * This is the platform-independent base DB implementation class.
  43. * This class will not be called directly. Rather, the adapter
  44. * class for the specific database will extend and instantiate it.
  45. *
  46. * @package CodeIgniter
  47. * @subpackage Drivers
  48. * @category Database
  49. * @author EllisLab Dev Team
  50. * @link https://codeigniter.com/user_guide/database/
  51. */
  52. abstract class CI_DB_driver {
  53. /**
  54. * Data Source Name / Connect string
  55. *
  56. * @var string
  57. */
  58. public $dsn;
  59. /**
  60. * Username
  61. *
  62. * @var string
  63. */
  64. public $username;
  65. /**
  66. * Password
  67. *
  68. * @var string
  69. */
  70. public $password;
  71. /**
  72. * Hostname
  73. *
  74. * @var string
  75. */
  76. public $hostname;
  77. /**
  78. * Database name
  79. *
  80. * @var string
  81. */
  82. public $database;
  83. /**
  84. * Database driver
  85. *
  86. * @var string
  87. */
  88. public $dbdriver = 'mysqli';
  89. /**
  90. * Sub-driver
  91. *
  92. * @used-by CI_DB_pdo_driver
  93. * @var string
  94. */
  95. public $subdriver;
  96. /**
  97. * Table prefix
  98. *
  99. * @var string
  100. */
  101. public $dbprefix = '';
  102. /**
  103. * Character set
  104. *
  105. * @var string
  106. */
  107. public $char_set = 'utf8';
  108. /**
  109. * Collation
  110. *
  111. * @var string
  112. */
  113. public $dbcollat = 'utf8_general_ci';
  114. /**
  115. * Encryption flag/data
  116. *
  117. * @var mixed
  118. */
  119. public $encrypt = FALSE;
  120. /**
  121. * Swap Prefix
  122. *
  123. * @var string
  124. */
  125. public $swap_pre = '';
  126. /**
  127. * Database port
  128. *
  129. * @var int
  130. */
  131. public $port = '';
  132. /**
  133. * Persistent connection flag
  134. *
  135. * @var bool
  136. */
  137. public $pconnect = FALSE;
  138. /**
  139. * Connection ID
  140. *
  141. * @var object|resource
  142. */
  143. public $conn_id = FALSE;
  144. /**
  145. * Result ID
  146. *
  147. * @var object|resource
  148. */
  149. public $result_id = FALSE;
  150. /**
  151. * Debug flag
  152. *
  153. * Whether to display error messages.
  154. *
  155. * @var bool
  156. */
  157. public $db_debug = FALSE;
  158. /**
  159. * Benchmark time
  160. *
  161. * @var int
  162. */
  163. public $benchmark = 0;
  164. /**
  165. * Executed queries count
  166. *
  167. * @var int
  168. */
  169. public $query_count = 0;
  170. /**
  171. * Bind marker
  172. *
  173. * Character used to identify values in a prepared statement.
  174. *
  175. * @var string
  176. */
  177. public $bind_marker = '?';
  178. /**
  179. * Save queries flag
  180. *
  181. * Whether to keep an in-memory history of queries for debugging purposes.
  182. *
  183. * @var bool
  184. */
  185. public $save_queries = TRUE;
  186. /**
  187. * Queries list
  188. *
  189. * @see CI_DB_driver::$save_queries
  190. * @var string[]
  191. */
  192. public $queries = array();
  193. /**
  194. * Query times
  195. *
  196. * A list of times that queries took to execute.
  197. *
  198. * @var array
  199. */
  200. public $query_times = array();
  201. /**
  202. * Data cache
  203. *
  204. * An internal generic value cache.
  205. *
  206. * @var array
  207. */
  208. public $data_cache = array();
  209. /**
  210. * Transaction enabled flag
  211. *
  212. * @var bool
  213. */
  214. public $trans_enabled = TRUE;
  215. /**
  216. * Strict transaction mode flag
  217. *
  218. * @var bool
  219. */
  220. public $trans_strict = TRUE;
  221. /**
  222. * Transaction depth level
  223. *
  224. * @var int
  225. */
  226. protected $_trans_depth = 0;
  227. /**
  228. * Transaction status flag
  229. *
  230. * Used with transactions to determine if a rollback should occur.
  231. *
  232. * @var bool
  233. */
  234. protected $_trans_status = TRUE;
  235. /**
  236. * Transaction failure flag
  237. *
  238. * Used with transactions to determine if a transaction has failed.
  239. *
  240. * @var bool
  241. */
  242. protected $_trans_failure = FALSE;
  243. /**
  244. * Cache On flag
  245. *
  246. * @var bool
  247. */
  248. public $cache_on = FALSE;
  249. /**
  250. * Cache directory path
  251. *
  252. * @var bool
  253. */
  254. public $cachedir = '';
  255. /**
  256. * Cache auto-delete flag
  257. *
  258. * @var bool
  259. */
  260. public $cache_autodel = FALSE;
  261. /**
  262. * DB Cache object
  263. *
  264. * @see CI_DB_cache
  265. * @var object
  266. */
  267. public $CACHE;
  268. /**
  269. * Protect identifiers flag
  270. *
  271. * @var bool
  272. */
  273. protected $_protect_identifiers = TRUE;
  274. /**
  275. * List of reserved identifiers
  276. *
  277. * Identifiers that must NOT be escaped.
  278. *
  279. * @var string[]
  280. */
  281. protected $_reserved_identifiers = array('*');
  282. /**
  283. * Identifier escape character
  284. *
  285. * @var string
  286. */
  287. protected $_escape_char = '"';
  288. /**
  289. * ESCAPE statement string
  290. *
  291. * @var string
  292. */
  293. protected $_like_escape_str = " ESCAPE '%s' ";
  294. /**
  295. * ESCAPE character
  296. *
  297. * @var string
  298. */
  299. protected $_like_escape_chr = '!';
  300. /**
  301. * ORDER BY random keyword
  302. *
  303. * @var array
  304. */
  305. protected $_random_keyword = array('RAND()', 'RAND(%d)');
  306. /**
  307. * COUNT string
  308. *
  309. * @used-by CI_DB_driver::count_all()
  310. * @used-by CI_DB_query_builder::count_all_results()
  311. *
  312. * @var string
  313. */
  314. protected $_count_string = 'SELECT COUNT(*) AS ';
  315. // --------------------------------------------------------------------
  316. /**
  317. * Class constructor
  318. *
  319. * @param array $params
  320. * @return void
  321. */
  322. public function __construct($params)
  323. {
  324. if (is_array($params))
  325. {
  326. foreach ($params as $key => $val)
  327. {
  328. $this->$key = $val;
  329. }
  330. }
  331. log_message('info', 'Database Driver Class Initialized');
  332. }
  333. // --------------------------------------------------------------------
  334. /**
  335. * Initialize Database Settings
  336. *
  337. * @return bool
  338. */
  339. public function initialize()
  340. {
  341. /* If an established connection is available, then there's
  342. * no need to connect and select the database.
  343. *
  344. * Depending on the database driver, conn_id can be either
  345. * boolean TRUE, a resource or an object.
  346. */
  347. if ($this->conn_id)
  348. {
  349. return TRUE;
  350. }
  351. // ----------------------------------------------------------------
  352. // Connect to the database and set the connection ID
  353. $this->conn_id = $this->db_connect($this->pconnect);
  354. // No connection resource? Check if there is a failover else throw an error
  355. if ( ! $this->conn_id)
  356. {
  357. // Check if there is a failover set
  358. if ( ! empty($this->failover) && is_array($this->failover))
  359. {
  360. // Go over all the failovers
  361. foreach ($this->failover as $failover)
  362. {
  363. // Replace the current settings with those of the failover
  364. foreach ($failover as $key => $val)
  365. {
  366. $this->$key = $val;
  367. }
  368. // Try to connect
  369. $this->conn_id = $this->db_connect($this->pconnect);
  370. // If a connection is made break the foreach loop
  371. if ($this->conn_id)
  372. {
  373. break;
  374. }
  375. }
  376. }
  377. // We still don't have a connection?
  378. if ( ! $this->conn_id)
  379. {
  380. log_message('error', 'Unable to connect to the database');
  381. if ($this->db_debug)
  382. {
  383. $this->display_error('db_unable_to_connect');
  384. }
  385. return FALSE;
  386. }
  387. }
  388. // Now we set the character set and that's all
  389. return $this->db_set_charset($this->char_set);
  390. }
  391. // --------------------------------------------------------------------
  392. /**
  393. * DB connect
  394. *
  395. * This is just a dummy method that all drivers will override.
  396. *
  397. * @return mixed
  398. */
  399. public function db_connect()
  400. {
  401. return TRUE;
  402. }
  403. // --------------------------------------------------------------------
  404. /**
  405. * Persistent database connection
  406. *
  407. * @return mixed
  408. */
  409. public function db_pconnect()
  410. {
  411. return $this->db_connect(TRUE);
  412. }
  413. // --------------------------------------------------------------------
  414. /**
  415. * Reconnect
  416. *
  417. * Keep / reestablish the db connection if no queries have been
  418. * sent for a length of time exceeding the server's idle timeout.
  419. *
  420. * This is just a dummy method to allow drivers without such
  421. * functionality to not declare it, while others will override it.
  422. *
  423. * @return void
  424. */
  425. public function reconnect()
  426. {
  427. }
  428. // --------------------------------------------------------------------
  429. /**
  430. * Select database
  431. *
  432. * This is just a dummy method to allow drivers without such
  433. * functionality to not declare it, while others will override it.
  434. *
  435. * @return bool
  436. */
  437. public function db_select()
  438. {
  439. return TRUE;
  440. }
  441. // --------------------------------------------------------------------
  442. /**
  443. * Last error
  444. *
  445. * @return array
  446. */
  447. public function error()
  448. {
  449. return array('code' => NULL, 'message' => NULL);
  450. }
  451. // --------------------------------------------------------------------
  452. /**
  453. * Set client character set
  454. *
  455. * @param string
  456. * @return bool
  457. */
  458. public function db_set_charset($charset)
  459. {
  460. if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset))
  461. {
  462. log_message('error', 'Unable to set database connection charset: '.$charset);
  463. if ($this->db_debug)
  464. {
  465. $this->display_error('db_unable_to_set_charset', $charset);
  466. }
  467. return FALSE;
  468. }
  469. return TRUE;
  470. }
  471. // --------------------------------------------------------------------
  472. /**
  473. * The name of the platform in use (mysql, mssql, etc...)
  474. *
  475. * @return string
  476. */
  477. public function platform()
  478. {
  479. return $this->dbdriver;
  480. }
  481. // --------------------------------------------------------------------
  482. /**
  483. * Database version number
  484. *
  485. * Returns a string containing the version of the database being used.
  486. * Most drivers will override this method.
  487. *
  488. * @return string
  489. */
  490. public function version()
  491. {
  492. if (isset($this->data_cache['version']))
  493. {
  494. return $this->data_cache['version'];
  495. }
  496. if (FALSE === ($sql = $this->_version()))
  497. {
  498. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  499. }
  500. $query = $this->query($sql)->row();
  501. return $this->data_cache['version'] = $query->ver;
  502. }
  503. // --------------------------------------------------------------------
  504. /**
  505. * Version number query string
  506. *
  507. * @return string
  508. */
  509. protected function _version()
  510. {
  511. return 'SELECT VERSION() AS ver';
  512. }
  513. // --------------------------------------------------------------------
  514. /**
  515. * Execute the query
  516. *
  517. * Accepts an SQL string as input and returns a result object upon
  518. * successful execution of a "read" type query. Returns boolean TRUE
  519. * upon successful execution of a "write" type query. Returns boolean
  520. * FALSE upon failure, and if the $db_debug variable is set to TRUE
  521. * will raise an error.
  522. *
  523. * @param string $sql
  524. * @param array $binds = FALSE An array of binding data
  525. * @param bool $return_object = NULL
  526. * @return mixed
  527. */
  528. public function query($sql, $binds = FALSE, $return_object = NULL)
  529. {
  530. if ($sql === '')
  531. {
  532. log_message('error', 'Invalid query: '.$sql);
  533. return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
  534. }
  535. elseif ( ! is_bool($return_object))
  536. {
  537. $return_object = ! $this->is_write_type($sql);
  538. }
  539. // Verify table prefix and replace if necessary
  540. if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
  541. {
  542. $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
  543. }
  544. // Compile binds if needed
  545. if ($binds !== FALSE)
  546. {
  547. $sql = $this->compile_binds($sql, $binds);
  548. }
  549. // Is query caching enabled? If the query is a "read type"
  550. // we will load the caching class and return the previously
  551. // cached query if it exists
  552. if ($this->cache_on === TRUE && $return_object === TRUE && $this->_cache_init())
  553. {
  554. $this->load_rdriver();
  555. if (FALSE !== ($cache = $this->CACHE->read($sql)))
  556. {
  557. return $cache;
  558. }
  559. }
  560. // Save the query for debugging
  561. if ($this->save_queries === TRUE)
  562. {
  563. $this->queries[] = $sql;
  564. }
  565. // Start the Query Timer
  566. $time_start = microtime(TRUE);
  567. // Run the Query
  568. if (FALSE === ($this->result_id = $this->simple_query($sql)))
  569. {
  570. if ($this->save_queries === TRUE)
  571. {
  572. $this->query_times[] = 0;
  573. }
  574. // This will trigger a rollback if transactions are being used
  575. if ($this->_trans_depth !== 0)
  576. {
  577. $this->_trans_status = FALSE;
  578. }
  579. // Grab the error now, as we might run some additional queries before displaying the error
  580. $error = $this->error();
  581. // Log errors
  582. log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql);
  583. if ($this->db_debug)
  584. {
  585. // We call this function in order to roll-back queries
  586. // if transactions are enabled. If we don't call this here
  587. // the error message will trigger an exit, causing the
  588. // transactions to remain in limbo.
  589. while ($this->_trans_depth !== 0)
  590. {
  591. $trans_depth = $this->_trans_depth;
  592. $this->trans_complete();
  593. if ($trans_depth === $this->_trans_depth)
  594. {
  595. log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
  596. break;
  597. }
  598. }
  599. // Display errors
  600. return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
  601. }
  602. return FALSE;
  603. }
  604. // Stop and aggregate the query time results
  605. $time_end = microtime(TRUE);
  606. $this->benchmark += $time_end - $time_start;
  607. if ($this->save_queries === TRUE)
  608. {
  609. $this->query_times[] = $time_end - $time_start;
  610. }
  611. // Increment the query counter
  612. $this->query_count++;
  613. // Will we have a result object instantiated? If not - we'll simply return TRUE
  614. if ($return_object !== TRUE)
  615. {
  616. // If caching is enabled we'll auto-cleanup any existing files related to this particular URI
  617. if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
  618. {
  619. $this->CACHE->delete();
  620. }
  621. return TRUE;
  622. }
  623. // Load and instantiate the result driver
  624. $driver = $this->load_rdriver();
  625. $RES = new $driver($this);
  626. // Is query caching enabled? If so, we'll serialize the
  627. // result object and save it to a cache file.
  628. if ($this->cache_on === TRUE && $this->_cache_init())
  629. {
  630. // We'll create a new instance of the result object
  631. // only without the platform specific driver since
  632. // we can't use it with cached data (the query result
  633. // resource ID won't be any good once we've cached the
  634. // result object, so we'll have to compile the data
  635. // and save it)
  636. $CR = new CI_DB_result($this);
  637. $CR->result_object = $RES->result_object();
  638. $CR->result_array = $RES->result_array();
  639. $CR->num_rows = $RES->num_rows();
  640. // Reset these since cached objects can not utilize resource IDs.
  641. $CR->conn_id = NULL;
  642. $CR->result_id = NULL;
  643. $this->CACHE->write($sql, $CR);
  644. }
  645. return $RES;
  646. }
  647. // --------------------------------------------------------------------
  648. /**
  649. * Load the result drivers
  650. *
  651. * @return string the name of the result class
  652. */
  653. public function load_rdriver()
  654. {
  655. $driver = 'CI_DB_'.$this->dbdriver.'_result';
  656. if ( ! class_exists($driver, FALSE))
  657. {
  658. require_once(BASEPATH.'database/DB_result.php');
  659. require_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
  660. }
  661. return $driver;
  662. }
  663. // --------------------------------------------------------------------
  664. /**
  665. * Simple Query
  666. * This is a simplified version of the query() function. Internally
  667. * we only use it when running transaction commands since they do
  668. * not require all the features of the main query() function.
  669. *
  670. * @param string the sql query
  671. * @return mixed
  672. */
  673. public function simple_query($sql)
  674. {
  675. if ( ! $this->conn_id)
  676. {
  677. if ( ! $this->initialize())
  678. {
  679. return FALSE;
  680. }
  681. }
  682. return $this->_execute($sql);
  683. }
  684. // --------------------------------------------------------------------
  685. /**
  686. * Disable Transactions
  687. * This permits transactions to be disabled at run-time.
  688. *
  689. * @return void
  690. */
  691. public function trans_off()
  692. {
  693. $this->trans_enabled = FALSE;
  694. }
  695. // --------------------------------------------------------------------
  696. /**
  697. * Enable/disable Transaction Strict Mode
  698. *
  699. * When strict mode is enabled, if you are running multiple groups of
  700. * transactions, if one group fails all subsequent groups will be
  701. * rolled back.
  702. *
  703. * If strict mode is disabled, each group is treated autonomously,
  704. * meaning a failure of one group will not affect any others
  705. *
  706. * @param bool $mode = TRUE
  707. * @return void
  708. */
  709. public function trans_strict($mode = TRUE)
  710. {
  711. $this->trans_strict = is_bool($mode) ? $mode : TRUE;
  712. }
  713. // --------------------------------------------------------------------
  714. /**
  715. * Start Transaction
  716. *
  717. * @param bool $test_mode = FALSE
  718. * @return bool
  719. */
  720. public function trans_start($test_mode = FALSE)
  721. {
  722. if ( ! $this->trans_enabled)
  723. {
  724. return FALSE;
  725. }
  726. return $this->trans_begin($test_mode);
  727. }
  728. // --------------------------------------------------------------------
  729. /**
  730. * Complete Transaction
  731. *
  732. * @return bool
  733. */
  734. public function trans_complete()
  735. {
  736. if ( ! $this->trans_enabled)
  737. {
  738. return FALSE;
  739. }
  740. // The query() function will set this flag to FALSE in the event that a query failed
  741. if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
  742. {
  743. $this->trans_rollback();
  744. // If we are NOT running in strict mode, we will reset
  745. // the _trans_status flag so that subsequent groups of
  746. // transactions will be permitted.
  747. if ($this->trans_strict === FALSE)
  748. {
  749. $this->_trans_status = TRUE;
  750. }
  751. log_message('debug', 'DB Transaction Failure');
  752. return FALSE;
  753. }
  754. return $this->trans_commit();
  755. }
  756. // --------------------------------------------------------------------
  757. /**
  758. * Lets you retrieve the transaction flag to determine if it has failed
  759. *
  760. * @return bool
  761. */
  762. public function trans_status()
  763. {
  764. return $this->_trans_status;
  765. }
  766. // --------------------------------------------------------------------
  767. /**
  768. * Begin Transaction
  769. *
  770. * @param bool $test_mode
  771. * @return bool
  772. */
  773. public function trans_begin($test_mode = FALSE)
  774. {
  775. if ( ! $this->trans_enabled)
  776. {
  777. return FALSE;
  778. }
  779. // When transactions are nested we only begin/commit/rollback the outermost ones
  780. elseif ($this->_trans_depth > 0)
  781. {
  782. $this->_trans_depth++;
  783. return TRUE;
  784. }
  785. // Reset the transaction failure flag.
  786. // If the $test_mode flag is set to TRUE transactions will be rolled back
  787. // even if the queries produce a successful result.
  788. $this->_trans_failure = ($test_mode === TRUE);
  789. if ($this->_trans_begin())
  790. {
  791. $this->_trans_depth++;
  792. return TRUE;
  793. }
  794. return FALSE;
  795. }
  796. // --------------------------------------------------------------------
  797. /**
  798. * Commit Transaction
  799. *
  800. * @return bool
  801. */
  802. public function trans_commit()
  803. {
  804. if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
  805. {
  806. return FALSE;
  807. }
  808. // When transactions are nested we only begin/commit/rollback the outermost ones
  809. elseif ($this->_trans_depth > 1 OR $this->_trans_commit())
  810. {
  811. $this->_trans_depth--;
  812. return TRUE;
  813. }
  814. return FALSE;
  815. }
  816. // --------------------------------------------------------------------
  817. /**
  818. * Rollback Transaction
  819. *
  820. * @return bool
  821. */
  822. public function trans_rollback()
  823. {
  824. if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
  825. {
  826. return FALSE;
  827. }
  828. // When transactions are nested we only begin/commit/rollback the outermost ones
  829. elseif ($this->_trans_depth > 1 OR $this->_trans_rollback())
  830. {
  831. $this->_trans_depth--;
  832. return TRUE;
  833. }
  834. return FALSE;
  835. }
  836. // --------------------------------------------------------------------
  837. /**
  838. * Compile Bindings
  839. *
  840. * @param string the sql statement
  841. * @param array an array of bind data
  842. * @return string
  843. */
  844. public function compile_binds($sql, $binds)
  845. {
  846. if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
  847. {
  848. return $sql;
  849. }
  850. elseif ( ! is_array($binds))
  851. {
  852. $binds = array($binds);
  853. $bind_count = 1;
  854. }
  855. else
  856. {
  857. // Make sure we're using numeric keys
  858. $binds = array_values($binds);
  859. $bind_count = count($binds);
  860. }
  861. // We'll need the marker length later
  862. $ml = strlen($this->bind_marker);
  863. // Make sure not to replace a chunk inside a string that happens to match the bind marker
  864. if ($c = preg_match_all("/'[^']*'|\"[^\"]*\"/i", $sql, $matches))
  865. {
  866. $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
  867. str_replace($matches[0],
  868. str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
  869. $sql, $c),
  870. $matches, PREG_OFFSET_CAPTURE);
  871. // Bind values' count must match the count of markers in the query
  872. if ($bind_count !== $c)
  873. {
  874. return $sql;
  875. }
  876. }
  877. elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
  878. {
  879. return $sql;
  880. }
  881. do
  882. {
  883. $c--;
  884. $escaped_value = $this->escape($binds[$c]);
  885. if (is_array($escaped_value))
  886. {
  887. $escaped_value = '('.implode(',', $escaped_value).')';
  888. }
  889. $sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml);
  890. }
  891. while ($c !== 0);
  892. return $sql;
  893. }
  894. // --------------------------------------------------------------------
  895. /**
  896. * Determines if a query is a "write" type.
  897. *
  898. * @param string An SQL query string
  899. * @return bool
  900. */
  901. public function is_write_type($sql)
  902. {
  903. return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', $sql);
  904. }
  905. // --------------------------------------------------------------------
  906. /**
  907. * Calculate the aggregate query elapsed time
  908. *
  909. * @param int The number of decimal places
  910. * @return string
  911. */
  912. public function elapsed_time($decimals = 6)
  913. {
  914. return number_format($this->benchmark, $decimals);
  915. }
  916. // --------------------------------------------------------------------
  917. /**
  918. * Returns the total number of queries
  919. *
  920. * @return int
  921. */
  922. public function total_queries()
  923. {
  924. return $this->query_count;
  925. }
  926. // --------------------------------------------------------------------
  927. /**
  928. * Returns the last query that was executed
  929. *
  930. * @return string
  931. */
  932. public function last_query()
  933. {
  934. return end($this->queries);
  935. }
  936. // --------------------------------------------------------------------
  937. /**
  938. * "Smart" Escape String
  939. *
  940. * Escapes data based on type
  941. * Sets boolean and null types
  942. *
  943. * @param string
  944. * @return mixed
  945. */
  946. public function escape($str)
  947. {
  948. if (is_array($str))
  949. {
  950. $str = array_map(array(&$this, 'escape'), $str);
  951. return $str;
  952. }
  953. elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
  954. {
  955. return "'".$this->escape_str($str)."'";
  956. }
  957. elseif (is_bool($str))
  958. {
  959. return ($str === FALSE) ? 0 : 1;
  960. }
  961. elseif ($str === NULL)
  962. {
  963. return 'NULL';
  964. }
  965. return $str;
  966. }
  967. // --------------------------------------------------------------------
  968. /**
  969. * Escape String
  970. *
  971. * @param string|string[] $str Input string
  972. * @param bool $like Whether or not the string will be used in a LIKE condition
  973. * @return string
  974. */
  975. public function escape_str($str, $like = FALSE)
  976. {
  977. if (is_array($str))
  978. {
  979. foreach ($str as $key => $val)
  980. {
  981. $str[$key] = $this->escape_str($val, $like);
  982. }
  983. return $str;
  984. }
  985. $str = $this->_escape_str($str);
  986. // escape LIKE condition wildcards
  987. if ($like === TRUE)
  988. {
  989. return str_replace(
  990. array($this->_like_escape_chr, '%', '_'),
  991. array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
  992. $str
  993. );
  994. }
  995. return $str;
  996. }
  997. // --------------------------------------------------------------------
  998. /**
  999. * Escape LIKE String
  1000. *
  1001. * Calls the individual driver for platform
  1002. * specific escaping for LIKE conditions
  1003. *
  1004. * @param string|string[]
  1005. * @return mixed
  1006. */
  1007. public function escape_like_str($str)
  1008. {
  1009. return $this->escape_str($str, TRUE);
  1010. }
  1011. // --------------------------------------------------------------------
  1012. /**
  1013. * Platform-dependent string escape
  1014. *
  1015. * @param string
  1016. * @return string
  1017. */
  1018. protected function _escape_str($str)
  1019. {
  1020. return str_replace("'", "''", remove_invisible_characters($str, FALSE));
  1021. }
  1022. // --------------------------------------------------------------------
  1023. /**
  1024. * Primary
  1025. *
  1026. * Retrieves the primary key. It assumes that the row in the first
  1027. * position is the primary key
  1028. *
  1029. * @param string $table Table name
  1030. * @return string
  1031. */
  1032. public function primary($table)
  1033. {
  1034. $fields = $this->list_fields($table);
  1035. return is_array($fields) ? current($fields) : FALSE;
  1036. }
  1037. // --------------------------------------------------------------------
  1038. /**
  1039. * "Count All" query
  1040. *
  1041. * Generates a platform-specific query string that counts all records in
  1042. * the specified database
  1043. *
  1044. * @param string
  1045. * @return int
  1046. */
  1047. public function count_all($table = '')
  1048. {
  1049. if ($table === '')
  1050. {
  1051. return 0;
  1052. }
  1053. $query = $this->query($this->_count_string.$this->escape_identifiers('numrows').' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE));
  1054. if ($query->num_rows() === 0)
  1055. {
  1056. return 0;
  1057. }
  1058. $query = $query->row();
  1059. $this->_reset_select();
  1060. return (int) $query->numrows;
  1061. }
  1062. // --------------------------------------------------------------------
  1063. /**
  1064. * Returns an array of table names
  1065. *
  1066. * @param string $constrain_by_prefix = FALSE
  1067. * @return array
  1068. */
  1069. public function list_tables($constrain_by_prefix = FALSE)
  1070. {
  1071. // Is there a cached result?
  1072. if (isset($this->data_cache['table_names']))
  1073. {
  1074. return $this->data_cache['table_names'];
  1075. }
  1076. if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
  1077. {
  1078. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1079. }
  1080. $this->data_cache['table_names'] = array();
  1081. $query = $this->query($sql);
  1082. foreach ($query->result_array() as $row)
  1083. {
  1084. // Do we know from which column to get the table name?
  1085. if ( ! isset($key))
  1086. {
  1087. if (isset($row['table_name']))
  1088. {
  1089. $key = 'table_name';
  1090. }
  1091. elseif (isset($row['TABLE_NAME']))
  1092. {
  1093. $key = 'TABLE_NAME';
  1094. }
  1095. else
  1096. {
  1097. /* We have no other choice but to just get the first element's key.
  1098. * Due to array_shift() accepting its argument by reference, if
  1099. * E_STRICT is on, this would trigger a warning. So we'll have to
  1100. * assign it first.
  1101. */
  1102. $key = array_keys($row);
  1103. $key = array_shift($key);
  1104. }
  1105. }
  1106. $this->data_cache['table_names'][] = $row[$key];
  1107. }
  1108. return $this->data_cache['table_names'];
  1109. }
  1110. // --------------------------------------------------------------------
  1111. /**
  1112. * Determine if a particular table exists
  1113. *
  1114. * @param string $table_name
  1115. * @return bool
  1116. */
  1117. public function table_exists($table_name)
  1118. {
  1119. return in_array($this->protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables());
  1120. }
  1121. // --------------------------------------------------------------------
  1122. /**
  1123. * Fetch Field Names
  1124. *
  1125. * @param string $table Table name
  1126. * @return array
  1127. */
  1128. public function list_fields($table)
  1129. {
  1130. // Is there a cached result?
  1131. if (isset($this->data_cache['field_names'][$table]))
  1132. {
  1133. return $this->data_cache['field_names'][$table];
  1134. }
  1135. if (FALSE === ($sql = $this->_list_columns($table)))
  1136. {
  1137. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1138. }
  1139. $query = $this->query($sql);
  1140. $this->data_cache['field_names'][$table] = array();
  1141. foreach ($query->result_array() as $row)
  1142. {
  1143. // Do we know from where to get the column's name?
  1144. if ( ! isset($key))
  1145. {
  1146. if (isset($row['column_name']))
  1147. {
  1148. $key = 'column_name';
  1149. }
  1150. elseif (isset($row['COLUMN_NAME']))
  1151. {
  1152. $key = 'COLUMN_NAME';
  1153. }
  1154. else
  1155. {
  1156. // We have no other choice but to just get the first element's key.
  1157. $key = key($row);
  1158. }
  1159. }
  1160. $this->data_cache['field_names'][$table][] = $row[$key];
  1161. }
  1162. return $this->data_cache['field_names'][$table];
  1163. }
  1164. // --------------------------------------------------------------------
  1165. /**
  1166. * Determine if a particular field exists
  1167. *
  1168. * @param string
  1169. * @param string
  1170. * @return bool
  1171. */
  1172. public function field_exists($field_name, $table_name)
  1173. {
  1174. return in_array($field_name, $this->list_fields($table_name));
  1175. }
  1176. // --------------------------------------------------------------------
  1177. /**
  1178. * Returns an object with field data
  1179. *
  1180. * @param string $table the table name
  1181. * @return array
  1182. */
  1183. public function field_data($table)
  1184. {
  1185. $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE)));
  1186. return ($query) ? $query->field_data() : FALSE;
  1187. }
  1188. // --------------------------------------------------------------------
  1189. /**
  1190. * Escape the SQL Identifiers
  1191. *
  1192. * This function escapes column and table names
  1193. *
  1194. * @param mixed
  1195. * @return mixed
  1196. */
  1197. public function escape_identifiers($item)
  1198. {
  1199. if ($this->_escape_char === '' OR empty($item) OR in_array($item, $this->_reserved_identifiers))
  1200. {
  1201. return $item;
  1202. }
  1203. elseif (is_array($item))
  1204. {
  1205. foreach ($item as $key => $value)
  1206. {
  1207. $item[$key] = $this->escape_identifiers($value);
  1208. }
  1209. return $item;
  1210. }
  1211. // Avoid breaking functions and literal values inside queries
  1212. elseif (ctype_digit($item) OR $item[0] === "'" OR ($this->_escape_char !== '"' && $item[0] === '"') OR strpos($item, '(') !== FALSE)
  1213. {
  1214. return $item;
  1215. }
  1216. static $preg_ec = array();
  1217. if (empty($preg_ec))
  1218. {
  1219. if (is_array($this->_escape_char))
  1220. {
  1221. $preg_ec = array(
  1222. preg_quote($this->_escape_char[0], '/'),
  1223. preg_quote($this->_escape_char[1], '/'),
  1224. $this->_escape_char[0],
  1225. $this->_escape_char[1]
  1226. );
  1227. }
  1228. else
  1229. {
  1230. $preg_ec[0] = $preg_ec[1] = preg_quote($this->_escape_char, '/');
  1231. $preg_ec[2] = $preg_ec[3] = $this->_escape_char;
  1232. }
  1233. }
  1234. foreach ($this->_reserved_identifiers as $id)
  1235. {
  1236. if (strpos($item, '.'.$id) !== FALSE)
  1237. {
  1238. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?\./i', $preg_ec[2].'$1'.$preg_ec[3].'.', $item);
  1239. }
  1240. }
  1241. return preg_replace('/'.$preg_ec[0].'?([^'.$preg_ec[1].'\.]+)'.$preg_ec[1].'?(\.)?/i', $preg_ec[2].'$1'.$preg_ec[3].'$2', $item);
  1242. }
  1243. // --------------------------------------------------------------------
  1244. /**
  1245. * Generate an insert string
  1246. *
  1247. * @param string the table upon which the query will be performed
  1248. * @param array an associative array data of key/values
  1249. * @return string
  1250. */
  1251. public function insert_string($table, $data)
  1252. {
  1253. $fields = $values = array();
  1254. foreach ($data as $key => $val)
  1255. {
  1256. $fields[] = $this->escape_identifiers($key);
  1257. $values[] = $this->escape($val);
  1258. }
  1259. return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
  1260. }
  1261. // --------------------------------------------------------------------
  1262. /**
  1263. * Insert statement
  1264. *
  1265. * Generates a platform-specific insert string from the supplied data
  1266. *
  1267. * @param string the table name
  1268. * @param array the insert keys
  1269. * @param array the insert values
  1270. * @return string
  1271. */
  1272. protected function _insert($table, $keys, $values)
  1273. {
  1274. return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
  1275. }
  1276. // --------------------------------------------------------------------
  1277. /**
  1278. * Generate an update string
  1279. *
  1280. * @param string the table upon which the query will be performed
  1281. * @param array an associative array data of key/values
  1282. * @param mixed the "where" statement
  1283. * @return string
  1284. */
  1285. public function update_string($table, $data, $where)
  1286. {
  1287. if (empty($where))
  1288. {
  1289. return FALSE;
  1290. }
  1291. $this->where($where);
  1292. $fields = array();
  1293. foreach ($data as $key => $val)
  1294. {
  1295. $fields[$this->protect_identifiers($key)] = $this->escape($val);
  1296. }
  1297. $sql = $this->_update($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields);
  1298. $this->_reset_write();
  1299. return $sql;
  1300. }
  1301. // --------------------------------------------------------------------
  1302. /**
  1303. * Update statement
  1304. *
  1305. * Generates a platform-specific update string from the supplied data
  1306. *
  1307. * @param string the table name
  1308. * @param array the update data
  1309. * @return string
  1310. */
  1311. protected function _update($table, $values)
  1312. {
  1313. foreach ($values as $key => $val)
  1314. {
  1315. $valstr[] = $key.' = '.$val;
  1316. }
  1317. return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
  1318. .$this->_compile_wh('qb_where')
  1319. .$this->_compile_order_by()
  1320. .($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
  1321. }
  1322. // --------------------------------------------------------------------
  1323. /**
  1324. * Tests whether the string has an SQL operator
  1325. *
  1326. * @param string
  1327. * @return bool
  1328. */
  1329. protected function _has_operator($str)
  1330. {
  1331. return (bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($str));
  1332. }
  1333. // --------------------------------------------------------------------
  1334. /**
  1335. * Returns the SQL string operator
  1336. *
  1337. * @param string
  1338. * @return string
  1339. */
  1340. protected function _get_operator($str)
  1341. {
  1342. static $_operators;
  1343. if (empty($_operators))
  1344. {
  1345. $_les = ($this->_like_escape_str !== '')
  1346. ? '\s+'.preg_quote(trim(sprintf($this->_like_escape_str, $this->_like_escape_chr)), '/')
  1347. : '';
  1348. $_operators = array(
  1349. '\s*(?:<|>|!)?=\s*', // =, <=, >=, !=
  1350. '\s*<>?\s*', // <, <>
  1351. '\s*>\s*', // >
  1352. '\s+IS NULL', // IS NULL
  1353. '\s+IS NOT NULL', // IS NOT NULL
  1354. '\s+EXISTS\s*\(.*\)', // EXISTS(sql)
  1355. '\s+NOT EXISTS\s*\(.*\)', // NOT EXISTS(sql)
  1356. '\s+BETWEEN\s+', // BETWEEN value AND value
  1357. '\s+IN\s*\(.*\)', // IN(list)
  1358. '\s+NOT IN\s*\(.*\)', // NOT IN (list)
  1359. '\s+LIKE\s+\S.*('.$_les.')?', // LIKE 'expr'[ ESCAPE '%s']
  1360. '\s+NOT LIKE\s+\S.*('.$_les.')?' // NOT LIKE 'expr'[ ESCAPE '%s']
  1361. );
  1362. }
  1363. return preg_match('/'.implode('|', $_operators).'/i', $str, $match)
  1364. ? $match[0] : FALSE;
  1365. }
  1366. // --------------------------------------------------------------------
  1367. /**
  1368. * Enables a native PHP function to be run, using a platform agnostic wrapper.
  1369. *
  1370. * @param string $function Function name
  1371. * @return mixed
  1372. */
  1373. public function call_function($function)
  1374. {
  1375. $driver = ($this->dbdriver === 'postgre') ? 'pg_' : $this->dbdriver.'_';
  1376. if (FALSE === strpos($driver, $function))
  1377. {
  1378. $function = $driver.$function;
  1379. }
  1380. if ( ! function_exists($function))
  1381. {
  1382. return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
  1383. }
  1384. return (func_num_args() > 1)
  1385. ? call_user_func_array($function, array_slice(func_get_args(), 1))
  1386. : call_user_func($function);
  1387. }
  1388. // --------------------------------------------------------------------
  1389. /**
  1390. * Set Cache Directory Path
  1391. *
  1392. * @param string the path to the cache directory
  1393. * @return void
  1394. */
  1395. public function cache_set_path($path = '')
  1396. {
  1397. $this->cachedir = $path;
  1398. }
  1399. // --------------------------------------------------------------------
  1400. /**
  1401. * Enable Query Caching
  1402. *
  1403. * @return bool cache_on value
  1404. */
  1405. public function cache_on()
  1406. {
  1407. return $this->cache_on = TRUE;
  1408. }
  1409. // --------------------------------------------------------------------
  1410. /**
  1411. * Disable Query Caching
  1412. *
  1413. * @return bool cache_on value
  1414. */
  1415. public function cache_off()
  1416. {
  1417. return $this->cache_on = FALSE;
  1418. }
  1419. // --------------------------------------------------------------------
  1420. /**
  1421. * Delete the cache files associated with a particular URI
  1422. *
  1423. * @param string $segment_one = ''
  1424. * @param string $segment_two = ''
  1425. * @return bool
  1426. */
  1427. public function cache_delete($segment_one = '', $segment_two = '')
  1428. {
  1429. return $this->_cache_init()
  1430. ? $this->CACHE->delete($segment_one, $segment_two)
  1431. : FALSE;
  1432. }
  1433. // --------------------------------------------------------------------
  1434. /**
  1435. * Delete All cache files
  1436. *
  1437. * @return bool
  1438. */
  1439. public function cache_delete_all()
  1440. {
  1441. return $this->_cache_init()
  1442. ? $this->CACHE->delete_all()
  1443. : FALSE;
  1444. }
  1445. // --------------------------------------------------------------------
  1446. /**
  1447. * Initialize the Cache Class
  1448. *
  1449. * @return bool
  1450. */
  1451. protected function _cache_init()
  1452. {
  1453. if ( ! class_exists('CI_DB_Cache', FALSE))
  1454. {
  1455. require_once(BASEPATH.'database/DB_cache.php');
  1456. }
  1457. elseif (is_object($this->CACHE))
  1458. {
  1459. return TRUE;
  1460. }
  1461. $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
  1462. return TRUE;
  1463. }
  1464. // --------------------------------------------------------------------
  1465. /**
  1466. * Close DB Connection
  1467. *
  1468. * @return void
  1469. */
  1470. public function close()
  1471. {
  1472. if ($this->conn_id)
  1473. {
  1474. $this->_close();
  1475. $this->conn_id = FALSE;
  1476. }
  1477. }
  1478. // --------------------------------------------------------------------
  1479. /**
  1480. * Close DB Connection
  1481. *
  1482. * This method would be overridden by most of the drivers.
  1483. *
  1484. * @return void
  1485. */
  1486. protected function _close()
  1487. {
  1488. $this->conn_id = FALSE;
  1489. }
  1490. // --------------------------------------------------------------------
  1491. /**
  1492. * Display an error message
  1493. *
  1494. * @param string the error message
  1495. * @param string any "swap" values
  1496. * @param bool whether to localize the message
  1497. * @return string sends the application/views/errors/error_db.php template
  1498. */
  1499. public function display_error($error = '', $swap = '', $native = FALSE)
  1500. {
  1501. $LANG =& load_class('Lang', 'core');
  1502. $LANG->load('db');
  1503. $heading = $LANG->line('db_error_heading');
  1504. if ($native === TRUE)
  1505. {
  1506. $message = (array) $error;
  1507. }
  1508. else
  1509. {
  1510. $message = is_array($error) ? $error : array(str_replace('%s', $swap, $LANG->line($error)));
  1511. }
  1512. // Find the most likely culprit of the error by going through
  1513. // the backtrace until the source file is no longer in the
  1514. // database folder.
  1515. $trace = debug_backtrace();
  1516. foreach ($trace as $call)
  1517. {
  1518. if (isset($call['file'], $call['class']))
  1519. {
  1520. // We'll need this on Windows, as APPPATH and BASEPATH will always use forward slashes
  1521. if (DIRECTORY_SEPARATOR !== '/')
  1522. {
  1523. $call['file'] = str_replace('\\', '/', $call['file']);
  1524. }
  1525. if (strpos($call['file'], BASEPATH.'database') === FALSE && strpos($call['class'], 'Loader') === FALSE)
  1526. {
  1527. // Found it - use a relative path for safety
  1528. $message[] = 'Filename: '.str_replace(array(APPPATH, BASEPATH), '', $call['file']);
  1529. $message[] = 'Line Number: '.$call['line'];
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. $error =& load_class('Exceptions', 'core');
  1535. echo $error->show_error($heading, $message, 'error_db');
  1536. exit(8); // EXIT_DATABASE
  1537. }
  1538. // --------------------------------------------------------------------
  1539. /**
  1540. * Protect Identifiers
  1541. *
  1542. * This function is used extensively by the Query Builder class, and by
  1543. * a couple functions in this class.
  1544. * It takes a column or table name (optionally with an alias) and inserts
  1545. * the table prefix onto it. Some logic is necessary in order to deal with
  1546. * column names that include the path. Consider a query like this:
  1547. *
  1548. * SELECT hostname.database.table.column AS c FROM hostname.database.table
  1549. *
  1550. * Or a query with aliasing:
  1551. *
  1552. * SELECT m.member_id, m.member_name FROM members AS m
  1553. *
  1554. * Since the column name can include up to four segments (host, DB, table, column)
  1555. * or also have an alias prefix, we need to do a bit of work to figure this out and
  1556. * insert the table prefix (if it exists) in the proper position, and escape only
  1557. * the correct identifiers.
  1558. *
  1559. * @param string
  1560. * @param bool
  1561. * @param mixed
  1562. * @param bool
  1563. * @return string
  1564. */
  1565. public function protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
  1566. {
  1567. if ( ! is_bool($protect_identifiers))
  1568. {
  1569. $protect_identifiers = $this->_protect_identifiers;
  1570. }
  1571. if (is_array($item))
  1572. {
  1573. $escaped_array = array();
  1574. foreach ($item as $k => $v)
  1575. {
  1576. $escaped_array[$this->protect_identifiers($k)] = $this->protect_identifiers($v, $prefix_single, $protect_identifiers, $field_exists);
  1577. }
  1578. return $escaped_array;
  1579. }
  1580. // This is basically a bug fix for queries that use MAX, MIN, etc.
  1581. // If a parenthesis is found we know that we do not need to
  1582. // escape the data or add a prefix. There's probably a more graceful
  1583. // way to deal with this, but I'm not thinking of it -- Rick
  1584. //
  1585. // Added exception for single quotes as well, we don't want to alter
  1586. // literal strings. -- Narf
  1587. if (strcspn($item, "()'") !== strlen($item))
  1588. {
  1589. return $item;
  1590. }
  1591. // Convert tabs or multiple spaces into single spaces
  1592. $item = preg_replace('/\s+/', ' ', trim($item));
  1593. // If the item has an alias declaration we remove it and set it aside.
  1594. // Note: strripos() is used in order to support spaces in table names
  1595. if ($offset = strripos($item, ' AS '))
  1596. {
  1597. $alias = ($protect_identifiers)
  1598. ? substr($item, $offset, 4).$this->escape_identifiers(substr($item, $offset + 4))
  1599. : substr($item, $offset);
  1600. $item = substr($item, 0, $offset);
  1601. }
  1602. elseif ($offset = strrpos($item, ' '))
  1603. {
  1604. $alias = ($protect_identifiers)
  1605. ? ' '.$this->escape_identifiers(substr($item, $offset + 1))
  1606. : substr($item, $offset);
  1607. $item = substr($item, 0, $offset);
  1608. }
  1609. else
  1610. {
  1611. $alias = '';
  1612. }
  1613. // Break the string apart if it contains periods, then insert the table prefix
  1614. // in the correct location, assuming the period doesn't indicate that we're dealing
  1615. // with an alias. While we're at it, we will escape the components
  1616. if (strpos($item, '.') !== FALSE)
  1617. {
  1618. $parts = explode('.', $item);
  1619. // Does the first segment of the exploded item match
  1620. // one of the aliases previously identified? If so,
  1621. // we have nothing more to do other than escape the item
  1622. //
  1623. // NOTE: The ! empty() condition prevents this method
  1624. // from breaking when QB isn't enabled.
  1625. if ( ! empty($this->qb_aliased_tables) && in_array($parts[0], $this->qb_aliased_tables))
  1626. {
  1627. if ($protect_identifiers === TRUE)
  1628. {
  1629. foreach ($parts as $key => $val)
  1630. {
  1631. if ( ! in_array($val, $this->_reserved_identifiers))
  1632. {
  1633. $parts[$key] = $this->escape_identifiers($val);
  1634. }
  1635. }
  1636. $item = implode('.', $parts);
  1637. }
  1638. return $item.$alias;
  1639. }
  1640. // Is there a table prefix defined in the config file? If not, no need to do anything
  1641. if ($this->dbprefix !== '')
  1642. {
  1643. // We now add the table prefix based on some logic.
  1644. // Do we have 4 segments (hostname.database.table.column)?
  1645. // If so, we add the table prefix to the column name in the 3rd segment.
  1646. if (isset($parts[3]))
  1647. {
  1648. $i = 2;
  1649. }
  1650. // Do we have 3 segments (database.table.column)?
  1651. // If so, we add the table prefix to the column name in 2nd position
  1652. elseif (isset($parts[2]))
  1653. {
  1654. $i = 1;
  1655. }
  1656. // Do we have 2 segments (table.column)?
  1657. // If so, we add the table prefix to the column name in 1st segment
  1658. else
  1659. {
  1660. $i = 0;
  1661. }
  1662. // This flag is set when the supplied $item does not contain a field name.
  1663. // This can happen when this function is being called from a JOIN.
  1664. if ($field_exists === FALSE)
  1665. {
  1666. $i++;
  1667. }
  1668. // Verify table prefix and replace if necessary
  1669. if ($this->swap_pre !== '' && strpos($parts[$i], $this->swap_pre) === 0)
  1670. {
  1671. $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]);
  1672. }
  1673. // We only add the table prefix if it does not already exist
  1674. elseif (strpos($parts[$i], $this->dbprefix) !== 0)
  1675. {
  1676. $parts[$i] = $this->dbprefix.$parts[$i];
  1677. }
  1678. // Put the parts back together
  1679. $item = implode('.', $parts);
  1680. }
  1681. if ($protect_identifiers === TRUE)
  1682. {
  1683. $item = $this->escape_identifiers($item);
  1684. }
  1685. return $item.$alias;
  1686. }
  1687. // Is there a table prefix? If not, no need to insert it
  1688. if ($this->dbprefix !== '')
  1689. {
  1690. // Verify table prefix and replace if necessary
  1691. if ($this->swap_pre !== '' && strpos($item, $this->swap_pre) === 0)
  1692. {
  1693. $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item);
  1694. }
  1695. // Do we prefix an item with no segments?
  1696. elseif ($prefix_single === TRUE && strpos($item, $this->dbprefix) !== 0)
  1697. {
  1698. $item = $this->dbprefix.$item;
  1699. }
  1700. }
  1701. if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers))
  1702. {
  1703. $item = $this->escape_identifiers($item);
  1704. }
  1705. return $item.$alias;
  1706. }
  1707. // --------------------------------------------------------------------
  1708. /**
  1709. * Dummy method that allows Query Builder class to be disabled
  1710. * and keep count_all() working.
  1711. *
  1712. * @return void
  1713. */
  1714. protected function _reset_select()
  1715. {
  1716. }
  1717. }