driver.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  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. $payload = $this->_serialize($payload);
  416. // encrypt the payload if needed
  417. $this->config['encrypt_cookie'] and $payload = \Crypt::encode($payload);
  418. // make sure it doesn't exceed the cookie size specification
  419. if (strlen($payload) > 4000)
  420. {
  421. throw new \FuelException('The session data stored by the application in the cookie exceeds 4Kb. Select a different session storage driver.');
  422. }
  423. // write the session cookie
  424. if ($this->config['expire_on_close'])
  425. {
  426. return \Cookie::set($this->config['cookie_name'], $payload, 0, $this->config['cookie_path'], $this->config['cookie_domain'], null, $this->config['cookie_http_only']);
  427. }
  428. else
  429. {
  430. 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']);
  431. }
  432. }
  433. // --------------------------------------------------------------------
  434. /**
  435. * read a cookie
  436. *
  437. * @access private
  438. * @return void
  439. */
  440. protected function _get_cookie()
  441. {
  442. // was the cookie posted?
  443. $cookie = \Input::post($this->config['post_cookie_name'], false);
  444. // if not found, fetch the regular cookie
  445. if ($cookie === false)
  446. {
  447. $cookie = \Cookie::get($this->config['cookie_name'], false);
  448. }
  449. if ($cookie !== false)
  450. {
  451. // fetch the payload
  452. $this->config['encrypt_cookie'] and $cookie = \Crypt::decode($cookie);
  453. $cookie = $this->_unserialize($cookie);
  454. // validate the cookie format: must be an array
  455. if (is_array($cookie))
  456. {
  457. // cookies use nested arrays, other drivers have a string value
  458. if (($this->config['driver'] === 'cookie' and ! is_array($cookie[0])) or
  459. ($this->config['driver'] !== 'cookie' and ! is_string($cookie[0])))
  460. {
  461. // invalid specific format
  462. $cookie = false;
  463. }
  464. }
  465. else
  466. {
  467. // invalid general format
  468. $cookie = false;
  469. }
  470. }
  471. // and the result
  472. return $cookie;
  473. }
  474. // --------------------------------------------------------------------
  475. /**
  476. * Serialize an array
  477. *
  478. * This function first converts any slashes found in the array to a temporary
  479. * marker, so when it gets unserialized the slashes will be preserved
  480. *
  481. * @access private
  482. * @param array
  483. * @return string
  484. */
  485. protected function _serialize($data)
  486. {
  487. if (is_array($data))
  488. {
  489. foreach ($data as $key => $val)
  490. {
  491. if (is_string($val))
  492. {
  493. $data[$key] = str_replace('\\', '{{slash}}', $val);
  494. }
  495. }
  496. }
  497. else
  498. {
  499. if (is_string($data))
  500. {
  501. $data = str_replace('\\', '{{slash}}', $data);
  502. }
  503. }
  504. return serialize($data);
  505. }
  506. // --------------------------------------------------------------------
  507. /**
  508. * Unserialize
  509. *
  510. * This function unserializes a data string, then converts any
  511. * temporary slash markers back to actual slashes
  512. *
  513. * @access private
  514. * @param array
  515. * @return string
  516. */
  517. protected function _unserialize($data)
  518. {
  519. $data = @unserialize($data);
  520. if (is_array($data))
  521. {
  522. foreach ($data as $key => $val)
  523. {
  524. if (is_string($val))
  525. {
  526. $data[$key] = str_replace('{{slash}}', '\\', $val);
  527. }
  528. }
  529. return $data;
  530. }
  531. return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
  532. }
  533. // --------------------------------------------------------------------
  534. /**
  535. * validate__config
  536. *
  537. * This function validates all global (driver independent) configuration values
  538. *
  539. * @access private
  540. * @param array
  541. * @return array
  542. */
  543. protected function _validate_config($config)
  544. {
  545. $validated = array();
  546. foreach ($config as $name => $item)
  547. {
  548. switch($name)
  549. {
  550. case 'driver':
  551. // if we get here, this one was ok... ;-)
  552. break;
  553. case 'match_ip':
  554. case 'match_ua':
  555. case 'cookie_http_only':
  556. case 'encrypt_cookie':
  557. case 'expire_on_close':
  558. case 'flash_expire_after_get':
  559. case 'flash_auto_expire':
  560. // make sure it's a boolean
  561. $item = (bool) $item;
  562. break;
  563. case 'post_cookie_name':
  564. case 'cookie_domain':
  565. // make sure it's a string
  566. $item = (string) $item;
  567. break;
  568. case 'cookie_path':
  569. // make sure it's a string
  570. $item = (string) $item;
  571. empty($item) and $item = '/';
  572. break;
  573. case 'expiration_time':
  574. // make sure it's an integer
  575. $item = (int) $item;
  576. // invalid? set it to two years from now
  577. $item <= 0 and $item = 86400 * 365 * 2;
  578. break;
  579. case 'rotation_time':
  580. // make sure it's an integer
  581. $item = (int) $item;
  582. // invalid? set it to 5 minutes
  583. $item <= 0 and $item = 300;
  584. break;
  585. case 'flash_id':
  586. // make sure it's a string
  587. $item = (string) $item;
  588. empty($item) and $item = 'flash';
  589. break;
  590. default:
  591. // ignore this setting
  592. break;
  593. }
  594. // store the validated result
  595. $validated[$name] = $item;
  596. }
  597. return $validated;
  598. }
  599. }