Session.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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 && 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. // Kill session data
  354. $this->userdata = array();
  355. }
  356. // --------------------------------------------------------------------
  357. /**
  358. * Fetch a specific item from the session array
  359. *
  360. * @access public
  361. * @param string
  362. * @return string
  363. */
  364. function userdata($item)
  365. {
  366. return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
  367. }
  368. // --------------------------------------------------------------------
  369. /**
  370. * Fetch all session data
  371. *
  372. * @access public
  373. * @return array
  374. */
  375. function all_userdata()
  376. {
  377. return $this->userdata;
  378. }
  379. // --------------------------------------------------------------------
  380. /**
  381. * Add or change data in the "userdata" array
  382. *
  383. * @access public
  384. * @param mixed
  385. * @param string
  386. * @return void
  387. */
  388. function set_userdata($newdata = array(), $newval = '')
  389. {
  390. if (is_string($newdata))
  391. {
  392. $newdata = array($newdata => $newval);
  393. }
  394. if (count($newdata) > 0)
  395. {
  396. foreach ($newdata as $key => $val)
  397. {
  398. $this->userdata[$key] = $val;
  399. }
  400. }
  401. $this->sess_write();
  402. }
  403. // --------------------------------------------------------------------
  404. /**
  405. * Delete a session variable from the "userdata" array
  406. *
  407. * @access array
  408. * @return void
  409. */
  410. function unset_userdata($newdata = array())
  411. {
  412. if (is_string($newdata))
  413. {
  414. $newdata = array($newdata => '');
  415. }
  416. if (count($newdata) > 0)
  417. {
  418. foreach ($newdata as $key => $val)
  419. {
  420. unset($this->userdata[$key]);
  421. }
  422. }
  423. $this->sess_write();
  424. }
  425. // ------------------------------------------------------------------------
  426. /**
  427. * Add or change flashdata, only available
  428. * until the next request
  429. *
  430. * @access public
  431. * @param mixed
  432. * @param string
  433. * @return void
  434. */
  435. function set_flashdata($newdata = array(), $newval = '')
  436. {
  437. if (is_string($newdata))
  438. {
  439. $newdata = array($newdata => $newval);
  440. }
  441. if (count($newdata) > 0)
  442. {
  443. foreach ($newdata as $key => $val)
  444. {
  445. $flashdata_key = $this->flashdata_key.':new:'.$key;
  446. $this->set_userdata($flashdata_key, $val);
  447. }
  448. }
  449. }
  450. // ------------------------------------------------------------------------
  451. /**
  452. * Keeps existing flashdata available to next request.
  453. *
  454. * @access public
  455. * @param string
  456. * @return void
  457. */
  458. function keep_flashdata($key)
  459. {
  460. // 'old' flashdata gets removed. Here we mark all
  461. // flashdata as 'new' to preserve it from _flashdata_sweep()
  462. // Note the function will return FALSE if the $key
  463. // provided cannot be found
  464. $old_flashdata_key = $this->flashdata_key.':old:'.$key;
  465. $value = $this->userdata($old_flashdata_key);
  466. $new_flashdata_key = $this->flashdata_key.':new:'.$key;
  467. $this->set_userdata($new_flashdata_key, $value);
  468. }
  469. // ------------------------------------------------------------------------
  470. /**
  471. * Fetch a specific flashdata item from the session array
  472. *
  473. * @access public
  474. * @param string
  475. * @return string
  476. */
  477. function flashdata($key)
  478. {
  479. $flashdata_key = $this->flashdata_key.':old:'.$key;
  480. return $this->userdata($flashdata_key);
  481. }
  482. // ------------------------------------------------------------------------
  483. /**
  484. * Identifies flashdata as 'old' for removal
  485. * when _flashdata_sweep() runs.
  486. *
  487. * @access private
  488. * @return void
  489. */
  490. function _flashdata_mark()
  491. {
  492. $userdata = $this->all_userdata();
  493. foreach ($userdata as $name => $value)
  494. {
  495. $parts = explode(':new:', $name);
  496. if (is_array($parts) && count($parts) === 2)
  497. {
  498. $new_name = $this->flashdata_key.':old:'.$parts[1];
  499. $this->set_userdata($new_name, $value);
  500. $this->unset_userdata($name);
  501. }
  502. }
  503. }
  504. // ------------------------------------------------------------------------
  505. /**
  506. * Removes all flashdata marked as 'old'
  507. *
  508. * @access private
  509. * @return void
  510. */
  511. function _flashdata_sweep()
  512. {
  513. $userdata = $this->all_userdata();
  514. foreach ($userdata as $key => $value)
  515. {
  516. if (strpos($key, ':old:'))
  517. {
  518. $this->unset_userdata($key);
  519. }
  520. }
  521. }
  522. // --------------------------------------------------------------------
  523. /**
  524. * Get the "now" time
  525. *
  526. * @access private
  527. * @return string
  528. */
  529. function _get_time()
  530. {
  531. if (strtolower($this->time_reference) == 'gmt')
  532. {
  533. $now = time();
  534. $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now));
  535. }
  536. else
  537. {
  538. $time = time();
  539. }
  540. return $time;
  541. }
  542. // --------------------------------------------------------------------
  543. /**
  544. * Write the session cookie
  545. *
  546. * @access public
  547. * @return void
  548. */
  549. function _set_cookie($cookie_data = NULL)
  550. {
  551. if (is_null($cookie_data))
  552. {
  553. $cookie_data = $this->userdata;
  554. }
  555. // Serialize the userdata for the cookie
  556. $cookie_data = $this->_serialize($cookie_data);
  557. if ($this->sess_encrypt_cookie == TRUE)
  558. {
  559. $cookie_data = $this->CI->encrypt->encode($cookie_data);
  560. }
  561. else
  562. {
  563. // if encryption is not used, we provide an md5 hash to prevent userside tampering
  564. $cookie_data = $cookie_data.md5($cookie_data.$this->encryption_key);
  565. }
  566. $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
  567. // Set the cookie
  568. setcookie(
  569. $this->sess_cookie_name,
  570. $cookie_data,
  571. $expire,
  572. $this->cookie_path,
  573. $this->cookie_domain,
  574. $this->cookie_secure
  575. );
  576. }
  577. // --------------------------------------------------------------------
  578. /**
  579. * Serialize an array
  580. *
  581. * This function first converts any slashes found in the array to a temporary
  582. * marker, so when it gets unserialized the slashes will be preserved
  583. *
  584. * @access private
  585. * @param array
  586. * @return string
  587. */
  588. function _serialize($data)
  589. {
  590. if (is_array($data))
  591. {
  592. foreach ($data as $key => $val)
  593. {
  594. if (is_string($val))
  595. {
  596. $data[$key] = str_replace('\\', '{{slash}}', $val);
  597. }
  598. }
  599. }
  600. else
  601. {
  602. if (is_string($data))
  603. {
  604. $data = str_replace('\\', '{{slash}}', $data);
  605. }
  606. }
  607. return serialize($data);
  608. }
  609. // --------------------------------------------------------------------
  610. /**
  611. * Unserialize
  612. *
  613. * This function unserializes a data string, then converts any
  614. * temporary slash markers back to actual slashes
  615. *
  616. * @access private
  617. * @param array
  618. * @return string
  619. */
  620. function _unserialize($data)
  621. {
  622. $data = @unserialize(strip_slashes($data));
  623. if (is_array($data))
  624. {
  625. foreach ($data as $key => $val)
  626. {
  627. if (is_string($val))
  628. {
  629. $data[$key] = str_replace('{{slash}}', '\\', $val);
  630. }
  631. }
  632. return $data;
  633. }
  634. return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
  635. }
  636. // --------------------------------------------------------------------
  637. /**
  638. * Garbage collection
  639. *
  640. * This deletes expired session rows from database
  641. * if the probability percentage is met
  642. *
  643. * @access public
  644. * @return void
  645. */
  646. function _sess_gc()
  647. {
  648. if ($this->sess_use_database != TRUE)
  649. {
  650. return;
  651. }
  652. srand(time());
  653. if ((rand() % 100) < $this->gc_probability)
  654. {
  655. $expire = $this->now - $this->sess_expiration;
  656. $this->CI->db->where("last_activity < {$expire}");
  657. $this->CI->db->delete($this->sess_table_name);
  658. log_message('debug', 'Session garbage collection performed.');
  659. }
  660. }
  661. }
  662. // END Session Class
  663. /* End of file Session.php */
  664. /* Location: ./system/libraries/Session.php */