CakeSession.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  19. * @link http://cakephp.org CakePHP(tm) Project
  20. * @package cake.libs
  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.libs
  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. */
  121. public static function init($base = null, $start = true) {
  122. self::$time = time();
  123. $checkAgent = Configure::read('Session.checkAgent');
  124. if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) {
  125. self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  126. }
  127. self::_setPath($base);
  128. self::_setHost(env('HTTP_HOST'));
  129. }
  130. /**
  131. * Setup the Path variable
  132. *
  133. * @param string $base base path
  134. * @return void
  135. */
  136. protected static function _setPath($base = null) {
  137. if (empty($base)) {
  138. self::$path = '/';
  139. return;
  140. }
  141. if (strpos($base, 'index.php') !== false) {
  142. $base = str_replace('index.php', '', $base);
  143. }
  144. if (strpos($base, '?') !== false) {
  145. $base = str_replace('?', '', $base);
  146. }
  147. self::$path = $base;
  148. }
  149. /**
  150. * Set the host name
  151. *
  152. * @param string $host Hostname
  153. * @return void
  154. */
  155. protected static function _setHost($host) {
  156. self::$host = $host;
  157. if (strpos(self::$host, ':') !== false) {
  158. self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
  159. }
  160. }
  161. /**
  162. * Starts the Session.
  163. *
  164. * @return boolean True if session was started
  165. */
  166. public static function start() {
  167. if (self::started()) {
  168. return true;
  169. }
  170. $id = self::id();
  171. session_write_close();
  172. self::_configureSession();
  173. self::_startSession();
  174. if (!$id && self::started()) {
  175. self::_checkValid();
  176. }
  177. self::$error = false;
  178. return self::started();
  179. }
  180. /**
  181. * Determine if Session has been started.
  182. *
  183. * @return boolean True if session has been started.
  184. */
  185. public static function started() {
  186. return isset($_SESSION) && session_id();
  187. }
  188. /**
  189. * Returns true if given variable is set in session.
  190. *
  191. * @param string $name Variable name to check for
  192. * @return boolean True if variable is there
  193. */
  194. public static function check($name = null) {
  195. if (!self::started() && !self::start()) {
  196. return false;
  197. }
  198. if (empty($name)) {
  199. return false;
  200. }
  201. $result = Set::classicExtract($_SESSION, $name);
  202. return isset($result);
  203. }
  204. /**
  205. * Returns the Session id
  206. *
  207. * @param id $name string
  208. * @return string Session id
  209. */
  210. public static function id($id = null) {
  211. if ($id) {
  212. self::$id = $id;
  213. session_id(self::$id);
  214. }
  215. if (self::started()) {
  216. return session_id();
  217. }
  218. return self::$id;
  219. }
  220. /**
  221. * Removes a variable from session.
  222. *
  223. * @param string $name Session variable to remove
  224. * @return boolean Success
  225. */
  226. public static function delete($name) {
  227. if (self::check($name)) {
  228. self::__overwrite($_SESSION, Set::remove($_SESSION, $name));
  229. return (self::check($name) == false);
  230. }
  231. self::__setError(2, __d('cake_dev', "%s doesn't exist", $name));
  232. return false;
  233. }
  234. /**
  235. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
  236. *
  237. * @param array $old Set of old variables => values
  238. * @param array $new New set of variable => value
  239. * @access private
  240. */
  241. private static function __overwrite(&$old, $new) {
  242. if (!empty($old)) {
  243. foreach ($old as $key => $var) {
  244. if (!isset($new[$key])) {
  245. unset($old[$key]);
  246. }
  247. }
  248. }
  249. foreach ($new as $key => $var) {
  250. $old[$key] = $var;
  251. }
  252. }
  253. /**
  254. * Return error description for given error number.
  255. *
  256. * @param integer $errorNumber Error to set
  257. * @return string Error as string
  258. * @access private
  259. */
  260. private 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. private 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. * @return void
  470. */
  471. protected static function _getHandler($handler) {
  472. list($plugin, $class) = pluginSplit($handler, true);
  473. App::uses($class, $plugin . 'Model/Datasource/Session');
  474. if (!class_exists($class)) {
  475. throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
  476. }
  477. $handler = new $class();
  478. if ($handler instanceof CakeSessionHandlerInterface) {
  479. return $handler;
  480. }
  481. throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
  482. }
  483. /**
  484. * Get one of the prebaked default session configurations.
  485. *
  486. * @return void
  487. */
  488. protected static function _defaultConfig($name) {
  489. $defaults = array(
  490. 'php' => array(
  491. 'cookie' => 'CAKEPHP',
  492. 'timeout' => 240,
  493. 'cookieTimeout' => 240,
  494. 'ini' => array(
  495. 'session.use_trans_sid' => 0,
  496. 'session.cookie_path' => self::$path,
  497. 'session.save_handler' => 'files'
  498. )
  499. ),
  500. 'cake' => array(
  501. 'cookie' => 'CAKEPHP',
  502. 'timeout' => 240,
  503. 'cookieTimeout' => 240,
  504. 'ini' => array(
  505. 'session.use_trans_sid' => 0,
  506. 'url_rewriter.tags' => '',
  507. 'session.serialize_handler' => 'php',
  508. 'session.use_cookies' => 1,
  509. 'session.cookie_path' => self::$path,
  510. 'session.auto_start' => 0,
  511. 'session.save_path' => TMP . 'sessions',
  512. 'session.save_handler' => 'files'
  513. )
  514. ),
  515. 'cache' => array(
  516. 'cookie' => 'CAKEPHP',
  517. 'timeout' => 240,
  518. 'cookieTimeout' => 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. 'cookieTimeout' => 240,
  536. 'ini' => array(
  537. 'session.use_trans_sid' => 0,
  538. 'url_rewriter.tags' => '',
  539. 'session.auto_start' => 0,
  540. 'session.use_cookies' => 1,
  541. 'session.cookie_path' => self::$path,
  542. 'session.save_handler' => 'user',
  543. 'session.serialize_handler' => 'php',
  544. ),
  545. 'handler' => array(
  546. 'engine' => 'DatabaseSession',
  547. 'model' => 'Session'
  548. )
  549. )
  550. );
  551. if (isset($defaults[$name])) {
  552. return $defaults[$name];
  553. }
  554. return false;
  555. }
  556. /**
  557. * Helper method to start a session
  558. *
  559. * @return boolean Success
  560. */
  561. protected static function _startSession() {
  562. if (headers_sent()) {
  563. if (empty($_SESSION)) {
  564. $_SESSION = array();
  565. }
  566. } elseif (!isset($_SESSION)) {
  567. session_cache_limiter ("must-revalidate");
  568. session_start();
  569. header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
  570. } else {
  571. session_start();
  572. }
  573. return true;
  574. }
  575. /**
  576. * Helper method to create a new session.
  577. *
  578. * @return void
  579. */
  580. protected static function _checkValid() {
  581. if (!self::started() && !self::start()) {
  582. self::$valid = false;
  583. return false;
  584. }
  585. if ($config = self::read('Config')) {
  586. $sessionConfig = Configure::read('Session');
  587. if (self::_validAgentAndTime()) {
  588. $time = $config['time'];
  589. self::write('Config.time', self::$sessionTime);
  590. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  591. $check = $config['countdown'];
  592. $check -= 1;
  593. self::write('Config.countdown', $check);
  594. if (time() > ($time - ($sessionConfig['timeout'] * 60) + 2) || $check < 1) {
  595. self::renew();
  596. self::write('Config.countdown', self::$requestCountdown);
  597. }
  598. }
  599. self::$valid = true;
  600. } else {
  601. self::destroy();
  602. self::$valid = false;
  603. self::__setError(1, 'Session Highjacking Attempted !!!');
  604. }
  605. } else {
  606. self::write('Config.userAgent', self::$_userAgent);
  607. self::write('Config.time', self::$sessionTime);
  608. self::write('Config.countdown', self::$requestCountdown);
  609. self::$valid = true;
  610. }
  611. }
  612. /**
  613. * Restarts this session.
  614. *
  615. * @return void
  616. */
  617. public static function renew() {
  618. if (session_id()) {
  619. if (session_id() != '' || isset($_COOKIE[session_name()])) {
  620. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  621. }
  622. session_regenerate_id(true);
  623. }
  624. }
  625. /**
  626. * Helper method to set an internal error message.
  627. *
  628. * @param integer $errorNumber Number of the error
  629. * @param string $errorMessage Description of the error
  630. * @return void
  631. * @access private
  632. */
  633. private static function __setError($errorNumber, $errorMessage) {
  634. if (self::$error === false) {
  635. self::$error = array();
  636. }
  637. self::$error[$errorNumber] = $errorMessage;
  638. self::$lastError = $errorNumber;
  639. }
  640. }
  641. /**
  642. * Interface for Session handlers. Custom session handler classes should implement
  643. * this interface as it allows CakeSession know how to map methods to session_set_save_handler()
  644. *
  645. * @package cake.libs
  646. */
  647. interface CakeSessionHandlerInterface {
  648. /**
  649. * Method called on open of a session.
  650. *
  651. * @return boolean Success
  652. */
  653. public function open();
  654. /**
  655. * Method called on close of a session.
  656. *
  657. * @return boolean Success
  658. */
  659. public function close();
  660. /**
  661. * Method used to read from a session.
  662. *
  663. * @param mixed $id The key of the value to read
  664. * @return mixed The value of the key or false if it does not exist
  665. */
  666. public function read($id);
  667. /**
  668. * Helper function called on write for sessions.
  669. *
  670. * @param integer $id ID that uniquely identifies session in database
  671. * @param mixed $data The value of the data to be saved.
  672. * @return boolean True for successful write, false otherwise.
  673. */
  674. public function write($id, $data);
  675. /**
  676. * Method called on the destruction of a session.
  677. *
  678. * @param integer $id ID that uniquely identifies session in database
  679. * @return boolean True for successful delete, false otherwise.
  680. */
  681. public function destroy($id);
  682. /**
  683. * Run the Garbage collection on the session storage. This method should vacuum all
  684. * expired or dead sessions.
  685. *
  686. * @param integer $expires Timestamp (defaults to current time)
  687. * @return boolean Success
  688. */
  689. public function gc($expires = null);
  690. }
  691. // Initialize the session
  692. CakeSession::init();