CakeSession.php 17 KB

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