Subversion-Projekte lars-tiefland.ci

Revision

Revision 2107 | Revision 2254 | Zur aktuellen Revision | 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
 *
2242 lars 9
 * Copyright (c) 2014 - 2018, 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/)
2242 lars 32
 * @copyright	Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
68 lars 33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 3.0.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * CodeIgniter Session Database Driver
42
 *
43
 * @package	CodeIgniter
44
 * @subpackage	Libraries
45
 * @category	Sessions
46
 * @author	Andrey Andreev
47
 * @link	https://codeigniter.com/user_guide/libraries/sessions.html
48
 */
49
class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface {
50
 
51
	/**
52
	 * DB object
53
	 *
54
	 * @var	object
55
	 */
56
	protected $_db;
57
 
58
	/**
59
	 * Row exists flag
60
	 *
61
	 * @var	bool
62
	 */
63
	protected $_row_exists = FALSE;
64
 
65
	/**
66
	 * Lock "driver" flag
67
	 *
68
	 * @var	string
69
	 */
70
	protected $_platform;
71
 
72
	// ------------------------------------------------------------------------
73
 
74
	/**
75
	 * Class constructor
76
	 *
77
	 * @param	array	$params	Configuration parameters
78
	 * @return	void
79
	 */
80
	public function __construct(&$params)
81
	{
82
		parent::__construct($params);
83
 
84
		$CI =& get_instance();
85
		isset($CI->db) OR $CI->load->database();
86
		$this->_db = $CI->db;
87
 
88
		if ( ! $this->_db instanceof CI_DB_query_builder)
89
		{
90
			throw new Exception('Query Builder not enabled for the configured database. Aborting.');
91
		}
92
		elseif ($this->_db->pconnect)
93
		{
94
			throw new Exception('Configured database connection is persistent. Aborting.');
95
		}
96
		elseif ($this->_db->cache_on)
97
		{
98
			throw new Exception('Configured database connection has cache enabled. Aborting.');
99
		}
100
 
101
		$db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver);
102
		if (strpos($db_driver, 'mysql') !== FALSE)
103
		{
104
			$this->_platform = 'mysql';
105
		}
106
		elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE))
107
		{
108
			$this->_platform = 'postgre';
109
		}
110
 
111
		// Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future.
112
		if ( ! isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name')))
113
		{
114
			log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".');
115
		}
116
	}
117
 
118
	// ------------------------------------------------------------------------
119
 
120
	/**
121
	 * Open
122
	 *
123
	 * Initializes the database connection
124
	 *
125
	 * @param	string	$save_path	Table name
126
	 * @param	string	$name		Session cookie name, unused
127
	 * @return	bool
128
	 */
129
	public function open($save_path, $name)
130
	{
131
		if (empty($this->_db->conn_id) && ! $this->_db->db_connect())
132
		{
133
			return $this->_fail();
134
		}
135
 
2242 lars 136
		$this->php5_validate_id();
137
 
68 lars 138
		return $this->_success;
139
	}
140
 
141
	// ------------------------------------------------------------------------
142
 
143
	/**
144
	 * Read
145
	 *
146
	 * Reads session data and acquires a lock
147
	 *
148
	 * @param	string	$session_id	Session ID
149
	 * @return	string	Serialized session data
150
	 */
151
	public function read($session_id)
