blob: d26ab0432620f15f10503c9395b6048c5c405b41 [file] [log] [blame]
Darren Hillc4e266b2011-08-30 15:40:27 -04001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.1.6 or newer
6 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 2.0
13 * @filesource
14 */
15
16
17/**
18 * Cookie-based session management driver
19 *
20 * This is the CI_Session functionality, as written by EllisLab, abstracted out to a driver.
21 * I have done a little updating for PHP5, and made minor changes to extract this functionality from
22 * the public interface (now in the Session Library), but effectively this code is unchanged.
23 *
24 * @package CodeIgniter
25 * @subpackage Libraries
26 * @category Sessions
Darren Hill5073a372011-08-31 13:54:19 -040027 * @author ExpressionEngine Dev Team
Darren Hillc4e266b2011-08-30 15:40:27 -040028 */
Darren Hill5073a372011-08-31 13:54:19 -040029class CI_Session_cookie extends CI_Session_driver {
Darren Hillc4e266b2011-08-30 15:40:27 -040030 private $sess_encrypt_cookie = FALSE;
31 private $sess_use_database = FALSE;
32 private $sess_table_name = '';
33 private $sess_expiration = 7200;
34 private $sess_expire_on_close = FALSE;
35 private $sess_match_ip = FALSE;
36 private $sess_match_useragent = TRUE;
37 private $sess_cookie_name = 'ci_session';
38 private $cookie_prefix = '';
39 private $cookie_path = '';
40 private $cookie_domain = '';
41 private $sess_time_to_update = 300;
42 private $encryption_key = '';
43 private $time_reference = 'time';
44 private $userdata = array();
45 private $CI = null;
46 private $now = 0;
47
48 const gc_probability = 5;
49
50 /**
51 * Initialize session driver object
52 *
53 * @access protected
54 * @return void
55 */
56 protected function initialize()
57 {
58 // Set the super object to a local variable for use throughout the class
59 $this->CI =& get_instance();
60
61 // Set all the session preferences, which can either be set
62 // manually via the $params array above or via the config file
63 foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration',
64 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path',
65 'cookie_domain', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key)
66 {
67 $this->$key = (isset($this->parent->params[$key])) ? $this->parent->params[$key] : $this->CI->config->item($key);
68 }
69
70 if ($this->encryption_key == '')
71 {
72 show_error('In order to use the Cookie Session driver you are required to set an encryption key '.
73 'in your config file.');
74 }
75
76 // Load the string helper so we can use the strip_slashes() function
77 $this->CI->load->helper('string');
78
79 // Do we need encryption? If so, load the encryption class
80 if ($this->sess_encrypt_cookie == TRUE)
81 {
82 $this->CI->load->library('encrypt');
83 }
84
85 // Are we using a database? If so, load it
86 if ($this->sess_use_database === TRUE && $this->sess_table_name != '')
87 {
88 $this->CI->load->database();
89 }
90
91 // Set the "now" time. Can either be GMT or server time, based on the config prefs.
92 // We use this to set the "last activity" time
93 $this->now = $this->_get_time();
94
95 // Set the session length. If the session expiration is
96 // set to zero we'll set the expiration two years from now.
97 if ($this->sess_expiration == 0)
98 {
99 $this->sess_expiration = (60*60*24*365*2);
100 }
101
102 // Set the cookie name
103 $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name;
104
105 // Run the Session routine. If a session doesn't exist we'll
106 // create a new one. If it does, we'll update it.
107 if ( ! $this->_sess_read())
108 {
109 $this->_sess_create();
110 }
111 else
112 {
113 $this->_sess_update();
114 }
115
116 // Delete expired sessions if necessary
117 $this->_sess_gc();
118 }
119
120 /**
121 * Write the session data
122 *
123 * @return void
124 */
125 public function sess_save()
126 {
127 // Are we saving custom data to the DB? If not, all we do is update the cookie
128 if ($this->sess_use_database === FALSE)
129 {
130 $this->_set_cookie();
131 return;
132 }
133
134 // set the custom userdata, the session data we will set in a second
135 $custom_userdata = $this->all_userdata();
136 $cookie_userdata = array();
137
138 // Before continuing, we need to determine if there is any custom data to deal with.
139 // Let's determine this by removing the default indexes to see if there's anything left in the array
140 // and set the session data while we're at it
141 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
142 {
143 unset($custom_userdata[$val]);
144 $cookie_userdata[$val] = $this->userdata($val);
145 }
146
147 // Did we find any custom data? If not, we turn the empty array into a string
148 // since there's no reason to serialize and store an empty array in the DB
149 if (count($custom_userdata) === 0)
150 {
151 $custom_userdata = '';
152 }
153 else
154 {
155 // Serialize the custom data array so we can store it
156 $custom_userdata = $this->_serialize($custom_userdata);
157 }
158
159 // Run the update query
160 $this->CI->db->where('session_id', $this->userdata('session_id'));
161 $this->CI->db->update($this->sess_table_name,
162 array('last_activity' => $this->userdata('last_activity'), 'user_data' => $custom_userdata));
163
164 // Write the cookie. Notice that we manually pass the cookie data array to the
165 // _set_cookie() function. Normally that function will store $this->userdata, but
166 // in this case that array contains custom data, which we do not want in the cookie.
167 $this->_set_cookie($cookie_userdata);
168 }
169
170 /**
171 * Destroy the current session
172 *
173 * @return void
174 */
175 public function sess_destroy()
176 {
177 // Kill the session DB row
178 if ($this->sess_use_database === TRUE && $this->has_userdata('session_id'))
179 {
180 $this->CI->db->where('session_id', $this->userdata['session_id']);
181 $this->CI->db->delete($this->sess_table_name);
182 }
183
184 // Kill the cookie
185 setcookie($this->sess_cookie_name, addslashes(serialize(array())), ($this->now - 31500000),
186 $this->cookie_path, $this->cookie_domain, 0);
187 }
188
189 /**
190 * Regenerate the current session
191 *
192 * Regenerate the session id
193 *
194 * @param boolean Destroy session data flag (default: false)
195 * @return void
196 */
197 public function sess_regenerate($destroy = false)
198 {
199 // Check destroy flag
200 if ($destroy)
201 {
202 // Destroy old session and create new one
203 $this->sess_destroy();
204 $this->_sess_create();
205 }
206 else
207 {
208 // Just force an update to recreate the id
209 $this->_sess_update(true);
210 }
211 }
212
213 /**
214 * Get a reference to user data array
215 *
216 * @return array - Reference to userdata
217 */
218 public function &get_userdata()
219 {
220 // Return reference to array
221 return $this->userdata;
222 }
223
224 /**
225 * Fetch the current session data if it exists
226 *
227 * @access private
228 * @return bool
229 */
230 private function _sess_read()
231 {
232 // Fetch the cookie
233 $session = $this->CI->input->cookie($this->sess_cookie_name);
234
235 // No cookie? Goodbye cruel world!...
236 if ($session === FALSE)
237 {
238 log_message('debug', 'A session cookie was not found.');
239 return FALSE;
240 }
241
242 // Decrypt the cookie data
243 if ($this->sess_encrypt_cookie == TRUE)
244 {
245 $session = $this->CI->encrypt->decode($session);
246 }
247 else
248 {
249 // encryption was not used, so we need to check the md5 hash
250 $hash = substr($session, strlen($session)-32); // get last 32 chars
251 $session = substr($session, 0, strlen($session)-32);
252
253 // Does the md5 hash match? This is to prevent manipulation of session data in userspace
254 if ($hash !== md5($session.$this->encryption_key))
255 {
256 log_message('error', 'The session cookie data did not match what was expected. '.
257 'This could be a possible hacking attempt.');
258 $this->sess_destroy();
259 return FALSE;
260 }
261 }
262
263 // Unserialize the session array
264 $session = $this->_unserialize($session);
265
266 // Is the session data we unserialized an array with the correct format?
267 if ( ! is_array($session) || ! isset($session['session_id']) || ! isset($session['ip_address']) ||
268 ! isset($session['user_agent']) || ! isset($session['last_activity']))
269 {
270 $this->sess_destroy();
271 return FALSE;
272 }
273
274 // Is the session current?
275 if (($session['last_activity'] + $this->sess_expiration) < $this->now())
276 {
277 $this->sess_destroy();
278 return FALSE;
279 }
280
281 // Does the IP Match?
282 if ($this->sess_match_ip == TRUE && $session['ip_address'] != $this->CI->input->ip_address())
283 {
284 $this->sess_destroy();
285 return FALSE;
286 }
287
288 // Does the User Agent Match?
289 if ($this->sess_match_useragent == TRUE &&
290 trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 50)))
291 {
292 $this->sess_destroy();
293 return FALSE;
294 }
295
296 // Is there a corresponding session in the DB?
297 if ($this->sess_use_database === TRUE)
298 {
299 $this->CI->db->where('session_id', $session['session_id']);
300
301 if ($this->sess_match_ip == TRUE)
302 {
303 $this->CI->db->where('ip_address', $session['ip_address']);
304 }
305
306 if ($this->sess_match_useragent == TRUE)
307 {
308 $this->CI->db->where('user_agent', $session['user_agent']);
309 }
310
311 $query = $this->CI->db->get($this->sess_table_name);
312
313 // No result? Kill it!
314 if ($query->num_rows() == 0)
315 {
316 $this->sess_destroy();
317 return FALSE;
318 }
319
320 // Is there custom data? If so, add it to the main session array
321 $row = $query->row();
322 if (isset($row->user_data) && $row->user_data != '')
323 {
324 $custom_data = $this->_unserialize($row->user_data);
325
326 if (is_array($custom_data))
327 {
328 foreach ($custom_data as $key => $val)
329 {
330 $session[$key] = $val;
331 }
332 }
333 }
334 }
335
336 // Session is valid!
337 $this->userdata = $session;
338 unset($session);
339
340 return TRUE;
341 }
342
343 /**
344 * Create a new session
345 *
346 * @access private
347 * @return void
348 */
349 private function _sess_create()
350 {
351 $sessid = '';
352 while (strlen($sessid) < 32)
353 {
354 $sessid .= mt_rand(0, mt_getrandmax());
355 }
356
357 // To make the session ID even more secure we'll combine it with the user's IP
358 $sessid .= $this->CI->input->ip_address();
359
360 $this->set_userdata('session_id', md5(uniqid($sessid, TRUE)));
361 $this->set_userdata('ip_address', $this->CI->input->ip_address());
362 $this->set_userdata('user_agent', substr($this->CI->input->user_agent(), 0, 50));
363 $this->set_userdata('last_activity',$this->now());
364
365
366 // Save the data to the DB if needed
367 if ($this->sess_use_database === TRUE)
368 {
369 $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->all_userdata()));
370 }
371
372 // Write the cookie
373 $this->_set_cookie();
374 }
375
376 /**
377 * Update an existing session
378 *
379 * @access private
380 * @param boolean Force update flag (default: false)
381 * @return void
382 */
383 private function _sess_update($force = false)
384 {
385 // We only update the session every five minutes by default (unless forced)
386 if (!$force && ($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now())
387 {
388 return;
389 }
390
391 // Save the old session id so we know which record to
392 // update in the database if we need it
393 $old_sessid = $this->userdata['session_id'];
394 $new_sessid = '';
395 while (strlen($new_sessid) < 32)
396 {
397 $new_sessid .= mt_rand(0, mt_getrandmax());
398 }
399
400 // To make the session ID even more secure we'll combine it with the user's IP
401 $new_sessid .= $this->CI->input->ip_address();
402
403 // Turn it into a hash
404 $new_sessid = md5(uniqid($new_sessid, TRUE));
405
406 // Update the session data in the session data array
407 $this->set_userdata('session_id', $new_sessid);
408 $this->set_userdata('last_activity', $this->now());
409
410 // _set_cookie() will handle this for us if we aren't using database sessions
411 // by pushing all userdata to the cookie.
412 $cookie_data = NULL;
413
414 // Update the session ID and last_activity field in the DB if needed
415 if ($this->sess_use_database === TRUE)
416 {
417 // set cookie explicitly to only have our session data
418 $cookie_data = array();
419 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
420 {
421 $cookie_data[$val] = $this->userdata[$val];
422 }
423
424 $this->CI->db->query($this->CI->db->update_string($this->sess_table_name,
425 array('last_activity' => $this->now(), 'session_id' => $new_sessid),
426 array('session_id' => $old_sessid)));
427 }
428
429 // Write the cookie
430 $this->_set_cookie($cookie_data);
431 }
432
433 /**
434 * Get the "now" time
435 *
436 * @access private
437 * @return int
438 */
439 private function _get_time()
440 {
441 if (strtolower($this->time_reference) == 'gmt')
442 {
443 $now = time();
444 $time = mktime(gmdate('H', $now), gmdate('i', $now), gmdate('s', $now), gmdate('m', $now),
445 gmdate('d', $now), gmdate('Y', $now));
446 }
447 else
448 {
449 $time = time();
450 }
451
452 return $time;
453 }
454
455 /**
456 * Write the session cookie
457 *
458 * @access private
459 * @param array Cookie name/value pairs
460 * @return void
461 */
462 private function _set_cookie(array $cookie_data = NULL)
463 {
464 if (is_null($cookie_data))
465 {
466 $cookie_data = $this->all_userdata();
467 }
468
469 // Serialize the userdata for the cookie
470 $cookie_data = $this->_serialize($cookie_data);
471
472 if ($this->sess_encrypt_cookie == TRUE)
473 {
474 $cookie_data = $this->CI->encrypt->encode($cookie_data);
475 }
476 else
477 {
478 // if encryption is not used, we provide an md5 hash to prevent userside tampering
479 $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
480 }
481
482 $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
483
484 // Set the cookie
485 setcookie($this->sess_cookie_name, $cookie_data, $expire, $this->cookie_path, $this->cookie_domain, 0);
486 }
487
488 /**
489 * Serialize an array
490 *
491 * This function first converts any slashes found in the array to a temporary
492 * marker, so when it gets unserialized the slashes will be preserved
493 *
494 * @access private
495 * @param mixed Data to serialize
496 * @return string
497 */
498 private function _serialize($data)
499 {
500 if (is_array($data))
501 {
502 foreach ($data as $key => $val)
503 {
504 if (is_string($val))
505 {
506 $data[$key] = str_replace('\\', '{{slash}}', $val);
507 }
508 }
509 }
510 else
511 {
512 if (is_string($data))
513 {
514 $data = str_replace('\\', '{{slash}}', $data);
515 }
516 }
517
518 return serialize($data);
519 }
520
521 /**
522 * Unserialize
523 *
524 * This function unserializes a data string, then converts any
525 * temporary slash markers back to actual slashes
526 *
527 * @access private
528 * @param string Data to unserialize
529 * @return mixed
530 */
531 private function _unserialize($data)
532 {
533 $data = @unserialize(strip_slashes($data));
534
535 if (is_array($data))
536 {
537 foreach ($data as $key => $val)
538 {
539 if (is_string($val))
540 {
541 $data[$key] = str_replace('{{slash}}', '\\', $val);
542 }
543 }
544
545 return $data;
546 }
547
548 return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
549 }
550
551 /**
552 * Garbage collection
553 *
554 * This deletes expired session rows from database
555 * if the probability percentage is met
556 *
557 * @access private
558 * @return void
559 */
560 private function _sess_gc()
561 {
562 if ($this->sess_use_database != TRUE)
563 {
564 return;
565 }
566
567 srand(time());
568 if ((rand() % 100) < self::gc_probability)
569 {
570 $expire = $this->now() - $this->sess_expiration;
571
572 $this->CI->db->where('last_activity < '.$expire);
573 $this->CI->db->delete($this->sess_table_name);
574
575 log_message('debug', 'Session garbage collection performed.');
576 }
577 }
578}
Darren Hill5073a372011-08-31 13:54:19 -0400579// END CI_Session_cookie Class
Darren Hillc4e266b2011-08-30 15:40:27 -0400580
581/* End of file Session_cookie.php */
Darren Hill5073a372011-08-31 13:54:19 -0400582/* Location: ./system/libraries/Session/drivers/Session_cookie.php */
Darren Hillc4e266b2011-08-30 15:40:27 -0400583?>