summaryrefslogtreecommitdiffstats
path: root/system/libraries/Session/drivers/Session_database_driver.php
blob: 2bdc4d0d56a39fb674eea82044ba4b4510da2b76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.2.4 or newer
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the Open Software License version 3.0
 *
 * This source file is subject to the Open Software License (OSL 3.0) that is
 * bundled with this package in the files license.txt / license.rst.  It is
 * also available through the world wide web at this URL:
 * http://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to obtain it
 * through the world wide web, please send an email to
 * licensing@ellislab.com so we can send you a copy immediately.
 *
 * @package		CodeIgniter
 * @author		Andrey Andreev
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
 * @license		http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * @link		http://codeigniter.com
 * @since		Version 3.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter Session Database Driver
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Sessions
 * @author		Andrey Andreev
 * @link		http://codeigniter.com/user_guide/libraries/sessions.html
 */
class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface {

	/**
	 * DB object
	 *
	 * @var	object
	 */
	protected $_db;

	/**
	 * DB table
	 *
	 * @var	string
	 */
	protected $_table;

	/**
	 * Session ID
	 *
	 * @var	string
	 */
	protected $_session_id;

	/**
	 * Row exists flag
	 *
	 * @var	bool
	 */
	protected $_row_exists = FALSE;

	/**
	 * Lock "driver" flag
	 *
	 * @var	string
	 */
	protected $_lock_driver;

	/**
	 * Lock status flag
	 *
	 * @var	bool
	 */
	protected $_lock = FALSE;

	/**
	 * Semaphore ID
	 *
	 * Used for locking if the database doesn't support advisory locks
	 *
	 * @var	resource
	 */
	protected $_sem;

	// ------------------------------------------------------------------------

	/**
	 * Class constructor
	 *
	 * @param	array	$params	Configuration parameters
	 * @return	void
	 */
	public function __construct(&$params)
	{
		parent::__construct($params);

		$CI =& get_instance();
		isset($CI->db) OR $CI->load->database();
		$this->_db =& $CI->db;

		if ( ! $this->_db instanceof CI_DB_query_builder)
		{
			throw new Exception('Query Builder not enabled for the configured database. Aborting.');
		}
		elseif ($this->_db->pconnect)
		{
			throw new Exception('Configured database connection is persistent. Aborting.');
		}

		$db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver);
		if (strpos($db_driver, 'mysql') !== FALSE)
		{
			$this->_lock_driver = 'mysql';
		}
		elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE))
		{
			$this->_lock_driver = 'postgre';
		}
		elseif (extension_loaded('sysvsem'))
		{
			$this->_lock_driver = 'semaphore';
		}

		isset($this->_table) OR $this->_table = config_item('sess_table_name');
	}

	// ------------------------------------------------------------------------

	public function open($save_path, $name)
	{
		return empty($this->_db->conn_id)
			? ( ! $this->_db->autoinit && $this->_db->db_connect())
			: TRUE;
	}

	// ------------------------------------------------------------------------

	public function read($session_id)
	{
		$this->_session_id = $session_id;
		if (($this->_lock = $this->_get_lock()) !== FALSE)
		{
			$this->_db
				->select('data')
				->from($this->_table)
				->where('id', $session_id);

			if ($this->_match_ip)
			{
				$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
			}

			if (($result = $this->_db->get()->row()) === NULL)
			{
				$this->_fingerprint = md5('');
				return '';
			}

			$this->_fingerprint = md5(rtrim($result->data));
			$this->_row_exists = TRUE;
			return $result->data;
		}

		$this->_fingerprint = md5('');
		return '';
	}

	public function write($session_id, $session_data)
	{
		if ($this->_lock === FALSE)
		{
			return FALSE;
		}

		if ($this->_row_exists === FALSE)
		{
			if ($this->_db->insert($this->_table, array('id' => $session_id, 'ip_address' => $_SERVER['REMOTE_ADDR'], 'timestamp' => time(), 'data' => $session_data)))
			{
				$this->_fingerprint = md5($session_data);
				return $this->_row_exists = TRUE;
			}

			return FALSE;
		}

		$this->_db->where('id', $session_id);
		if ($this->_match_ip)
		{
			$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
		}

		$update_data = ($this->_fingerprint === md5($session_data))
			? array('timestamp' => time())
			: array('timestamp' => time(), 'data' => $session_data);

		if ($this->_db->update($this->_table, $update_data))
		{
			$this->_fingerprint = md5($session_data);
			return TRUE;
		}

		return FALSE;
	}

	// ------------------------------------------------------------------------

	public function close()
	{
		return ($this->_lock)
			? $this->_release_lock()
			: TRUE;
	}

	// ------------------------------------------------------------------------

	public function destroy($session_id)
	{
		if ($this->_lock)
		{
			$this->_db->where('id', $session_id);
			if ($this->_match_ip)
			{
				$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
			}

			return $this->_db->delete($this->_table)
				? ($this->close() && $this->_cookie_destroy())
				: FALSE;
		}

		return ($this->close() && $this->_cookie_destroy());
	}

	// ------------------------------------------------------------------------

	public function gc($maxlifetime)
	{
		return $this->_db->delete($this->_table, 'timestamp < '.(time() - $maxlifetime));
	}

	// ------------------------------------------------------------------------

	protected function _get_lock()
	{
		if ($this->_lock_driver === 'mysql')
		{
			$arg = $this->_session_id
				.($this->_match_ip ? '_'.$_SERVER['REMOTE_ADDR'] : '');
			return (bool) $this->_db
				->query("SELECT GET_LOCK('".$arg."', 10) AS ci_session_lock")
				->row()
				->ci_session_lock;
		}
		elseif ($this->_lock_driver === 'postgre')
		{
			$arg = "hashtext('".$this->_session_id."')"
				.($this->_match_ip ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : '');

			return (bool) $this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')');
		}
		elseif ($this->_lock_driver === 'semaphore')
		{
			if (($this->_sem = sem_get($arg, 1, 0644)) === FALSE)
			{
				return FALSE;
			}

			if ( ! sem_acquire($this->_sem))
			{
				sem_remove($this->_sem);
				return FALSE;
			}

			return TRUE;
		}

		return TRUE;
	}

	// ------------------------------------------------------------------------

	protected function _release_lock()
	{
		if ($this->_lock_driver === 'mysql')
		{
			$arg = $this->_session_id
				.($this->_match_ip ? '_'.$_SERVER['REMOTE_ADDR'] : '');

			return (bool) $this->_db
				->query("SELECT RELEASE_LOCK('".$arg."') AS ci_session_lock")
				->row()
				->ci_session_lock;
		}
		elseif ($this->_lock_driver === 'postgre')
		{
			$arg = "hashtext('".$this->_session_id."')"
				.($this->_match_ip ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : '');

			return (bool) $this->_db->simple_query('SELECT pg_advisory_unlock('.$arg.')');
		}
		elseif ($this->_lock_driver === 'semaphore')
		{
			sem_release($this->_sem);
			sem_remove($this->_sem);
		}

		return TRUE;
	}

}

/* End of file Session_database_driver.php */
/* Location: ./system/libraries/Session/drivers/Session_database_driver.php */