Session.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. * @since CakePHP(tm) v .0.10.0.1222
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Model\Datasource;
  16. use Cake\Core\App;
  17. use Cake\Core\Configure;
  18. use Cake\Error;
  19. use Cake\Model\Datasource\Session\SessionHandlerInterface;
  20. use Cake\Utility\Hash;
  21. /**
  22. * Session class for CakePHP.
  23. *
  24. * CakePHP abstracts the handling of sessions. There are several convenient methods to access session information.
  25. * This class is the implementation of those methods. They are mostly used by the Session Component.
  26. *
  27. */
  28. class Session {
  29. /**
  30. * True if the Session is still valid
  31. *
  32. * @var boolean
  33. */
  34. public static $valid = false;
  35. /**
  36. * Error messages for this session
  37. *
  38. * @var array
  39. */
  40. public static $error = false;
  41. /**
  42. * User agent string
  43. *
  44. * @var string
  45. */
  46. protected static $_userAgent = '';
  47. /**
  48. * Path to where the session is active.
  49. *
  50. * @var string
  51. */
  52. public static $path = '/';
  53. /**
  54. * Error number of last occurred error
  55. *
  56. * @var integer
  57. */
  58. public static $lastError = null;
  59. /**
  60. * Start time for this session.
  61. *
  62. * @var integer
  63. */
  64. public static $time = false;
  65. /**
  66. * Cookie lifetime
  67. *
  68. * @var integer
  69. */
  70. public static $cookieLifeTime;
  71. /**
  72. * Time when this session becomes invalid.
  73. *
  74. * @var integer
  75. */
  76. public static $sessionTime = false;
  77. /**
  78. * Current Session id
  79. *
  80. * @var string
  81. */
  82. public static $id = null;
  83. /**
  84. * Hostname
  85. *
  86. * @var string
  87. */
  88. public static $host = null;
  89. /**
  90. * Session timeout multiplier factor
  91. *
  92. * @var integer
  93. */
  94. public static $timeout = null;
  95. /**
  96. * Number of requests that can occur during a session time without the session being renewed.
  97. * This feature is only used when config value `Session.autoRegenerate` is set to true.
  98. *
  99. * @var integer
  100. * @see Cake\Model\Datasource\Session::_checkValid()
  101. */
  102. public static $requestCountdown = 10;
  103. /**
  104. * Pseudo constructor.
  105. *
  106. * @param string $base The base path for the Session
  107. * @return void
  108. */
  109. public static function init($base = null) {
  110. static::$time = time();
  111. $checkAgent = Configure::read('Session.checkAgent');
  112. if (env('HTTP_USER_AGENT')) {
  113. static::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  114. }
  115. static::_setPath($base);
  116. static::_setHost(env('HTTP_HOST'));
  117. register_shutdown_function('session_write_close');
  118. }
  119. /**
  120. * Setup the Path variable
  121. *
  122. * @param string $base base path
  123. * @return void
  124. */
  125. protected static function _setPath($base = null) {
  126. if (empty($base)) {
  127. static::$path = '/';
  128. return;
  129. }
  130. if (strpos($base, 'index.php') !== false) {
  131. $base = str_replace('index.php', '', $base);
  132. }
  133. if (strpos($base, '?') !== false) {
  134. $base = str_replace('?', '', $base);
  135. }
  136. static::$path = $base;
  137. }
  138. /**
  139. * Set the host name
  140. *
  141. * @param string $host Hostname
  142. * @return void
  143. */
  144. protected static function _setHost($host) {
  145. static::$host = $host;
  146. if (strpos(static::$host, ':') !== false) {
  147. static::$host = substr(static::$host, 0, strpos(static::$host, ':'));
  148. }
  149. }
  150. /**
  151. * Starts the Session.
  152. *
  153. * @return boolean True if session was started
  154. */
  155. public static function start() {
  156. if (static::started()) {
  157. return true;
  158. }
  159. static::init();
  160. $id = static::id();
  161. session_write_close();
  162. static::_configureSession();
  163. static::_startSession();
  164. if (!$id && static::started()) {
  165. static::_checkValid();
  166. }
  167. static::$error = false;
  168. return static::started();
  169. }
  170. /**
  171. * Determine if Session has been started.
  172. *
  173. * @return boolean True if session has been started.
  174. */
  175. public static function started() {
  176. return isset($_SESSION) && session_id();
  177. }
  178. /**
  179. * Returns true if given variable is set in session.
  180. *
  181. * @param string $name Variable name to check for
  182. * @return boolean True if variable is there
  183. */
  184. public static function check($name = null) {
  185. if (!static::start()) {
  186. return false;
  187. }
  188. if (empty($name)) {
  189. return false;
  190. }
  191. return Hash::get($_SESSION, $name) !== null;
  192. }
  193. /**
  194. * Returns the session id.
  195. * Calling this method will not auto start the session. You might have to manually
  196. * assert a started session.
  197. *
  198. * Passing an id into it, you can also replace the session id if the session
  199. * has not already been started.
  200. * Note that depending on the session handler, not all characters are allowed
  201. * within the session id. For example, the file session handler only allows
  202. * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
  203. *
  204. * @param string $id Id to replace the current session id
  205. * @return string Session id
  206. */
  207. public static function id($id = null) {
  208. if ($id) {
  209. static::$id = $id;
  210. session_id(static::$id);
  211. }
  212. if (static::started()) {
  213. return session_id();
  214. }
  215. return static::$id;
  216. }
  217. /**
  218. * Removes a variable from session.
  219. *
  220. * @param string $name Session variable to remove
  221. * @return boolean Success
  222. */
  223. public static function delete($name) {
  224. if (static::check($name)) {
  225. static::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
  226. return !static::check($name);
  227. }
  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(static::$error) || !array_key_exists($errorNumber, static::$error)) {
  257. return false;
  258. }
  259. return static::$error[$errorNumber];
  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 (static::$lastError) {
  268. return static::_error(static::$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 (static::read('Config')) {
  279. if (static::_validAgentAndTime() && static::$error === false) {
  280. static::$valid = true;
  281. } else {
  282. static::$valid = false;
  283. static::_setError(1, 'Session Highjacking Attempted !!!');
  284. }
  285. }
  286. return static::$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 Session it checks the current static::$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 = static::read('Config');
  298. $validAgent = (
  299. Configure::read('Session.checkAgent') === false ||
  300. static::$_userAgent == $config['userAgent']
  301. );
  302. return ($validAgent && static::$time <= $config['time']);
  303. }
  304. /**
  305. * Get / Set the user agent
  306. *
  307. * @param string $userAgent Set the user agent
  308. * @return string Current user agent
  309. */
  310. public static function userAgent($userAgent = null) {
  311. if ($userAgent) {
  312. static::$_userAgent = $userAgent;
  313. }
  314. if (empty(static::$_userAgent)) {
  315. Session::init(static::$path);
  316. }
  317. return static::$_userAgent;
  318. }
  319. /**
  320. * Returns given session variable, or all of them, if no parameters given.
  321. *
  322. * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
  323. * @return mixed The value of the session variable
  324. */
  325. public static function read($name = null) {
  326. if (!static::start()) {
  327. return false;
  328. }
  329. if ($name === null) {
  330. return static::_returnSessionVars();
  331. }
  332. if (empty($name)) {
  333. return false;
  334. }
  335. $result = Hash::get($_SESSION, $name);
  336. if (isset($result)) {
  337. return $result;
  338. }
  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. static::_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 (!static::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. static::_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. self::start();
  386. session_destroy();
  387. self::clear();
  388. }
  389. /**
  390. * Clears the session, the session id, and renews the session.
  391. *
  392. * @return void
  393. */
  394. public static function clear() {
  395. $_SESSION = null;
  396. static::$id = null;
  397. static::start();
  398. static::renew();
  399. }
  400. /**
  401. * Helper method to initialize a session, based on CakePHP core settings.
  402. *
  403. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  404. *
  405. * @return void
  406. * @throws Cake\Error\Exception Throws exceptions when ini_set() fails.
  407. */
  408. protected static function _configureSession() {
  409. $sessionConfig = Configure::read('Session');
  410. if (isset($sessionConfig['defaults'])) {
  411. $defaults = static::_defaultConfig($sessionConfig['defaults']);
  412. if ($defaults) {
  413. $sessionConfig = Hash::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 (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
  432. $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
  433. }
  434. if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
  435. $sessionConfig['ini']['session.cookie_httponly'] = 1;
  436. }
  437. if (empty($_SESSION)) {
  438. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  439. foreach ($sessionConfig['ini'] as $setting => $value) {
  440. if (ini_set($setting, $value) === false) {
  441. throw new Error\Exception(sprintf(
  442. __d('cake_dev', 'Unable to configure the session, setting %s failed.'),
  443. $setting
  444. ));
  445. }
  446. }
  447. }
  448. }
  449. if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
  450. call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
  451. }
  452. if (!empty($sessionConfig['handler']['engine'])) {
  453. $handler = static::_getHandler($sessionConfig['handler']['engine']);
  454. session_set_save_handler(
  455. array($handler, 'open'),
  456. array($handler, 'close'),
  457. array($handler, 'read'),
  458. array($handler, 'write'),
  459. array($handler, 'destroy'),
  460. array($handler, 'gc')
  461. );
  462. }
  463. Configure::write('Session', $sessionConfig);
  464. static::$sessionTime = static::$time + ($sessionConfig['timeout'] * 60);
  465. }
  466. /**
  467. * Find the handler class and make sure it implements the correct interface.
  468. *
  469. * @param string $class
  470. * @return void
  471. * @throws Cake\Error\Exception
  472. */
  473. protected static function _getHandler($class) {
  474. $class = App::className($class, 'Model/Datasource/Session');
  475. if (!class_exists($class)) {
  476. throw new Error\Exception(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  477. }
  478. $handler = new $class();
  479. if ($handler instanceof SessionHandlerInterface) {
  480. return $handler;
  481. }
  482. throw new Error\Exception(__d('cake_dev', 'Chosen SessionHandler does not implement SessionHandlerInterface it cannot be used with an engine key.'));
  483. }
  484. /**
  485. * Get one of the prebaked default session configurations.
  486. *
  487. * @param string $name
  488. * @return boolean|array
  489. */
  490. protected static function _defaultConfig($name) {
  491. $defaults = array(
  492. 'php' => array(
  493. 'checkAgent' => false,
  494. 'cookie' => 'CAKEPHP',
  495. 'timeout' => 240,
  496. 'ini' => array(
  497. 'session.use_trans_sid' => 0,
  498. 'session.cookie_path' => static::$path
  499. )
  500. ),
  501. 'cake' => array(
  502. 'checkAgent' => false,
  503. 'cookie' => 'CAKEPHP',
  504. 'timeout' => 240,
  505. 'ini' => array(
  506. 'session.use_trans_sid' => 0,
  507. 'url_rewriter.tags' => '',
  508. 'session.serialize_handler' => 'php',
  509. 'session.use_cookies' => 1,
  510. 'session.cookie_path' => static::$path,
  511. 'session.save_path' => TMP . 'sessions',
  512. 'session.save_handler' => 'files'
  513. )
  514. ),
  515. 'cache' => array(
  516. 'checkAgent' => false,
  517. 'cookie' => 'CAKEPHP',
  518. 'timeout' => 240,
  519. 'ini' => array(
  520. 'session.use_trans_sid' => 0,
  521. 'url_rewriter.tags' => '',
  522. 'session.use_cookies' => 1,
  523. 'session.cookie_path' => static::$path,
  524. 'session.save_handler' => 'user',
  525. ),
  526. 'handler' => array(
  527. 'engine' => 'CacheSession',
  528. 'config' => 'default'
  529. )
  530. ),
  531. 'database' => array(
  532. 'checkAgent' => false,
  533. 'cookie' => 'CAKEPHP',
  534. 'timeout' => 240,
  535. 'ini' => array(
  536. 'session.use_trans_sid' => 0,
  537. 'url_rewriter.tags' => '',
  538. 'session.use_cookies' => 1,
  539. 'session.cookie_path' => static::$path,
  540. 'session.save_handler' => 'user',
  541. 'session.serialize_handler' => 'php',
  542. ),
  543. 'handler' => array(
  544. 'engine' => 'DatabaseSession',
  545. 'model' => 'Session'
  546. )
  547. )
  548. );
  549. if (isset($defaults[$name])) {
  550. return $defaults[$name];
  551. }
  552. return false;
  553. }
  554. /**
  555. * Helper method to start a session
  556. *
  557. * @return boolean Success
  558. */
  559. protected static function _startSession() {
  560. if (headers_sent()) {
  561. if (empty($_SESSION)) {
  562. $_SESSION = array();
  563. }
  564. } else {
  565. // For IE<=8
  566. session_cache_limiter("must-revalidate");
  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 (!static::start()) {
  578. static::$valid = false;
  579. return false;
  580. }
  581. if ($config = static::read('Config')) {
  582. $sessionConfig = Configure::read('Session');
  583. if (static::_validAgentAndTime()) {
  584. static::write('Config.time', static::$sessionTime);
  585. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  586. $check = $config['countdown'];
  587. $check -= 1;
  588. static::write('Config.countdown', $check);
  589. if ($check < 1) {
  590. static::renew();
  591. static::write('Config.countdown', static::$requestCountdown);
  592. }
  593. }
  594. static::$valid = true;
  595. } else {
  596. static::destroy();
  597. static::$valid = false;
  598. static::_setError(1, 'Session Highjacking Attempted !!!');
  599. }
  600. } else {
  601. static::write('Config.userAgent', static::$_userAgent);
  602. static::write('Config.time', static::$sessionTime);
  603. static::write('Config.countdown', static::$requestCountdown);
  604. static::$valid = true;
  605. }
  606. }
  607. /**
  608. * Restarts this session.
  609. *
  610. * @return void
  611. */
  612. public static function renew() {
  613. if (session_id()) {
  614. if (session_id() || isset($_COOKIE[session_name()])) {
  615. setcookie(Configure::read('Session.cookie'), '', time() - 42000, static::$path);
  616. }
  617. session_regenerate_id(true);
  618. }
  619. }
  620. /**
  621. * Helper method to set an internal error message.
  622. *
  623. * @param integer $errorNumber Number of the error
  624. * @param string $errorMessage Description of the error
  625. * @return void
  626. */
  627. protected static function _setError($errorNumber, $errorMessage) {
  628. if (static::$error === false) {
  629. static::$error = array();
  630. }
  631. static::$error[$errorNumber] = $errorMessage;
  632. static::$lastError = $errorNumber;
  633. }
  634. }