Subversion-Projekte lars-tiefland.ci

Revision

Revision 2257 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
2414 lars 9
 * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
68 lars 10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
2414 lars 32
 * @copyright	Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
33
 * @license	https://opensource.org/licenses/MIT	MIT License
68 lars 34
 * @link	https://codeigniter.com
35
 * @since	Version 1.3.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * MySQLi Database Adapter Class
42
 *
43
 * Note: _DB is an extender class that the app controller
44
 * creates dynamically based on whether the query builder
45
 * class is being used or not.
46
 *
47
 * @package		CodeIgniter
48
 * @subpackage	Drivers
49
 * @category	Database
50
 * @author		EllisLab Dev Team
51
 * @link		https://codeigniter.com/user_guide/database/
52
 */
53
class CI_DB_mysqli_driver extends CI_DB {
54
 
55
	/**
56
	 * Database driver
57
	 *
58
	 * @var	string
59
	 */
60
	public $dbdriver = 'mysqli';
61
 
62
	/**
63
	 * Compression flag
64
	 *
65
	 * @var	bool
66
	 */
67
	public $compress = FALSE;
68
 
69
	/**
70
	 * DELETE hack flag
71
	 *
72
	 * Whether to use the MySQL "delete hack" which allows the number
73
	 * of affected rows to be shown. Uses a preg_replace when enabled,
74
	 * adding a bit more processing to all queries.
75
	 *
76
	 * @var	bool
77
	 */
78
	public $delete_hack = TRUE;
79
 
80
	/**
81
	 * Strict ON flag
82
	 *
83
	 * Whether we're running in strict SQL mode.
84
	 *
85
	 * @var	bool
86
	 */
87
	public $stricton;
88
 
89
	// --------------------------------------------------------------------
90
 
91
	/**
92
	 * Identifier escape character
93
	 *
94
	 * @var	string
95
	 */
96
	protected $_escape_char = '`';
97
 
98
	// --------------------------------------------------------------------
99
 
100
	/**
101
	 * MySQLi object
102
	 *
103
	 * Has to be preserved without being assigned to $conn_id.
104
	 *
105
	 * @var	MySQLi
106
	 */
107
	protected $_mysqli;
108
 
109
	// --------------------------------------------------------------------
110
 
111
	/**
112
	 * Database connection
113
	 *
114
	 * @param	bool	$persistent
115
	 * @return	object
116
	 */
117
	public function db_connect($persistent = FALSE)
118
	{
119
		// Do we have a socket path?
120
		if ($this->hostname[0] === '/')
121
		{
122
			$hostname = NULL;
123
			$port = NULL;
124
			$socket = $this->hostname;
125
		}
126
		else
127
		{
1257 lars 128
			$hostname = ($persistent === TRUE)
68 lars 129
				? 'p:'.$this->hostname : $this->hostname;
130
			$port = empty($this->port) ? NULL : $this->port;
131
			$socket = NULL;
132
		}
133
 
134
		$client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
135
		$this->_mysqli = mysqli_init();
136
 
137
		$this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
138
 
139
		if (isset($this->stricton))
140
		{
141
			if ($this->stricton)
142
			{
143
				$this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")');
144
			}
145
			else
146
			{
147
				$this->_mysqli->options(MYSQLI_INIT_COMMAND,
148
					'SET SESSION sql_mode =
149
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
150
					@@sql_mode,
151
					"STRICT_ALL_TABLES,", ""),
152
					",STRICT_ALL_TABLES", ""),
153
					"STRICT_ALL_TABLES", ""),
154
					"STRICT_TRANS_TABLES,", ""),
155
					",STRICT_TRANS_TABLES", ""),
156
					"STRICT_TRANS_TABLES", "")'
157
				);
158
			}
159
		}
160
 
161
		if (is_array($this->encrypt))
162
		{
163
			$ssl = array();
164
			empty($this->encrypt['ssl_key'])    OR $ssl['key']    = $this->encrypt['ssl_key'];
165
			empty($this->encrypt['ssl_cert'])   OR $ssl['cert']   = $this->encrypt['ssl_cert'];
166
			empty($this->encrypt['ssl_ca'])     OR $ssl['ca']     = $this->encrypt['ssl_ca'];
167
			empty($this->encrypt['ssl_capath']) OR $ssl['capath'] = $this->encrypt['ssl_capath'];
168
			empty($this->encrypt['ssl_cipher']) OR $ssl['cipher'] = $this->encrypt['ssl_cipher'];
169
 
2414 lars 170
			if (isset($this->encrypt['ssl_verify']))
68 lars 171
			{
2414 lars 172
				$client_flags |= MYSQLI_CLIENT_SSL;
173
 
174
				if ($this->encrypt['ssl_verify'])
68 lars 175
				{
2414 lars 176
					defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE);
68 lars 177
				}
2414 lars 178
				// Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
179
				// to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
180
				// constant ...
181
				//
182
				// https://secure.php.net/ChangeLog-5.php#5.6.16
183
				// https://bugs.php.net/bug.php?id=68344
184
				elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT'))
185
				{
186
					$client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
187
				}
188
			}
