CakeSession.php 19 KB

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