152
	{
153
		if ($this->_get_lock($session_id) !== FALSE)
154
		{
155
			// Prevent previous QB calls from messing with our queries
156
			$this->_db->reset_query();
157
 
158
			// Needed by write() to detect session_regenerate_id() calls
159
			$this->_session_id = $session_id;
160
 
161
			$this->_db
162
				->select('data')
163
				->from($this->_config['save_path'])
164
				->where('id', $session_id);
165
 
166
			if ($this->_config['match_ip'])
167
			{
168
				$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
169
			}
170
 
171
			if ( ! ($result = $this->_db->get()) OR ($result = $result->row()) === NULL)
172
			{
173
				// PHP7 will reuse the same SessionHandler object after
174
				// ID regeneration, so we need to explicitly set this to
175
				// FALSE instead of relying on the default ...
176
				$this->_row_exists = FALSE;
177
				$this->_fingerprint = md5('');
178
				return '';
179
			}
180
 
181
			// PostgreSQL's variant of a BLOB datatype is Bytea, which is a
182
			// PITA to work with, so we use base64-encoded data in a TEXT
183
			// field instead.
184
			$result = ($this->_platform === 'postgre')
185
				? base64_decode(rtrim($result->data))
186
				: $result->data;
187
 
188
			$this->_fingerprint = md5($result);
189
			$this->_row_exists = TRUE;
190
			return $result;
191
		}
192
 
193
		$this->_fingerprint = md5('');
194
		return '';
195
	}
196
 
197
	// ------------------------------------------------------------------------
198
 
199
	/**
200
	 * Write
201
	 *
202
	 * Writes (create / update) session data
203
	 *
204
	 * @param	string	$session_id	Session ID
205
	 * @param	string	$session_data	Serialized session data
206
	 * @return	bool
207
	 */
208
	public function write($session_id, $session_data)
209
	{
210
		// Prevent previous QB calls from messing with our queries
211
		$this->_db->reset_query();
212
 
213
		// Was the ID regenerated?
2107 lars 214
		if (isset($this->_session_id) && $session_id !== $this->_session_id)
68 lars 215
		{
216
			if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
217
			{
218
				return $this->_fail();
219
			}
220
 
221
			$this->_row_exists = FALSE;
222
			$this->_session_id = $session_id;
223
		}
2107 lars 224
		elseif ($this->_lock === FALSE)
225
		{
226
			return $this->_fail();
227
		}
68 lars 228
 
229
		if ($this->_row_exists === FALSE)
230
		{
231
			$insert_data = array(
232
				'id' => $session_id,
233
				'ip_address' => $_SERVER['REMOTE_ADDR'],
234
				'timestamp' => time(),
235
				'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data)
236
			);
237
 
238
			if ($this->_db->insert($this->_config['save_path'], $insert_data))
239
			{
240
				$this->_fingerprint = md5($session_data);
241
				$this->_row_exists = TRUE;
242
				return $this->_success;
243
			}
244
 
245
			return $this->_fail();
246
		}
247
 
248
		$this->_db->where('id', $session_id);
249
		if ($this->_config['match_ip'])
250
		{
251
			$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
252
		}
253
 
254
		$update_data = array('timestamp' => time());
255
		if ($this->_fingerprint !== md5($session_data))
256
		{
257
			$update_data['data'] = ($this->_platform === 'postgre')
258
				? base64_encode($session_data)
259
				: $session_data;
260
		}
261
 
262
		if ($this->_db->update($this->_config['save_path'], $update_data))
263
		{
264
			$this->_fingerprint = md5($session_data);
265
			return $this->_success;
266
		}
267
 
268
		return $this->_fail();
269
	}
270
 
271
	// ------------------------------------------------------------------------
272
 
273
	/**
274
	 * Close
275
	 *
276
	 * Releases locks
277
	 *
278
	 * @return	bool
279
	 */
280
	public function close()
281
	{
282
		return ($this->_lock && ! $this->_release_lock())
283
			? $this->_fail()
284
			: $this->_success;
285
	}
286
 
287
	// ------------------------------------------------------------------------
288
 
289
	/**
290
	 * Destroy
291
	 *
292
	 * Destroys the current session.
293
	 *
294
	 * @param	string	$session_id	Session ID
295
	 * @return	bool
296
	 */
297
	public function destroy($session_id)
298
	{
299
		if ($this->_lock)
300
		{
301
			// Prevent previous QB calls from messing with our queries
302
			$this->_db->reset_query();
303
 
304
			$this->_db->where('id', $session_id);
305
			if ($this->_config['match_ip'])
306
			{
307
				$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
308
			}
309
 
310
			if ( ! $this->_db->delete($this->_config['save_path']))
311
			{
312
				return $this->_fail();
313
			}
314
		}
315
 
316
		if ($this->close() === $this->_success)
317
		{
318
			$this->_cookie_destroy();
319
			return $this->_success;
320
		}
321
 
322
		return $this->_fail();
323
	}