68 lars 189
 
2414 lars 190
			if ( ! empty($ssl))
191
			{
68 lars 192
				$client_flags |= MYSQLI_CLIENT_SSL;
193
				$this->_mysqli->ssl_set(
194
					isset($ssl['key'])    ? $ssl['key']    : NULL,
195
					isset($ssl['cert'])   ? $ssl['cert']   : NULL,
196
					isset($ssl['ca'])     ? $ssl['ca']     : NULL,
197
					isset($ssl['capath']) ? $ssl['capath'] : NULL,
198
					isset($ssl['cipher']) ? $ssl['cipher'] : NULL
199
				);
200
			}
201
		}
202
 
203
		if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags))
204
		{
205
			// Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails
206
			if (
207
				($client_flags & MYSQLI_CLIENT_SSL)
208
				&& version_compare($this->_mysqli->client_info, '5.7.3', '<=')
209
				&& empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
210
			)
211
			{
212
				$this->_mysqli->close();
213
				$message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
214
				log_message('error', $message);
2107 lars 215
				return ($this->db_debug) ? $this->display_error($message, '', TRUE) : FALSE;
68 lars 216
			}
217
 
218
			return $this->_mysqli;
219
		}
220
 
221
		return FALSE;
222
	}
223
 
224
	// --------------------------------------------------------------------
225
 
226
	/**
227
	 * Reconnect
228
	 *
229
	 * Keep / reestablish the db connection if no queries have been
230
	 * sent for a length of time exceeding the server's idle timeout
231
	 *
232
	 * @return	void
233
	 */
234
	public function reconnect()
235
	{
236
		if ($this->conn_id !== FALSE && $this->conn_id->ping() === FALSE)
237
		{
238
			$this->conn_id = FALSE;
239
		}
240
	}
241
 
242
	// --------------------------------------------------------------------
243
 
244
	/**
245
	 * Select the database
246
	 *
247
	 * @param	string	$database
248
	 * @return	bool
249
	 */
250
	public function db_select($database = '')
251
	{
252
		if ($database === '')
253
		{
254
			$database = $this->database;
255
		}
256
 
257
		if ($this->conn_id->select_db($database))
258
		{
259
			$this->database = $database;
260
			$this->data_cache = array();
261
			return TRUE;
262
		}
263
 
264
		return FALSE;
265
	}
266
 
267
	// --------------------------------------------------------------------
268
 
269
	/**
270
	 * Set client character set
271
	 *
272
	 * @param	string	$charset
273
	 * @return	bool
274
	 */
275
	protected function _db_set_charset($charset)
276
	{
277
		return $this->conn_id->set_charset($charset);
278
	}
279
 
280
	// --------------------------------------------------------------------
281
 
282
	/**
283
	 * Database version number
284
	 *
285
	 * @return	string
286
	 */
287
	public function version()
288
	{
289
		if (isset($this->data_cache['version']))
290
		{
291
			return $this->data_cache['version'];
292
		}
293
 
294
		return $this->data_cache['version'] = $this->conn_id->server_info;
295
	}
296
 
297
	// --------------------------------------------------------------------
298
 
299
	/**
300
	 * Execute the query
301
	 *
302
	 * @param	string	$sql	an SQL query
303
	 * @return	mixed
304
	 */
305
	protected function _execute($sql)
306
	{
307
		return $this->conn_id->query($this->_prep_query($sql));
308
	}
309
 
310
	// --------------------------------------------------------------------
311
 
312
	/**
313
	 * Prep the query
314
	 *
315
	 * If needed, each database adapter can prep the query string
316
	 *
317
	 * @param	string	$sql	an SQL query
318
	 * @return	string
319
	 */
320
	protected function _prep_query($sql)
321
	{
322
		// mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
323
		// modifies the query so that it a proper number of affected rows is returned.
324
		if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
325
		{
326
			return trim($sql).' WHERE 1=1';
327
		}
328
 
329
		return $sql;
330
	}
331
 
332
	// --------------------------------------------------------------------
333
 
334
	/**
335
	 * Begin Transaction
336
	 *
337
	 * @return	bool
338
	 */
339
	protected function _trans_begin()
340
	{
341
		$this->conn_id->autocommit(FALSE);
342
		return is_php('5.5')
343
			? $this->conn_id->begin_transaction()
344
			: $this->simple_query('START TRANSACTION'); // can also be BEGIN or BEGIN WORK
345
	}
346
 
347
	// --------------------------------------------------------------------
348
 
349
	/**
350
	 * Commit Transaction
351
	 *
352
	 * @return	bool
353
	 */
354
	protected function _trans_commit()
355
	{
356
		if ($this->conn_id->commit())
357
		{
358
			$this->conn_id->autocommit(TRUE);
359
			return TRUE;
360
		}
361
 
362
		return FALSE;
363
	}
