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.

544 lines
13 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.3.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * MySQLi Database Adapter Class
  41. *
  42. * Note: _DB is an extender class that the app controller
  43. * creates dynamically based on whether the query builder
  44. * class is being used or not.
  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. class CI_DB_mysqli_driver extends CI_DB {
  53. /**
  54. * Database driver
  55. *
  56. * @var string
  57. */
  58. public $dbdriver = 'mysqli';
  59. /**
  60. * Compression flag
  61. *
  62. * @var bool
  63. */
  64. public $compress = FALSE;
  65. /**
  66. * DELETE hack flag
  67. *
  68. * Whether to use the MySQL "delete hack" which allows the number
  69. * of affected rows to be shown. Uses a preg_replace when enabled,
  70. * adding a bit more processing to all queries.
  71. *
  72. * @var bool
  73. */
  74. public $delete_hack = TRUE;
  75. /**
  76. * Strict ON flag
  77. *
  78. * Whether we're running in strict SQL mode.
  79. *
  80. * @var bool
  81. */
  82. public $stricton;
  83. // --------------------------------------------------------------------
  84. /**
  85. * Identifier escape character
  86. *
  87. * @var string
  88. */
  89. protected $_escape_char = '`';
  90. // --------------------------------------------------------------------
  91. /**
  92. * MySQLi object
  93. *
  94. * Has to be preserved without being assigned to $conn_id.
  95. *
  96. * @var MySQLi
  97. */
  98. protected $_mysqli;
  99. // --------------------------------------------------------------------
  100. /**
  101. * Database connection
  102. *
  103. * @param bool $persistent
  104. * @return object
  105. */
  106. public function db_connect($persistent = FALSE)
  107. {
  108. // Do we have a socket path?
  109. if ($this->hostname[0] === '/')
  110. {
  111. $hostname = NULL;
  112. $port = NULL;
  113. $socket = $this->hostname;
  114. }
  115. else
  116. {
  117. $hostname = ($persistent === TRUE)
  118. ? 'p:'.$this->hostname : $this->hostname;
  119. $port = empty($this->port) ? NULL : $this->port;
  120. $socket = NULL;
  121. }
  122. $client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
  123. $this->_mysqli = mysqli_init();
  124. $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
  125. if (isset($this->stricton))
  126. {
  127. if ($this->stricton)
  128. {
  129. $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")');
  130. }
  131. else
  132. {
  133. $this->_mysqli->options(MYSQLI_INIT_COMMAND,
  134. 'SET SESSION sql_mode =
  135. REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  136. @@sql_mode,
  137. "STRICT_ALL_TABLES,", ""),
  138. ",STRICT_ALL_TABLES", ""),
  139. "STRICT_ALL_TABLES", ""),
  140. "STRICT_TRANS_TABLES,", ""),
  141. ",STRICT_TRANS_TABLES", ""),
  142. "STRICT_TRANS_TABLES", "")'
  143. );
  144. }
  145. }
  146. if (is_array($this->encrypt))
  147. {
  148. $ssl = array();
  149. empty($this->encrypt['ssl_key']) OR $ssl['key'] = $this->encrypt['ssl_key'];
  150. empty($this->encrypt['ssl_cert']) OR $ssl['cert'] = $this->encrypt['ssl_cert'];
  151. empty($this->encrypt['ssl_ca']) OR $ssl['ca'] = $this->encrypt['ssl_ca'];
  152. empty($this->encrypt['ssl_capath']) OR $ssl['capath'] = $this->encrypt['ssl_capath'];
  153. empty($this->encrypt['ssl_cipher']) OR $ssl['cipher'] = $this->encrypt['ssl_cipher'];
  154. if ( ! empty($ssl))
  155. {
  156. if (isset($this->encrypt['ssl_verify']))
  157. {
  158. if ($this->encrypt['ssl_verify'])
  159. {
  160. defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE);
  161. }
  162. // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
  163. // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
  164. // constant ...
  165. //
  166. // https://secure.php.net/ChangeLog-5.php#5.6.16
  167. // https://bugs.php.net/bug.php?id=68344
  168. elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT'))
  169. {
  170. $client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
  171. }
  172. }
  173. $client_flags |= MYSQLI_CLIENT_SSL;
  174. $this->_mysqli->ssl_set(
  175. isset($ssl['key']) ? $ssl['key'] : NULL,
  176. isset($ssl['cert']) ? $ssl['cert'] : NULL,
  177. isset($ssl['ca']) ? $ssl['ca'] : NULL,
  178. isset($ssl['capath']) ? $ssl['capath'] : NULL,
  179. isset($ssl['cipher']) ? $ssl['cipher'] : NULL
  180. );
  181. }
  182. }
  183. if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags))
  184. {
  185. // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails
  186. if (
  187. ($client_flags & MYSQLI_CLIENT_SSL)
  188. && version_compare($this->_mysqli->client_info, '5.7.3', '<=')
  189. && empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
  190. )
  191. {
  192. $this->_mysqli->close();
  193. $message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
  194. log_message('error', $message);
  195. return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE;
  196. }
  197. return $this->_mysqli;
  198. }
  199. return FALSE;
  200. }
  201. // --------------------------------------------------------------------
  202. /**
  203. * Reconnect
  204. *
  205. * Keep / reestablish the db connection if no queries have been
  206. * sent for a length of time exceeding the server's idle timeout
  207. *
  208. * @return void
  209. */
  210. public function reconnect()
  211. {
  212. if ($this->conn_id !== FALSE && $this->conn_id->ping() === FALSE)
  213. {
  214. $this->conn_id = FALSE;
  215. }
  216. }
  217. // --------------------------------------------------------------------
  218. /**
  219. * Select the database
  220. *
  221. * @param string $database
  222. * @return bool
  223. */
  224. public function db_select($database = '')
  225. {
  226. if ($database === '')
  227. {
  228. $database = $this->database;
  229. }
  230. if ($this->conn_id->select_db($database))
  231. {
  232. $this->database = $database;
  233. $this->data_cache = array();
  234. return TRUE;
  235. }
  236. return FALSE;
  237. }
  238. // --------------------------------------------------------------------
  239. /**
  240. * Set client character set
  241. *
  242. * @param string $charset
  243. * @return bool
  244. */
  245. protected function _db_set_charset($charset)
  246. {
  247. return $this->conn_id->set_charset($charset);
  248. }
  249. // --------------------------------------------------------------------
  250. /**
  251. * Database version number
  252. *
  253. * @return string
  254. */
  255. public function version()
  256. {
  257. if (isset($this->data_cache['version']))
  258. {
  259. return $this->data_cache['version'];
  260. }
  261. return $this->data_cache['version'] = $this->conn_id->server_info;
  262. }
  263. // --------------------------------------------------------------------
  264. /**
  265. * Execute the query
  266. *
  267. * @param string $sql an SQL query
  268. * @return mixed
  269. */
  270. protected function _execute($sql)
  271. {
  272. return $this->conn_id->query($this->_prep_query($sql));
  273. }
  274. // --------------------------------------------------------------------
  275. /**
  276. * Prep the query
  277. *
  278. * If needed, each database adapter can prep the query string
  279. *
  280. * @param string $sql an SQL query
  281. * @return string
  282. */
  283. protected function _prep_query($sql)
  284. {
  285. // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
  286. // modifies the query so that it a proper number of affected rows is returned.
  287. if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
  288. {
  289. return trim($sql).' WHERE 1=1';
  290. }
  291. return $sql;
  292. }
  293. // --------------------------------------------------------------------
  294. /**
  295. * Begin Transaction
  296. *
  297. * @return bool
  298. */
  299. protected function _trans_begin()
  300. {
  301. $this->conn_id->autocommit(FALSE);
  302. return is_php('5.5')
  303. ? $this->conn_id->begin_transaction()
  304. : $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
  305. }
  306. // --------------------------------------------------------------------
  307. /**
  308. * Commit Transaction
  309. *
  310. * @return bool
  311. */
  312. protected function _trans_commit()
  313. {
  314. if ($this->conn_id->commit())
  315. {
  316. $this->conn_id->autocommit(TRUE);
  317. return TRUE;
  318. }
  319. return FALSE;
  320. }
  321. // --------------------------------------------------------------------
  322. /**
  323. * Rollback Transaction
  324. *
  325. * @return bool
  326. */
  327. protected function _trans_rollback()
  328. {
  329. if ($this->conn_id->rollback())
  330. {
  331. $this->conn_id->autocommit(TRUE);
  332. return TRUE;
  333. }
  334. return FALSE;
  335. }
  336. // --------------------------------------------------------------------
  337. /**
  338. * Platform-dependent string escape
  339. *
  340. * @param string
  341. * @return string
  342. */
  343. protected function _escape_str($str)
  344. {
  345. return $this->conn_id->real_escape_string($str);
  346. }
  347. // --------------------------------------------------------------------
  348. /**
  349. * Affected Rows
  350. *
  351. * @return int
  352. */
  353. public function affected_rows()
  354. {
  355. return $this->conn_id->affected_rows;
  356. }
  357. // --------------------------------------------------------------------
  358. /**
  359. * Insert ID
  360. *
  361. * @return int
  362. */
  363. public function insert_id()
  364. {
  365. return $this->conn_id->insert_id;
  366. }
  367. // --------------------------------------------------------------------
  368. /**
  369. * List table query
  370. *
  371. * Generates a platform-specific query string so that the table names can be fetched
  372. *
  373. * @param bool $prefix_limit
  374. * @return string
  375. */
  376. protected function _list_tables($prefix_limit = FALSE)
  377. {
  378. $sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database);
  379. if ($prefix_limit !== FALSE && $this->dbprefix !== '')
  380. {
  381. return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
  382. }
  383. return $sql;
  384. }
  385. // --------------------------------------------------------------------
  386. /**
  387. * Show column query
  388. *
  389. * Generates a platform-specific query string so that the column names can be fetched
  390. *
  391. * @param string $table
  392. * @return string
  393. */
  394. protected function _list_columns($table = '')
  395. {
  396. return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE);
  397. }
  398. // --------------------------------------------------------------------
  399. /**
  400. * Returns an object with field data
  401. *
  402. * @param string $table
  403. * @return array
  404. */
  405. public function field_data($table)
  406. {
  407. if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE)
  408. {
  409. return FALSE;
  410. }
  411. $query = $query->result_object();
  412. $retval = array();
  413. for ($i = 0, $c = count($query); $i < $c; $i++)
  414. {
  415. $retval[$i] = new stdClass();
  416. $retval[$i]->name = $query[$i]->Field;
  417. sscanf($query[$i]->Type, '%[a-z](%d)',
  418. $retval[$i]->type,
  419. $retval[$i]->max_length
  420. );
  421. $retval[$i]->default = $query[$i]->Default;
  422. $retval[$i]->primary_key = (int) ($query[$i]->Key === 'PRI');
  423. }
  424. return $retval;
  425. }
  426. // --------------------------------------------------------------------
  427. /**
  428. * Error
  429. *
  430. * Returns an array containing code and message of the last
  431. * database error that has occurred.
  432. *
  433. * @return array
  434. */
  435. public function error()
  436. {
  437. if ( ! empty($this->_mysqli->connect_errno))
  438. {
  439. return array(
  440. 'code' => $this->_mysqli->connect_errno,
  441. 'message' => $this->_mysqli->connect_error
  442. );
  443. }
  444. return array('code' => $this->conn_id->errno, 'message' => $this->conn_id->error);
  445. }
  446. // --------------------------------------------------------------------
  447. /**
  448. * FROM tables
  449. *
  450. * Groups tables in FROM clauses if needed, so there is no confusion
  451. * about operator precedence.
  452. *
  453. * @return string
  454. */
  455. protected function _from_tables()
  456. {
  457. if ( ! empty($this->qb_join) && count($this->qb_from) > 1)
  458. {
  459. return '('.implode(', ', $this->qb_from).')';
  460. }
  461. return implode(', ', $this->qb_from);
  462. }
  463. // --------------------------------------------------------------------
  464. /**
  465. * Close DB Connection
  466. *
  467. * @return void
  468. */
  469. protected function _close()
  470. {
  471. $this->conn_id->close();
  472. }
  473. }