PageRenderTime 54ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/common/libraries/plugin/pear/MDB2/Driver/mysqli.php

https://bitbucket.org/cbenelug/chamilo
PHP | 2043 lines | 1329 code | 187 blank | 527 comment | 232 complexity | 6453067155dacf7c4e23d7e0e1b5b5d7 MD5 | raw file
Possible License(s): GPL-3.0, MIT, GPL-2.0, BSD-3-Clause, LGPL-2.1, LGPL-3.0
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mysqli.php 137 2009-11-09 13:24:37Z vanpouckesven $
  47. //
  48. /**
  49. * MDB2 MySQLi driver
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_mysqli extends MDB2_Driver_Common
  56. {
  57. // {{{ properties
  58. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
  59. var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
  60. var $sql_comments = array(array('start' => '-- ', 'end' => "\n", 'escape' => false),
  61. array('start' => '#', 'end' => "\n", 'escape' => false),
  62. array('start' => '/*', 'end' => '*/', 'escape' => false));
  63. var $server_capabilities_checked = false;
  64. var $start_transaction = false;
  65. var $varchar_max_length = 255;
  66. // }}}
  67. // {{{ constructor
  68. /**
  69. * Constructor
  70. */
  71. function __construct()
  72. {
  73. parent :: __construct();
  74. $this->phptype = 'mysqli';
  75. $this->dbsyntax = 'mysql';
  76. $this->supported['sequences'] = 'emulated';
  77. $this->supported['indexes'] = true;
  78. $this->supported['affected_rows'] = true;
  79. $this->supported['transactions'] = false;
  80. $this->supported['savepoints'] = false;
  81. $this->supported['summary_functions'] = true;
  82. $this->supported['order_by_text'] = true;
  83. $this->supported['current_id'] = 'emulated';
  84. $this->supported['limit_queries'] = true;
  85. $this->supported['LOBs'] = true;
  86. $this->supported['replace'] = true;
  87. $this->supported['sub_selects'] = 'emulated';
  88. $this->supported['triggers'] = false;
  89. $this->supported['auto_increment'] = true;
  90. $this->supported['primary_key'] = true;
  91. $this->supported['result_introspection'] = true;
  92. $this->supported['prepared_statements'] = 'emulated';
  93. $this->supported['identifier_quoting'] = true;
  94. $this->supported['pattern_escaping'] = true;
  95. $this->supported['new_link'] = true;
  96. $this->options['DBA_username'] = false;
  97. $this->options['DBA_password'] = false;
  98. $this->options['default_table_type'] = '';
  99. $this->options['multi_query'] = false;
  100. $this->options['max_identifiers_length'] = 64;
  101. $this->_reCheckSupportedOptions();
  102. }
  103. // }}}
  104. // {{{ _reCheckSupportedOptions()
  105. /**
  106. * If the user changes certain options, other capabilities may depend
  107. * on the new settings, so we need to check them (again).
  108. *
  109. * @access private
  110. */
  111. function _reCheckSupportedOptions()
  112. {
  113. $this->supported['transactions'] = $this->options['use_transactions'];
  114. $this->supported['savepoints'] = $this->options['use_transactions'];
  115. if ($this->options['default_table_type'])
  116. {
  117. switch (strtoupper($this->options['default_table_type']))
  118. {
  119. case 'BLACKHOLE' :
  120. case 'MEMORY' :
  121. case 'ARCHIVE' :
  122. case 'CSV' :
  123. case 'HEAP' :
  124. case 'ISAM' :
  125. case 'MERGE' :
  126. case 'MRG_ISAM' :
  127. case 'ISAM' :
  128. case 'MRG_MYISAM' :
  129. case 'MYISAM' :
  130. $this->supported['savepoints'] = false;
  131. $this->supported['transactions'] = false;
  132. $this->warnings[] = $this->options['default_table_type'] . ' is not a supported default table type';
  133. break;
  134. }
  135. }
  136. }
  137. // }}}
  138. // {{{ function setOption($option, $value)
  139. /**
  140. * set the option for the db class
  141. *
  142. * @param string option name
  143. * @param mixed value for the option
  144. *
  145. * @return mixed MDB2_OK or MDB2 Error Object
  146. *
  147. * @access public
  148. */
  149. function setOption($option, $value)
  150. {
  151. $res = parent :: setOption($option, $value);
  152. $this->_reCheckSupportedOptions();
  153. }
  154. // }}}
  155. // {{{ errorInfo()
  156. /**
  157. * This method is used to collect information about an error
  158. *
  159. * @param integer $error
  160. * @return array
  161. * @access public
  162. */
  163. function errorInfo($error = null)
  164. {
  165. if ($this->connection)
  166. {
  167. $native_code = @mysqli_errno($this->connection);
  168. $native_msg = @mysqli_error($this->connection);
  169. }
  170. else
  171. {
  172. $native_code = @mysqli_connect_errno();
  173. $native_msg = @mysqli_connect_error();
  174. }
  175. if (is_null($error))
  176. {
  177. static $ecode_map;
  178. if (empty($ecode_map))
  179. {
  180. $ecode_map = array(1000 => MDB2_ERROR_INVALID, //hashchk
  181. 1001 => MDB2_ERROR_INVALID, //isamchk
  182. 1004 => MDB2_ERROR_CANNOT_CREATE, 1005 => MDB2_ERROR_CANNOT_CREATE,
  183. 1006 => MDB2_ERROR_CANNOT_CREATE, 1007 => MDB2_ERROR_ALREADY_EXISTS,
  184. 1008 => MDB2_ERROR_CANNOT_DROP, 1009 => MDB2_ERROR_CANNOT_DROP, 1010 => MDB2_ERROR_CANNOT_DROP,
  185. 1011 => MDB2_ERROR_CANNOT_DELETE, 1022 => MDB2_ERROR_ALREADY_EXISTS,
  186. 1029 => MDB2_ERROR_NOT_FOUND, 1032 => MDB2_ERROR_NOT_FOUND, 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  187. 1045 => MDB2_ERROR_ACCESS_VIOLATION, 1046 => MDB2_ERROR_NODBSELECTED,
  188. 1048 => MDB2_ERROR_CONSTRAINT, 1049 => MDB2_ERROR_NOSUCHDB, 1050 => MDB2_ERROR_ALREADY_EXISTS,
  189. 1051 => MDB2_ERROR_NOSUCHTABLE, 1054 => MDB2_ERROR_NOSUCHFIELD,
  190. 1060 => MDB2_ERROR_ALREADY_EXISTS, 1061 => MDB2_ERROR_ALREADY_EXISTS,
  191. 1062 => MDB2_ERROR_ALREADY_EXISTS, 1064 => MDB2_ERROR_SYNTAX, 1067 => MDB2_ERROR_INVALID,
  192. 1072 => MDB2_ERROR_NOT_FOUND, 1086 => MDB2_ERROR_ALREADY_EXISTS, 1091 => MDB2_ERROR_NOT_FOUND,
  193. 1100 => MDB2_ERROR_NOT_LOCKED, 1109 => MDB2_ERROR_NOT_FOUND, 1125 => MDB2_ERROR_ALREADY_EXISTS,
  194. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW, 1138 => MDB2_ERROR_INVALID,
  195. 1142 => MDB2_ERROR_ACCESS_VIOLATION, 1143 => MDB2_ERROR_ACCESS_VIOLATION,
  196. 1146 => MDB2_ERROR_NOSUCHTABLE, 1149 => MDB2_ERROR_SYNTAX, 1169 => MDB2_ERROR_CONSTRAINT,
  197. 1176 => MDB2_ERROR_NOT_FOUND, 1177 => MDB2_ERROR_NOSUCHTABLE, 1213 => MDB2_ERROR_DEADLOCK,
  198. 1216 => MDB2_ERROR_CONSTRAINT, 1217 => MDB2_ERROR_CONSTRAINT,
  199. 1227 => MDB2_ERROR_ACCESS_VIOLATION, 1235 => MDB2_ERROR_CANNOT_CREATE,
  200. 1299 => MDB2_ERROR_INVALID_DATE, 1300 => MDB2_ERROR_INVALID, 1304 => MDB2_ERROR_ALREADY_EXISTS,
  201. 1305 => MDB2_ERROR_NOT_FOUND, 1306 => MDB2_ERROR_CANNOT_DROP, 1307 => MDB2_ERROR_CANNOT_CREATE,
  202. 1334 => MDB2_ERROR_CANNOT_ALTER, 1339 => MDB2_ERROR_NOT_FOUND, 1356 => MDB2_ERROR_INVALID,
  203. 1359 => MDB2_ERROR_ALREADY_EXISTS, 1360 => MDB2_ERROR_NOT_FOUND, 1363 => MDB2_ERROR_NOT_FOUND,
  204. 1365 => MDB2_ERROR_DIVZERO, 1451 => MDB2_ERROR_CONSTRAINT, 1452 => MDB2_ERROR_CONSTRAINT,
  205. 1542 => MDB2_ERROR_CANNOT_DROP, 1546 => MDB2_ERROR_CONSTRAINT, 1582 => MDB2_ERROR_CONSTRAINT,
  206. 2003 => MDB2_ERROR_CONNECT_FAILED, 2019 => MDB2_ERROR_INVALID);
  207. }
  208. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS)
  209. {
  210. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  211. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  212. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  213. }
  214. else
  215. {
  216. // Doing this in case mode changes during runtime.
  217. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  218. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  219. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  220. }
  221. if (isset($ecode_map[$native_code]))
  222. {
  223. $error = $ecode_map[$native_code];
  224. }
  225. }
  226. return array($error, $native_code, $native_msg);
  227. }
  228. // }}}
  229. // {{{ escape()
  230. /**
  231. * Quotes a string so it can be safely used in a query. It will quote
  232. * the text so it can safely be used within a query.
  233. *
  234. * @param string the input string to quote
  235. * @param bool escape wildcards
  236. *
  237. * @return string quoted string
  238. *
  239. * @access public
  240. */
  241. function escape($text, $escape_wildcards = false)
  242. {
  243. if ($escape_wildcards)
  244. {
  245. $text = $this->escapePattern($text);
  246. }
  247. $connection = $this->getConnection();
  248. if (PEAR :: isError($connection))
  249. {
  250. return $connection;
  251. }
  252. $text = @mysqli_real_escape_string($connection, $text);
  253. return $text;
  254. }
  255. // }}}
  256. // {{{ beginTransaction()
  257. /**
  258. * Start a transaction or set a savepoint.
  259. *
  260. * @param string name of a savepoint to set
  261. * @return mixed MDB2_OK on success, a MDB2 error on failure
  262. *
  263. * @access public
  264. */
  265. function beginTransaction($savepoint = null)
  266. {
  267. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true,
  268. 'savepoint' => $savepoint));
  269. $this->_getServerCapabilities();
  270. if (! is_null($savepoint))
  271. {
  272. if (! $this->supports('savepoints'))
  273. {
  274. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'savepoints are not supported', __FUNCTION__);
  275. }
  276. if (! $this->in_transaction)
  277. {
  278. return $this->raiseError(MDB2_ERROR_INVALID, null, null, 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  279. }
  280. $query = 'SAVEPOINT ' . $savepoint;
  281. return $this->_doQuery($query, true);
  282. }
  283. elseif ($this->in_transaction)
  284. {
  285. return MDB2_OK; //nothing to do
  286. }
  287. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
  288. $result = & $this->_doQuery($query, true);
  289. if (PEAR :: isError($result))
  290. {
  291. return $result;
  292. }
  293. $this->in_transaction = true;
  294. return MDB2_OK;
  295. }
  296. // }}}
  297. // {{{ commit()
  298. /**
  299. * Commit the database changes done during a transaction that is in
  300. * progress or release a savepoint. This function may only be called when
  301. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  302. * transaction is implicitly started after committing the pending changes.
  303. *
  304. * @param string name of a savepoint to release
  305. * @return mixed MDB2_OK on success, a MDB2 error on failure
  306. *
  307. * @access public
  308. */
  309. function commit($savepoint = null)
  310. {
  311. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true,
  312. 'savepoint' => $savepoint));
  313. if (! $this->in_transaction)
  314. {
  315. return $this->raiseError(MDB2_ERROR_INVALID, null, null, 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  316. }
  317. if (! is_null($savepoint))
  318. {
  319. if (! $this->supports('savepoints'))
  320. {
  321. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'savepoints are not supported', __FUNCTION__);
  322. }
  323. $server_info = $this->getServerVersion();
  324. if (version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '5.0.3', '<'))
  325. {
  326. return MDB2_OK;
  327. }
  328. $query = 'RELEASE SAVEPOINT ' . $savepoint;
  329. return $this->_doQuery($query, true);
  330. }
  331. if (! $this->supports('transactions'))
  332. {
  333. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'transactions are not supported', __FUNCTION__);
  334. }
  335. $result = & $this->_doQuery('COMMIT', true);
  336. if (PEAR :: isError($result))
  337. {
  338. return $result;
  339. }
  340. if (! $this->start_transaction)
  341. {
  342. $query = 'SET AUTOCOMMIT = 1';
  343. $result = & $this->_doQuery($query, true);
  344. if (PEAR :: isError($result))
  345. {
  346. return $result;
  347. }
  348. }
  349. $this->in_transaction = false;
  350. return MDB2_OK;
  351. }
  352. // }}}
  353. // {{{ rollback()
  354. /**
  355. * Cancel any database changes done during a transaction or since a specific
  356. * savepoint that is in progress. This function may only be called when
  357. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  358. * transaction is implicitly started after canceling the pending changes.
  359. *
  360. * @param string name of a savepoint to rollback to
  361. * @return mixed MDB2_OK on success, a MDB2 error on failure
  362. *
  363. * @access public
  364. */
  365. function rollback($savepoint = null)
  366. {
  367. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true,
  368. 'savepoint' => $savepoint));
  369. if (! $this->in_transaction)
  370. {
  371. return $this->raiseError(MDB2_ERROR_INVALID, null, null, 'rollback cannot be done changes are auto committed', __FUNCTION__);
  372. }
  373. if (! is_null($savepoint))
  374. {
  375. if (! $this->supports('savepoints'))
  376. {
  377. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'savepoints are not supported', __FUNCTION__);
  378. }
  379. $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint;
  380. return $this->_doQuery($query, true);
  381. }
  382. $query = 'ROLLBACK';
  383. $result = & $this->_doQuery($query, true);
  384. if (PEAR :: isError($result))
  385. {
  386. return $result;
  387. }
  388. if (! $this->start_transaction)
  389. {
  390. $query = 'SET AUTOCOMMIT = 1';
  391. $result = & $this->_doQuery($query, true);
  392. if (PEAR :: isError($result))
  393. {
  394. return $result;
  395. }
  396. }
  397. $this->in_transaction = false;
  398. return MDB2_OK;
  399. }
  400. // }}}
  401. // {{{ function setTransactionIsolation()
  402. /**
  403. * Set the transacton isolation level.
  404. *
  405. * @param string standard isolation level
  406. * READ UNCOMMITTED (allows dirty reads)
  407. * READ COMMITTED (prevents dirty reads)
  408. * REPEATABLE READ (prevents nonrepeatable reads)
  409. * SERIALIZABLE (prevents phantom reads)
  410. * @return mixed MDB2_OK on success, a MDB2 error on failure
  411. *
  412. * @access public
  413. * @since 2.1.1
  414. */
  415. function setTransactionIsolation($isolation)
  416. {
  417. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  418. if (! $this->supports('transactions'))
  419. {
  420. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'transactions are not supported', __FUNCTION__);
  421. }
  422. switch ($isolation)
  423. {
  424. case 'READ UNCOMMITTED' :
  425. case 'READ COMMITTED' :
  426. case 'REPEATABLE READ' :
  427. case 'SERIALIZABLE' :
  428. break;
  429. default :
  430. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, 'isolation level is not supported: ' . $isolation, __FUNCTION__);
  431. }
  432. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  433. return $this->_doQuery($query, true);
  434. }
  435. // }}}
  436. // {{{ _doConnect()
  437. /**
  438. * do the grunt work of the connect
  439. *
  440. * @return connection on success or MDB2 Error Object on failure
  441. * @access protected
  442. */
  443. function _doConnect($username, $password, $persistent = false)
  444. {
  445. if (! PEAR :: loadExtension($this->phptype))
  446. {
  447. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'extension ' . $this->phptype . ' is not compiled into PHP', __FUNCTION__);
  448. }
  449. $connection = @mysqli_init();
  450. if (! empty($this->dsn['charset']) && defined('MYSQLI_SET_CHARSET_NAME'))
  451. {
  452. @mysqli_options($connection, MYSQLI_SET_CHARSET_NAME, $this->dsn['charset']);
  453. }
  454. if ($this->options['ssl'])
  455. {
  456. @mysqli_ssl_set($connection, empty($this->dsn['key']) ? null : $this->dsn['key'], empty($this->dsn['cert']) ? null : $this->dsn['cert'], empty($this->dsn['ca']) ? null : $this->dsn['ca'], empty($this->dsn['capath']) ? null : $this->dsn['capath'], empty($this->dsn['cipher']) ? null : $this->dsn['cipher']);
  457. }
  458. if (! @mysqli_real_connect($connection, $this->dsn['hostspec'], $username, $password, $this->database_name, $this->dsn['port'], $this->dsn['socket']))
  459. {
  460. if (($err = @mysqli_connect_error()) != '')
  461. {
  462. return $this->raiseError(null, null, null, $err, __FUNCTION__);
  463. }
  464. else
  465. {
  466. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, 'unable to establish a connection', __FUNCTION__);
  467. }
  468. }
  469. if (! empty($this->dsn['charset']) && ! defined('MYSQLI_SET_CHARSET_NAME'))
  470. {
  471. $result = $this->setCharset($this->dsn['charset'], $connection);
  472. if (PEAR :: isError($result))
  473. {
  474. return $result;
  475. }
  476. }
  477. return $connection;
  478. }
  479. // }}}
  480. // {{{ connect()
  481. /**
  482. * Connect to the database
  483. *
  484. * @return true on success, MDB2 Error Object on failure
  485. */
  486. function connect()
  487. {
  488. if (is_object($this->connection))
  489. {
  490. if (count(array_diff($this->connected_dsn, $this->dsn)) == 0)
  491. {
  492. //if (MDB2::areEquals($this->connected_dsn, $this->dsn)) { //memory leak fixed, so no need for heavier areEquals function
  493. return MDB2_OK;
  494. }
  495. $this->connection = 0;
  496. }
  497. $connection = $this->_doConnect($this->dsn['username'], $this->dsn['password']);
  498. if (PEAR :: isError($connection))
  499. {
  500. return $connection;
  501. }
  502. $this->connection = $connection;
  503. $this->connected_dsn = $this->dsn;
  504. $this->connected_database_name = $this->database_name;
  505. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  506. $this->_getServerCapabilities();
  507. return MDB2_OK;
  508. }
  509. // }}}
  510. // {{{ setCharset()
  511. /**
  512. * Set the charset on the current connection
  513. *
  514. * @param string charset (or array(charset, collation))
  515. * @param resource connection handle
  516. *
  517. * @return true on success, MDB2 Error Object on failure
  518. */
  519. function setCharset($charset, $connection = null)
  520. {
  521. if (is_null($connection))
  522. {
  523. $connection = $this->getConnection();
  524. if (PEAR :: isError($connection))
  525. {
  526. return $connection;
  527. }
  528. }
  529. $collation = null;
  530. if (is_array($charset) && 2 == count($charset))
  531. {
  532. $collation = array_pop($charset);
  533. $charset = array_pop($charset);
  534. }
  535. $client_info = mysqli_get_client_version();
  536. if (OS_WINDOWS && ((40111 > $client_info) || ((50000 <= $client_info) && (50006 > $client_info))))
  537. {
  538. $query = "SET NAMES '" . mysqli_real_escape_string($connection, $charset) . "'";
  539. if (! is_null($collation))
  540. {
  541. $query .= " COLLATE '" . mysqli_real_escape_string($connection, $collation) . "'";
  542. }
  543. return $this->_doQuery($query, true, $connection);
  544. }
  545. if (! $result = mysqli_set_charset($connection, $charset))
  546. {
  547. $err = & $this->raiseError(null, null, null, 'Could not set client character set', __FUNCTION__);
  548. return $err;
  549. }
  550. return $result;
  551. }
  552. // }}}
  553. // {{{ databaseExists()
  554. /**
  555. * check if given database name is exists?
  556. *
  557. * @param string $name name of the database that should be checked
  558. *
  559. * @return mixed true/false on success, a MDB2 error on failure
  560. * @access public
  561. */
  562. function databaseExists($name)
  563. {
  564. $connection = $this->_doConnect($this->dsn['username'], $this->dsn['password']);
  565. if (PEAR :: isError($connection))
  566. {
  567. return $connection;
  568. }
  569. $result = @mysqli_select_db($connection, $name);
  570. @mysqli_close($connection);
  571. return $result;
  572. }
  573. // }}}
  574. // {{{ disconnect()
  575. /**
  576. * Log out and disconnect from the database.
  577. *
  578. * @param boolean $force if the disconnect should be forced even if the
  579. * connection is opened persistently
  580. * @return mixed true on success, false if not connected and error
  581. * object on error
  582. * @access public
  583. */
  584. function disconnect($force = true)
  585. {
  586. if (is_object($this->connection))
  587. {
  588. if ($this->in_transaction)
  589. {
  590. $dsn = $this->dsn;
  591. $database_name = $this->database_name;
  592. $persistent = $this->options['persistent'];
  593. $this->dsn = $this->connected_dsn;
  594. $this->database_name = $this->connected_database_name;
  595. $this->options['persistent'] = $this->opened_persistent;
  596. $this->rollback();
  597. $this->dsn = $dsn;
  598. $this->database_name = $database_name;
  599. $this->options['persistent'] = $persistent;
  600. }
  601. if ($force)
  602. {
  603. $ok = @mysqli_close($this->connection);
  604. if (! $ok)
  605. {
  606. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED, null, null, null, __FUNCTION__);
  607. }
  608. }
  609. }
  610. else
  611. {
  612. return false;
  613. }
  614. return parent :: disconnect($force);
  615. }
  616. // }}}
  617. // {{{ standaloneQuery()
  618. /**
  619. * execute a query as DBA
  620. *
  621. * @param string $query the SQL query
  622. * @param mixed $types array that contains the types of the columns in
  623. * the result set
  624. * @param boolean $is_manip if the query is a manipulation query
  625. * @return mixed MDB2_OK on success, a MDB2 error on failure
  626. * @access public
  627. */
  628. function &standaloneQuery($query, $types = null, $is_manip = false)
  629. {
  630. $user = $this->options['DBA_username'] ? $this->options['DBA_username'] : $this->dsn['username'];
  631. $pass = $this->options['DBA_password'] ? $this->options['DBA_password'] : $this->dsn['password'];
  632. $connection = $this->_doConnect($user, $pass);
  633. if (PEAR :: isError($connection))
  634. {
  635. return $connection;
  636. }
  637. $offset = $this->offset;
  638. $limit = $this->limit;
  639. $this->offset = $this->limit = 0;
  640. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  641. $result = & $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  642. if (! PEAR :: isError($result))
  643. {
  644. $result = $this->_affectedRows($connection, $result);
  645. }
  646. @mysqli_close($connection);
  647. return $result;
  648. }
  649. // }}}
  650. // {{{ _doQuery()
  651. /**
  652. * Execute a query
  653. * @param string $query query
  654. * @param boolean $is_manip if the query is a manipulation query
  655. * @param resource $connection
  656. * @param string $database_name
  657. * @return result or error object
  658. * @access protected
  659. */
  660. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  661. {
  662. $this->last_query = $query;
  663. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  664. if ($result)
  665. {
  666. if (PEAR :: isError($result))
  667. {
  668. return $result;
  669. }
  670. $query = $result;
  671. }
  672. if ($this->options['disable_query'])
  673. {
  674. $result = $is_manip ? 0 : null;
  675. return $result;
  676. }
  677. if (is_null($connection))
  678. {
  679. $connection = $this->getConnection();
  680. if (PEAR :: isError($connection))
  681. {
  682. return $connection;
  683. }
  684. }
  685. if (is_null($database_name))
  686. {
  687. $database_name = $this->database_name;
  688. }
  689. if ($database_name)
  690. {
  691. if ($database_name != $this->connected_database_name)
  692. {
  693. if (! @mysqli_select_db($connection, $database_name))
  694. {
  695. $err = $this->raiseError(null, null, null, 'Could not select the database: ' . $database_name, __FUNCTION__);
  696. return $err;
  697. }
  698. $this->connected_database_name = $database_name;
  699. }
  700. }
  701. if ($this->options['multi_query'])
  702. {
  703. $result = mysqli_multi_query($connection, $query);
  704. }
  705. else
  706. {
  707. $resultmode = $this->options['result_buffering'] ? MYSQLI_USE_RESULT : MYSQLI_USE_RESULT;
  708. $result = mysqli_query($connection, $query);
  709. }
  710. if (! $result)
  711. {
  712. $err = & $this->raiseError(null, null, null, 'Could not execute statement', __FUNCTION__);
  713. return $err;
  714. }
  715. if ($this->options['multi_query'])
  716. {
  717. if ($this->options['result_buffering'])
  718. {
  719. if (! ($result = @mysqli_store_result($connection)))
  720. {
  721. $err = & $this->raiseError(null, null, null, 'Could not get the first result from a multi query', __FUNCTION__);
  722. return $err;
  723. }
  724. }
  725. elseif (! ($result = @mysqli_use_result($connection)))
  726. {
  727. $err = & $this->raiseError(null, null, null, 'Could not get the first result from a multi query', __FUNCTION__);
  728. return $err;
  729. }
  730. }
  731. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  732. return $result;
  733. }
  734. // }}}
  735. // {{{ _affectedRows()
  736. /**
  737. * Returns the number of rows affected
  738. *
  739. * @param resource $result
  740. * @param resource $connection
  741. * @return mixed MDB2 Error Object or the number of rows affected
  742. * @access private
  743. */
  744. function _affectedRows($connection, $result = null)
  745. {
  746. if (is_null($connection))
  747. {
  748. $connection = $this->getConnection();
  749. if (PEAR :: isError($connection))
  750. {
  751. return $connection;
  752. }
  753. }
  754. return @mysqli_affected_rows($connection);
  755. }
  756. // }}}
  757. // {{{ _modifyQuery()
  758. /**
  759. * Changes a query string for various DBMS specific reasons
  760. *
  761. * @param string $query query to modify
  762. * @param boolean $is_manip if it is a DML query
  763. * @param integer $limit limit the number of rows
  764. * @param integer $offset start reading from given offset
  765. * @return string modified query
  766. * @access protected
  767. */
  768. function _modifyQuery($query, $is_manip, $limit, $offset)
  769. {
  770. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT)
  771. {
  772. // "DELETE FROM table" gives 0 affected rows in MySQL.
  773. // This little hack lets you know how many rows were deleted.
  774. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query))
  775. {
  776. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', 'DELETE FROM \1 WHERE 1=1', $query);
  777. }
  778. }
  779. if ($limit > 0 && ! preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query))
  780. {
  781. $query = rtrim($query);
  782. if (substr($query, - 1) == ';')
  783. {
  784. $query = substr($query, 0, - 1);
  785. }
  786. // LIMIT doesn't always come last in the query
  787. // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  788. $after = '';
  789. if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches))
  790. {
  791. $after = $matches[0];
  792. $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
  793. }
  794. elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches))
  795. {
  796. $after = $matches[0];
  797. $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
  798. }
  799. elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches))
  800. {
  801. $after = $matches[0];
  802. $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
  803. }
  804. if ($is_manip)
  805. {
  806. return $query . " LIMIT $limit" . $after;
  807. }
  808. else
  809. {
  810. return $query . " LIMIT $offset, $limit" . $after;
  811. }
  812. }
  813. return $query;
  814. }
  815. // }}}
  816. // {{{ getServerVersion()
  817. /**
  818. * return version information about the server
  819. *
  820. * @param bool $native determines if the raw version string should be returned
  821. * @return mixed array/string with version information or MDB2 error object
  822. * @access public
  823. */
  824. function getServerVersion($native = false)
  825. {
  826. $connection = $this->getConnection();
  827. if (PEAR :: isError($connection))
  828. {
  829. return $connection;
  830. }
  831. if ($this->connected_server_info)
  832. {
  833. $server_info = $this->connected_server_info;
  834. }
  835. else
  836. {
  837. $server_info = @mysqli_get_server_info($connection);
  838. }
  839. if (! $server_info)
  840. {
  841. return $this->raiseError(null, null, null, 'Could not get server information', __FUNCTION__);
  842. }
  843. // cache server_info
  844. $this->connected_server_info = $server_info;
  845. if (! $native)
  846. {
  847. $tmp = explode('.', $server_info, 3);
  848. if (isset($tmp[2]) && strpos($tmp[2], '-'))
  849. {
  850. $tmp2 = explode('-', @$tmp[2], 2);
  851. }
  852. else
  853. {
  854. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  855. $tmp2[1] = null;
  856. }
  857. $server_info = array('major' => isset($tmp[0]) ? $tmp[0] : null, 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  858. 'patch' => $tmp2[0], 'extra' => $tmp2[1], 'native' => $server_info);
  859. }
  860. return $server_info;
  861. }
  862. // }}}
  863. // {{{ _getServerCapabilities()
  864. /**
  865. * Fetch some information about the server capabilities
  866. * (transactions, subselects, prepared statements, etc).
  867. *
  868. * @access private
  869. */
  870. function _getServerCapabilities()
  871. {
  872. if (! $this->server_capabilities_checked)
  873. {
  874. $this->server_capabilities_checked = true;
  875. //set defaults
  876. $this->supported['sub_selects'] = 'emulated';
  877. $this->supported['prepared_statements'] = 'emulated';
  878. $this->supported['triggers'] = false;
  879. $this->start_transaction = false;
  880. $this->varchar_max_length = 255;
  881. $server_info = $this->getServerVersion();
  882. if (is_array($server_info))
  883. {
  884. $server_version = $server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'];
  885. if (! version_compare($server_version, '4.1.0', '<'))
  886. {
  887. $this->supported['sub_selects'] = true;
  888. $this->supported['prepared_statements'] = true;
  889. }
  890. // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
  891. if (version_compare($server_version, '4.1.0', '>='))
  892. {
  893. if (version_compare($server_version, '4.1.1', '<'))
  894. {
  895. $this->supported['savepoints'] = false;
  896. }
  897. }
  898. elseif (version_compare($server_version, '4.0.14', '<'))
  899. {
  900. $this->supported['savepoints'] = false;
  901. }
  902. if (! version_compare($server_version, '4.0.11', '<'))
  903. {
  904. $this->start_transaction = true;
  905. }
  906. if (! version_compare($server_version, '5.0.3', '<'))
  907. {
  908. $this->varchar_max_length = 65532;
  909. }
  910. if (! version_compare($server_version, '5.0.2', '<'))
  911. {
  912. $this->supported['triggers'] = true;
  913. }
  914. }
  915. }
  916. }
  917. // }}}
  918. // {{{ function _skipUserDefinedVariable($query, $position)
  919. /**
  920. * Utility method, used by prepare() to avoid misinterpreting MySQL user
  921. * defined variables (SELECT @x:=5) for placeholders.
  922. * Check if the placeholder is a false positive, i.e. if it is an user defined
  923. * variable instead. If so, skip it and advance the position, otherwise
  924. * return the current position, which is valid
  925. *
  926. * @param string $query
  927. * @param integer $position current string cursor position
  928. * @return integer $new_position
  929. * @access protected
  930. */
  931. function _skipUserDefinedVariable($query, $position)
  932. {
  933. $found = strpos(strrev(substr($query, 0, $position)), '@');
  934. if ($found === false)
  935. {
  936. return $position;
  937. }
  938. $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
  939. $substring = substr($query, $pos, $position - $pos + 2);
  940. if (preg_match('/^@\w+\s*:=$/', $substring))
  941. {
  942. return $position + 1; //found an user defined variable: skip it
  943. }
  944. return $position;
  945. }
  946. // }}}
  947. // {{{ prepare()
  948. /**
  949. * Prepares a query for multiple execution with execute().
  950. * With some database backends, this is emulated.
  951. * prepare() requires a generic query as string like
  952. * 'INSERT INTO numbers VALUES(?,?)' or
  953. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  954. * The ? and :name and are placeholders which can be set using
  955. * bindParam() and the query can be sent off using the execute() method.
  956. * The allowed format for :name can be set with the 'bindname_format' option.
  957. *
  958. * @param string $query the query to prepare
  959. * @param mixed $types array that contains the types of the placeholders
  960. * @param mixed $result_types array that contains the types of the columns in
  961. * the result set or MDB2_PREPARE_RESULT, if set to
  962. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  963. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  964. * @return mixed resource handle for the prepared query on success, a MDB2
  965. * error on failure
  966. * @access public
  967. * @see bindParam, execute
  968. */
  969. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  970. {
  971. if ($this->options['emulate_prepared'] || $this->supported['prepared_statements'] !== true)
  972. {
  973. $obj = & parent :: prepare($query, $types, $result_types, $lobs);
  974. return $obj;
  975. }
  976. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  977. $offset = $this->offset;
  978. $limit = $this->limit;
  979. $this->offset = $this->limit = 0;
  980. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  981. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  982. if ($result)
  983. {
  984. if (PEAR :: isError($result))
  985. {
  986. return $result;
  987. }
  988. $query = $result;
  989. }
  990. $placeholder_type_guess = $placeholder_type = null;
  991. $question = '?';
  992. $colon = ':';
  993. $positions = array();
  994. $position = 0;
  995. while ($position < strlen($query))
  996. {
  997. $q_position = strpos($query, $question, $position);
  998. $c_position = strpos($query, $colon, $position);
  999. if ($q_position && $c_position)
  1000. {
  1001. $p_position = min($q_position, $c_position);
  1002. }
  1003. elseif ($q_position)
  1004. {
  1005. $p_position = $q_position;
  1006. }
  1007. elseif ($c_position)
  1008. {
  1009. $p_position = $c_position;
  1010. }
  1011. else
  1012. {
  1013. break;
  1014. }
  1015. if (is_null($placeholder_type))
  1016. {
  1017. $placeholder_type_guess = $query[$p_position];
  1018. }
  1019. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  1020. if (PEAR :: isError($new_pos))
  1021. {
  1022. return $new_pos;
  1023. }
  1024. if ($new_pos != $position)
  1025. {
  1026. $position = $new_pos;
  1027. continue; //evaluate again starting from the new position
  1028. }
  1029. //make sure this is not part of an user defined variable
  1030. $new_pos = $this->_skipUserDefinedVariable($query, $position);
  1031. if ($new_pos != $position)
  1032. {
  1033. $position = $new_pos;
  1034. continue; //evaluate again starting from the new position
  1035. }
  1036. if ($query[$position] == $placeholder_type_guess)
  1037. {
  1038. if (is_null($placeholder_type))
  1039. {
  1040. $placeholder_type = $query[$p_position];
  1041. $question = $colon = $placeholder_type;
  1042. }
  1043. if ($placeholder_type == ':')
  1044. {
  1045. $regexp = '/^.{' . ($position + 1) . '}(' . $this->options['bindname_format'] . ').*$/s';
  1046. $parameter = preg_replace($regexp, '\\1', $query);
  1047. if ($parameter === '')
  1048. {
  1049. $err = & $this->raiseError(MDB2_ERROR_SYNTAX, null, null, 'named parameter name must match "bindname_format" option', __FUNCTION__);
  1050. return $err;
  1051. }
  1052. $positions[$p_position] = $parameter;
  1053. $query = substr_replace($query, '?', $position, strlen($parameter) + 1);
  1054. }
  1055. else
  1056. {
  1057. $positions[$p_position] = count($positions);
  1058. }
  1059. $position = $p_position + 1;
  1060. }
  1061. else
  1062. {
  1063. $position = $p_position;
  1064. }
  1065. }
  1066. $connection = $this->getConnection();
  1067. if (PEAR :: isError($connection))
  1068. {
  1069. return $connection;
  1070. }
  1071. if (! $is_manip)
  1072. {
  1073. static $prep_statement_counter = 1;
  1074. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter ++ . sha1(microtime() + mt_rand()));
  1075. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  1076. $query = "PREPARE $statement_name FROM " . $this->quote($query, 'text');
  1077. $statement = & $this->_doQuery($query, true, $connection);
  1078. if (PEAR :: isError($statement))
  1079. {
  1080. return $statement;
  1081. }
  1082. $statement = $statement_name;
  1083. }
  1084. else
  1085. {
  1086. $statement = @mysqli_prepare($connection, $query);
  1087. if (! $statement)
  1088. {
  1089. $err = & $this->raiseError(null, null, null, 'Unable to create prepared statement handle', __FUNCTION__);
  1090. return $err;
  1091. }
  1092. }
  1093. $class_name = 'MDB2_Statement_' . $this->phptype;
  1094. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  1095. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  1096. return $obj;
  1097. }
  1098. // }}}
  1099. // {{{ replace()
  1100. /**
  1101. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  1102. * query, except that if there is already a row in the table with the same
  1103. * key field values, the old row is deleted before the new row is inserted.
  1104. *
  1105. * The REPLACE type of query does not make part of the SQL standards. Since
  1106. * practically only MySQL implements it natively, this type of query is
  1107. * emulated through this method for other DBMS using standard types of
  1108. * queries inside a transaction to assure the atomicity of the operation.
  1109. *
  1110. * @access public
  1111. *
  1112. * @param string $table name of the table on which the REPLACE query will
  1113. * be executed.
  1114. * @param array $fields associative array that describes the fields and the
  1115. * values that will be inserted or updated in the specified table. The
  1116. * indexes of the array are the names of all the fields of the table. The
  1117. * values of the array are also associative arrays that describe the
  1118. * values and other properties of the table fields.
  1119. *
  1120. * Here follows a list of field properties that need to be specified:
  1121. *
  1122. * value:
  1123. * Value to be assigned to the specified field. This value may be
  1124. * of specified in database independent type format as this
  1125. * function can perform the necessary datatype conversions.
  1126. *
  1127. * Default:
  1128. * this property is required unless the Null property
  1129. * is set to 1.
  1130. *
  1131. * type
  1132. * Name of the type of the field. Currently, all types Metabase
  1133. * are supported except for clob and blob.
  1134. *
  1135. * Default: no type conversion
  1136. *
  1137. * null
  1138. * Boolean property that indicates that the value for this field
  1139. * should be set to null.
  1140. *
  1141. * The default value for fields missing in INSERT queries may be
  1142. * specified the definition of a table. Often, the default value
  1143. * is already null, but since the REPLACE may be emulated using
  1144. * an UPDATE query, make sure that all fields of the table are
  1145. * listed in this function argument array.
  1146. *
  1147. * Default: 0
  1148. *
  1149. * key
  1150. * Boolean property that indicates that this field should be
  1151. * handled as a primary key or at least as part of the compound
  1152. * unique index of the table that will determine the row that will
  1153. * updated if it exists or inserted a new row otherwise.
  1154. *
  1155. * This function will fail if no key field is specified or if the
  1156. * value of a key field is set to null because fields that are
  1157. * part of unique index they may not be null.
  1158. *
  1159. * Default: 0
  1160. *
  1161. * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
  1162. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1163. */
  1164. function replace($table, $fields)
  1165. {
  1166. $count = count($fields);
  1167. $query = $values = '';
  1168. $keys = $colnum = 0;
  1169. for(reset($fields); $colnum < $count; next($fields), $colnum ++)
  1170. {
  1171. $name = key($fields);
  1172. if ($colnum > 0)
  1173. {
  1174. $query .= ',';
  1175. $values .= ',';
  1176. }
  1177. $query .= $this->quoteIdentifier($name, true);
  1178. if (isset($fields[$name]['null']) && $fields[$name]['null'])
  1179. {
  1180. $value = 'NULL';
  1181. }
  1182. else
  1183. {
  1184. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  1185. $value = $this->quote($fields[$name]['value'], $type);
  1186. if (PEAR :: isError($value))
  1187. {
  1188. return $value;
  1189. }
  1190. }
  1191. $values .= $value;
  1192. if (isset($fields[$name]['key']) && $fields[$name]['key'])
  1193. {
  1194. if ($value === 'NULL')
  1195. {
  1196. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, 'key value ' . $name . ' may not be NULL', __FUNCTION__);
  1197. }
  1198. $keys ++;
  1199. }
  1200. }
  1201. if ($keys == 0)
  1202. {
  1203. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, 'not specified which fields are keys', __FUNCTION__);
  1204. }
  1205. $connection = $this->getConnection();
  1206. if (PEAR :: isError($connection))
  1207. {
  1208. return $connection;
  1209. }
  1210. $table = $this->quoteIdentifier($table, true);
  1211. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1212. $result = & $this->_doQuery($query, true, $connection);
  1213. if (PEAR :: isError($result))
  1214. {
  1215. return $result;
  1216. }
  1217. return $this->_affectedRows($connection, $result);
  1218. }
  1219. // }}}
  1220. // {{{ nextID()
  1221. /**
  1222. * Returns the next free id of a sequence
  1223. *
  1224. * @param string $seq_name name of the sequence
  1225. * @param boolean $ondemand when true the sequence is
  1226. * automatic created, if it
  1227. * not exists
  1228. *
  1229. * @return mixed MDB2 Error Object or id
  1230. * @access public
  1231. */
  1232. function nextID($seq_name, $ondemand = true)
  1233. {
  1234. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1235. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1236. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1237. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  1238. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1239. $result = & $this->_doQuery($query, true);
  1240. $this->popExpect();
  1241. $this->popErrorHandling();
  1242. if (PEAR :: isError($result))
  1243. {
  1244. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE)
  1245. {
  1246. $this->loadModule('Manager', null, true);
  1247. $result = $this->manager->createSequence($seq_name);
  1248. if (PEAR :: isError($result))
  1249. {
  1250. return $this->raiseError($result, null, null, 'on demand sequence ' . $seq_name . ' could not be created', __FUNCTION__);
  1251. }
  1252. else
  1253. {
  1254. return $this->nextID($seq_name, false);
  1255. }
  1256. }
  1257. return $result;
  1258. }
  1259. $value = $this->lastInsertID();
  1260. if (is_numeric($value))
  1261. {
  1262. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1263. $result = & $this->_doQuery($query, true);
  1264. if (PEAR :: isError($result))
  1265. {
  1266. $this->warnings[] = 'nextID: could not delete previous sequence table values from ' . $seq_name;
  1267. }
  1268. }
  1269. return $value;
  1270. }
  1271. // }}}
  1272. // {{{ lastInsertID()
  1273. /**
  1274. * Returns the autoincrement ID if supported or $id or fetches the current
  1275. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1276. *
  1277. * @param string $table name of the table into which a new row was inserted
  1278. * @param string $field name of the field into which a new row was inserted
  1279. * @return mixed MDB2 Error Object or id
  1280. * @access public
  1281. */
  1282. function lastInsertID($table = null, $field = null)
  1283. {
  1284. // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1285. return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
  1286. }
  1287. // }}}
  1288. // {{{ currID()
  1289. /**
  1290. * Returns the current id of a sequence
  1291. *
  1292. * @param string $seq_name name of the sequence
  1293. * @return mixed MDB2 Error Object or id
  1294. * @access public
  1295. */
  1296. function currID($seq_name)
  1297. {
  1298. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1299. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1300. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1301. return $this->queryOne($query, 'integer');
  1302. }
  1303. }
  1304. /**
  1305. * MDB2 MySQLi result driver
  1306. *
  1307. * @package MDB2
  1308. * @category Database
  1309. * @author Lukas Smith <smith@pooteeweet.org>
  1310. */
  1311. class MDB2_Result_mysqli extends MDB2_Result_Common
  1312. {
  1313. // }}}
  1314. // {{{ fetchRow()
  1315. /**
  1316. * Fetch a row and insert the data into an existing array.
  1317. *
  1318. * @param int $fetchmode how the array data should be indexed
  1319. * @param int $rownum number of the row where the data can be found
  1320. * @return int data array on success, a MDB2 error on failure
  1321. * @access public
  1322. */
  1323. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1324. {
  1325. if (! is_null($rownum))
  1326. {
  1327. $seek = $this->seek($rownum);
  1328. if (PEAR :: isError($seek))
  1329. {
  1330. return $seek;
  1331. }
  1332. }
  1333. if ($fetchmode == MDB2_FETCHMODE_DEFAULT)
  1334. {
  1335. $fetchmode = $this->db->fetchmode;
  1336. }
  1337. if ($fetchmode & MDB2_FETCHMODE_ASSOC)
  1338. {
  1339. $row = @mysqli_fetch_assoc($this->result);
  1340. if (is_array($row) && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  1341. {
  1342. $row = array_change_key_case($row, $this->db->options['field_case']);
  1343. }
  1344. }
  1345. else
  1346. {
  1347. $row = @mysqli_fetch_row($this->result);
  1348. }
  1349. if (! $row)
  1350. {
  1351. if ($this->result === false)
  1352. {
  1353. $err = & $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'resultset has already been freed', __FUNCTION__);
  1354. return $err;
  1355. }
  1356. $null = null;
  1357. return $null;
  1358. }
  1359. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1360. $rtrim = false;
  1361. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM)
  1362. {
  1363. if (empty($this->types))
  1364. {
  1365. $mode += MDB2_PORTABILITY_RTRIM;
  1366. }
  1367. else
  1368. {
  1369. $rtrim = true;
  1370. }
  1371. }
  1372. if ($mode)
  1373. {
  1374. $this->db->_fixResultArrayValues($row, $mode);
  1375. }
  1376. if (! ($fetchmode & MDB2_FETCHMODE_ASSOC) && ! empty($this->types))
  1377. {
  1378. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1379. }
  1380. elseif (($fetchmode & MDB2_FETCHMODE_ASSOC) && ! empty($this->types_assoc))
  1381. {
  1382. $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
  1383. }
  1384. if (! empty($this->values))
  1385. {
  1386. $this->_assignBindColumns($row);
  1387. }
  1388. if ($fetchmode === MDB2_FETCHMODE_OBJECT)
  1389. {
  1390. $object_class = $this->db->options['fetch_class'];
  1391. if ($object_class == 'stdClass')
  1392. {
  1393. $row = (object) $row;
  1394. }
  1395. else
  1396. {
  1397. $row = new $object_class($row);
  1398. }
  1399. }
  1400. ++ $this->rownum;
  1401. return $row;
  1402. }
  1403. // }}}
  1404. // {{{ _getColumnNames()
  1405. /**
  1406. * Retrieve the names of columns returned by the DBMS in a query result.
  1407. *
  1408. * @return mixed Array variable that holds the names of columns as keys
  1409. * or an MDB2 error on failure.
  1410. * Some DBMS may not return any columns when the result set
  1411. * does not contain any rows.
  1412. * @access private
  1413. */
  1414. function _getColumnNames()
  1415. {
  1416. $columns = array();
  1417. $numcols = $this->numCols();
  1418. if (PEAR :: isError($numcols))
  1419. {
  1420. return $numcols;
  1421. }
  1422. for($column = 0; $column < $numcols; $column ++)
  1423. {
  1424. $column_info = @mysqli_fetch_field_direct($this->result, $column);
  1425. $columns[$column_info->name] = $column;
  1426. }
  1427. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  1428. {
  1429. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1430. }
  1431. return $columns;
  1432. }
  1433. // }}}
  1434. // {{{ numCols()
  1435. /**
  1436. * Count the number of columns returned by the DBMS in a query result.
  1437. *
  1438. * @return mixed integer value with the number of columns, a MDB2 error
  1439. * on failure
  1440. * @access public
  1441. */
  1442. function numCols()
  1443. {
  1444. $cols = @mysqli_num_fields($this->result);
  1445. if (is_null($cols))
  1446. {
  1447. if ($this->result === false)
  1448. {
  1449. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'resultset has already been freed', __FUNCTION__);
  1450. }
  1451. elseif (is_null($this->result))
  1452. {
  1453. return count($this->types);
  1454. }
  1455. return $this->db->raiseError(null, null, null, 'Could not get column count', __FUNCTION__);
  1456. }
  1457. return $cols;
  1458. }
  1459. // }}}
  1460. // {{{ nextResult()
  1461. /**
  1462. * Move the internal result pointer to the next available result
  1463. *
  1464. * @return true on success, false if there is no more result set or an error object on failure
  1465. * @access public
  1466. */
  1467. function nextResult()
  1468. {
  1469. $connection = $this->db->getConnection();
  1470. if (PEAR :: isError($connection))
  1471. {
  1472. return $connection;
  1473. }
  1474. if (! @mysqli_more_results($connection))
  1475. {
  1476. return false;
  1477. }
  1478. if (! @mysqli_next_result($connection))
  1479. {
  1480. return false;
  1481. }
  1482. if (! ($this->result = @mysqli_use_result($connection)))
  1483. {
  1484. return false;
  1485. }
  1486. return MDB2_OK;
  1487. }
  1488. // }}}
  1489. // {{{ free()
  1490. /**
  1491. * Free the internal resources associated with result.
  1492. *
  1493. * @return boolean true on success, false if result is invalid
  1494. * @access public
  1495. */
  1496. function free()
  1497. {
  1498. if (is_object($this->result) && $this->db->connection)
  1499. {
  1500. $free = @mysqli_free_result($this->result);
  1501. if ($free === false)
  1502. {
  1503. return $this->db->raiseError(null, null, null, 'Could not free result', __FUNCTION__);
  1504. }
  1505. }
  1506. $this->result = false;
  1507. return MDB2_OK;
  1508. }
  1509. }
  1510. /**
  1511. * MDB2 MySQLi buffered result driver
  1512. *
  1513. * @package MDB2
  1514. * @category Database
  1515. * @author Lukas Smith <smith@pooteeweet.org>
  1516. */
  1517. class MDB2_BufferedResult_mysqli extends MDB2_Result_mysqli
  1518. {
  1519. // }}}
  1520. // {{{ seek()
  1521. /**
  1522. * Seek to a specific row in a result set
  1523. *
  1524. * @param int $rownum number of the row where the data can be found
  1525. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1526. * @access public
  1527. */
  1528. function seek($rownum = 0)
  1529. {
  1530. if ($this->rownum != ($rownum - 1) && ! @mysqli_data_seek($this->result, $rownum))
  1531. {
  1532. if ($this->result === false)
  1533. {
  1534. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'resultset has already been freed', __FUNCTION__);
  1535. }
  1536. elseif (is_null($this->result))
  1537. {
  1538. return MDB2_OK;
  1539. }
  1540. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null, 'tried to seek to an invalid row number (' . $rownum . ')', __FUNCTION__);
  1541. }
  1542. $this->rownum = $rownum - 1;
  1543. return MDB2_OK;
  1544. }
  1545. // }}}
  1546. // {{{ valid()
  1547. /**
  1548. * Check if the end of the result set has been reached
  1549. *
  1550. * @return mixed true or false on sucess, a MDB2 error on failure
  1551. * @access public
  1552. */
  1553. function valid()
  1554. {
  1555. $numrows = $this->numRows();
  1556. if (PEAR :: isError($numrows))
  1557. {
  1558. return $numrows;
  1559. }
  1560. return $this->rownum < ($numrows - 1);
  1561. }
  1562. // }}}
  1563. // {{{ numRows()
  1564. /**
  1565. * Returns the number of rows in a result object
  1566. *
  1567. * @return mixed MDB2 Error Object or the number of rows
  1568. * @access public
  1569. */
  1570. function numRows()
  1571. {
  1572. $rows = @mysqli_num_rows($this->result);
  1573. if (is_null($rows))
  1574. {
  1575. if ($this->result === false)
  1576. {
  1577. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'resultset has already been freed', __FUNCTION__);
  1578. }
  1579. elseif (is_null($this->result))
  1580. {
  1581. return 0;
  1582. }
  1583. return $this->db->raiseError(null, null, null, 'Could not get row count', __FUNCTION__);
  1584. }
  1585. return $rows;
  1586. }
  1587. // }}}
  1588. // {{{ nextResult()
  1589. /**
  1590. * Move the internal result pointer to the next available result
  1591. *
  1592. * @param a valid result resource
  1593. * @return true on success, false if there is no more result set or an error object on failure
  1594. * @access public
  1595. */
  1596. function nextResult()
  1597. {
  1598. $connection = $this->db->getConnection();
  1599. if (PEAR :: isError($connection))
  1600. {
  1601. return $connection;
  1602. }
  1603. if (! @mysqli_more_results($connection))
  1604. {
  1605. return false;
  1606. }
  1607. if (! @mysqli_next_result($connection))
  1608. {
  1609. return false;
  1610. }
  1611. if (! ($this->result = @mysqli_store_result($connection)))
  1612. {
  1613. return false;
  1614. }
  1615. return MDB2_OK;
  1616. }
  1617. }
  1618. /**
  1619. * MDB2 MySQLi statement driver
  1620. *
  1621. * @package MDB2
  1622. * @category Database
  1623. * @author Lukas Smith <smith@pooteeweet.org>
  1624. */
  1625. class MDB2_Statement_mysqli extends MDB2_Statement_Common
  1626. {
  1627. // {{{ _execute()
  1628. /**
  1629. * Execute a prepared query statement helper method.
  1630. *
  1631. * @param mixed $result_class string which specifies which result class to use
  1632. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1633. *
  1634. * @return mixed MDB2_Result or integer (affected rows) on success,
  1635. * a MDB2 error on failure
  1636. * @access private
  1637. */
  1638. function &_execute($result_class = true, $result_wrap_class = false)
  1639. {
  1640. if (is_null($this->statement))
  1641. {
  1642. $result = & parent :: _execute($result_class, $result_wrap_class);
  1643. return $result;
  1644. }
  1645. $this->db->last_query = $this->query;
  1646. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre',
  1647. 'parameters' => $this->values));
  1648. if ($this->db->getOption('disable_query'))
  1649. {
  1650. $result = $this->is_manip ? 0 : null;
  1651. return $result;
  1652. }
  1653. $connection = $this->db->getConnection();
  1654. if (PEAR :: isError($connection))
  1655. {
  1656. return $connection;
  1657. }
  1658. if (! is_object($this->statement))
  1659. {
  1660. $query = 'EXECUTE ' . $this->statement;
  1661. }
  1662. if (! empty($this->positions))
  1663. {
  1664. $parameters = array(0 => $this->statement, 1 => '');
  1665. $parameter_references = array();
  1666. $lobs = array();
  1667. $i = 0;
  1668. foreach ($this->positions as $index => $parameter)
  1669. {
  1670. if (! array_key_exists($parameter, $this->values))
  1671. {
  1672. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $parameter, __FUNCTION__);
  1673. }
  1674. $value = $this->values[$parameter];
  1675. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1676. if (! is_object($this->statement))
  1677. {
  1678. if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include'])
  1679. {
  1680. if (! is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match))
  1681. {
  1682. if ($match[1] == 'file://')
  1683. {
  1684. $value = $match[2];
  1685. }
  1686. $value = @fopen($value, 'r');
  1687. $close = true;
  1688. }
  1689. if (is_resource($value))
  1690. {
  1691. $data = '';
  1692. while (! @feof($value))
  1693. {
  1694. $data .= @fread($value, $this->db->options['lob_buffer_length']);
  1695. }
  1696. if ($close)
  1697. {
  1698. @fclose($value);
  1699. }
  1700. $value = $data;
  1701. }
  1702. }
  1703. $quoted = $this->db->quote($value, $type);
  1704. if (PEAR :: isError($quoted))
  1705. {
  1706. return $quoted;
  1707. }
  1708. $param_query = 'SET @' . $parameter . ' = ' . $quoted;
  1709. $result = $this->db->_doQuery($param_query, true, $connection);
  1710. if (PEAR :: isError($result))
  1711. {
  1712. return $result;
  1713. }
  1714. }
  1715. else
  1716. {
  1717. if (is_resource($value) || $type == 'clob' || $type == 'blob')
  1718. {
  1719. $parameters[] = null;
  1720. $parameters[1] .= 'b';
  1721. $lobs[$i] = $parameter;
  1722. }
  1723. else
  1724. {
  1725. $quoted = $this->db->quote($value, $type, false);
  1726. if (PEAR :: isError($quoted))
  1727. {
  1728. return $quoted;
  1729. }
  1730. $parameter_references[$index] = $quoted;
  1731. $parameters[] = &$parameter_references[$index];
  1732. $parameters[1] .= $this->db->datatype->mapPrepareDatatype($type);
  1733. }
  1734. ++ $i;
  1735. }
  1736. }
  1737. if (! is_object($this->statement))
  1738. {
  1739. $query .= ' USING @' . implode(', @', array_values($this->positions));
  1740. }
  1741. else
  1742. {
  1743. $result = @call_user_func_array('mysqli_stmt_bind_param', $parameters);
  1744. if ($result === false)
  1745. {
  1746. $err = & $this->db->raiseError(null, null, null, 'Unable to bind parameters', __FUNCTION__);
  1747. return $err;
  1748. }
  1749. foreach ($lobs as $i => $parameter)
  1750. {
  1751. $value = $this->values[$parameter];
  1752. $close = false;
  1753. if (! is_resource($value))
  1754. {
  1755. $close = true;
  1756. if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match))
  1757. {
  1758. if ($match[1] == 'file://')
  1759. {
  1760. $value = $match[2];
  1761. }
  1762. $value = @fopen($value, 'r');
  1763. }
  1764. else
  1765. {
  1766. $fp = @tmpfile();
  1767. @fwrite($fp, $value);
  1768. @rewind($fp);
  1769. $value = $fp;
  1770. }
  1771. }
  1772. while (! @feof($value))
  1773. {
  1774. $data = @fread($value, $this->db->options['lob_buffer_length']);
  1775. @mysqli_stmt_send_long_data($this->statement, $i, $data);
  1776. }
  1777. if ($close)
  1778. {
  1779. @fclose($value);
  1780. }
  1781. }
  1782. }
  1783. }
  1784. if (! is_object($this->statement))
  1785. {
  1786. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1787. if (PEAR :: isError($result))
  1788. {
  1789. return $result;
  1790. }
  1791. if ($this->is_manip)
  1792. {
  1793. $affected_rows = $this->db->_affectedRows($connection, $result);
  1794. return $affected_rows;
  1795. }
  1796. $result = & $this->db->_wrapResult($result, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset);
  1797. }
  1798. else
  1799. {
  1800. if (! @mysqli_stmt_execute($this->statement))
  1801. {
  1802. $err = & $this->db->raiseError(null, null, null, 'Unable to execute statement', __FUNCTION__);
  1803. return $err;
  1804. }
  1805. if ($this->is_manip)
  1806. {
  1807. $affected_rows = @mysqli_stmt_affected_rows($this->statement);
  1808. return $affected_rows;
  1809. }
  1810. if ($this->db->options['result_buffering'])
  1811. {
  1812. @mysqli_stmt_store_result($this->statement);
  1813. }
  1814. $result = & $this->db->_wrapResult($this->statement, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset);
  1815. }
  1816. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post',
  1817. 'result' => $result));
  1818. return $result;
  1819. }
  1820. // }}}
  1821. // {{{ free()
  1822. /**
  1823. * Release resources allocated for the specified prepared query.
  1824. *
  1825. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1826. * @access public
  1827. */
  1828. function free()
  1829. {
  1830. if (is_null($this->positions))
  1831. {
  1832. return $this->db->raiseError(MDB2_ERROR, null, null, 'Prepared statement has already been freed', __FUNCTION__);
  1833. }
  1834. $result = MDB2_OK;
  1835. if (is_object($this->statement))
  1836. {
  1837. if (! @mysqli_stmt_close($this->statement))
  1838. {
  1839. $result = $this->db->raiseError(null, null, null, 'Could not free statement', __FUNCTION__);
  1840. }
  1841. }
  1842. elseif (! is_null($this->statement))
  1843. {
  1844. $connection = $this->db->getConnection();
  1845. if (PEAR :: isError($connection))
  1846. {
  1847. return $connection;
  1848. }
  1849. $query = 'DEALLOCATE PREPARE ' . $this->statement;
  1850. $result = $this->db->_doQuery($query, true, $connection);
  1851. }
  1852. parent :: free();
  1853. return $result;
  1854. }
  1855. }
  1856. ?>