PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/system/libraries/Session.php

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