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-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')) {
  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. return Hash::get($_SESSION, $name) !== null;
  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, Hash::remove($_SESSION, $name));
  224. return !self::check($name);
  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. }
  258. return self::$error[$errorNumber];
  259. }
  260. /**
  261. * Returns last occurred error as a string, if any.
  262. *
  263. * @return mixed Error description as a string, or false.
  264. */
  265. public static function error() {
  266. if (self::$lastError) {
  267. return self::_error(self::$lastError);
  268. }
  269. return false;
  270. }
  271. /**
  272. * Returns true if session is valid.
  273. *
  274. * @return boolean Success
  275. */
  276. public static function valid() {
  277. if (self::read('Config')) {
  278. if (self::_validAgentAndTime() && self::$error === false) {
  279. self::$valid = true;
  280. } else {
  281. self::$valid = false;
  282. self::_setError(1, 'Session Highjacking Attempted !!!');
  283. }
  284. }
  285. return self::$valid;
  286. }
  287. /**
  288. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  289. * Since timeouts are implemented in CakeSession it checks the current self::$time
  290. * against the time the session is set to expire. The User agent is only checked
  291. * if Session.checkAgent == true.
  292. *
  293. * @return boolean
  294. */
  295. protected static function _validAgentAndTime() {
  296. $config = self::read('Config');
  297. $validAgent = (
  298. Configure::read('Session.checkAgent') === false ||
  299. self::$_userAgent == $config['userAgent']
  300. );
  301. return ($validAgent && self::$time <= $config['time']);
  302. }
  303. /**
  304. * Get / Set the userAgent
  305. *
  306. * @param string $userAgent Set the userAgent
  307. * @return void
  308. */
  309. public static function userAgent($userAgent = null) {
  310. if ($userAgent) {
  311. self::$_userAgent = $userAgent;
  312. }
  313. if (empty(self::$_userAgent)) {
  314. CakeSession::init(self::$path);
  315. }
  316. return self::$_userAgent;
  317. }
  318. /**
  319. * Returns given session variable, or all of them, if no parameters given.
  320. *
  321. * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
  322. * @return mixed The value of the session variable
  323. */
  324. public static function read($name = null) {
  325. if (!self::started() && !self::start()) {
  326. return false;
  327. }
  328. if (is_null($name)) {
  329. return self::_returnSessionVars();
  330. }
  331. if (empty($name)) {
  332. return false;
  333. }
  334. $result = Hash::get($_SESSION, $name);
  335. if (isset($result)) {
  336. return $result;
  337. }
  338. self::_setError(2, "$name doesn't exist");
  339. return null;
  340. }
  341. /**
  342. * Returns all session variables.
  343. *
  344. * @return mixed Full $_SESSION array, or false on error.
  345. */
  346. protected static function _returnSessionVars() {
  347. if (!empty($_SESSION)) {
  348. return $_SESSION;
  349. }
  350. self::_setError(2, 'No Session vars set');
  351. return false;
  352. }
  353. /**
  354. * Writes value to given session variable name.
  355. *
  356. * @param string|array $name Name of variable
  357. * @param string $value Value to write
  358. * @return boolean True if the write was successful, false if the write failed
  359. */
  360. public static function write($name, $value = null) {
  361. if (!self::started() && !self::start()) {
  362. return false;
  363. }
  364. if (empty($name)) {
  365. return false;
  366. }
  367. $write = $name;
  368. if (!is_array($name)) {
  369. $write = array($name => $value);
  370. }
  371. foreach ($write as $key => $val) {
  372. self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
  373. if (Hash::get($_SESSION, $key) !== $val) {
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. /**
  380. * Helper method to destroy invalid sessions.
  381. *
  382. * @return void
  383. */
  384. public static function destroy() {
  385. if (!self::started()) {
  386. self::start();
  387. }
  388. session_destroy();
  389. self::clear();
  390. }
  391. /**
  392. * Clears the session, the session id, and renew's the session.
  393. *
  394. * @return void
  395. */
  396. public static function clear() {
  397. $_SESSION = null;
  398. self::$id = null;
  399. self::start();
  400. self::renew();
  401. }
  402. /**
  403. * Helper method to initialize a session, based on Cake core settings.
  404. *
  405. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  406. *
  407. * @return void
  408. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  409. */
  410. protected static function _configureSession() {
  411. $sessionConfig = Configure::read('Session');
  412. if (isset($sessionConfig['defaults'])) {
  413. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  414. if ($defaults) {
  415. $sessionConfig = Hash::merge($defaults, $sessionConfig);
  416. }
  417. }
  418. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  419. $sessionConfig['ini']['session.cookie_secure'] = 1;
  420. }
  421. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  422. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  423. }
  424. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  425. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  426. }
  427. if (!isset($sessionConfig['ini']['session.name'])) {
  428. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  429. }
  430. if (!empty($sessionConfig['handler'])) {
  431. $sessionConfig['ini']['session.save_handler'] = 'user';
  432. }
  433. if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
  434. $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
  435. }
  436. if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
  437. $sessionConfig['ini']['session.cookie_httponly'] = 1;
  438. }
  439. if (empty($_SESSION)) {
  440. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  441. foreach ($sessionConfig['ini'] as $setting => $value) {
  442. if (ini_set($setting, $value) === false) {
  443. throw new CakeSessionException(sprintf(
  444. __d('cake_dev', 'Unable to configure the session, setting %s failed.'),
  445. $setting
  446. ));
  447. }
  448. }
  449. }
  450. }
  451. if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
  452. call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
  453. }
  454. if (!empty($sessionConfig['handler']['engine'])) {
  455. $handler = self::_getHandler($sessionConfig['handler']['engine']);
  456. session_set_save_handler(
  457. array($handler, 'open'),
  458. array($handler, 'close'),
  459. array($handler, 'read'),
  460. array($handler, 'write'),
  461. array($handler, 'destroy'),
  462. array($handler, 'gc')
  463. );
  464. }
  465. Configure::write('Session', $sessionConfig);
  466. self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
  467. }
  468. /**
  469. * Find the handler class and make sure it implements the correct interface.
  470. *
  471. * @param string $handler
  472. * @return void
  473. * @throws CakeSessionException
  474. */
  475. protected static function _getHandler($handler) {
  476. list($plugin, $class) = pluginSplit($handler, true);
  477. App::uses($class, $plugin . 'Model/Datasource/Session');
  478. if (!class_exists($class)) {
  479. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  480. }
  481. $handler = new $class();
  482. if ($handler instanceof CakeSessionHandlerInterface) {
  483. return $handler;
  484. }
  485. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
  486. }
  487. /**
  488. * Get one of the prebaked default session configurations.
  489. *
  490. * @param string $name
  491. * @return boolean|array
  492. */
  493. protected static function _defaultConfig($name) {
  494. $defaults = array(
  495. 'php' => array(
  496. 'cookie' => 'CAKEPHP',
  497. 'timeout' => 240,
  498. 'ini' => array(
  499. 'session.use_trans_sid' => 0,
  500. 'session.cookie_path' => self::$path
  501. )
  502. ),
  503. 'cake' => array(
  504. 'cookie' => 'CAKEPHP',
  505. 'timeout' => 240,
  506. 'ini' => array(
  507. 'session.use_trans_sid' => 0,
  508. 'url_rewriter.tags' => '',
  509. 'session.serialize_handler' => 'php',
  510. 'session.use_cookies' => 1,
  511. 'session.cookie_path' => self::$path,
  512. 'session.auto_start' => 0,
  513. 'session.save_path' => TMP . 'sessions',
  514. 'session.save_handler' => 'files'
  515. )
  516. ),
  517. 'cache' => array(
  518. 'cookie' => 'CAKEPHP',
  519. 'timeout' => 240,
  520. 'ini' => array(
  521. 'session.use_trans_sid' => 0,
  522. 'url_rewriter.tags' => '',
  523. 'session.auto_start' => 0,
  524. 'session.use_cookies' => 1,
  525. 'session.cookie_path' => self::$path,
  526. 'session.save_handler' => 'user',
  527. ),
  528. 'handler' => array(
  529. 'engine' => 'CacheSession',
  530. 'config' => 'default'
  531. )
  532. ),
  533. 'database' => array(
  534. 'cookie' => 'CAKEPHP',
  535. 'timeout' => 240,
  536. 'ini' => array(
  537. 'session.use_trans_sid' => 0,
  538. 'url_rewriter.tags' => '',
  539. 'session.auto_start' => 0,
  540. 'session.use_cookies' => 1,
  541. 'session.cookie_path' => self::$path,
  542. 'session.save_handler' => 'user',
  543. 'session.serialize_handler' => 'php',
  544. ),
  545. 'handler' => array(
  546. 'engine' => 'DatabaseSession',
  547. 'model' => 'Session'
  548. )
  549. )
  550. );
  551. if (isset($defaults[$name])) {
  552. return $defaults[$name];
  553. }
  554. return false;
  555. }
  556. /**
  557. * Helper method to start a session
  558. *
  559. * @return boolean Success
  560. */
  561. protected static function _startSession() {
  562. if (headers_sent()) {
  563. if (empty($_SESSION)) {
  564. $_SESSION = array();
  565. }
  566. } else {
  567. // For IE<=8
  568. session_cache_limiter("must-revalidate");
  569. session_start();
  570. }
  571. return true;
  572. }
  573. /**
  574. * Helper method to create a new session.
  575. *
  576. * @return void
  577. */
  578. protected static function _checkValid() {
  579. if (!self::started() && !self::start()) {
  580. self::$valid = false;
  581. return false;
  582. }
  583. if ($config = self::read('Config')) {
  584. $sessionConfig = Configure::read('Session');
  585. if (self::_validAgentAndTime()) {
  586. self::write('Config.time', self::$sessionTime);
  587. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  588. $check = $config['countdown'];
  589. $check -= 1;
  590. self::write('Config.countdown', $check);
  591. if ($check < 1) {
  592. self::renew();
  593. self::write('Config.countdown', self::$requestCountdown);
  594. }
  595. }
  596. self::$valid = true;
  597. } else {
  598. self::destroy();
  599. self::$valid = false;
  600. self::_setError(1, 'Session Highjacking Attempted !!!');
  601. }
  602. } else {
  603. self::write('Config.userAgent', self::$_userAgent);
  604. self::write('Config.time', self::$sessionTime);
  605. self::write('Config.countdown', self::$requestCountdown);
  606. self::$valid = true;
  607. }
  608. }
  609. /**
  610. * Restarts this session.
  611. *
  612. * @return void
  613. */
  614. public static function renew() {
  615. if (session_id()) {
  616. if (session_id() || isset($_COOKIE[session_name()])) {
  617. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  618. }
  619. session_regenerate_id(true);
  620. }
  621. }
  622. /**
  623. * Helper method to set an internal error message.
  624. *
  625. * @param integer $errorNumber Number of the error
  626. * @param string $errorMessage Description of the error
  627. * @return void
  628. */
  629. protected static function _setError($errorNumber, $errorMessage) {
  630. if (self::$error === false) {
  631. self::$error = array();
  632. }
  633. self::$error[$errorNumber] = $errorMessage;
  634. self::$lastError = $errorNumber;
  635. }
  636. }