CakeSession.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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-2011, 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-2011, 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('Set', '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 `Session.autoRegenerate` is set to true.
  104. *
  105. * @var integer
  106. * @see CakeSession::_checkValid()
  107. */
  108. public static $requestCountdown = 10;
  109. /**
  110. * Constructor.
  111. *
  112. * @param string $base The base path for the Session
  113. * @param boolean $start Should session be started right now
  114. * @return void
  115. */
  116. public static function init($base = null, $start = true) {
  117. self::$time = time();
  118. $checkAgent = Configure::read('Session.checkAgent');
  119. if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) {
  120. self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  121. }
  122. self::_setPath($base);
  123. self::_setHost(env('HTTP_HOST'));
  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. $id = self::id();
  166. session_write_close();
  167. self::_configureSession();
  168. self::_startSession();
  169. if (!$id && self::started()) {
  170. self::_checkValid();
  171. }
  172. self::$error = false;
  173. return self::started();
  174. }
  175. /**
  176. * Determine if Session has been started.
  177. *
  178. * @return boolean True if session has been started.
  179. */
  180. public static function started() {
  181. return isset($_SESSION) && session_id();
  182. }
  183. /**
  184. * Returns true if given variable is set in session.
  185. *
  186. * @param string $name Variable name to check for
  187. * @return boolean True if variable is there
  188. */
  189. public static function check($name = null) {
  190. if (!self::started() && !self::start()) {
  191. return false;
  192. }
  193. if (empty($name)) {
  194. return false;
  195. }
  196. $result = Set::classicExtract($_SESSION, $name);
  197. return isset($result);
  198. }
  199. /**
  200. * Returns the Session id
  201. *
  202. * @param string $id
  203. * @return string Session id
  204. */
  205. public static function id($id = null) {
  206. if ($id) {
  207. self::$id = $id;
  208. session_id(self::$id);
  209. }
  210. if (self::started()) {
  211. return session_id();
  212. }
  213. return self::$id;
  214. }
  215. /**
  216. * Removes a variable from session.
  217. *
  218. * @param string $name Session variable to remove
  219. * @return boolean Success
  220. */
  221. public static function delete($name) {
  222. if (self::check($name)) {
  223. self::_overwrite($_SESSION, Set::remove($_SESSION, $name));
  224. return (self::check($name) == false);
  225. }
  226. self::_setError(2, __d('cake_dev', "%s doesn't exist", $name));
  227. return false;
  228. }
  229. /**
  230. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
  231. *
  232. * @param array $old Set of old variables => values
  233. * @param array $new New set of variable => value
  234. * @return void
  235. */
  236. protected static function _overwrite(&$old, $new) {
  237. if (!empty($old)) {
  238. foreach ($old as $key => $var) {
  239. if (!isset($new[$key])) {
  240. unset($old[$key]);
  241. }
  242. }
  243. }
  244. foreach ($new as $key => $var) {
  245. $old[$key] = $var;
  246. }
  247. }
  248. /**
  249. * Return error description for given error number.
  250. *
  251. * @param integer $errorNumber Error to set
  252. * @return string Error as string
  253. */
  254. protected static function _error($errorNumber) {
  255. if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
  256. return false;
  257. } else {
  258. return self::$error[$errorNumber];
  259. }
  260. }
  261. /**
  262. * Returns last occurred error as a string, if any.
  263. *
  264. * @return mixed Error description as a string, or false.
  265. */
  266. public static function error() {
  267. if (self::$lastError) {
  268. return self::_error(self::$lastError);
  269. }
  270. return false;
  271. }
  272. /**
  273. * Returns true if session is valid.
  274. *
  275. * @return boolean Success
  276. */
  277. public static function valid() {
  278. if (self::read('Config')) {
  279. if (self::_validAgentAndTime() && self::$error === false) {
  280. self::$valid = true;
  281. } else {
  282. self::$valid = false;
  283. self::_setError(1, 'Session Highjacking Attempted !!!');
  284. }
  285. }
  286. return self::$valid;
  287. }
  288. /**
  289. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  290. * Since timeouts are implemented in CakeSession it checks the current self::$time
  291. * against the time the session is set to expire. The User agent is only checked
  292. * if Session.checkAgent == true.
  293. *
  294. * @return boolean
  295. */
  296. protected static function _validAgentAndTime() {
  297. $config = self::read('Config');
  298. $validAgent = (
  299. Configure::read('Session.checkAgent') === false ||
  300. self::$_userAgent == $config['userAgent']
  301. );
  302. return ($validAgent && self::$time <= $config['time']);
  303. }
  304. /**
  305. * Get / Set the userAgent
  306. *
  307. * @param string $userAgent Set the userAgent
  308. * @return void
  309. */
  310. public static function userAgent($userAgent = null) {
  311. if ($userAgent) {
  312. self::$_userAgent = $userAgent;
  313. }
  314. return self::$_userAgent;
  315. }
  316. /**
  317. * Returns given session variable, or all of them, if no parameters given.
  318. *
  319. * @param mixed $name The name of the session variable (or a path as sent to Set.extract)
  320. * @return mixed The value of the session variable
  321. */
  322. public static function read($name = null) {
  323. if (!self::started() && !self::start()) {
  324. return false;
  325. }
  326. if (is_null($name)) {
  327. return self::_returnSessionVars();
  328. }
  329. if (empty($name)) {
  330. return false;
  331. }
  332. $result = Set::classicExtract($_SESSION, $name);
  333. if (!is_null($result)) {
  334. return $result;
  335. }
  336. self::_setError(2, "$name doesn't exist");
  337. return null;
  338. }
  339. /**
  340. * Returns all session variables.
  341. *
  342. * @return mixed Full $_SESSION array, or false on error.
  343. */
  344. protected static function _returnSessionVars() {
  345. if (!empty($_SESSION)) {
  346. return $_SESSION;
  347. }
  348. self::_setError(2, 'No Session vars set');
  349. return false;
  350. }
  351. /**
  352. * Writes value to given session variable name.
  353. *
  354. * @param mixed $name Name of variable
  355. * @param string $value Value to write
  356. * @return boolean True if the write was successful, false if the write failed
  357. */
  358. public static function write($name, $value = null) {
  359. if (!self::started() && !self::start()) {
  360. return false;
  361. }
  362. if (empty($name)) {
  363. return false;
  364. }
  365. $write = $name;
  366. if (!is_array($name)) {
  367. $write = array($name => $value);
  368. }
  369. foreach ($write as $key => $val) {
  370. self::_overwrite($_SESSION, Set::insert($_SESSION, $key, $val));
  371. if (Set::classicExtract($_SESSION, $key) !== $val) {
  372. return false;
  373. }
  374. }
  375. return true;
  376. }
  377. /**
  378. * Helper method to destroy invalid sessions.
  379. *
  380. * @return void
  381. */
  382. public static function destroy() {
  383. if (self::started()) {
  384. session_destroy();
  385. }
  386. self::clear();
  387. }
  388. /**
  389. * Clears the session, the session id, and renew's the session.
  390. *
  391. * @return void
  392. */
  393. public static function clear() {
  394. $_SESSION = null;
  395. self::$id = null;
  396. self::start();
  397. self::renew();
  398. }
  399. /**
  400. * Helper method to initialize a session, based on Cake core settings.
  401. *
  402. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  403. *
  404. * @return void
  405. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  406. */
  407. protected static function _configureSession() {
  408. $sessionConfig = Configure::read('Session');
  409. $iniSet = function_exists('ini_set');
  410. if (isset($sessionConfig['defaults'])) {
  411. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  412. if ($defaults) {
  413. $sessionConfig = Set::merge($defaults, $sessionConfig);
  414. }
  415. }
  416. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  417. $sessionConfig['ini']['session.cookie_secure'] = 1;
  418. }
  419. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  420. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  421. }
  422. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  423. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  424. }
  425. if (!isset($sessionConfig['ini']['session.name'])) {
  426. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  427. }
  428. if (!empty($sessionConfig['handler'])) {
  429. $sessionConfig['ini']['session.save_handler'] = 'user';
  430. }
  431. if (empty($_SESSION)) {
  432. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  433. foreach ($sessionConfig['ini'] as $setting => $value) {
  434. if (ini_set($setting, $value) === false) {
  435. throw new CakeSessionException(sprintf(
  436. __d('cake_dev', 'Unable to configure the session, setting %s failed.'),
  437. $setting
  438. ));
  439. }
  440. }
  441. }
  442. }
  443. if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
  444. call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
  445. }
  446. if (!empty($sessionConfig['handler']['engine'])) {
  447. $handler = self::_getHandler($sessionConfig['handler']['engine']);
  448. session_set_save_handler(
  449. array($handler, 'open'),
  450. array($handler, 'close'),
  451. array($handler, 'read'),
  452. array($handler, 'write'),
  453. array($handler, 'destroy'),
  454. array($handler, 'gc')
  455. );
  456. }
  457. Configure::write('Session', $sessionConfig);
  458. self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
  459. }
  460. /**
  461. * Find the handler class and make sure it implements the correct interface.
  462. *
  463. * @param string $handler
  464. * @return void
  465. * @throws CakeSessionException
  466. */
  467. protected static function _getHandler($handler) {
  468. list($plugin, $class) = pluginSplit($handler, true);
  469. App::uses($class, $plugin . 'Model/Datasource/Session');
  470. if (!class_exists($class)) {
  471. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  472. }
  473. $handler = new $class();
  474. if ($handler instanceof CakeSessionHandlerInterface) {
  475. return $handler;
  476. }
  477. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
  478. }
  479. /**
  480. * Get one of the prebaked default session configurations.
  481. *
  482. * @param string $name
  483. * @return boolean|array
  484. */
  485. protected static function _defaultConfig($name) {
  486. $defaults = array(
  487. 'php' => array(
  488. 'cookie' => 'CAKEPHP',
  489. 'timeout' => 240,
  490. 'cookieTimeout' => 240,
  491. 'ini' => array(
  492. 'session.use_trans_sid' => 0,
  493. 'session.cookie_path' => self::$path
  494. )
  495. ),
  496. 'cake' => array(
  497. 'cookie' => 'CAKEPHP',
  498. 'timeout' => 240,
  499. 'cookieTimeout' => 240,
  500. 'ini' => array(
  501. 'session.use_trans_sid' => 0,
  502. 'url_rewriter.tags' => '',
  503. 'session.serialize_handler' => 'php',
  504. 'session.use_cookies' => 1,
  505. 'session.cookie_path' => self::$path,
  506. 'session.auto_start' => 0,
  507. 'session.save_path' => TMP . 'sessions',
  508. 'session.save_handler' => 'files'
  509. )
  510. ),
  511. 'cache' => array(
  512. 'cookie' => 'CAKEPHP',
  513. 'timeout' => 240,
  514. 'cookieTimeout' => 240,
  515. 'ini' => array(
  516. 'session.use_trans_sid' => 0,
  517. 'url_rewriter.tags' => '',
  518. 'session.auto_start' => 0,
  519. 'session.use_cookies' => 1,
  520. 'session.cookie_path' => self::$path,
  521. 'session.save_handler' => 'user',
  522. ),
  523. 'handler' => array(
  524. 'engine' => 'CacheSession',
  525. 'config' => 'default'
  526. )
  527. ),
  528. 'database' => array(
  529. 'cookie' => 'CAKEPHP',
  530. 'timeout' => 240,
  531. 'cookieTimeout' => 240,
  532. 'ini' => array(
  533. 'session.use_trans_sid' => 0,
  534. 'url_rewriter.tags' => '',
  535. 'session.auto_start' => 0,
  536. 'session.use_cookies' => 1,
  537. 'session.cookie_path' => self::$path,
  538. 'session.save_handler' => 'user',
  539. 'session.serialize_handler' => 'php',
  540. ),
  541. 'handler' => array(
  542. 'engine' => 'DatabaseSession',
  543. 'model' => 'Session'
  544. )
  545. )
  546. );
  547. if (isset($defaults[$name])) {
  548. return $defaults[$name];
  549. }
  550. return false;
  551. }
  552. /**
  553. * Helper method to start a session
  554. *
  555. * @return boolean Success
  556. */
  557. protected static function _startSession() {
  558. if (headers_sent()) {
  559. if (empty($_SESSION)) {
  560. $_SESSION = array();
  561. }
  562. } elseif (!isset($_SESSION)) {
  563. session_cache_limiter ("must-revalidate");
  564. session_start();
  565. header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
  566. } else {
  567. session_start();
  568. }
  569. return true;
  570. }
  571. /**
  572. * Helper method to create a new session.
  573. *
  574. * @return void
  575. */
  576. protected static function _checkValid() {
  577. if (!self::started() && !self::start()) {
  578. self::$valid = false;
  579. return false;
  580. }
  581. if ($config = self::read('Config')) {
  582. $sessionConfig = Configure::read('Session');
  583. if (self::_validAgentAndTime()) {
  584. $time = $config['time'];
  585. self::write('Config.time', self::$sessionTime);
  586. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  587. $check = $config['countdown'];
  588. $check -= 1;
  589. self::write('Config.countdown', $check);
  590. if (time() > ($time - ($sessionConfig['timeout'] * 60) + 2) || $check < 1) {
  591. self::renew();
  592. self::write('Config.countdown', self::$requestCountdown);
  593. }
  594. }
  595. self::$valid = true;
  596. } else {
  597. self::destroy();
  598. self::$valid = false;
  599. self::_setError(1, 'Session Highjacking Attempted !!!');
  600. }
  601. } else {
  602. self::write('Config.userAgent', self::$_userAgent);
  603. self::write('Config.time', self::$sessionTime);
  604. self::write('Config.countdown', self::$requestCountdown);
  605. self::$valid = true;
  606. }
  607. }
  608. /**
  609. * Restarts this session.
  610. *
  611. * @return void
  612. */
  613. public static function renew() {
  614. if (session_id()) {
  615. if (session_id() != '' || isset($_COOKIE[session_name()])) {
  616. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  617. }
  618. session_regenerate_id(true);
  619. }
  620. }
  621. /**
  622. * Helper method to set an internal error message.
  623. *
  624. * @param integer $errorNumber Number of the error
  625. * @param string $errorMessage Description of the error
  626. * @return void
  627. */
  628. protected static function _setError($errorNumber, $errorMessage) {
  629. if (self::$error === false) {
  630. self::$error = array();
  631. }
  632. self::$error[$errorNumber] = $errorMessage;
  633. self::$lastError = $errorNumber;
  634. }
  635. }
  636. // Initialize the session
  637. CakeSession::init();