1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 4.3.2 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2009, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * @package CodeIgniter
22 * @subpackage Libraries
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/sessions.html
29 var $sess_encrypt_cookie = FALSE;
30 var $sess_use_database = FALSE;
31 var $sess_table_name = '';
32 var $sess_expiration = 7200;
33 var $sess_match_ip = FALSE;
34 var $sess_match_useragent = TRUE;
35 var $sess_cookie_name = 'ci_session';
36 var $cookie_prefix = '';
37 var $cookie_path = '';
38 var $cookie_domain = '';
39 var $sess_time_to_update = 300;
40 var $encryption_key = '';
41 var $flashdata_key = 'flash';
42 var $time_reference = 'time';
43 var $gc_probability = 5;
44 var $userdata = array();
51 * The constructor runs the session routines automatically
52 * whenever the class is instantiated.
54 function CI_Session($params = array())
56 log_message('debug', "Session Class Initialized");
58 // Set the super object to a local variable for use throughout the class
59 $this->CI =& get_instance();
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', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key)
65 $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key);
68 // Load the string helper so we can use the strip_slashes() function
69 $this->CI->load->helper('string');
71 // Do we need encryption? If so, load the encryption class
72 if ($this->sess_encrypt_cookie == TRUE)
74 $this->CI->load->library('encrypt');
77 // Are we using a database? If so, load it
78 if ($this->sess_use_database === TRUE AND $this->sess_table_name != '')
80 $this->CI->load->database();
83 // Set the "now" time. Can either be GMT or server time, based on the
84 // config prefs. We use this to set the "last activity" time
85 $this->now = $this->_get_time();
87 // Set the session length. If the session expiration is
88 // set to zero we'll set the expiration two years from now.
89 if ($this->sess_expiration == 0)
91 $this->sess_expiration = (60*60*24*365*2);
94 // Set the cookie name
95 $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name;
97 // Run the Session routine. If a session doesn't exist we'll
98 // create a new one. If it does, we'll update it.
99 if ( ! $this->sess_read())
101 $this->sess_create();
105 $this->sess_update();
108 // Delete 'old' flashdata (from last request)
109 $this->_flashdata_sweep();
111 // Mark all new flashdata as old (data will be deleted before next request)
112 $this->_flashdata_mark();
114 // Delete expired sessions if necessary
117 log_message('debug', "Session routines successfully run");
120 // --------------------------------------------------------------------
123 * Fetch the current session data if it exists
131 $session = $this->CI->input->cookie($this->sess_cookie_name);
133 // No cookie? Goodbye cruel world!...
134 if ($session === FALSE)
136 log_message('debug', 'A session cookie was not found.');
140 // Decrypt the cookie data
141 if ($this->sess_encrypt_cookie == TRUE)
143 $session = $this->CI->encrypt->decode($session);
147 // encryption was not used, so we need to check the md5 hash
148 $hash = substr($session, strlen($session)-32); // get last 32 chars
149 $session = substr($session, 0, strlen($session)-32);
151 // Does the md5 hash match? This is to prevent manipulation of session data in userspace
152 if ($hash !== md5($session.$this->encryption_key))
154 log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.');
155 $this->sess_destroy();
160 // Unserialize the session array
161 $session = $this->_unserialize($session);
163 // Is the session data we unserialized an array with the correct format?
164 if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity']))
166 $this->sess_destroy();
170 // Is the session current?
171 if (($session['last_activity'] + $this->sess_expiration) < $this->now)
173 $this->sess_destroy();
177 // Does the IP Match?
178 if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
180 $this->sess_destroy();
184 // Does the User Agent Match?
185 if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 50)))
187 $this->sess_destroy();
191 // Is there a corresponding session in the DB?
192 if ($this->sess_use_database === TRUE)
194 $this->CI->db->where('session_id', $session['session_id']);
196 if ($this->sess_match_ip == TRUE)
198 $this->CI->db->where('ip_address', $session['ip_address']);
201 if ($this->sess_match_useragent == TRUE)
203 $this->CI->db->where('user_agent', $session['user_agent']);
206 $query = $this->CI->db->get($this->sess_table_name);
208 // No result? Kill it!
209 if ($query->num_rows() == 0)
211 $this->sess_destroy();
215 // Is there custom data? If so, add it to the main session array
216 $row = $query->row();
217 if (isset($row->user_data) AND $row->user_data != '')
219 $custom_data = $this->_unserialize($row->user_data);
221 if (is_array($custom_data))
223 foreach ($custom_data as $key => $val)
225 $session[$key] = $val;
232 $this->userdata = $session;
238 // --------------------------------------------------------------------
241 * Write the session data
246 function sess_write()
248 // Are we saving custom data to the DB? If not, all we do is update the cookie
249 if ($this->sess_use_database === FALSE)
251 $this->_set_cookie();
255 // set the custom userdata, the session data we will set in a second
256 $custom_userdata = $this->userdata;
257 $cookie_userdata = array();
259 // Before continuing, we need to determine if there is any custom data to deal with.
260 // Let's determine this by removing the default indexes to see if there's anything left in the array
261 // and set the session data while we're at it
262 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
264 unset($custom_userdata[$val]);
265 $cookie_userdata[$val] = $this->userdata[$val];
268 // Did we find any custom data? If not, we turn the empty array into a string
269 // since there's no reason to serialize and store an empty array in the DB
270 if (count($custom_userdata) === 0)
272 $custom_userdata = '';
276 // Serialize the custom data array so we can store it
277 $custom_userdata = $this->_serialize($custom_userdata);
280 // Run the update query
281 $this->CI->db->where('session_id', $this->userdata['session_id']);
282 $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));
284 // Write the cookie. Notice that we manually pass the cookie data array to the
285 // _set_cookie() function. Normally that function will store $this->userdata, but
286 // in this case that array contains custom data, which we do not want in the cookie.
287 $this->_set_cookie($cookie_userdata);
290 // --------------------------------------------------------------------
293 * Create a new session
298 function sess_create()
301 while (strlen($sessid) < 32)
303 $sessid .= mt_rand(0, mt_getrandmax());
306 // To make the session ID even more secure we'll combine it with the user's IP
307 $sessid .= $this->CI->input->ip_address();
309 $this->userdata = array(
310 'session_id' => md5(uniqid($sessid, TRUE)),
311 'ip_address' => $this->CI->input->ip_address(),
312 'user_agent' => substr($this->CI->input->user_agent(), 0, 50),
313 'last_activity' => $this->now
317 // Save the data to the DB if needed
318 if ($this->sess_use_database === TRUE)
320 $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
324 $this->_set_cookie();
327 // --------------------------------------------------------------------
330 * Update an existing session
335 function sess_update()
337 // We only update the session every five minutes by default
338 if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
343 // Save the old session id so we know which record to
344 // update in the database if we need it
345 $old_sessid = $this->userdata['session_id'];
347 while (strlen($new_sessid) < 32)
349 $new_sessid .= mt_rand(0, mt_getrandmax());
352 // To make the session ID even more secure we'll combine it with the user's IP
353 $new_sessid .= $this->CI->input->ip_address();
355 // Turn it into a hash
356 $new_sessid = md5(uniqid($new_sessid, TRUE));
358 // Update the session data in the session data array
359 $this->userdata['session_id'] = $new_sessid;
360 $this->userdata['last_activity'] = $this->now;
362 // _set_cookie() will handle this for us if we aren't using database sessions
363 // by pushing all userdata to the cookie.
366 // Update the session ID and last_activity field in the DB if needed
367 if ($this->sess_use_database === TRUE)
369 // set cookie explicitly to only have our session data
370 $cookie_data = array();
371 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
373 $cookie_data[$val] = $this->userdata[$val];
376 $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
380 $this->_set_cookie($cookie_data);
383 // --------------------------------------------------------------------
386 * Destroy the current session
391 function sess_destroy()
393 // Kill the session DB row
394 if ($this->sess_use_database === TRUE AND isset($this->userdata['session_id']))
396 $this->CI->db->where('session_id', $this->userdata['session_id']);
397 $this->CI->db->delete($this->sess_table_name);
402 $this->sess_cookie_name,
403 addslashes(serialize(array())),
404 ($this->now - 31500000),
406 $this->cookie_domain,
411 // --------------------------------------------------------------------
414 * Fetch a specific item from the session array
420 function userdata($item)
422 return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
425 // --------------------------------------------------------------------
428 * Fetch all session data
433 function all_userdata()
435 return ( ! isset($this->userdata)) ? FALSE : $this->userdata;
438 // --------------------------------------------------------------------
441 * Add or change data in the "userdata" array
448 function set_userdata($newdata = array(), $newval = '')
450 if (is_string($newdata))
452 $newdata = array($newdata => $newval);
455 if (count($newdata) > 0)
457 foreach ($newdata as $key => $val)
459 $this->userdata[$key] = $val;
466 // --------------------------------------------------------------------
469 * Delete a session variable from the "userdata" array
474 function unset_userdata($newdata = array())
476 if (is_string($newdata))
478 $newdata = array($newdata => '');
481 if (count($newdata) > 0)
483 foreach ($newdata as $key => $val)
485 unset($this->userdata[$key]);
492 // ------------------------------------------------------------------------
495 * Add or change flashdata, only available
496 * until the next request
503 function set_flashdata($newdata = array(), $newval = '')
505 if (is_string($newdata))
507 $newdata = array($newdata => $newval);
510 if (count($newdata) > 0)
512 foreach ($newdata as $key => $val)
514 $flashdata_key = $this->flashdata_key.':new:'.$key;
515 $this->set_userdata($flashdata_key, $val);
520 // ------------------------------------------------------------------------
523 * Keeps existing flashdata available to next request.
529 function keep_flashdata($key)
531 // 'old' flashdata gets removed. Here we mark all
532 // flashdata as 'new' to preserve it from _flashdata_sweep()
533 // Note the function will return FALSE if the $key
534 // provided cannot be found
535 $old_flashdata_key = $this->flashdata_key.':old:'.$key;
536 $value = $this->userdata($old_flashdata_key);
538 $new_flashdata_key = $this->flashdata_key.':new:'.$key;
539 $this->set_userdata($new_flashdata_key, $value);
542 // ------------------------------------------------------------------------
545 * Fetch a specific flashdata item from the session array
551 function flashdata($key)
553 $flashdata_key = $this->flashdata_key.':old:'.$key;
554 return $this->userdata($flashdata_key);
557 // ------------------------------------------------------------------------
560 * Identifies flashdata as 'old' for removal
561 * when _flashdata_sweep() runs.
566 function _flashdata_mark()
568 $userdata = $this->all_userdata();
569 foreach ($userdata as $name => $value)
571 $parts = explode(':new:', $name);
572 if (is_array($parts) && count($parts) === 2)
574 $new_name = $this->flashdata_key.':old:'.$parts[1];
575 $this->set_userdata($new_name, $value);
576 $this->unset_userdata($name);
581 // ------------------------------------------------------------------------
584 * Removes all flashdata marked as 'old'
590 function _flashdata_sweep()
592 $userdata = $this->all_userdata();
593 foreach ($userdata as $key => $value)
595 if (strpos($key, ':old:'))
597 $this->unset_userdata($key);
603 // --------------------------------------------------------------------
613 if (strtolower($this->time_reference) == 'gmt')
616 $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
626 // --------------------------------------------------------------------
629 * Write the session cookie
634 function _set_cookie($cookie_data = NULL)
636 if (is_null($cookie_data))
638 $cookie_data = $this->userdata;
641 // Serialize the userdata for the cookie
642 $cookie_data = $this->_serialize($cookie_data);
644 if ($this->sess_encrypt_cookie == TRUE)
646 $cookie_data = $this->CI->encrypt->encode($cookie_data);
650 // if encryption is not used, we provide an md5 hash to prevent userside tampering
651 $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
656 $this->sess_cookie_name,
658 $this->sess_expiration + time(),
660 $this->cookie_domain,
665 // --------------------------------------------------------------------
670 * This function first converts any slashes found in the array to a temporary
671 * marker, so when it gets unserialized the slashes will be preserved
677 function _serialize($data)
681 foreach ($data as $key => $val)
683 $data[$key] = str_replace('\\', '{{slash}}', $val);
688 $data = str_replace('\\', '{{slash}}', $data);
691 return serialize($data);
694 // --------------------------------------------------------------------
699 * This function unserializes a data string, then converts any
700 * temporary slash markers back to actual slashes
706 function _unserialize($data)
708 $data = @unserialize(strip_slashes($data));
712 foreach ($data as $key => $val)
714 $data[$key] = str_replace('{{slash}}', '\\', $val);
720 return str_replace('{{slash}}', '\\', $data);
723 // --------------------------------------------------------------------
728 * This deletes expired session rows from database
729 * if the probability percentage is met
736 if ($this->sess_use_database != TRUE)
742 if ((rand() % 100) < $this->gc_probability)
744 $expire = $this->now - $this->sess_expiration;
746 $this->CI->db->where("last_activity < {$expire}");
747 $this->CI->db->delete($this->sess_table_name);
749 log_message('debug', 'Session garbage collection performed.');
757 /* End of file Session.php */
758 /* Location: ./system/libraries/Session.php */