324
 
325
	// ------------------------------------------------------------------------
326
 
327
	/**
328
	 * Garbage Collector
329
	 *
330
	 * Deletes expired sessions
331
	 *
332
	 * @param	int 	$maxlifetime	Maximum lifetime of sessions
333
	 * @return	bool
334
	 */
335
	public function gc($maxlifetime)
336
	{
337
		// Prevent previous QB calls from messing with our queries
338
		$this->_db->reset_query();
339
 
340
		return ($this->_db->delete($this->_config['save_path'], 'timestamp < '.(time() - $maxlifetime)))
341
			? $this->_success
342
			: $this->_fail();
343
	}
344
 
2242 lars 345
	// --------------------------------------------------------------------
346
 
347
	/**
348
	 * Validate ID
349
	 *
350
	 * Checks whether a session ID record exists server-side,
351
	 * to enforce session.use_strict_mode.
352
	 *
353
	 * @param	string	$id
354
	 * @return	bool
355
	 */
356
	public function validateId($id)
357
	{
358
		// Prevent previous QB calls from messing with our queries
359
		$this->_db->reset_query();
360
 
361
		$this->_db->select('1')->from($this->_config['save_path'])->where('id', $id);
362
		empty($this->_config['match_ip']) OR $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
363
		$result = $this->_db->get();
364
		empty($result) OR $result = $result->row();
365
 
366
		return ! empty($result);
367
	}
368
 
68 lars 369
	// ------------------------------------------------------------------------
370
 
371
	/**
372
	 * Get lock
373
	 *
374
	 * Acquires a lock, depending on the underlying platform.
375
	 *
376
	 * @param	string	$session_id	Session ID
377
	 * @return	bool
378
	 */
379
	protected function _get_lock($session_id)
380
	{
381
		if ($this->_platform === 'mysql')
382
		{
2049 lars 383
			$arg = md5($session_id.($this->_config['match_ip'] ? '_'.$_SERVER['REMOTE_ADDR'] : ''));
68 lars 384
			if ($this->_db->query("SELECT GET_LOCK('".$arg."', 300) AS ci_session_lock")->row()->ci_session_lock)
385
			{
386
				$this->_lock = $arg;
387
				return TRUE;
388
			}
389
 
390
			return FALSE;
391
		}
392
		elseif ($this->_platform === 'postgre')
393
		{
394
			$arg = "hashtext('".$session_id."')".($this->_config['match_ip'] ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : '');
395
			if ($this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')'))
396
			{
397
				$this->_lock = $arg;
398
				return TRUE;
399
			}
400
 
401
			return FALSE;
402
		}
403
 
404
		return parent::_get_lock($session_id);
405
	}
406
 
407
	// ------------------------------------------------------------------------
408
 
409
	/**
410
	 * Release lock
411
	 *
412
	 * Releases a previously acquired lock
413
	 *
414
	 * @return	bool
415
	 */
416
	protected function _release_lock()
417
	{
418
		if ( ! $this->_lock)
419
		{
420
			return TRUE;
421
		}
422
 
423
		if ($this->_platform === 'mysql')
424
		{
425
			if ($this->_db->query("SELECT RELEASE_LOCK('".$this->_lock."') AS ci_session_lock")->row()->ci_session_lock)
426
			{
427
				$this->_lock = FALSE;
428
				return TRUE;
429
			}
430
 
431
			return FALSE;
432
		}
433
		elseif ($this->_platform === 'postgre')
434
		{
435
			if ($this->_db->simple_query('SELECT pg_advisory_unlock('.$this->_lock.')'))
436
			{
437
				$this->_lock = FALSE;
438
				return TRUE;
439
			}
440
 
441
			return FALSE;
442
		}
443
 
444
		return parent::_release_lock();
445
	}
2049 lars 446
}