blob: 53ff4f5d37becce0a1afa9a5d3e95304f886bc9e [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +00001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
Greg Aker741de1c2010-11-10 14:52:57 -06005 * An open source application development framework for PHP 5.1.6 or newer
Derek Allard2067d1a2008-11-13 22:59:24 +00006 *
7 * @package CodeIgniter
8 * @author ExpressionEngine Dev Team
Greg Aker0711dc82011-01-05 10:49:40 -06009 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
Derek Allard2067d1a2008-11-13 22:59:24 +000010 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
12 * @since Version 1.0
13 * @filesource
14 */
15
16// ------------------------------------------------------------------------
17
18/**
19 * Session Class
20 *
21 * @package CodeIgniter
22 * @subpackage Libraries
23 * @category Sessions
24 * @author ExpressionEngine Dev Team
25 * @link http://codeigniter.com/user_guide/libraries/sessions.html
26 */
27class CI_Session {
28
29 var $sess_encrypt_cookie = FALSE;
30 var $sess_use_database = FALSE;
31 var $sess_table_name = '';
32 var $sess_expiration = 7200;
Derek Joneseaa71ba2010-09-02 10:32:07 -050033 var $sess_expire_on_close = FALSE;
Derek Allard2067d1a2008-11-13 22:59:24 +000034 var $sess_match_ip = FALSE;
35 var $sess_match_useragent = TRUE;
36 var $sess_cookie_name = 'ci_session';
37 var $cookie_prefix = '';
38 var $cookie_path = '';
39 var $cookie_domain = '';
40 var $sess_time_to_update = 300;
41 var $encryption_key = '';
Barry Mienydd671972010-10-04 16:33:58 +020042 var $flashdata_key = 'flash';
Derek Allard2067d1a2008-11-13 22:59:24 +000043 var $time_reference = 'time';
44 var $gc_probability = 5;
45 var $userdata = array();
46 var $CI;
47 var $now;
48
49 /**
50 * Session Constructor
51 *
52 * The constructor runs the session routines automatically
53 * whenever the class is instantiated.
54 */
Greg Akera9263282010-11-10 15:26:43 -060055 public function __construct($params = array())
Derek Allard2067d1a2008-11-13 22:59:24 +000056 {
57 log_message('debug', "Session Class Initialized");
58
59 // Set the super object to a local variable for use throughout the class
60 $this->CI =& get_instance();
61
62 // Set all the session preferences, which can either be set
63 // manually via the $params array above or via the config file
Derek Jones71eee842010-10-05 09:40:43 -050064 foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', '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)
Derek Allard2067d1a2008-11-13 22:59:24 +000065 {
66 $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key);
67 }
68
Derek Jones5485db52010-08-30 21:31:08 -050069 if ($this->encryption_key == '')
70 {
71 show_error('In order to use the Session class you are required to set an encryption key in your config file.');
72 }
73
Derek Allard2067d1a2008-11-13 22:59:24 +000074 // Load the string helper so we can use the strip_slashes() function
75 $this->CI->load->helper('string');
76
77 // Do we need encryption? If so, load the encryption class
78 if ($this->sess_encrypt_cookie == TRUE)
79 {
80 $this->CI->load->library('encrypt');
81 }
82
83 // Are we using a database? If so, load it
84 if ($this->sess_use_database === TRUE AND $this->sess_table_name != '')
85 {
86 $this->CI->load->database();
87 }
88
89 // Set the "now" time. Can either be GMT or server time, based on the
90 // config prefs. We use this to set the "last activity" time
91 $this->now = $this->_get_time();
92
93 // Set the session length. If the session expiration is
94 // set to zero we'll set the expiration two years from now.
95 if ($this->sess_expiration == 0)
96 {
97 $this->sess_expiration = (60*60*24*365*2);
98 }
Barry Mienydd671972010-10-04 16:33:58 +020099
Derek Allard2067d1a2008-11-13 22:59:24 +0000100 // Set the cookie name
101 $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name;
102
103 // Run the Session routine. If a session doesn't exist we'll
104 // create a new one. If it does, we'll update it.
105 if ( ! $this->sess_read())
106 {
107 $this->sess_create();
108 }
109 else
110 {
111 $this->sess_update();
112 }
113
114 // Delete 'old' flashdata (from last request)
Barry Mienydd671972010-10-04 16:33:58 +0200115 $this->_flashdata_sweep();
Derek Allard2067d1a2008-11-13 22:59:24 +0000116
117 // Mark all new flashdata as old (data will be deleted before next request)
Barry Mienydd671972010-10-04 16:33:58 +0200118 $this->_flashdata_mark();
Derek Allard2067d1a2008-11-13 22:59:24 +0000119
120 // Delete expired sessions if necessary
121 $this->_sess_gc();
122
123 log_message('debug', "Session routines successfully run");
124 }
125
126 // --------------------------------------------------------------------
127
128 /**
129 * Fetch the current session data if it exists
130 *
131 * @access public
132 * @return bool
133 */
134 function sess_read()
135 {
136 // Fetch the cookie
137 $session = $this->CI->input->cookie($this->sess_cookie_name);
138
139 // No cookie? Goodbye cruel world!...
140 if ($session === FALSE)
141 {
142 log_message('debug', 'A session cookie was not found.');
143 return FALSE;
144 }
145
146 // Decrypt the cookie data
147 if ($this->sess_encrypt_cookie == TRUE)
148 {
149 $session = $this->CI->encrypt->decode($session);
150 }
151 else
152 {
153 // encryption was not used, so we need to check the md5 hash
154 $hash = substr($session, strlen($session)-32); // get last 32 chars
155 $session = substr($session, 0, strlen($session)-32);
156
157 // Does the md5 hash match? This is to prevent manipulation of session data in userspace
158 if ($hash !== md5($session.$this->encryption_key))
159 {
160 log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.');
161 $this->sess_destroy();
162 return FALSE;
163 }
164 }
165
166 // Unserialize the session array
167 $session = $this->_unserialize($session);
168
169 // Is the session data we unserialized an array with the correct format?
170 if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity']))
171 {
172 $this->sess_destroy();
173 return FALSE;
174 }
175
176 // Is the session current?
177 if (($session['last_activity'] + $this->sess_expiration) < $this->now)
178 {
179 $this->sess_destroy();
180 return FALSE;
181 }
182
183 // Does the IP Match?
184 if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
185 {
186 $this->sess_destroy();
187 return FALSE;
188 }
189
190 // Does the User Agent Match?
191 if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 50)))
192 {
193 $this->sess_destroy();
194 return FALSE;
195 }
196
197 // Is there a corresponding session in the DB?
198 if ($this->sess_use_database === TRUE)
199 {
200 $this->CI->db->where('session_id', $session['session_id']);
201
202 if ($this->sess_match_ip == TRUE)
203 {
204 $this->CI->db->where('ip_address', $session['ip_address']);
205 }
206
207 if ($this->sess_match_useragent == TRUE)
208 {
209 $this->CI->db->where('user_agent', $session['user_agent']);
210 }
211
212 $query = $this->CI->db->get($this->sess_table_name);
213
214 // No result? Kill it!
215 if ($query->num_rows() == 0)
216 {
217 $this->sess_destroy();
218 return FALSE;
219 }
220
221 // Is there custom data? If so, add it to the main session array
222 $row = $query->row();
223 if (isset($row->user_data) AND $row->user_data != '')
224 {
225 $custom_data = $this->_unserialize($row->user_data);
226
227 if (is_array($custom_data))
228 {
229 foreach ($custom_data as $key => $val)
230 {
231 $session[$key] = $val;
232 }
233 }
234 }
235 }
236
237 // Session is valid!
238 $this->userdata = $session;
239 unset($session);
240
241 return TRUE;
242 }
243
244 // --------------------------------------------------------------------
245
246 /**
247 * Write the session data
248 *
249 * @access public
250 * @return void
251 */
252 function sess_write()
253 {
254 // Are we saving custom data to the DB? If not, all we do is update the cookie
255 if ($this->sess_use_database === FALSE)
256 {
257 $this->_set_cookie();
258 return;
259 }
260
261 // set the custom userdata, the session data we will set in a second
262 $custom_userdata = $this->userdata;
263 $cookie_userdata = array();
264
265 // Before continuing, we need to determine if there is any custom data to deal with.
266 // Let's determine this by removing the default indexes to see if there's anything left in the array
267 // and set the session data while we're at it
268 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
269 {
270 unset($custom_userdata[$val]);
271 $cookie_userdata[$val] = $this->userdata[$val];
272 }
273
274 // Did we find any custom data? If not, we turn the empty array into a string
275 // since there's no reason to serialize and store an empty array in the DB
276 if (count($custom_userdata) === 0)
277 {
278 $custom_userdata = '';
279 }
280 else
281 {
282 // Serialize the custom data array so we can store it
283 $custom_userdata = $this->_serialize($custom_userdata);
284 }
285
286 // Run the update query
287 $this->CI->db->where('session_id', $this->userdata['session_id']);
288 $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));
289
290 // Write the cookie. Notice that we manually pass the cookie data array to the
291 // _set_cookie() function. Normally that function will store $this->userdata, but
292 // in this case that array contains custom data, which we do not want in the cookie.
293 $this->_set_cookie($cookie_userdata);
294 }
295
296 // --------------------------------------------------------------------
297
298 /**
299 * Create a new session
300 *
301 * @access public
302 * @return void
303 */
304 function sess_create()
305 {
306 $sessid = '';
307 while (strlen($sessid) < 32)
308 {
309 $sessid .= mt_rand(0, mt_getrandmax());
310 }
311
312 // To make the session ID even more secure we'll combine it with the user's IP
313 $sessid .= $this->CI->input->ip_address();
314
315 $this->userdata = array(
Barry Mienydd671972010-10-04 16:33:58 +0200316 'session_id' => md5(uniqid($sessid, TRUE)),
317 'ip_address' => $this->CI->input->ip_address(),
318 'user_agent' => substr($this->CI->input->user_agent(), 0, 50),
Derek Allard2067d1a2008-11-13 22:59:24 +0000319 'last_activity' => $this->now
320 );
321
322
323 // Save the data to the DB if needed
324 if ($this->sess_use_database === TRUE)
325 {
326 $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
327 }
328
329 // Write the cookie
330 $this->_set_cookie();
331 }
332
333 // --------------------------------------------------------------------
334
335 /**
336 * Update an existing session
337 *
338 * @access public
339 * @return void
340 */
341 function sess_update()
342 {
343 // We only update the session every five minutes by default
344 if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
345 {
346 return;
347 }
348
349 // Save the old session id so we know which record to
350 // update in the database if we need it
351 $old_sessid = $this->userdata['session_id'];
352 $new_sessid = '';
353 while (strlen($new_sessid) < 32)
354 {
355 $new_sessid .= mt_rand(0, mt_getrandmax());
356 }
357
358 // To make the session ID even more secure we'll combine it with the user's IP
359 $new_sessid .= $this->CI->input->ip_address();
360
361 // Turn it into a hash
362 $new_sessid = md5(uniqid($new_sessid, TRUE));
363
364 // Update the session data in the session data array
365 $this->userdata['session_id'] = $new_sessid;
366 $this->userdata['last_activity'] = $this->now;
367
368 // _set_cookie() will handle this for us if we aren't using database sessions
369 // by pushing all userdata to the cookie.
370 $cookie_data = NULL;
371
372 // Update the session ID and last_activity field in the DB if needed
373 if ($this->sess_use_database === TRUE)
374 {
375 // set cookie explicitly to only have our session data
376 $cookie_data = array();
377 foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
378 {
379 $cookie_data[$val] = $this->userdata[$val];
380 }
381
382 $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)));
383 }
384
385 // Write the cookie
386 $this->_set_cookie($cookie_data);
387 }
388
389 // --------------------------------------------------------------------
390
391 /**
392 * Destroy the current session
393 *
394 * @access public
395 * @return void
396 */
397 function sess_destroy()
398 {
399 // Kill the session DB row
400 if ($this->sess_use_database === TRUE AND isset($this->userdata['session_id']))
401 {
402 $this->CI->db->where('session_id', $this->userdata['session_id']);
403 $this->CI->db->delete($this->sess_table_name);
404 }
405
406 // Kill the cookie
407 setcookie(
408 $this->sess_cookie_name,
409 addslashes(serialize(array())),
410 ($this->now - 31500000),
411 $this->cookie_path,
412 $this->cookie_domain,
413 0
414 );
415 }
416
417 // --------------------------------------------------------------------
418
419 /**
420 * Fetch a specific item from the session array
421 *
422 * @access public
423 * @param string
424 * @return string
425 */
426 function userdata($item)
427 {
428 return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
429 }
430
431 // --------------------------------------------------------------------
432
433 /**
434 * Fetch all session data
435 *
436 * @access public
437 * @return mixed
438 */
439 function all_userdata()
440 {
441 return ( ! isset($this->userdata)) ? FALSE : $this->userdata;
442 }
443
444 // --------------------------------------------------------------------
445
446 /**
447 * Add or change data in the "userdata" array
448 *
449 * @access public
450 * @param mixed
451 * @param string
452 * @return void
453 */
454 function set_userdata($newdata = array(), $newval = '')
455 {
456 if (is_string($newdata))
457 {
458 $newdata = array($newdata => $newval);
459 }
460
461 if (count($newdata) > 0)
462 {
463 foreach ($newdata as $key => $val)
464 {
465 $this->userdata[$key] = $val;
466 }
467 }
468
469 $this->sess_write();
470 }
471
472 // --------------------------------------------------------------------
473
474 /**
475 * Delete a session variable from the "userdata" array
476 *
477 * @access array
478 * @return void
479 */
480 function unset_userdata($newdata = array())
481 {
482 if (is_string($newdata))
483 {
484 $newdata = array($newdata => '');
485 }
486
487 if (count($newdata) > 0)
488 {
489 foreach ($newdata as $key => $val)
490 {
491 unset($this->userdata[$key]);
492 }
493 }
494
495 $this->sess_write();
496 }
497
498 // ------------------------------------------------------------------------
499
500 /**
501 * Add or change flashdata, only available
502 * until the next request
503 *
504 * @access public
505 * @param mixed
506 * @param string
507 * @return void
508 */
509 function set_flashdata($newdata = array(), $newval = '')
510 {
511 if (is_string($newdata))
512 {
513 $newdata = array($newdata => $newval);
514 }
515
516 if (count($newdata) > 0)
517 {
518 foreach ($newdata as $key => $val)
519 {
520 $flashdata_key = $this->flashdata_key.':new:'.$key;
521 $this->set_userdata($flashdata_key, $val);
522 }
523 }
524 }
525
526 // ------------------------------------------------------------------------
527
528 /**
529 * Keeps existing flashdata available to next request.
530 *
531 * @access public
532 * @param string
533 * @return void
534 */
535 function keep_flashdata($key)
536 {
537 // 'old' flashdata gets removed. Here we mark all
538 // flashdata as 'new' to preserve it from _flashdata_sweep()
539 // Note the function will return FALSE if the $key
540 // provided cannot be found
541 $old_flashdata_key = $this->flashdata_key.':old:'.$key;
542 $value = $this->userdata($old_flashdata_key);
543
544 $new_flashdata_key = $this->flashdata_key.':new:'.$key;
545 $this->set_userdata($new_flashdata_key, $value);
546 }
547
548 // ------------------------------------------------------------------------
549
550 /**
551 * Fetch a specific flashdata item from the session array
552 *
553 * @access public
554 * @param string
555 * @return string
556 */
557 function flashdata($key)
558 {
559 $flashdata_key = $this->flashdata_key.':old:'.$key;
560 return $this->userdata($flashdata_key);
561 }
562
563 // ------------------------------------------------------------------------
564
565 /**
566 * Identifies flashdata as 'old' for removal
567 * when _flashdata_sweep() runs.
568 *
569 * @access private
570 * @return void
571 */
572 function _flashdata_mark()
573 {
574 $userdata = $this->all_userdata();
575 foreach ($userdata as $name => $value)
576 {
577 $parts = explode(':new:', $name);
578 if (is_array($parts) && count($parts) === 2)
579 {
580 $new_name = $this->flashdata_key.':old:'.$parts[1];
581 $this->set_userdata($new_name, $value);
582 $this->unset_userdata($name);
583 }
584 }
585 }
586
587 // ------------------------------------------------------------------------
588
589 /**
590 * Removes all flashdata marked as 'old'
591 *
592 * @access private
593 * @return void
594 */
595
596 function _flashdata_sweep()
597 {
598 $userdata = $this->all_userdata();
599 foreach ($userdata as $key => $value)
600 {
601 if (strpos($key, ':old:'))
602 {
603 $this->unset_userdata($key);
604 }
605 }
606
607 }
608
609 // --------------------------------------------------------------------
610
611 /**
612 * Get the "now" time
613 *
614 * @access private
615 * @return string
616 */
617 function _get_time()
618 {
619 if (strtolower($this->time_reference) == 'gmt')
620 {
621 $now = time();
622 $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
623 }
624 else
625 {
626 $time = time();
627 }
628
629 return $time;
630 }
631
632 // --------------------------------------------------------------------
633
634 /**
635 * Write the session cookie
636 *
637 * @access public
638 * @return void
639 */
640 function _set_cookie($cookie_data = NULL)
641 {
642 if (is_null($cookie_data))
643 {
644 $cookie_data = $this->userdata;
645 }
646
647 // Serialize the userdata for the cookie
648 $cookie_data = $this->_serialize($cookie_data);
649
650 if ($this->sess_encrypt_cookie == TRUE)
651 {
652 $cookie_data = $this->CI->encrypt->encode($cookie_data);
653 }
654 else
655 {
656 // if encryption is not used, we provide an md5 hash to prevent userside tampering
657 $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
658 }
Barry Mienydd671972010-10-04 16:33:58 +0200659
Derek Joneseaa71ba2010-09-02 10:32:07 -0500660 $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
Barry Mienydd671972010-10-04 16:33:58 +0200661
Derek Allard2067d1a2008-11-13 22:59:24 +0000662 // Set the cookie
663 setcookie(
664 $this->sess_cookie_name,
665 $cookie_data,
Derek Joneseaa71ba2010-09-02 10:32:07 -0500666 $expire,
Derek Allard2067d1a2008-11-13 22:59:24 +0000667 $this->cookie_path,
668 $this->cookie_domain,
669 0
670 );
671 }
672
673 // --------------------------------------------------------------------
674
675 /**
676 * Serialize an array
677 *
678 * This function first converts any slashes found in the array to a temporary
679 * marker, so when it gets unserialized the slashes will be preserved
680 *
681 * @access private
682 * @param array
683 * @return string
684 */
685 function _serialize($data)
686 {
687 if (is_array($data))
688 {
689 foreach ($data as $key => $val)
690 {
Derek Jones133e6662010-03-29 11:36:42 -0500691 if (is_string($val))
692 {
Barry Mienydd671972010-10-04 16:33:58 +0200693 $data[$key] = str_replace('\\', '{{slash}}', $val);
Derek Jones133e6662010-03-29 11:36:42 -0500694 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000695 }
696 }
697 else
698 {
Derek Jones133e6662010-03-29 11:36:42 -0500699 if (is_string($data))
700 {
Barry Mienydd671972010-10-04 16:33:58 +0200701 $data = str_replace('\\', '{{slash}}', $data);
Derek Jones133e6662010-03-29 11:36:42 -0500702 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000703 }
704
705 return serialize($data);
706 }
707
708 // --------------------------------------------------------------------
709
710 /**
711 * Unserialize
712 *
713 * This function unserializes a data string, then converts any
714 * temporary slash markers back to actual slashes
715 *
716 * @access private
717 * @param array
718 * @return string
719 */
720 function _unserialize($data)
721 {
722 $data = @unserialize(strip_slashes($data));
723
724 if (is_array($data))
725 {
726 foreach ($data as $key => $val)
727 {
Derek Jones133e6662010-03-29 11:36:42 -0500728 if (is_string($val))
729 {
Barry Mienydd671972010-10-04 16:33:58 +0200730 $data[$key] = str_replace('{{slash}}', '\\', $val);
Derek Jones133e6662010-03-29 11:36:42 -0500731 }
Derek Allard2067d1a2008-11-13 22:59:24 +0000732 }
733
734 return $data;
735 }
736
Derek Jones133e6662010-03-29 11:36:42 -0500737 return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
Derek Allard2067d1a2008-11-13 22:59:24 +0000738 }
739
740 // --------------------------------------------------------------------
741
742 /**
743 * Garbage collection
744 *
745 * This deletes expired session rows from database
746 * if the probability percentage is met
747 *
748 * @access public
749 * @return void
750 */
751 function _sess_gc()
752 {
753 if ($this->sess_use_database != TRUE)
754 {
755 return;
756 }
757
758 srand(time());
759 if ((rand() % 100) < $this->gc_probability)
760 {
761 $expire = $this->now - $this->sess_expiration;
762
763 $this->CI->db->where("last_activity < {$expire}");
764 $this->CI->db->delete($this->sess_table_name);
765
766 log_message('debug', 'Session garbage collection performed.');
767 }
768 }
769
770
771}
772// END Session Class
773
774/* End of file Session.php */
Derek Jonesa3ffbbb2008-05-11 18:18:29 +0000775/* Location: ./system/libraries/Session.php */