CakeSession.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. *
  15. * Licensed under The MIT License
  16. * For full copyright and license information, please see the LICENSE.txt
  17. * Redistributions of files must retain the above copyright notice.
  18. *
  19. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  20. * @link http://cakephp.org CakePHP(tm) Project
  21. * @package Cake.Model.Datasource
  22. * @since CakePHP(tm) v .0.10.0.1222
  23. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  24. */
  25. App::uses('Hash', 'Utility');
  26. App::uses('Security', 'Utility');
  27. /**
  28. * Session class for Cake.
  29. *
  30. * Cake abstracts the handling of sessions. There are several convenient methods to access session information.
  31. * This class is the implementation of those methods. They are mostly used by the Session Component.
  32. *
  33. * @package Cake.Model.Datasource
  34. */
  35. class CakeSession {
  36. /**
  37. * True if the Session is still valid
  38. *
  39. * @var boolean
  40. */
  41. public static $valid = false;
  42. /**
  43. * Error messages for this session
  44. *
  45. * @var array
  46. */
  47. public static $error = false;
  48. /**
  49. * User agent string
  50. *
  51. * @var string
  52. */
  53. protected static $_userAgent = '';
  54. /**
  55. * Path to where the session is active.
  56. *
  57. * @var string
  58. */
  59. public static $path = '/';
  60. /**
  61. * Error number of last occurred error
  62. *
  63. * @var integer
  64. */
  65. public static $lastError = null;
  66. /**
  67. * Start time for this session.
  68. *
  69. * @var integer
  70. */
  71. public static $time = false;
  72. /**
  73. * Cookie lifetime
  74. *
  75. * @var integer
  76. */
  77. public static $cookieLifeTime;
  78. /**
  79. * Time when this session becomes invalid.
  80. *
  81. * @var integer
  82. */
  83. public static $sessionTime = false;
  84. /**
  85. * Current Session id
  86. *
  87. * @var string
  88. */
  89. public static $id = null;
  90. /**
  91. * Hostname
  92. *
  93. * @var string
  94. */
  95. public static $host = null;
  96. /**
  97. * Session timeout multiplier factor
  98. *
  99. * @var integer
  100. */
  101. public static $timeout = null;
  102. /**
  103. * Number of requests that can occur during a session time without the session being renewed.
  104. * This feature is only used when config value `Session.autoRegenerate` is set to true.
  105. *
  106. * @var integer
  107. * @see CakeSession::_checkValid()
  108. */
  109. public static $requestCountdown = 10;
  110. /**
  111. * Pseudo constructor.
  112. *
  113. * @param string $base The base path for the Session
  114. * @return void
  115. */
  116. public static function init($base = null) {
  117. self::$time = time();
  118. $checkAgent = Configure::read('Session.checkAgent');
  119. if (env('HTTP_USER_AGENT')) {
  120. self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  121. }
  122. self::_setPath($base);
  123. self::_setHost(env('HTTP_HOST'));
  124. register_shutdown_function('session_write_close');
  125. }
  126. /**
  127. * Setup the Path variable
  128. *
  129. * @param string $base base path
  130. * @return void
  131. */
  132. protected static function _setPath($base = null) {
  133. if (empty($base)) {
  134. self::$path = '/';
  135. return;
  136. }
  137. if (strpos($base, 'index.php') !== false) {
  138. $base = str_replace('index.php', '', $base);
  139. }
  140. if (strpos($base, '?') !== false) {
  141. $base = str_replace('?', '', $base);
  142. }
  143. self::$path = $base;
  144. }
  145. /**
  146. * Set the host name
  147. *
  148. * @param string $host Hostname
  149. * @return void
  150. */
  151. protected static function _setHost($host) {
  152. self::$host = $host;
  153. if (strpos(self::$host, ':') !== false) {
  154. self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
  155. }
  156. }
  157. /**
  158. * Starts the Session.
  159. *
  160. * @return boolean True if session was started
  161. */
  162. public static function start() {
  163. if (self::started()) {
  164. return true;
  165. }
  166. self::init();
  167. $id = self::id();
  168. session_write_close();
  169. self::_configureSession();
  170. self::_startSession();
  171. if (!$id && self::started()) {
  172. self::_checkValid();
  173. }
  174. self::$error = false;
  175. return self::started();
  176. }
  177. /**
  178. * Determine if Session has been started.
  179. *
  180. * @return boolean True if session has been started.
  181. */
  182. public static function started() {
  183. return isset($_SESSION) && session_id();
  184. }
  185. /**
  186. * Returns true if given variable is set in session.
  187. *
  188. * @param string $name Variable name to check for
  189. * @return boolean True if variable is there
  190. */
  191. public static function check($name = null) {
  192. if (!self::start()) {
  193. return false;
  194. }
  195. if (empty($name)) {
  196. return false;
  197. }
  198. return Hash::get($_SESSION, $name) !== null;
  199. }
  200. /**
  201. * Returns the session id.
  202. * Calling this method will not auto start the session. You might have to manually
  203. * assert a started session.
  204. *
  205. * Passing an id into it, you can also replace the session id if the session
  206. * has not already been started.
  207. * Note that depending on the session handler, not all characters are allowed
  208. * within the session id. For example, the file session handler only allows
  209. * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
  210. *
  211. * @param string $id Id to replace the current session id
  212. * @return string Session id
  213. */
  214. public static function id($id = null) {
  215. if ($id) {
  216. self::$id = $id;
  217. session_id(self::$id);
  218. }
  219. if (self::started()) {
  220. return session_id();
  221. }
  222. return self::$id;
  223. }
  224. /**
  225. * Removes a variable from session.
  226. *
  227. * @param string $name Session variable to remove
  228. * @return boolean Success
  229. */
  230. public static function delete($name) {
  231. if (self::check($name)) {
  232. self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
  233. return !self::check($name);
  234. }
  235. return false;
  236. }
  237. /**
  238. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
  239. *
  240. * @param array $old Set of old variables => values
  241. * @param array $new New set of variable => value
  242. * @return void
  243. */
  244. protected static function _overwrite(&$old, $new) {
  245. if (!empty($old)) {
  246. foreach ($old as $key => $var) {
  247. if (!isset($new[$key])) {
  248. unset($old[$key]);
  249. }
  250. }
  251. }
  252. foreach ($new as $key => $var) {
  253. $old[$key] = $var;
  254. }
  255. }
  256. /**
  257. * Return error description for given error number.
  258. *
  259. * @param integer $errorNumber Error to set
  260. * @return string Error as string
  261. */
  262. protected static function _error($errorNumber) {
  263. if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
  264. return false;
  265. }
  266. return self::$error[$errorNumber];
  267. }
  268. /**
  269. * Returns last occurred error as a string, if any.
  270. *
  271. * @return mixed Error description as a string, or false.
  272. */
  273. public static function error() {
  274. if (self::$lastError) {
  275. return self::_error(self::$lastError);
  276. }
  277. return false;
  278. }
  279. /**
  280. * Returns true if session is valid.
  281. *
  282. * @return boolean Success
  283. */
  284. public static function valid() {
  285. if (self::read('Config')) {
  286. if (self::_validAgentAndTime() && self::$error === false) {
  287. self::$valid = true;
  288. } else {
  289. self::$valid = false;
  290. self::_setError(1, 'Session Highjacking Attempted !!!');
  291. }
  292. }
  293. return self::$valid;
  294. }
  295. /**
  296. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  297. * Since timeouts are implemented in CakeSession it checks the current self::$time
  298. * against the time the session is set to expire. The User agent is only checked
  299. * if Session.checkAgent == true.
  300. *
  301. * @return boolean
  302. */
  303. protected static function _validAgentAndTime() {
  304. $config = self::read('Config');
  305. $validAgent = (
  306. Configure::read('Session.checkAgent') === false ||
  307. self::$_userAgent == $config['userAgent']
  308. );
  309. return ($validAgent && self::$time <= $config['time']);
  310. }
  311. /**
  312. * Get / Set the user agent
  313. *
  314. * @param string $userAgent Set the user agent
  315. * @return string Current user agent
  316. */
  317. public static function userAgent($userAgent = null) {
  318. if ($userAgent) {
  319. self::$_userAgent = $userAgent;
  320. }
  321. if (empty(self::$_userAgent)) {
  322. CakeSession::init(self::$path);
  323. }
  324. return self::$_userAgent;
  325. }
  326. /**
  327. * Returns given session variable, or all of them, if no parameters given.
  328. *
  329. * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
  330. * @return mixed The value of the session variable
  331. */
  332. public static function read($name = null) {
  333. if (!self::start()) {
  334. return false;
  335. }
  336. if ($name === null) {
  337. return self::_returnSessionVars();
  338. }
  339. if (empty($name)) {
  340. return false;
  341. }
  342. $result = Hash::get($_SESSION, $name);
  343. if (isset($result)) {
  344. return $result;
  345. }
  346. return null;
  347. }
  348. /**
  349. * Returns all session variables.
  350. *
  351. * @return mixed Full $_SESSION array, or false on error.
  352. */
  353. protected static function _returnSessionVars() {
  354. if (!empty($_SESSION)) {
  355. return $_SESSION;
  356. }
  357. self::_setError(2, 'No Session vars set');
  358. return false;
  359. }
  360. /**
  361. * Writes value to given session variable name.
  362. *
  363. * @param string|array $name Name of variable
  364. * @param string $value Value to write
  365. * @return boolean True if the write was successful, false if the write failed
  366. */
  367. public static function write($name, $value = null) {
  368. if (!self::start()) {
  369. return false;
  370. }
  371. if (empty($name)) {
  372. return false;
  373. }
  374. $write = $name;
  375. if (!is_array($name)) {
  376. $write = array($name => $value);
  377. }
  378. foreach ($write as $key => $val) {
  379. self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
  380. if (Hash::get($_SESSION, $key) !== $val) {
  381. return false;
  382. }
  383. }
  384. return true;
  385. }
  386. /**
  387. * Helper method to destroy invalid sessions.
  388. *
  389. * @return void
  390. */
  391. public static function destroy() {
  392. self::start();
  393. session_destroy();
  394. self::clear();
  395. }
  396. /**
  397. * Clears the session, the session id, and renews the session.
  398. *
  399. * @return void
  400. */
  401. public static function clear() {
  402. $_SESSION = null;
  403. self::$id = null;
  404. self::start();
  405. self::renew();
  406. }
  407. /**
  408. * Helper method to initialize a session, based on Cake core settings.
  409. *
  410. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  411. *
  412. * @return void
  413. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  414. */
  415. protected static function _configureSession() {
  416. $sessionConfig = Configure::read('Session');
  417. if (isset($sessionConfig['defaults'])) {
  418. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  419. if ($defaults) {
  420. $sessionConfig = Hash::merge($defaults, $sessionConfig);
  421. }
  422. }
  423. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  424. $sessionConfig['ini']['session.cookie_secure'] = 1;
  425. }
  426. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  427. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  428. }
  429. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  430. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  431. }
  432. if (!isset($sessionConfig['ini']['session.name'])) {
  433. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  434. }
  435. if (!empty($sessionConfig['handler'])) {
  436. $sessionConfig['ini']['session.save_handler'] = 'user';
  437. }
  438. if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
  439. $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
  440. }
  441. if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
  442. $sessionConfig['ini']['session.cookie_httponly'] = 1;
  443. }
  444. if (empty($_SESSION)) {
  445. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  446. foreach ($sessionConfig['ini'] as $setting => $value) {
  447. if (ini_set($setting, $value) === false) {
  448. throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
  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.save_path' => TMP . 'sessions',
  515. 'session.save_handler' => 'files'
  516. )
  517. ),
  518. 'cache' => array(
  519. 'cookie' => 'CAKEPHP',
  520. 'timeout' => 240,
  521. 'ini' => array(
  522. 'session.use_trans_sid' => 0,
  523. 'url_rewriter.tags' => '',
  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.use_cookies' => 1,
  540. 'session.cookie_path' => self::$path,
  541. 'session.save_handler' => 'user',
  542. 'session.serialize_handler' => 'php',
  543. ),
  544. 'handler' => array(
  545. 'engine' => 'DatabaseSession',
  546. 'model' => 'Session'
  547. )
  548. )
  549. );
  550. if (isset($defaults[$name])) {
  551. return $defaults[$name];
  552. }
  553. return false;
  554. }
  555. /**
  556. * Helper method to start a session
  557. *
  558. * @return boolean Success
  559. */
  560. protected static function _startSession() {
  561. if (headers_sent()) {
  562. if (empty($_SESSION)) {
  563. $_SESSION = array();
  564. }
  565. } else {
  566. // For IE<=8
  567. session_cache_limiter("must-revalidate");
  568. session_start();
  569. }
  570. return true;
  571. }
  572. /**
  573. * Helper method to create a new session.
  574. *
  575. * @return void
  576. */
  577. protected static function _checkValid() {
  578. if (!self::start()) {
  579. self::$valid = false;
  580. return false;
  581. }
  582. if ($config = self::read('Config')) {
  583. $sessionConfig = Configure::read('Session');
  584. if (self::_validAgentAndTime()) {
  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 ($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. }