CakeSession.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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-2011, 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-2011, 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. * 'Security.level' setting, "high", "medium", or "low".
  67. *
  68. * @var string
  69. */
  70. public static $security = null;
  71. /**
  72. * Start time for this session.
  73. *
  74. * @var integer
  75. */
  76. public static $time = false;
  77. /**
  78. * Cookie lifetime
  79. *
  80. * @var integer
  81. */
  82. public static $cookieLifeTime;
  83. /**
  84. * Time when this session becomes invalid.
  85. *
  86. * @var integer
  87. */
  88. public static $sessionTime = false;
  89. /**
  90. * Current Session id
  91. *
  92. * @var string
  93. */
  94. public static $id = null;
  95. /**
  96. * Hostname
  97. *
  98. * @var string
  99. */
  100. public static $host = null;
  101. /**
  102. * Session timeout multiplier factor
  103. *
  104. * @var integer
  105. */
  106. public static $timeout = null;
  107. /**
  108. * Number of requests that can occur during a session time without the session being renewed.
  109. * This feature is only used when `Session.harden` is set to true.
  110. *
  111. * @var integer
  112. * @see CakeSession::_checkValid()
  113. */
  114. public static $requestCountdown = 10;
  115. /**
  116. * Constructor.
  117. *
  118. * @param string $base The base path for the Session
  119. * @param boolean $start Should session be started right now
  120. * @return void
  121. */
  122. public static function init($base = null, $start = true) {
  123. self::$time = time();
  124. $checkAgent = Configure::read('Session.checkAgent');
  125. if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) {
  126. self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  127. }
  128. self::_setPath($base);
  129. self::_setHost(env('HTTP_HOST'));
  130. }
  131. /**
  132. * Setup the Path variable
  133. *
  134. * @param string $base base path
  135. * @return void
  136. */
  137. protected static function _setPath($base = null) {
  138. if (empty($base)) {
  139. self::$path = '/';
  140. return;
  141. }
  142. if (strpos($base, 'index.php') !== false) {
  143. $base = str_replace('index.php', '', $base);
  144. }
  145. if (strpos($base, '?') !== false) {
  146. $base = str_replace('?', '', $base);
  147. }
  148. self::$path = $base;
  149. }
  150. /**
  151. * Set the host name
  152. *
  153. * @param string $host Hostname
  154. * @return void
  155. */
  156. protected static function _setHost($host) {
  157. self::$host = $host;
  158. if (strpos(self::$host, ':') !== false) {
  159. self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
  160. }
  161. }
  162. /**
  163. * Starts the Session.
  164. *
  165. * @return boolean True if session was started
  166. */
  167. public static function start() {
  168. if (self::started()) {
  169. return true;
  170. }
  171. $id = self::id();
  172. session_write_close();
  173. self::_configureSession();
  174. self::_startSession();
  175. if (!$id && self::started()) {
  176. self::_checkValid();
  177. }
  178. self::$error = false;
  179. return self::started();
  180. }
  181. /**
  182. * Determine if Session has been started.
  183. *
  184. * @return boolean True if session has been started.
  185. */
  186. public static function started() {
  187. return isset($_SESSION) && session_id();
  188. }
  189. /**
  190. * Returns true if given variable is set in session.
  191. *
  192. * @param string $name Variable name to check for
  193. * @return boolean True if variable is there
  194. */
  195. public static function check($name = null) {
  196. if (!self::started() && !self::start()) {
  197. return false;
  198. }
  199. if (empty($name)) {
  200. return false;
  201. }
  202. $result = Set::classicExtract($_SESSION, $name);
  203. return isset($result);
  204. }
  205. /**
  206. * Returns the Session id
  207. *
  208. * @param string $id
  209. * @return string Session id
  210. */
  211. public static function id($id = null) {
  212. if ($id) {
  213. self::$id = $id;
  214. session_id(self::$id);
  215. }
  216. if (self::started()) {
  217. return session_id();
  218. }
  219. return self::$id;
  220. }
  221. /**
  222. * Removes a variable from session.
  223. *
  224. * @param string $name Session variable to remove
  225. * @return boolean Success
  226. */
  227. public static function delete($name) {
  228. if (self::check($name)) {
  229. self::_overwrite($_SESSION, Set::remove($_SESSION, $name));
  230. return (self::check($name) == false);
  231. }
  232. self::_setError(2, __d('cake_dev', "%s doesn't exist", $name));
  233. return false;
  234. }
  235. /**
  236. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
  237. *
  238. * @param array $old Set of old variables => values
  239. * @param array $new New set of variable => value
  240. * @return void
  241. */
  242. protected static function _overwrite(&$old, $new) {
  243. if (!empty($old)) {
  244. foreach ($old as $key => $var) {
  245. if (!isset($new[$key])) {
  246. unset($old[$key]);
  247. }
  248. }
  249. }
  250. foreach ($new as $key => $var) {
  251. $old[$key] = $var;
  252. }
  253. }
  254. /**
  255. * Return error description for given error number.
  256. *
  257. * @param integer $errorNumber Error to set
  258. * @return string Error as string
  259. */
  260. protected static function _error($errorNumber) {
  261. if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
  262. return false;
  263. } else {
  264. return self::$error[$errorNumber];
  265. }
  266. }
  267. /**
  268. * Returns last occurred error as a string, if any.
  269. *
  270. * @return mixed Error description as a string, or false.
  271. */
  272. public static function error() {
  273. if (self::$lastError) {
  274. return self::_error(self::$lastError);
  275. }
  276. return false;
  277. }
  278. /**
  279. * Returns true if session is valid.
  280. *
  281. * @return boolean Success
  282. */
  283. public static function valid() {
  284. if (self::read('Config')) {
  285. if (self::_validAgentAndTime() && self::$error === false) {
  286. self::$valid = true;
  287. } else {
  288. self::$valid = false;
  289. self::_setError(1, 'Session Highjacking Attempted !!!');
  290. }
  291. }
  292. return self::$valid;
  293. }
  294. /**
  295. * Tests that the user agent is valid and that the session hasn't 'timed out'.
  296. * Since timeouts are implemented in CakeSession it checks the current self::$time
  297. * against the time the session is set to expire. The User agent is only checked
  298. * if Session.checkAgent == true.
  299. *
  300. * @return boolean
  301. */
  302. protected static function _validAgentAndTime() {
  303. $config = self::read('Config');
  304. $validAgent = (
  305. Configure::read('Session.checkAgent') === false ||
  306. self::$_userAgent == $config['userAgent']
  307. );
  308. return ($validAgent && self::$time <= $config['time']);
  309. }
  310. /**
  311. * Get / Set the userAgent
  312. *
  313. * @param string $userAgent Set the userAgent
  314. * @return void
  315. */
  316. public static function userAgent($userAgent = null) {
  317. if ($userAgent) {
  318. self::$_userAgent = $userAgent;
  319. }
  320. return self::$_userAgent;
  321. }
  322. /**
  323. * Returns given session variable, or all of them, if no parameters given.
  324. *
  325. * @param mixed $name The name of the session variable (or a path as sent to Set.extract)
  326. * @return mixed The value of the session variable
  327. */
  328. public static function read($name = null) {
  329. if (!self::started() && !self::start()) {
  330. return false;
  331. }
  332. if (is_null($name)) {
  333. return self::_returnSessionVars();
  334. }
  335. if (empty($name)) {
  336. return false;
  337. }
  338. $result = Set::classicExtract($_SESSION, $name);
  339. if (!is_null($result)) {
  340. return $result;
  341. }
  342. self::_setError(2, "$name doesn't exist");
  343. return null;
  344. }
  345. /**
  346. * Returns all session variables.
  347. *
  348. * @return mixed Full $_SESSION array, or false on error.
  349. */
  350. protected static function _returnSessionVars() {
  351. if (!empty($_SESSION)) {
  352. return $_SESSION;
  353. }
  354. self::_setError(2, 'No Session vars set');
  355. return false;
  356. }
  357. /**
  358. * Writes value to given session variable name.
  359. *
  360. * @param mixed $name Name of variable
  361. * @param string $value Value to write
  362. * @return boolean True if the write was successful, false if the write failed
  363. */
  364. public static function write($name, $value = null) {
  365. if (!self::started() && !self::start()) {
  366. return false;
  367. }
  368. if (empty($name)) {
  369. return false;
  370. }
  371. $write = $name;
  372. if (!is_array($name)) {
  373. $write = array($name => $value);
  374. }
  375. foreach ($write as $key => $val) {
  376. self::_overwrite($_SESSION, Set::insert($_SESSION, $key, $val));
  377. if (Set::classicExtract($_SESSION, $key) !== $val) {
  378. return false;
  379. }
  380. }
  381. return true;
  382. }
  383. /**
  384. * Helper method to destroy invalid sessions.
  385. *
  386. * @return void
  387. */
  388. public static function destroy() {
  389. if (self::started()) {
  390. session_destroy();
  391. }
  392. self::clear();
  393. }
  394. /**
  395. * Clears the session, the session id, and renew's the session.
  396. *
  397. * @return void
  398. */
  399. public static function clear() {
  400. $_SESSION = null;
  401. self::$id = null;
  402. self::start();
  403. self::renew();
  404. }
  405. /**
  406. * Helper method to initialize a session, based on Cake core settings.
  407. *
  408. * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
  409. *
  410. * @return void
  411. * @throws CakeSessionException Throws exceptions when ini_set() fails.
  412. */
  413. protected static function _configureSession() {
  414. $sessionConfig = Configure::read('Session');
  415. $iniSet = function_exists('ini_set');
  416. if (isset($sessionConfig['defaults'])) {
  417. $defaults = self::_defaultConfig($sessionConfig['defaults']);
  418. if ($defaults) {
  419. $sessionConfig = Set::merge($defaults, $sessionConfig);
  420. }
  421. }
  422. if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
  423. $sessionConfig['ini']['session.cookie_secure'] = 1;
  424. }
  425. if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
  426. $sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
  427. }
  428. if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
  429. $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
  430. }
  431. if (!isset($sessionConfig['ini']['session.name'])) {
  432. $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
  433. }
  434. if (!empty($sessionConfig['handler'])) {
  435. $sessionConfig['ini']['session.save_handler'] = 'user';
  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 CakeSessionException(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 = self::_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. self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
  465. }
  466. /**
  467. * Find the handler class and make sure it implements the correct interface.
  468. *
  469. * @param string $handler
  470. * @return void
  471. * @throws CakeSessionException
  472. */
  473. protected static function _getHandler($handler) {
  474. list($plugin, $class) = pluginSplit($handler, true);
  475. App::uses($class, $plugin . 'Model/Datasource/Session');
  476. if (!class_exists($class)) {
  477. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  478. }
  479. $handler = new $class();
  480. if ($handler instanceof CakeSessionHandlerInterface) {
  481. return $handler;
  482. }
  483. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
  484. }
  485. /**
  486. * Get one of the prebaked default session configurations.
  487. *
  488. * @param string $name
  489. * @return boolean|array
  490. */
  491. protected static function _defaultConfig($name) {
  492. $defaults = array(
  493. 'php' => array(
  494. 'cookie' => 'CAKEPHP',
  495. 'timeout' => 240,
  496. 'cookieTimeout' => 240,
  497. 'ini' => array(
  498. 'session.use_trans_sid' => 0,
  499. 'session.cookie_path' => self::$path,
  500. 'session.save_handler' => 'files'
  501. )
  502. ),
  503. 'cake' => array(
  504. 'cookie' => 'CAKEPHP',
  505. 'timeout' => 240,
  506. 'cookieTimeout' => 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' => self::$path,
  513. 'session.auto_start' => 0,
  514. 'session.save_path' => TMP . 'sessions',
  515. 'session.save_handler' => 'files'
  516. )
  517. ),
  518. 'cache' => array(
  519. 'cookie' => 'CAKEPHP',
  520. 'timeout' => 240,
  521. 'cookieTimeout' => 240,
  522. 'ini' => array(
  523. 'session.use_trans_sid' => 0,
  524. 'url_rewriter.tags' => '',
  525. 'session.auto_start' => 0,
  526. 'session.use_cookies' => 1,
  527. 'session.cookie_path' => self::$path,
  528. 'session.save_handler' => 'user',
  529. ),
  530. 'handler' => array(
  531. 'engine' => 'CacheSession',
  532. 'config' => 'default'
  533. )
  534. ),
  535. 'database' => array(
  536. 'cookie' => 'CAKEPHP',
  537. 'timeout' => 240,
  538. 'cookieTimeout' => 240,
  539. 'ini' => array(
  540. 'session.use_trans_sid' => 0,
  541. 'url_rewriter.tags' => '',
  542. 'session.auto_start' => 0,
  543. 'session.use_cookies' => 1,
  544. 'session.cookie_path' => self::$path,
  545. 'session.save_handler' => 'user',
  546. 'session.serialize_handler' => 'php',
  547. ),
  548. 'handler' => array(
  549. 'engine' => 'DatabaseSession',
  550. 'model' => 'Session'
  551. )
  552. )
  553. );
  554. if (isset($defaults[$name])) {
  555. return $defaults[$name];
  556. }
  557. return false;
  558. }
  559. /**
  560. * Helper method to start a session
  561. *
  562. * @return boolean Success
  563. */
  564. protected static function _startSession() {
  565. if (headers_sent()) {
  566. if (empty($_SESSION)) {
  567. $_SESSION = array();
  568. }
  569. } elseif (!isset($_SESSION)) {
  570. session_cache_limiter ("must-revalidate");
  571. session_start();
  572. header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
  573. } else {
  574. session_start();
  575. }
  576. return true;
  577. }
  578. /**
  579. * Helper method to create a new session.
  580. *
  581. * @return void
  582. */
  583. protected static function _checkValid() {
  584. if (!self::started() && !self::start()) {
  585. self::$valid = false;
  586. return false;
  587. }
  588. if ($config = self::read('Config')) {
  589. $sessionConfig = Configure::read('Session');
  590. if (self::_validAgentAndTime()) {
  591. $time = $config['time'];
  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 (time() > ($time - ($sessionConfig['timeout'] * 60) + 2) || $check < 1) {
  598. self::renew();
  599. self::write('Config.countdown', self::$requestCountdown);
  600. }
  601. }
  602. self::$valid = true;
  603. } else {
  604. self::destroy();
  605. self::$valid = false;
  606. self::_setError(1, 'Session Highjacking Attempted !!!');
  607. }
  608. } else {
  609. self::write('Config.userAgent', self::$_userAgent);
  610. self::write('Config.time', self::$sessionTime);
  611. self::write('Config.countdown', self::$requestCountdown);
  612. self::$valid = true;
  613. }
  614. }
  615. /**
  616. * Restarts this session.
  617. *
  618. * @return void
  619. */
  620. public static function renew() {
  621. if (session_id()) {
  622. if (session_id() != '' || isset($_COOKIE[session_name()])) {
  623. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  624. }
  625. session_regenerate_id(true);
  626. }
  627. }
  628. /**
  629. * Helper method to set an internal error message.
  630. *
  631. * @param integer $errorNumber Number of the error
  632. * @param string $errorMessage Description of the error
  633. * @return void
  634. */
  635. protected static function _setError($errorNumber, $errorMessage) {
  636. if (self::$error === false) {
  637. self::$error = array();
  638. }
  639. self::$error[$errorNumber] = $errorMessage;
  640. self::$lastError = $errorNumber;
  641. }
  642. }
  643. /**
  644. * Interface for Session handlers. Custom session handler classes should implement
  645. * this interface as it allows CakeSession know how to map methods to session_set_save_handler()
  646. *
  647. * @package Cake.Model.Datasource
  648. */
  649. interface CakeSessionHandlerInterface {
  650. /**
  651. * Method called on open of a session.
  652. *
  653. * @return boolean Success
  654. */
  655. public function open();
  656. /**
  657. * Method called on close of a session.
  658. *
  659. * @return boolean Success
  660. */
  661. public function close();
  662. /**
  663. * Method used to read from a session.
  664. *
  665. * @param mixed $id The key of the value to read
  666. * @return mixed The value of the key or false if it does not exist
  667. */
  668. public function read($id);
  669. /**
  670. * Helper function called on write for sessions.
  671. *
  672. * @param integer $id ID that uniquely identifies session in database
  673. * @param mixed $data The value of the data to be saved.
  674. * @return boolean True for successful write, false otherwise.
  675. */
  676. public function write($id, $data);
  677. /**
  678. * Method called on the destruction of a session.
  679. *
  680. * @param integer $id ID that uniquely identifies session in database
  681. * @return boolean True for successful delete, false otherwise.
  682. */
  683. public function destroy($id);
  684. /**
  685. * Run the Garbage collection on the session storage. This method should vacuum all
  686. * expired or dead sessions.
  687. *
  688. * @param integer $expires Timestamp (defaults to current time)
  689. * @return boolean Success
  690. */
  691. public function gc($expires = null);
  692. }
  693. // Initialize the session
  694. CakeSession::init();