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