Subversion-Projekte lars-tiefland.ci

Revision

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