PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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