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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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 (($checkAgent === true || $checkAgent === null) && 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::started() && !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. *
  203. * @param string $id
  204. * @return string Session id
  205. */
  206. public static function id($id = null) {
  207. if ($id) {
  208. self::$id = $id;
  209. session_id(self::$id);
  210. }
  211. if (self::started()) {
  212. return session_id();
  213. }
  214. return self::$id;
  215. }
  216. /**
  217. * Removes a variable from session.
  218. *
  219. * @param string $name Session variable to remove
  220. * @return boolean Success
  221. */
  222. public static function delete($name) {
  223. if (self::check($name)) {
  224. self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
  225. return !self::check($name);
  226. }
  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. return null;
  339. }
  340. /**
  341. * Returns all session variables.
  342. *
  343. * @return mixed Full $_SESSION array, or false on error.
  344. */
  345. protected static function _returnSessionVars() {
  346. if (!empty($_SESSION)) {
  347. return $_SESSION;
  348. }
  349. self::_setError(2, 'No Session vars set');
  350. return false;
  351. }
  352. /**
  353. * Writes value to given session variable name.
  354. *
  355. * @param string|array $name Name of variable
  356. * @param string $value Value to write
  357. * @return boolean True if the write was successful, false if the write failed
  358. */
  359. public static function write($name, $value = null) {
  360. if (!self::started() && !self::start()) {
  361. return false;
  362. }
  363. if (empty($name)) {
  364. return false;
  365. }
  366. $write = $name;
  367. if (!is_array($name)) {
  368. $write = array($name => $value);
  369. }
  370. foreach ($write as $key => $val) {
  371. self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
  372. if (Hash::get($_SESSION, $key) !== $val) {
  373. return false;
  374. }
  375. }
  376. return true;
  377. }
  378. /**
  379. * Helper method to destroy invalid sessions.
  380. *
  381. * @return void
  382. */
  383. public static function destroy() {
  384. if (!self::started()) {
  385. self::start();
  386. }
  387. session_destroy();
  388. self::clear();
  389. }
  390. /**
  391. * Clears the session, the session id, and renews the session.
  392. *
  393. * @return void
  394. */
  395. public static function clear() {
  396. $_SESSION = null;
  397. self::$id = null;
  398. self::start();
  399. self::renew();
  400. }
  401. /**
  402. * Helper method to initialize a session, based on Cake core settings.
  403. *
  404. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  405. *
  406. * @return void
  407. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  408. */
  409. protected static function _configureSession() {
  410. $sessionConfig = Configure::read('Session');
  411. if (isset($sessionConfig['defaults'])) {
  412. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  413. if ($defaults) {
  414. $sessionConfig = Hash::merge($defaults, $sessionConfig);
  415. }
  416. }
  417. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  418. $sessionConfig['ini']['session.cookie_secure'] = 1;
  419. }
  420. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  421. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  422. }
  423. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  424. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  425. }
  426. if (!isset($sessionConfig['ini']['session.name'])) {
  427. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  428. }
  429. if (!empty($sessionConfig['handler'])) {
  430. $sessionConfig['ini']['session.save_handler'] = 'user';
  431. }
  432. if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
  433. $sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
  434. }
  435. if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
  436. $sessionConfig['ini']['session.cookie_httponly'] = 1;
  437. }
  438. if (empty($_SESSION)) {
  439. if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
  440. foreach ($sessionConfig['ini'] as $setting => $value) {
  441. if (ini_set($setting, $value) === false) {
  442. throw new CakeSessionException(sprintf(
  443. __d('cake_dev', 'Unable to configure the session, setting %s failed.'),
  444. $setting
  445. ));
  446. }
  447. }
  448. }
  449. }
  450. if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
  451. call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
  452. }
  453. if (!empty($sessionConfig['handler']['engine'])) {
  454. $handler = self::_getHandler($sessionConfig['handler']['engine']);
  455. session_set_save_handler(
  456. array($handler, 'open'),
  457. array($handler, 'close'),
  458. array($handler, 'read'),
  459. array($handler, 'write'),
  460. array($handler, 'destroy'),
  461. array($handler, 'gc')
  462. );
  463. }
  464. Configure::write('Session', $sessionConfig);
  465. self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
  466. }
  467. /**
  468. * Find the handler class and make sure it implements the correct interface.
  469. *
  470. * @param string $handler
  471. * @return void
  472. * @throws CakeSessionException
  473. */
  474. protected static function _getHandler($handler) {
  475. list($plugin, $class) = pluginSplit($handler, true);
  476. App::uses($class, $plugin . 'Model/Datasource/Session');
  477. if (!class_exists($class)) {
  478. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  479. }
  480. $handler = new $class();
  481. if ($handler instanceof CakeSessionHandlerInterface) {
  482. return $handler;
  483. }
  484. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface 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. 'cookie' => 'CAKEPHP',
  496. 'timeout' => 240,
  497. 'ini' => array(
  498. 'session.use_trans_sid' => 0,
  499. 'session.cookie_path' => self::$path
  500. )
  501. ),
  502. 'cake' => array(
  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' => self::$path,
  511. 'session.auto_start' => 0,
  512. 'session.save_path' => TMP . 'sessions',
  513. 'session.save_handler' => 'files'
  514. )
  515. ),
  516. 'cache' => array(
  517. 'cookie' => 'CAKEPHP',
  518. 'timeout' => 240,
  519. 'ini' => array(
  520. 'session.use_trans_sid' => 0,
  521. 'url_rewriter.tags' => '',
  522. 'session.auto_start' => 0,
  523. 'session.use_cookies' => 1,
  524. 'session.cookie_path' => self::$path,
  525. 'session.save_handler' => 'user',
  526. ),
  527. 'handler' => array(
  528. 'engine' => 'CacheSession',
  529. 'config' => 'default'
  530. )
  531. ),
  532. 'database' => array(
  533. 'cookie' => 'CAKEPHP',
  534. 'timeout' => 240,
  535. 'ini' => array(
  536. 'session.use_trans_sid' => 0,
  537. 'url_rewriter.tags' => '',
  538. 'session.auto_start' => 0,
  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::started() && !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. }