CakeSession.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. <?php
  2. /**
  3. * Session class for Cake.
  4. *
  5. * Cake abstracts the handling of sessions.
  6. * There are several convenient methods to access session information.
  7. * This class is the implementation of those methods.
  8. * They are mostly used by the Session Component.
  9. *
  10. * PHP 5
  11. *
  12. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  13. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. *
  15. * Licensed under The MIT License
  16. * Redistributions of files must retain the above copyright notice.
  17. *
  18. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  19. * @link http://cakephp.org CakePHP(tm) Project
  20. * @package Cake.Model.Datasource
  21. * @since CakePHP(tm) v .0.10.0.1222
  22. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  23. */
  24. App::uses('Hash', 'Utility');
  25. App::uses('Security', 'Utility');
  26. /**
  27. * Session class for Cake.
  28. *
  29. * Cake abstracts the handling of sessions. There are several convenient methods to access session information.
  30. * This class is the implementation of those methods. They are mostly used by the Session Component.
  31. *
  32. * @package Cake.Model.Datasource
  33. */
  34. class CakeSession {
  35. /**
  36. * True if the Session is still valid
  37. *
  38. * @var boolean
  39. */
  40. public static $valid = false;
  41. /**
  42. * Error messages for this session
  43. *
  44. * @var array
  45. */
  46. public static $error = false;
  47. /**
  48. * User agent string
  49. *
  50. * @var string
  51. */
  52. protected static $_userAgent = '';
  53. /**
  54. * Path to where the session is active.
  55. *
  56. * @var string
  57. */
  58. public static $path = '/';
  59. /**
  60. * Error number of last occurred error
  61. *
  62. * @var integer
  63. */
  64. public static $lastError = null;
  65. /**
  66. * Start time for this session.
  67. *
  68. * @var integer
  69. */
  70. public static $time = false;
  71. /**
  72. * Cookie lifetime
  73. *
  74. * @var integer
  75. */
  76. public static $cookieLifeTime;
  77. /**
  78. * Time when this session becomes invalid.
  79. *
  80. * @var integer
  81. */
  82. public static $sessionTime = false;
  83. /**
  84. * Current Session id
  85. *
  86. * @var string
  87. */
  88. public static $id = null;
  89. /**
  90. * Hostname
  91. *
  92. * @var string
  93. */
  94. public static $host = null;
  95. /**
  96. * Session timeout multiplier factor
  97. *
  98. * @var integer
  99. */
  100. public static $timeout = null;
  101. /**
  102. * Number of requests that can occur during a session time without the session being renewed.
  103. * This feature is only used when config value `Session.autoRegenerate` is set to true.
  104. *
  105. * @var integer
  106. * @see CakeSession::_checkValid()
  107. */
  108. public static $requestCountdown = 10;
  109. /**
  110. * Pseudo constructor.
  111. *
  112. * @param string $base The base path for the Session
  113. * @return void
  114. */
  115. public static function init($base = null) {
  116. self::$time = time();
  117. $checkAgent = Configure::read('Session.checkAgent');
  118. if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) {
  119. self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  120. }
  121. self::_setPath($base);
  122. self::_setHost(env('HTTP_HOST'));
  123. register_shutdown_function('session_write_close');
  124. }
  125. /**
  126. * Setup the Path variable
  127. *
  128. * @param string $base base path
  129. * @return void
  130. */
  131. protected static function _setPath($base = null) {
  132. if (empty($base)) {
  133. self::$path = '/';
  134. return;
  135. }
  136. if (strpos($base, 'index.php') !== false) {
  137. $base = str_replace('index.php', '', $base);
  138. }
  139. if (strpos($base, '?') !== false) {
  140. $base = str_replace('?', '', $base);
  141. }
  142. self::$path = $base;
  143. }
  144. /**
  145. * Set the host name
  146. *
  147. * @param string $host Hostname
  148. * @return void
  149. */
  150. protected static function _setHost($host) {
  151. self::$host = $host;
  152. if (strpos(self::$host, ':') !== false) {
  153. self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
  154. }
  155. }
  156. /**
  157. * Starts the Session.
  158. *
  159. * @return boolean True if session was started
  160. */
  161. public static function start() {
  162. if (self::started()) {
  163. return true;
  164. }
  165. self::init();
  166. $id = self::id();
  167. session_write_close();
  168. self::_configureSession();
  169. self::_startSession();
  170. if (!$id && self::started()) {
  171. self::_checkValid();
  172. }
  173. self::$error = false;
  174. return self::started();
  175. }
  176. /**
  177. * Determine if Session has been started.
  178. *
  179. * @return boolean True if session has been started.
  180. */
  181. public static function started() {
  182. return isset($_SESSION) && session_id();
  183. }
  184. /**
  185. * Returns true if given variable is set in session.
  186. *
  187. * @param string $name Variable name to check for
  188. * @return boolean True if variable is there
  189. */
  190. public static function check($name = null) {
  191. if (!self::started() && !self::start()) {
  192. return false;
  193. }
  194. if (empty($name)) {
  195. return false;
  196. }
  197. $result = Hash::get($_SESSION, $name);
  198. return isset($result);
  199. }
  200. /**
  201. * Returns the Session id
  202. *
  203. * @param string $id
  204. * @return string Session id
  205. */
  206. public static function id($id = null) {
  207. if ($id) {
  208. self::$id = $id;
  209. session_id(self::$id);
  210. }
  211. if (self::started()) {
  212. return session_id();
  213. }
  214. return self::$id;
  215. }
  216. /**
  217. * Removes a variable from session.
  218. *
  219. * @param string $name Session variable to remove
  220. * @return boolean Success
  221. */
  222. public static function delete($name) {
  223. if (self::check($name)) {
  224. self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
  225. return (self::check($name) == false);
  226. }
  227. self::_setError(2, __d('cake_dev', "%s doesn't exist", $name));
  228. return false;
  229. }
  230. /**
  231. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
  232. *
  233. * @param array $old Set of old variables => values
  234. * @param array $new New set of variable => value
  235. * @return void
  236. */
  237. protected static function _overwrite(&$old, $new) {
  238. if (!empty($old)) {
  239. foreach ($old as $key => $var) {
  240. if (!isset($new[$key])) {
  241. unset($old[$key]);
  242. }
  243. }
  244. }
  245. foreach ($new as $key => $var) {
  246. $old[$key] = $var;
  247. }
  248. }
  249. /**
  250. * Return error description for given error number.
  251. *
  252. * @param integer $errorNumber Error to set
  253. * @return string Error as string
  254. */
  255. protected static function _error($errorNumber) {
  256. if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
  257. return false;
  258. } else {
  259. return self::$error[$errorNumber];
  260. }
  261. }
  262. /**
  263. * Returns last occurred error as a string, if any.
  264. *
  265. * @return mixed Error description as a string, or false.
  266. */
  267. public static function error() {
  268. if (self::$lastError) {
  269. return self::_error(self::$lastError);
  270. }
  271. return false;
  272. }
  273. /**
  274. * Returns true if session is valid.
  275. *
  276. * @return boolean Success
  277. */
  278. public static function valid() {
  279. if (self::read('Config')) {
  280. if (self::_validAgentAndTime() && self::$error === false) {
  281. self::$valid = true;
  282. } else {
  283. self::$valid = false;
  284. self::_setError(1, 'Session Highjacking Attempted !!!');
  285. }
  286. }
  287. return self::$valid;
  288. }
  289. /**
  290. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  291. * Since timeouts are implemented in CakeSession it checks the current self::$time
  292. * against the time the session is set to expire. The User agent is only checked
  293. * if Session.checkAgent == true.
  294. *
  295. * @return boolean
  296. */
  297. protected static function _validAgentAndTime() {
  298. $config = self::read('Config');
  299. $validAgent = (
  300. Configure::read('Session.checkAgent') === false ||
  301. self::$_userAgent == $config['userAgent']
  302. );
  303. return ($validAgent && self::$time <= $config['time']);
  304. }
  305. /**
  306. * Get / Set the userAgent
  307. *
  308. * @param string $userAgent Set the userAgent
  309. * @return void
  310. */
  311. public static function userAgent($userAgent = null) {
  312. if ($userAgent) {
  313. self::$_userAgent = $userAgent;
  314. }
  315. if (empty(self::$_userAgent)) {
  316. CakeSession::init(self::$path);
  317. }
  318. return self::$_userAgent;
  319. }
  320. /**
  321. * Returns given session variable, or all of them, if no parameters given.
  322. *
  323. * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
  324. * @return mixed The value of the session variable
  325. */
  326. public static function read($name = null) {
  327. if (!self::started() && !self::start()) {
  328. return false;
  329. }
  330. if (is_null($name)) {
  331. return self::_returnSessionVars();
  332. }
  333. if (empty($name)) {
  334. return false;
  335. }
  336. $result = Hash::get($_SESSION, $name);
  337. if (isset($result)) {
  338. return $result;
  339. }
  340. self::_setError(2, "$name doesn't exist");
  341. return null;
  342. }
  343. /**
  344. * Returns all session variables.
  345. *
  346. * @return mixed Full $_SESSION array, or false on error.
  347. */
  348. protected static function _returnSessionVars() {
  349. if (!empty($_SESSION)) {
  350. return $_SESSION;
  351. }
  352. self::_setError(2, 'No Session vars set');
  353. return false;
  354. }
  355. /**
  356. * Writes value to given session variable name.
  357. *
  358. * @param string|array $name Name of variable
  359. * @param string $value Value to write
  360. * @return boolean True if the write was successful, false if the write failed
  361. */
  362. public static function write($name, $value = null) {
  363. if (!self::started() && !self::start()) {
  364. return false;
  365. }
  366. if (empty($name)) {
  367. return false;
  368. }
  369. $write = $name;
  370. if (!is_array($name)) {
  371. $write = array($name => $value);
  372. }
  373. foreach ($write as $key => $val) {
  374. self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
  375. if (Hash::get($_SESSION, $key) !== $val) {
  376. return false;
  377. }
  378. }
  379. return true;
  380. }
  381. /**
  382. * Helper method to destroy invalid sessions.
  383. *
  384. * @return void
  385. */
  386. public static function destroy() {
  387. if (self::started()) {
  388. session_destroy();
  389. }
  390. self::clear();
  391. }
  392. /**
  393. * Clears the session, the session id, and renew's the session.
  394. *
  395. * @return void
  396. */
  397. public static function clear() {
  398. $_SESSION = null;
  399. self::$id = null;
  400. self::start();
  401. self::renew();
  402. }
  403. /**
  404. * Helper method to initialize a session, based on Cake core settings.
  405. *
  406. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  407. *
  408. * @return void
  409. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  410. */
  411. protected static function _configureSession() {
  412. $sessionConfig = Configure::read('Session');
  413. $iniSet = function_exists('ini_set');
  414. if (isset($sessionConfig['defaults'])) {
  415. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  416. if ($defaults) {
  417. $sessionConfig = Hash::merge($defaults, $sessionConfig);
  418. }
  419. }
  420. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  421. $sessionConfig['ini']['session.cookie_secure'] = 1;
  422. }
  423. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  424. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  425. }
  426. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  427. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  428. }
  429. if (!isset($sessionConfig['ini']['session.name'])) {
  430. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  431. }
  432. if (!empty($sessionConfig['handler'])) {
  433. $sessionConfig['ini']['session.save_handler'] = 'user';
  434. }
  435. if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
  436. $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
  437. }
  438. if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
  439. $sessionConfig['ini']['session.cookie_httponly'] = 1;
  440. }
  441. if (empty($_SESSION)) {
  442. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  443. foreach ($sessionConfig['ini'] as $setting => $value) {
  444. if (ini_set($setting, $value) === false) {
  445. throw new CakeSessionException(sprintf(
  446. __d('cake_dev', 'Unable to configure the session, setting %s failed.'),
  447. $setting
  448. ));
  449. }
  450. }
  451. }
  452. }
  453. if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
  454. call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
  455. }
  456. if (!empty($sessionConfig['handler']['engine'])) {
  457. $handler = self::_getHandler($sessionConfig['handler']['engine']);
  458. session_set_save_handler(
  459. array($handler, 'open'),
  460. array($handler, 'close'),
  461. array($handler, 'read'),
  462. array($handler, 'write'),
  463. array($handler, 'destroy'),
  464. array($handler, 'gc')
  465. );
  466. }
  467. Configure::write('Session', $sessionConfig);
  468. self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
  469. }
  470. /**
  471. * Find the handler class and make sure it implements the correct interface.
  472. *
  473. * @param string $handler
  474. * @return void
  475. * @throws CakeSessionException
  476. */
  477. protected static function _getHandler($handler) {
  478. list($plugin, $class) = pluginSplit($handler, true);
  479. App::uses($class, $plugin . 'Model/Datasource/Session');
  480. if (!class_exists($class)) {
  481. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  482. }
  483. $handler = new $class();
  484. if ($handler instanceof CakeSessionHandlerInterface) {
  485. return $handler;
  486. }
  487. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
  488. }
  489. /**
  490. * Get one of the prebaked default session configurations.
  491. *
  492. * @param string $name
  493. * @return boolean|array
  494. */
  495. protected static function _defaultConfig($name) {
  496. $defaults = array(
  497. 'php' => array(
  498. 'cookie' => 'CAKEPHP',
  499. 'timeout' => 240,
  500. 'ini' => array(
  501. 'session.use_trans_sid' => 0,
  502. 'session.cookie_path' => self::$path
  503. )
  504. ),
  505. 'cake' => array(
  506. 'cookie' => 'CAKEPHP',
  507. 'timeout' => 240,
  508. 'ini' => array(
  509. 'session.use_trans_sid' => 0,
  510. 'url_rewriter.tags' => '',
  511. 'session.serialize_handler' => 'php',
  512. 'session.use_cookies' => 1,
  513. 'session.cookie_path' => self::$path,
  514. 'session.auto_start' => 0,
  515. 'session.save_path' => TMP . 'sessions',
  516. 'session.save_handler' => 'files'
  517. )
  518. ),
  519. 'cache' => array(
  520. 'cookie' => 'CAKEPHP',
  521. 'timeout' => 240,
  522. 'ini' => array(
  523. 'session.use_trans_sid' => 0,
  524. 'url_rewriter.tags' => '',
  525. 'session.auto_start' => 0,
  526. 'session.use_cookies' => 1,
  527. 'session.cookie_path' => self::$path,
  528. 'session.save_handler' => 'user',
  529. ),
  530. 'handler' => array(
  531. 'engine' => 'CacheSession',
  532. 'config' => 'default'
  533. )
  534. ),
  535. 'database' => array(
  536. 'cookie' => 'CAKEPHP',
  537. 'timeout' => 240,
  538. 'ini' => array(
  539. 'session.use_trans_sid' => 0,
  540. 'url_rewriter.tags' => '',
  541. 'session.auto_start' => 0,
  542. 'session.use_cookies' => 1,
  543. 'session.cookie_path' => self::$path,
  544. 'session.save_handler' => 'user',
  545. 'session.serialize_handler' => 'php',
  546. ),
  547. 'handler' => array(
  548. 'engine' => 'DatabaseSession',
  549. 'model' => 'Session'
  550. )
  551. )
  552. );
  553. if (isset($defaults[$name])) {
  554. return $defaults[$name];
  555. }
  556. return false;
  557. }
  558. /**
  559. * Helper method to start a session
  560. *
  561. * @return boolean Success
  562. */
  563. protected static function _startSession() {
  564. if (headers_sent()) {
  565. if (empty($_SESSION)) {
  566. $_SESSION = array();
  567. }
  568. } else {
  569. // For IE<=8
  570. session_cache_limiter("must-revalidate");
  571. session_start();
  572. }
  573. return true;
  574. }
  575. /**
  576. * Helper method to create a new session.
  577. *
  578. * @return void
  579. */
  580. protected static function _checkValid() {
  581. if (!self::started() && !self::start()) {
  582. self::$valid = false;
  583. return false;
  584. }
  585. if ($config = self::read('Config')) {
  586. $sessionConfig = Configure::read('Session');
  587. if (self::_validAgentAndTime()) {
  588. self::write('Config.time', self::$sessionTime);
  589. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  590. $check = $config['countdown'];
  591. $check -= 1;
  592. self::write('Config.countdown', $check);
  593. if ($check < 1) {
  594. self::renew();
  595. self::write('Config.countdown', self::$requestCountdown);
  596. }
  597. }
  598. self::$valid = true;
  599. } else {
  600. self::destroy();
  601. self::$valid = false;
  602. self::_setError(1, 'Session Highjacking Attempted !!!');
  603. }
  604. } else {
  605. self::write('Config.userAgent', self::$_userAgent);
  606. self::write('Config.time', self::$sessionTime);
  607. self::write('Config.countdown', self::$requestCountdown);
  608. self::$valid = true;
  609. }
  610. }
  611. /**
  612. * Restarts this session.
  613. *
  614. * @return void
  615. */
  616. public static function renew() {
  617. if (session_id()) {
  618. if (session_id() != '' || isset($_COOKIE[session_name()])) {
  619. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  620. }
  621. session_regenerate_id(true);
  622. }
  623. }
  624. /**
  625. * Helper method to set an internal error message.
  626. *
  627. * @param integer $errorNumber Number of the error
  628. * @param string $errorMessage Description of the error
  629. * @return void
  630. */
  631. protected static function _setError($errorNumber, $errorMessage) {
  632. if (self::$error === false) {
  633. self::$error = array();
  634. }
  635. self::$error[$errorNumber] = $errorMessage;
  636. self::$lastError = $errorNumber;
  637. }
  638. }