PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/classes/session/driver.php

https://bitbucket.org/trujka/codegrounds
PHP | 731 lines | 355 code | 105 blank | 271 comment | 30 complexity | b0c75321c288d919e89c1ccd16cca853 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.6
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. abstract class Session_Driver
  14. {
  15. /*
  16. * @var session class configuration
  17. */
  18. protected $config = array();
  19. /*
  20. * @var session indentification keys
  21. */
  22. protected $keys = array();
  23. /*
  24. * @var session variable data
  25. */
  26. protected $data = array();
  27. /*
  28. * @var session flash data
  29. */
  30. protected $flash = array();
  31. /*
  32. * @var session time object
  33. */
  34. protected $time = null;
  35. // --------------------------------------------------------------------
  36. // abstract methods
  37. // --------------------------------------------------------------------
  38. /**
  39. * create a new session
  40. *
  41. * @access public
  42. * @return void
  43. */
  44. abstract function create();
  45. // --------------------------------------------------------------------
  46. // generic driver methods
  47. // --------------------------------------------------------------------
  48. /**
  49. * destroy the current session
  50. *
  51. * @access public
  52. * @return Fuel\Core\Session_Driver
  53. */
  54. public function destroy()
  55. {
  56. // delete the session cookie
  57. \Cookie::delete($this->config['cookie_name']);
  58. // reset the stored session data
  59. $this->keys = $this->flash = $this->data = array();
  60. return $this;
  61. }
  62. /**
  63. * read the session
  64. *
  65. * @access public
  66. * @return Fuel\Core\Session_Driver
  67. */
  68. public function read()
  69. {
  70. // do we need to create a new session?
  71. empty($this->keys) and $this->create();
  72. // mark the loaded flash data, auto-expire if configured
  73. foreach($this->flash as $key => $value)
  74. {
  75. if ($this->config['flash_auto_expire'] === true)
  76. {
  77. $this->flash[$key]['state'] = 'expire';
  78. }
  79. else
  80. {
  81. $this->flash[$key]['state'] = 'loaded';
  82. }
  83. }
  84. return $this;
  85. }
  86. // --------------------------------------------------------------------
  87. /**
  88. * write the session
  89. *
  90. * @access public
  91. * @return Fuel\Core\Session_Driver
  92. */
  93. public function write()
  94. {
  95. // create the session if it doesn't exist
  96. empty($this->keys) and $this->create();
  97. $this->_cleanup_flash();
  98. return $this;
  99. }
  100. // --------------------------------------------------------------------
  101. /**
  102. * generic driver initialisation
  103. *
  104. * @access public
  105. * @return void
  106. */
  107. public function init()
  108. {
  109. // get a time object
  110. $this->time = \Date::time();
  111. }
  112. // --------------------------------------------------------------------
  113. /**
  114. * set session variables
  115. *
  116. * @param string|array name of the variable to set or array of values, array(name => value)
  117. * @param mixed value
  118. * @access public
  119. * @return Fuel\Core\Session_Driver
  120. */
  121. public function set($name, $value = null)
  122. {
  123. is_null($name) or \Arr::set($this->data, $name, $value);
  124. return $this;
  125. }
  126. // --------------------------------------------------------------------
  127. /**
  128. * get session variables
  129. *
  130. * @access public
  131. * @param string name of the variable to get
  132. * @param mixed default value to return if the variable does not exist
  133. * @return mixed
  134. */
  135. public function get($name, $default = null)
  136. {
  137. if (is_null($name))
  138. {
  139. return $this->data;
  140. }
  141. return \Arr::get($this->data, $name, $default);
  142. }
  143. // --------------------------------------------------------------------
  144. /**
  145. * get session key variables
  146. *
  147. * @access public
  148. * @param string name of the variable to get, default is 'session_id'
  149. * @return mixed contents of the requested variable, or false if not found
  150. */
  151. public function key($name = 'session_id')
  152. {
  153. return isset($this->keys[$name]) ? $this->keys[$name] : false;
  154. }
  155. // --------------------------------------------------------------------
  156. /**
  157. * delete session variables
  158. *
  159. * @param string name of the variable to delete
  160. * @param mixed value
  161. * @access public
  162. * @return Fuel\Core\Session_Driver
  163. */
  164. public function delete($name)
  165. {
  166. \Arr::delete($this->data, $name);
  167. return $this;
  168. }
  169. // --------------------------------------------------------------------
  170. /**
  171. * force a session_id rotation
  172. *
  173. * @access public
  174. * @param boolean, if true, force a session id rotation
  175. * @return Fuel\Core\Session_Driver
  176. */
  177. public function rotate($force = true)
  178. {
  179. // do we have a session?
  180. if ( ! empty($this->keys))
  181. {
  182. // existing session. need to rotate the session id?
  183. if ($force or ($this->config['rotation_time'] and $this->keys['created'] + $this->config['rotation_time'] <= $this->time->get_timestamp()))
  184. {
  185. // generate a new session id, and update the create timestamp
  186. $this->keys['previous_id'] = $this->keys['session_id'];
  187. $this->keys['session_id'] = $this->_new_session_id();
  188. $this->keys['created'] = $this->time->get_timestamp();
  189. $this->keys['updated'] = $this->keys['created'];
  190. }
  191. }
  192. return $this;
  193. }
  194. // --------------------------------------------------------------------
  195. /**
  196. * set session flash variables
  197. *
  198. * @param string name of the variable to set
  199. * @param mixed value
  200. * @access public
  201. * @return Fuel\Core\Session_Driver
  202. */
  203. public function set_flash($name, $value)
  204. {
  205. if (strpos($name, '.') !== false)
  206. {
  207. $keys = explode('.', $name, 2);
  208. $name = array_shift($keys);
  209. }
  210. else
  211. {
  212. $keys = false;
  213. }
  214. if ($keys)
  215. {
  216. isset($this->flash[$this->config['flash_id'].'::'.$name]['value']) or $this->flash[$this->config['flash_id'].'::'.$name] = array('state' => 'new', 'value' => array());
  217. \Arr::set($this->flash[$this->config['flash_id'].'::'.$name]['value'], $keys[0], $value);
  218. }
  219. else
  220. {
  221. $this->flash[$this->config['flash_id'].'::'.$name] = array('state' => 'new', 'value' => $value);
  222. }
  223. return $this;
  224. }
  225. // --------------------------------------------------------------------
  226. /**
  227. * get session flash variables
  228. *
  229. * @access public
  230. * @param string name of the variable to get
  231. * @param mixed default value to return if the variable does not exist
  232. * @param bool true if the flash variable needs to expire immediately, false to use "flash_auto_expire"
  233. * @return mixed
  234. */
  235. public function get_flash($name, $default = null, $expire = null)
  236. {
  237. // if no expiration is given, use the config default
  238. is_bool($expire) or $expire = $this->config['flash_expire_after_get'];
  239. if (is_null($name))
  240. {
  241. $default = array();
  242. foreach($this->flash as $key => $value)
  243. {
  244. $key = substr($key, strpos($key, '::')+2);
  245. $default[$key] = $value;
  246. }
  247. }
  248. else
  249. {
  250. // check if we need to run an Arr:get()
  251. if (strpos($name, '.') !== false)
  252. {
  253. $keys = explode('.', $name, 2);
  254. $name = array_shift($keys);
  255. }
  256. else
  257. {
  258. $keys = false;
  259. }
  260. if (isset($this->flash[$this->config['flash_id'].'::'.$name]))
  261. {
  262. // if it's not a var set in this request, mark it for expiration
  263. if ($this->flash[$this->config['flash_id'].'::'.$name]['state'] !== 'new' or $expire)
  264. {
  265. $this->flash[$this->config['flash_id'].'::'.$name]['state'] = 'expire';
  266. }
  267. if ($keys)
  268. {
  269. $default = \Arr::get($this->flash[$this->config['flash_id'].'::'.$name]['value'], $keys[0], $default);
  270. }
  271. else
  272. {
  273. $default = $this->flash[$this->config['flash_id'].'::'.$name]['value'];
  274. }
  275. }
  276. }
  277. return ($default instanceof \Closure) ? $default() : $default;
  278. }
  279. // --------------------------------------------------------------------
  280. /**
  281. * keep session flash variables
  282. *
  283. * @access public
  284. * @param string name of the variable to keep
  285. * @return Fuel\Core\Session_Driver
  286. */
  287. public function keep_flash($name)
  288. {
  289. if (is_null($name))
  290. {
  291. foreach($this->flash as $key => $value)
  292. {
  293. $this->flash[$key]['state'] = 'new';
  294. }
  295. }
  296. elseif (isset($this->flash[$this->config['flash_id'].'::'.$name]))
  297. {
  298. $this->flash[$this->config['flash_id'].'::'.$name]['state'] = 'new';
  299. }
  300. return $this;
  301. }
  302. // --------------------------------------------------------------------
  303. /**
  304. * delete session flash variables
  305. *
  306. * @param string name of the variable to delete
  307. * @param mixed value
  308. * @access public
  309. * @return Fuel\Core\Session_Driver
  310. */
  311. public function delete_flash($name)
  312. {
  313. if (is_null($name))
  314. {
  315. $this->flash = array();
  316. }
  317. elseif (isset($this->flash[$this->config['flash_id'].'::'.$name]))
  318. {
  319. unset($this->flash[$this->config['flash_id'].'::'.$name]);
  320. }
  321. return $this;
  322. }
  323. // --------------------------------------------------------------------
  324. /**
  325. * set the session flash id
  326. *
  327. * @param string name of the id to set
  328. * @access public
  329. * @return Fuel\Core\Session_Driver
  330. */
  331. public function set_flash_id($name)
  332. {
  333. $this->config['flash_id'] = (string) $name;
  334. return $this;
  335. }
  336. // --------------------------------------------------------------------
  337. /**
  338. * get the current session flash id
  339. *
  340. * @access public
  341. * @return string name of the flash id
  342. */
  343. public function get_flash_id()
  344. {
  345. return $this->config['flash_id'];
  346. }
  347. // --------------------------------------------------------------------
  348. /**
  349. * get a runtime config value
  350. *
  351. * @param string name of the config variable to get
  352. * @access public
  353. * @return mixed
  354. */
  355. public function get_config($name)
  356. {
  357. return isset($this->config[$name]) ? $this->config[$name] : null;
  358. }
  359. // --------------------------------------------------------------------
  360. /**
  361. * set a runtime config value
  362. *
  363. * @param string name of the config variable to set
  364. * @access public
  365. * @return Fuel\Core\Session_Driver
  366. */
  367. public function set_config($name, $value = null)
  368. {
  369. if (isset($this->config[$name])) $this->config[$name] = $value;
  370. return $this;
  371. }
  372. // --------------------------------------------------------------------
  373. /**
  374. * removes flash variables marked as old
  375. *
  376. * @access private
  377. * @return void
  378. */
  379. protected function _cleanup_flash()
  380. {
  381. foreach($this->flash as $key => $value)
  382. {
  383. if ($value['state'] === 'expire')
  384. {
  385. unset($this->flash[$key]);
  386. }
  387. }
  388. }
  389. // --------------------------------------------------------------------
  390. /**
  391. * generate a new session id
  392. *
  393. * @access private
  394. * @return void
  395. */
  396. protected function _new_session_id()
  397. {
  398. $session_id = '';
  399. while (strlen($session_id) < 32)
  400. {
  401. $session_id .= mt_rand(0, mt_getrandmax());
  402. }
  403. return md5(uniqid($session_id, TRUE));
  404. }
  405. // --------------------------------------------------------------------
  406. /**
  407. * write a cookie
  408. *
  409. * @access private
  410. * @param array, cookie payload
  411. * @return void
  412. */
  413. protected function _set_cookie($payload = array())
  414. {
  415. if ($this->config['enable_cookie'])
  416. {
  417. $payload = $this->_serialize($payload);
  418. // encrypt the payload if needed
  419. $this->config['encrypt_cookie'] and $payload = \Crypt::encode($payload);
  420. // make sure it doesn't exceed the cookie size specification
  421. if (strlen($payload) > 4000)
  422. {
  423. throw new \FuelException('The session data stored by the application in the cookie exceeds 4Kb. Select a different session storage driver.');
  424. }
  425. // write the session cookie
  426. if ($this->config['expire_on_close'])
  427. {
  428. return \Cookie::set($this->config['cookie_name'], $payload, 0, $this->config['cookie_path'], $this->config['cookie_domain'], null, $this->config['cookie_http_only']);
  429. }
  430. else
  431. {
  432. return \Cookie::set($this->config['cookie_name'], $payload, $this->config['expiration_time'], $this->config['cookie_path'], $this->config['cookie_domain'], null, $this->config['cookie_http_only']);
  433. }
  434. }
  435. }
  436. // --------------------------------------------------------------------
  437. /**
  438. * read a cookie
  439. *
  440. * @access private
  441. * @return void
  442. */
  443. protected function _get_cookie()
  444. {
  445. // was the cookie value posted?
  446. $cookie = \Input::post($this->config['post_cookie_name'], false);
  447. // if not found, fetch the regular cookie
  448. if ($cookie === false)
  449. {
  450. $cookie = \Cookie::get($this->config['cookie_name'], false);
  451. }
  452. // if not found, check the URL for a cookie
  453. if ($cookie === false)
  454. {
  455. $cookie = \Input::get($this->config['cookie_name'], false);
  456. }
  457. // if not found, was a session-id present in the HTTP header?
  458. if ($cookie === false)
  459. {
  460. $cookie = \Input::headers($this->config['header_header_name'], false);
  461. }
  462. if ($cookie !== false)
  463. {
  464. // fetch the payload
  465. $this->config['encrypt_cookie'] and $cookie = \Crypt::decode($cookie);
  466. $cookie = $this->_unserialize($cookie);
  467. // validate the cookie format: must be an array
  468. if (is_array($cookie))
  469. {
  470. // cookies use nested arrays, other drivers have a string value
  471. if (($this->config['driver'] === 'cookie' and ! is_array($cookie[0])) or
  472. ($this->config['driver'] !== 'cookie' and ! is_string($cookie[0])))
  473. {
  474. // invalid specific format
  475. $cookie = false;
  476. }
  477. }
  478. // or a string containing the session id
  479. elseif (is_string($cookie) and strlen($cookie) == 32)
  480. {
  481. $cookie = array($cookie);
  482. }
  483. // invalid general format
  484. else
  485. {
  486. $cookie = false;
  487. }
  488. }
  489. // and the result
  490. return $cookie;
  491. }
  492. // --------------------------------------------------------------------
  493. /**
  494. * Serialize an array
  495. *
  496. * This function first converts any slashes found in the array to a temporary
  497. * marker, so when it gets unserialized the slashes will be preserved
  498. *
  499. * @access private
  500. * @param array
  501. * @return string
  502. */
  503. protected function _serialize($data)
  504. {
  505. if (is_array($data))
  506. {
  507. foreach ($data as $key => $val)
  508. {
  509. if (is_string($val))
  510. {
  511. $data[$key] = str_replace('\\', '{{slash}}', $val);
  512. }
  513. }
  514. }
  515. else
  516. {
  517. if (is_string($data))
  518. {
  519. $data = str_replace('\\', '{{slash}}', $data);
  520. }
  521. }
  522. return serialize($data);
  523. }
  524. // --------------------------------------------------------------------
  525. /**
  526. * Unserialize
  527. *
  528. * This function unserializes a data string, then converts any
  529. * temporary slash markers back to actual slashes
  530. *
  531. * @access private
  532. * @param array
  533. * @return string
  534. */
  535. protected function _unserialize($input)
  536. {
  537. $data = @unserialize($input);
  538. if (is_array($data))
  539. {
  540. foreach ($data as $key => $val)
  541. {
  542. if (is_string($val))
  543. {
  544. $data[$key] = str_replace('{{slash}}', '\\', $val);
  545. }
  546. }
  547. return $data;
  548. }
  549. elseif ($data === false)
  550. {
  551. is_string($input) and $data = array($input);
  552. }
  553. return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
  554. }
  555. // --------------------------------------------------------------------
  556. /**
  557. * validate__config
  558. *
  559. * This function validates all global (driver independent) configuration values
  560. *
  561. * @access private
  562. * @param array
  563. * @return array
  564. */
  565. protected function _validate_config($config)
  566. {
  567. $validated = array();
  568. foreach ($config as $name => $item)
  569. {
  570. switch($name)
  571. {
  572. case 'driver':
  573. // if we get here, this one was ok... ;-)
  574. break;
  575. case 'match_ip':
  576. case 'match_ua':
  577. case 'enable_cookie':
  578. case 'cookie_http_only':
  579. case 'encrypt_cookie':
  580. case 'expire_on_close':
  581. case 'flash_expire_after_get':
  582. case 'flash_auto_expire':
  583. // make sure it's a boolean
  584. $item = (bool) $item;
  585. break;
  586. case 'post_cookie_name':
  587. case 'http_header_name':
  588. case 'cookie_domain':
  589. // make sure it's a string
  590. $item = (string) $item;
  591. break;
  592. case 'cookie_path':
  593. // make sure it's a string
  594. $item = (string) $item;
  595. empty($item) and $item = '/';
  596. break;
  597. case 'expiration_time':
  598. // make sure it's an integer
  599. $item = (int) $item;
  600. // invalid? set it to two years from now
  601. $item <= 0 and $item = 86400 * 365 * 2;
  602. break;
  603. case 'rotation_time':
  604. // make sure it's an integer
  605. $item = (int) $item;
  606. // invalid? set it to 5 minutes
  607. $item <= 0 and $item = 300;
  608. break;
  609. case 'flash_id':
  610. // make sure it's a string
  611. $item = (string) $item;
  612. empty($item) and $item = 'flash';
  613. break;
  614. default:
  615. // ignore this setting
  616. break;
  617. }
  618. // store the validated result
  619. $validated[$name] = $item;
  620. }
  621. return $validated;
  622. }
  623. }