364
 
365
	// --------------------------------------------------------------------
366
 
367
	/**
368
	 * Rollback Transaction
369
	 *
370
	 * @return	bool
371
	 */
372
	protected function _trans_rollback()
373
	{
374
		if ($this->conn_id->rollback())
375
		{
376
			$this->conn_id->autocommit(TRUE);
377
			return TRUE;
378
		}
379
 
380
		return FALSE;
381
	}
382
 
383
	// --------------------------------------------------------------------
384
 
385
	/**
2107 lars 386
	 * Platform-dependent string escape
68 lars 387
	 *
388
	 * @param	string
389
	 * @return	string
390
	 */
391
	protected function _escape_str($str)
392
	{
393
		return $this->conn_id->real_escape_string($str);
394
	}
395
 
396
	// --------------------------------------------------------------------
397
 
398
	/**
399
	 * Affected Rows
400
	 *
401
	 * @return	int
402
	 */
403
	public function affected_rows()
404
	{
405
		return $this->conn_id->affected_rows;
406
	}
407
 
408
	// --------------------------------------------------------------------
409
 
410
	/**
411
	 * Insert ID
412
	 *
413
	 * @return	int
414
	 */
415
	public function insert_id()
416
	{
417
		return $this->conn_id->insert_id;
418
	}
419
 
420
	// --------------------------------------------------------------------
421
 
422
	/**
423
	 * List table query
424
	 *
425
	 * Generates a platform-specific query string so that the table names can be fetched
426
	 *
427
	 * @param	bool	$prefix_limit
428
	 * @return	string
429
	 */
430
	protected function _list_tables($prefix_limit = FALSE)
431
	{
2414 lars 432
		$sql = 'SHOW TABLES FROM '.$this->_escape_char.$this->database.$this->_escape_char;
68 lars 433
 
434
		if ($prefix_limit !== FALSE && $this->dbprefix !== '')
435
		{
436
			return $sql." LIKE '".$this->escape_like_str($this->dbprefix)."%'";
437
		}
438
 
439
		return $sql;
440
	}
441
 
442
	// --------------------------------------------------------------------
443
 
444
	/**
445
	 * Show column query
446
	 *
447
	 * Generates a platform-specific query string so that the column names can be fetched
448
	 *
449
	 * @param	string	$table
450
	 * @return	string
451
	 */
452
	protected function _list_columns($table = '')
453
	{
454
		return 'SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE);
455
	}
456
 
457
	// --------------------------------------------------------------------
458
 
459
	/**
460
	 * Returns an object with field data
461
	 *
462
	 * @param	string	$table
463
	 * @return	array
464
	 */
465
	public function field_data($table)
466
	{
467
		if (($query = $this->query('SHOW COLUMNS FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE))) === FALSE)
468
		{
469
			return FALSE;
470
		}
471
		$query = $query->result_object();
472
 
473
		$retval = array();
474
		for ($i = 0, $c = count($query); $i < $c; $i++)
475
		{
476
			$retval[$i]			= new stdClass();
477
			$retval[$i]->name		= $query[$i]->Field;
478
 
479
			sscanf($query[$i]->Type, '%[a-z](%d)',
480
				$retval[$i]->type,
481
				$retval[$i]->max_length
482
			);
483
 
484
			$retval[$i]->default		= $query[$i]->Default;
485
			$retval[$i]->primary_key	= (int) ($query[$i]->Key === 'PRI');
486
		}
487
 
488
		return $retval;
489
	}
490
 
491
	// --------------------------------------------------------------------
492
 
493
	/**
494
	 * Error
495
	 *
496
	 * Returns an array containing code and message of the last
497
	 * database error that has occurred.
498
	 *
499
	 * @return	array
500
	 */
501
	public function error()
502
	{
503
		if ( ! empty($this->_mysqli->connect_errno))
504
		{
505
			return array(
1257 lars 506
				'code'    => $this->_mysqli->connect_errno,
507
				'message' => $this->_mysqli->connect_error
68 lars 508
			);
509
		}
510
 
511
		return array('code' => $this->conn_id->errno, 'message' => $this->conn_id->error);
512
	}
513
 
514
	// --------------------------------------------------------------------
515
 
516
	/**
517
	 * FROM tables
518
	 *
519
	 * Groups tables in FROM clauses if needed, so there is no confusion
520
	 * about operator precedence.
521
	 *
522
	 * @return	string
523
	 */
524
	protected function _from_tables()
525
	{
526
		if ( ! empty($this->qb_join) && count($this->qb_from) > 1)
527
		{
528
			return '('.implode(', ', $this->qb_from).')';
529
		}
530
 
531
		return implode(', ', $this->qb_from);
532
	}
533
 
534
	// --------------------------------------------------------------------
535
 
536
	/**
537
	 * Close DB Connection
538
	 *
539
	 * @return	void
540
	 */
541
	protected function _close()
542
	{
543
		$this->conn_id->close();
544
	}
545
 
546
}