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