CakeSession.php 16 KB

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