PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/system/libraries/Session.php

https://bitbucket.org/hlevine/myclientbase-south-african-version
PHP | 777 lines | 414 code | 113 blank | 250 comment | 61 complexity | 0f165598001e26cc9667dadd78018fe6 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, GPL-2.0
  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. 'user_data' => ''
  274. );
  275. // Save the data to the DB if needed
  276. if ($this->sess_use_database === TRUE)
  277. {
  278. $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
  279. }
  280. // Write the cookie
  281. $this->_set_cookie();
  282. }
  283. // --------------------------------------------------------------------
  284. /**
  285. * Update an existing session
  286. *
  287. * @access public
  288. * @return void
  289. */
  290. function sess_update()
  291. {
  292. // We only update the session every five minutes by default
  293. if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
  294. {
  295. return;
  296. }
  297. // Save the old session id so we know which record to
  298. // update in the database if we need it
  299. $old_sessid = $this->userdata['session_id'];
  300. $new_sessid = '';
  301. while (strlen($new_sessid) < 32)
  302. {
  303. $new_sessid .= mt_rand(0, mt_getrandmax());
  304. }
  305. // To make the session ID even more secure we'll combine it with the user's IP
  306. $new_sessid .= $this->CI->input->ip_address();
  307. // Turn it into a hash
  308. $new_sessid = md5(uniqid($new_sessid, TRUE));
  309. // Update the session data in the session data array
  310. $this->userdata['session_id'] = $new_sessid;
  311. $this->userdata['last_activity'] = $this->now;
  312. // _set_cookie() will handle this for us if we aren't using database sessions
  313. // by pushing all userdata to the cookie.
  314. $cookie_data = NULL;
  315. // Update the session ID and last_activity field in the DB if needed
  316. if ($this->sess_use_database === TRUE)
  317. {
  318. // set cookie explicitly to only have our session data
  319. $cookie_data = array();
  320. foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
  321. {
  322. $cookie_data[$val] = $this->userdata[$val];
  323. }
  324. $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)));
  325. }
  326. // Write the cookie
  327. $this->_set_cookie($cookie_data);
  328. }
  329. // --------------------------------------------------------------------
  330. /**
  331. * Destroy the current session
  332. *
  333. * @access public
  334. * @return void
  335. */
  336. function sess_destroy()
  337. {
  338. // Kill the session DB row
  339. if ($this->sess_use_database === TRUE AND isset($this->userdata['session_id']))
  340. {
  341. $this->CI->db->where('session_id', $this->userdata['session_id']);
  342. $this->CI->db->delete($this->sess_table_name);
  343. }
  344. // Kill the cookie
  345. setcookie(
  346. $this->sess_cookie_name,
  347. addslashes(serialize(array())),
  348. ($this->now - 31500000),
  349. $this->cookie_path,
  350. $this->cookie_domain,
  351. 0
  352. );
  353. }
  354. // --------------------------------------------------------------------
  355. /**
  356. * Fetch a specific item from the session array
  357. *
  358. * @access public
  359. * @param string
  360. * @return string
  361. */
  362. function userdata($item)
  363. {
  364. return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
  365. }
  366. // --------------------------------------------------------------------
  367. /**
  368. * Fetch all session data
  369. *
  370. * @access public
  371. * @return array
  372. */
  373. function all_userdata()
  374. {
  375. return $this->userdata;
  376. }
  377. // --------------------------------------------------------------------
  378. /**
  379. * Add or change data in the "userdata" array
  380. *
  381. * @access public
  382. * @param mixed
  383. * @param string
  384. * @return void
  385. */
  386. function set_userdata($newdata = array(), $newval = '')
  387. {
  388. if (is_string($newdata))
  389. {
  390. $newdata = array($newdata => $newval);
  391. }
  392. if (count($newdata) > 0)
  393. {
  394. foreach ($newdata as $key => $val)
  395. {
  396. $this->userdata[$key] = $val;
  397. }
  398. }
  399. $this->sess_write();
  400. }
  401. // --------------------------------------------------------------------
  402. /**
  403. * Delete a session variable from the "userdata" array
  404. *
  405. * @access array
  406. * @return void
  407. */
  408. function unset_userdata($newdata = array())
  409. {
  410. if (is_string($newdata))
  411. {
  412. $newdata = array($newdata => '');
  413. }
  414. if (count($newdata) > 0)
  415. {
  416. foreach ($newdata as $key => $val)
  417. {
  418. unset($this->userdata[$key]);
  419. }
  420. }
  421. $this->sess_write();
  422. }
  423. // ------------------------------------------------------------------------
  424. /**
  425. * Add or change flashdata, only available
  426. * until the next request
  427. *
  428. * @access public
  429. * @param mixed
  430. * @param string
  431. * @return void
  432. */
  433. function set_flashdata($newdata = array(), $newval = '')
  434. {
  435. if (is_string($newdata))
  436. {
  437. $newdata = array($newdata => $newval);
  438. }
  439. if (count($newdata) > 0)
  440. {
  441. foreach ($newdata as $key => $val)
  442. {
  443. $flashdata_key = $this->flashdata_key.':new:'.$key;
  444. $this->set_userdata($flashdata_key, $val);
  445. }
  446. }
  447. }
  448. // ------------------------------------------------------------------------
  449. /**
  450. * Keeps existing flashdata available to next request.
  451. *
  452. * @access public
  453. * @param string
  454. * @return void
  455. */
  456. function keep_flashdata($key)
  457. {
  458. // 'old' flashdata gets removed. Here we mark all
  459. // flashdata as 'new' to preserve it from _flashdata_sweep()
  460. // Note the function will return FALSE if the $key
  461. // provided cannot be found
  462. $old_flashdata_key = $this->flashdata_key.':old:'.$key;
  463. $value = $this->userdata($old_flashdata_key);
  464. $new_flashdata_key = $this->flashdata_key.':new:'.$key;
  465. $this->set_userdata($new_flashdata_key, $value);
  466. }
  467. // ------------------------------------------------------------------------
  468. /**
  469. * Fetch a specific flashdata item from the session array
  470. *
  471. * @access public
  472. * @param string
  473. * @return string
  474. */
  475. function flashdata($key)
  476. {
  477. $flashdata_key = $this->flashdata_key.':old:'.$key;
  478. return $this->userdata($flashdata_key);
  479. }
  480. // ------------------------------------------------------------------------
  481. /**
  482. * Identifies flashdata as 'old' for removal
  483. * when _flashdata_sweep() runs.
  484. *
  485. * @access private
  486. * @return void
  487. */
  488. function _flashdata_mark()
  489. {
  490. $userdata = $this->all_userdata();
  491. foreach ($userdata as $name => $value)
  492. {
  493. $parts = explode(':new:', $name);
  494. if (is_array($parts) && count($parts) === 2)
  495. {
  496. $new_name = $this->flashdata_key.':old:'.$parts[1];
  497. $this->set_userdata($new_name, $value);
  498. $this->unset_userdata($name);
  499. }
  500. }
  501. }
  502. // ------------------------------------------------------------------------
  503. /**
  504. * Removes all flashdata marked as 'old'
  505. *
  506. * @access private
  507. * @return void
  508. */
  509. function _flashdata_sweep()
  510. {
  511. $userdata = $this->all_userdata();
  512. foreach ($userdata as $key => $value)
  513. {
  514. if (strpos($key, ':old:'))
  515. {
  516. $this->unset_userdata($key);
  517. }
  518. }
  519. }
  520. // --------------------------------------------------------------------
  521. /**
  522. * Get the "now" time
  523. *
  524. * @access private
  525. * @return string
  526. */
  527. function _get_time()
  528. {
  529. if (strtolower($this->time_reference) == 'gmt')
  530. {
  531. $now = time();
  532. $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
  533. }
  534. else
  535. {
  536. $time = time();
  537. }
  538. return $time;
  539. }
  540. // --------------------------------------------------------------------
  541. /**
  542. * Write the session cookie
  543. *
  544. * @access public
  545. * @return void
  546. */
  547. function _set_cookie($cookie_data = NULL)
  548. {
  549. if (is_null($cookie_data))
  550. {
  551. $cookie_data = $this->userdata;
  552. }
  553. // Serialize the userdata for the cookie
  554. $cookie_data = $this->_serialize($cookie_data);
  555. if ($this->sess_encrypt_cookie == TRUE)
  556. {
  557. $cookie_data = $this->CI->encrypt->encode($cookie_data);
  558. }
  559. else
  560. {
  561. // if encryption is not used, we provide an md5 hash to prevent userside tampering
  562. $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
  563. }
  564. $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
  565. // Set the cookie
  566. setcookie(
  567. $this->sess_cookie_name,
  568. $cookie_data,
  569. $expire,
  570. $this->cookie_path,
  571. $this->cookie_domain,
  572. $this->cookie_secure
  573. );
  574. }
  575. // --------------------------------------------------------------------
  576. /**
  577. * Serialize an array
  578. *
  579. * This function first converts any slashes found in the array to a temporary
  580. * marker, so when it gets unserialized the slashes will be preserved
  581. *
  582. * @access private
  583. * @param array
  584. * @return string
  585. */
  586. function _serialize($data)
  587. {
  588. if (is_array($data))
  589. {
  590. foreach ($data as $key => $val)
  591. {
  592. if (is_string($val))
  593. {
  594. $data[$key] = str_replace('\\', '{{slash}}', $val);
  595. }
  596. }
  597. }
  598. else
  599. {
  600. if (is_string($data))
  601. {
  602. $data = str_replace('\\', '{{slash}}', $data);
  603. }
  604. }
  605. return serialize($data);
  606. }
  607. // --------------------------------------------------------------------
  608. /**
  609. * Unserialize
  610. *
  611. * This function unserializes a data string, then converts any
  612. * temporary slash markers back to actual slashes
  613. *
  614. * @access private
  615. * @param array
  616. * @return string
  617. */
  618. function _unserialize($data)
  619. {
  620. $data = @unserialize(strip_slashes($data));
  621. if (is_array($data))
  622. {
  623. foreach ($data as $key => $val)
  624. {
  625. if (is_string($val))
  626. {
  627. $data[$key] = str_replace('{{slash}}', '\\', $val);
  628. }
  629. }
  630. return $data;
  631. }
  632. return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
  633. }
  634. // --------------------------------------------------------------------
  635. /**
  636. * Garbage collection
  637. *
  638. * This deletes expired session rows from database
  639. * if the probability percentage is met
  640. *
  641. * @access public
  642. * @return void
  643. */
  644. function _sess_gc()
  645. {
  646. if ($this->sess_use_database != TRUE)
  647. {
  648. return;
  649. }
  650. srand(time());
  651. if ((rand() % 100) < $this->gc_probability)
  652. {
  653. $expire = $this->now - $this->sess_expiration;
  654. $this->CI->db->where("last_activity < {$expire}");
  655. $this->CI->db->delete($this->sess_table_name);
  656. log_message('debug', 'Session garbage collection performed.');
  657. }
  658. }
  659. }
  660. // END Session Class
  661. /* End of file Session.php */
  662. /* Location: ./system/libraries/Session.php */