Session.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.Model.Datasource
  13. * @since CakePHP(tm) v .0.10.0.1222
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Model\Datasource;
  17. use Cake\Core\App;
  18. use Cake\Core\Configure;
  19. use Cake\Error;
  20. use Cake\Model\Datasource\Session\SessionHandlerInterface;
  21. use Cake\Utility\Hash;
  22. /**
  23. * Session class for Cake.
  24. *
  25. * Cake abstracts the handling of sessions. There are several convenient methods to access session information.
  26. * This class is the implementation of those methods. They are mostly used by the Session Component.
  27. *
  28. * @package Cake.Model.Datasource
  29. */
  30. class Session {
  31. /**
  32. * True if the Session is still valid
  33. *
  34. * @var boolean
  35. */
  36. public static $valid = false;
  37. /**
  38. * Error messages for this session
  39. *
  40. * @var array
  41. */
  42. public static $error = false;
  43. /**
  44. * User agent string
  45. *
  46. * @var string
  47. */
  48. protected static $_userAgent = '';
  49. /**
  50. * Path to where the session is active.
  51. *
  52. * @var string
  53. */
  54. public static $path = '/';
  55. /**
  56. * Error number of last occurred error
  57. *
  58. * @var integer
  59. */
  60. public static $lastError = null;
  61. /**
  62. * Start time for this session.
  63. *
  64. * @var integer
  65. */
  66. public static $time = false;
  67. /**
  68. * Cookie lifetime
  69. *
  70. * @var integer
  71. */
  72. public static $cookieLifeTime;
  73. /**
  74. * Time when this session becomes invalid.
  75. *
  76. * @var integer
  77. */
  78. public static $sessionTime = false;
  79. /**
  80. * Current Session id
  81. *
  82. * @var string
  83. */
  84. public static $id = null;
  85. /**
  86. * Hostname
  87. *
  88. * @var string
  89. */
  90. public static $host = null;
  91. /**
  92. * Session timeout multiplier factor
  93. *
  94. * @var integer
  95. */
  96. public static $timeout = null;
  97. /**
  98. * Number of requests that can occur during a session time without the session being renewed.
  99. * This feature is only used when config value `Session.autoRegenerate` is set to true.
  100. *
  101. * @var integer
  102. * @see Cake\Model\Datasource\Session::_checkValid()
  103. */
  104. public static $requestCountdown = 10;
  105. /**
  106. * Pseudo constructor.
  107. *
  108. * @param string $base The base path for the Session
  109. * @return void
  110. */
  111. public static function init($base = null) {
  112. static::$time = time();
  113. $checkAgent = Configure::read('Session.checkAgent');
  114. if (env('HTTP_USER_AGENT')) {
  115. static::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  116. }
  117. static::_setPath($base);
  118. static::_setHost(env('HTTP_HOST'));
  119. register_shutdown_function('session_write_close');
  120. }
  121. /**
  122. * Setup the Path variable
  123. *
  124. * @param string $base base path
  125. * @return void
  126. */
  127. protected static function _setPath($base = null) {
  128. if (empty($base)) {
  129. static::$path = '/';
  130. return;
  131. }
  132. if (strpos($base, 'index.php') !== false) {
  133. $base = str_replace('index.php', '', $base);
  134. }
  135. if (strpos($base, '?') !== false) {
  136. $base = str_replace('?', '', $base);
  137. }
  138. static::$path = $base;
  139. }
  140. /**
  141. * Set the host name
  142. *
  143. * @param string $host Hostname
  144. * @return void
  145. */
  146. protected static function _setHost($host) {
  147. static::$host = $host;
  148. if (strpos(static::$host, ':') !== false) {
  149. static::$host = substr(static::$host, 0, strpos(static::$host, ':'));
  150. }
  151. }
  152. /**
  153. * Starts the Session.
  154. *
  155. * @return boolean True if session was started
  156. */
  157. public static function start() {
  158. if (static::started()) {
  159. return true;
  160. }
  161. static::init();
  162. $id = static::id();
  163. session_write_close();
  164. static::_configureSession();
  165. static::_startSession();
  166. if (!$id && static::started()) {
  167. static::_checkValid();
  168. }
  169. static::$error = false;
  170. return static::started();
  171. }
  172. /**
  173. * Determine if Session has been started.
  174. *
  175. * @return boolean True if session has been started.
  176. */
  177. public static function started() {
  178. return isset($_SESSION) && session_id();
  179. }
  180. /**
  181. * Returns true if given variable is set in session.
  182. *
  183. * @param string $name Variable name to check for
  184. * @return boolean True if variable is there
  185. */
  186. public static function check($name = null) {
  187. if (!static::start()) {
  188. return false;
  189. }
  190. if (empty($name)) {
  191. return false;
  192. }
  193. return Hash::get($_SESSION, $name) !== null;
  194. }
  195. /**
  196. * Returns the session id.
  197. * Calling this method will not auto start the session. You might have to manually
  198. * assert a started session.
  199. *
  200. * Passing an id into it, you can also replace the session id if the session
  201. * has not already been started.
  202. * Note that depending on the session handler, not all characters are allowed
  203. * within the session id. For example, the file session handler only allows
  204. * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
  205. *
  206. * @param string $id Id to replace the current session id
  207. * @return string Session id
  208. */
  209. public static function id($id = null) {
  210. if ($id) {
  211. static::$id = $id;
  212. session_id(static::$id);
  213. }
  214. if (static::started()) {
  215. return session_id();
  216. }
  217. return static::$id;
  218. }
  219. /**
  220. * Removes a variable from session.
  221. *
  222. * @param string $name Session variable to remove
  223. * @return boolean Success
  224. */
  225. public static function delete($name) {
  226. if (static::check($name)) {
  227. static::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
  228. return !static::check($name);
  229. }
  230. return false;
  231. }
  232. /**
  233. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
  234. *
  235. * @param array $old Set of old variables => values
  236. * @param array $new New set of variable => value
  237. * @return void
  238. */
  239. protected static function _overwrite(&$old, $new) {
  240. if (!empty($old)) {
  241. foreach ($old as $key => $var) {
  242. if (!isset($new[$key])) {
  243. unset($old[$key]);
  244. }
  245. }
  246. }
  247. foreach ($new as $key => $var) {
  248. $old[$key] = $var;
  249. }
  250. }
  251. /**
  252. * Return error description for given error number.
  253. *
  254. * @param integer $errorNumber Error to set
  255. * @return string Error as string
  256. */
  257. protected static function _error($errorNumber) {
  258. if (!is_array(static::$error) || !array_key_exists($errorNumber, static::$error)) {
  259. return false;
  260. }
  261. return static::$error[$errorNumber];
  262. }
  263. /**
  264. * Returns last occurred error as a string, if any.
  265. *
  266. * @return mixed Error description as a string, or false.
  267. */
  268. public static function error() {
  269. if (static::$lastError) {
  270. return static::_error(static::$lastError);
  271. }
  272. return false;
  273. }
  274. /**
  275. * Returns true if session is valid.
  276. *
  277. * @return boolean Success
  278. */
  279. public static function valid() {
  280. if (static::read('Config')) {
  281. if (static::_validAgentAndTime() && static::$error === false) {
  282. static::$valid = true;
  283. } else {
  284. static::$valid = false;
  285. static::_setError(1, 'Session Highjacking Attempted !!!');
  286. }
  287. }
  288. return static::$valid;
  289. }
  290. /**
  291. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  292. * Since timeouts are implemented in Session it checks the current static::$time
  293. * against the time the session is set to expire. The User agent is only checked
  294. * if Session.checkAgent == true.
  295. *
  296. * @return boolean
  297. */
  298. protected static function _validAgentAndTime() {
  299. $config = static::read('Config');
  300. $validAgent = (
  301. Configure::read('Session.checkAgent') === false ||
  302. static::$_userAgent == $config['userAgent']
  303. );
  304. return ($validAgent && static::$time <= $config['time']);
  305. }
  306. /**
  307. * Get / Set the user agent
  308. *
  309. * @param string $userAgent Set the user agent
  310. * @return string Current user agent
  311. */
  312. public static function userAgent($userAgent = null) {
  313. if ($userAgent) {
  314. static::$_userAgent = $userAgent;
  315. }
  316. if (empty(static::$_userAgent)) {
  317. Session::init(static::$path);
  318. }
  319. return static::$_userAgent;
  320. }
  321. /**
  322. * Returns given session variable, or all of them, if no parameters given.
  323. *
  324. * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
  325. * @return mixed The value of the session variable
  326. */
  327. public static function read($name = null) {
  328. if (!static::start()) {
  329. return false;
  330. }
  331. if ($name === null) {
  332. return static::_returnSessionVars();
  333. }
  334. if (empty($name)) {
  335. return false;
  336. }
  337. $result = Hash::get($_SESSION, $name);
  338. if (isset($result)) {
  339. return $result;
  340. }
  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. static::_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 (!static::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. static::_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. self::start();
  388. session_destroy();
  389. self::clear();
  390. }
  391. /**
  392. * Clears the session, the session id, and renews the session.
  393. *
  394. * @return void
  395. */
  396. public static function clear() {
  397. $_SESSION = null;
  398. static::$id = null;
  399. static::start();
  400. static::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 Cake\Error\Exception Throws exceptions when ini_set() fails.
  409. */
  410. protected static function _configureSession() {
  411. $sessionConfig = Configure::read('Session');
  412. if (isset($sessionConfig['defaults'])) {
  413. $defaults = static::_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 Error\Exception(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 = static::_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. static::$sessionTime = static::$time + ($sessionConfig['timeout'] * 60);
  467. }
  468. /**
  469. * Find the handler class and make sure it implements the correct interface.
  470. *
  471. * @param string $class
  472. * @return void
  473. * @throws Cake\Error\Exception
  474. */
  475. protected static function _getHandler($class) {
  476. $class = App::className($class, 'Model/Datasource/Session');
  477. if (!class_exists($class)) {
  478. throw new Error\Exception(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  479. }
  480. $handler = new $class();
  481. if ($handler instanceof SessionHandlerInterface) {
  482. return $handler;
  483. }
  484. throw new Error\Exception(__d('cake_dev', 'Chosen SessionHandler does not implement SessionHandlerInterface it cannot be used with an engine key.'));
  485. }
  486. /**
  487. * Get one of the prebaked default session configurations.
  488. *
  489. * @param string $name
  490. * @return boolean|array
  491. */
  492. protected static function _defaultConfig($name) {
  493. $defaults = array(
  494. 'php' => array(
  495. 'checkAgent' => false,
  496. 'cookie' => 'CAKEPHP',
  497. 'timeout' => 240,
  498. 'ini' => array(
  499. 'session.use_trans_sid' => 0,
  500. 'session.cookie_path' => static::$path
  501. )
  502. ),
  503. 'cake' => array(
  504. 'checkAgent' => false,
  505. 'cookie' => 'CAKEPHP',
  506. 'timeout' => 240,
  507. 'ini' => array(
  508. 'session.use_trans_sid' => 0,
  509. 'url_rewriter.tags' => '',
  510. 'session.serialize_handler' => 'php',
  511. 'session.use_cookies' => 1,
  512. 'session.cookie_path' => static::$path,
  513. 'session.save_path' => TMP . 'sessions',
  514. 'session.save_handler' => 'files'
  515. )
  516. ),
  517. 'cache' => array(
  518. 'checkAgent' => false,
  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' => static::$path,
  526. 'session.save_handler' => 'user',
  527. ),
  528. 'handler' => array(
  529. 'engine' => 'CacheSession',
  530. 'config' => 'default'
  531. )
  532. ),
  533. 'database' => array(
  534. 'checkAgent' => false,
  535. 'cookie' => 'CAKEPHP',
  536. 'timeout' => 240,
  537. 'ini' => array(
  538. 'session.use_trans_sid' => 0,
  539. 'url_rewriter.tags' => '',
  540. 'session.use_cookies' => 1,
  541. 'session.cookie_path' => static::$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 (!static::start()) {
  580. static::$valid = false;
  581. return false;
  582. }
  583. if ($config = static::read('Config')) {
  584. $sessionConfig = Configure::read('Session');
  585. if (static::_validAgentAndTime()) {
  586. static::write('Config.time', static::$sessionTime);
  587. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  588. $check = $config['countdown'];
  589. $check -= 1;
  590. static::write('Config.countdown', $check);
  591. if ($check < 1) {
  592. static::renew();
  593. static::write('Config.countdown', static::$requestCountdown);
  594. }
  595. }
  596. static::$valid = true;
  597. } else {
  598. static::destroy();
  599. static::$valid = false;
  600. static::_setError(1, 'Session Highjacking Attempted !!!');
  601. }
  602. } else {
  603. static::write('Config.userAgent', static::$_userAgent);
  604. static::write('Config.time', static::$sessionTime);
  605. static::write('Config.countdown', static::$requestCountdown);
  606. static::$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, static::$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 (static::$error === false) {
  631. static::$error = array();
  632. }
  633. static::$error[$errorNumber] = $errorMessage;
  634. static::$lastError = $errorNumber;
  635. }
  636. }