PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Datasource/CakeSession.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 751 lines | 432 code | 53 blank | 266 comment | 74 complexity | 7d3e5fdac066c610ec4dbf48ebe79d5a MD5 | raw file
  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. )
  501. ),
  502. 'cake' => array(
  503. 'cookie' => 'CAKEPHP',
  504. 'timeout' => 240,
  505. 'cookieTimeout' => 240,
  506. 'ini' => array(
  507. 'session.use_trans_sid' => 0,
  508. 'url_rewriter.tags' => '',
  509. 'session.serialize_handler' => 'php',
  510. 'session.use_cookies' => 1,
  511. 'session.cookie_path' => self::$path,
  512. 'session.auto_start' => 0,
  513. 'session.save_path' => TMP . 'sessions',
  514. 'session.save_handler' => 'files'
  515. )
  516. ),
  517. 'cache' => array(
  518. 'cookie' => 'CAKEPHP',
  519. 'timeout' => 240,
  520. 'cookieTimeout' => 240,
  521. 'ini' => array(
  522. 'session.use_trans_sid' => 0,
  523. 'url_rewriter.tags' => '',
  524. 'session.auto_start' => 0,
  525. 'session.use_cookies' => 1,
  526. 'session.cookie_path' => self::$path,
  527. 'session.save_handler' => 'user',
  528. ),
  529. 'handler' => array(
  530. 'engine' => 'CacheSession',
  531. 'config' => 'default'
  532. )
  533. ),
  534. 'database' => array(
  535. 'cookie' => 'CAKEPHP',
  536. 'timeout' => 240,
  537. 'cookieTimeout' => 240,
  538. 'ini' => array(
  539. 'session.use_trans_sid' => 0,
  540. 'url_rewriter.tags' => '',
  541. 'session.auto_start' => 0,
  542. 'session.use_cookies' => 1,
  543. 'session.cookie_path' => self::$path,
  544. 'session.save_handler' => 'user',
  545. 'session.serialize_handler' => 'php',
  546. ),
  547. 'handler' => array(
  548. 'engine' => 'DatabaseSession',
  549. 'model' => 'Session'
  550. )
  551. )
  552. );
  553. if (isset($defaults[$name])) {
  554. return $defaults[$name];
  555. }
  556. return false;
  557. }
  558. /**
  559. * Helper method to start a session
  560. *
  561. * @return boolean Success
  562. */
  563. protected static function _startSession() {
  564. if (headers_sent()) {
  565. if (empty($_SESSION)) {
  566. $_SESSION = array();
  567. }
  568. } elseif (!isset($_SESSION)) {
  569. session_cache_limiter ("must-revalidate");
  570. session_start();
  571. header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
  572. } else {
  573. session_start();
  574. }
  575. return true;
  576. }
  577. /**
  578. * Helper method to create a new session.
  579. *
  580. * @return void
  581. */
  582. protected static function _checkValid() {
  583. if (!self::started() && !self::start()) {
  584. self::$valid = false;
  585. return false;
  586. }
  587. if ($config = self::read('Config')) {
  588. $sessionConfig = Configure::read('Session');
  589. if (self::_validAgentAndTime()) {
  590. $time = $config['time'];
  591. self::write('Config.time', self::$sessionTime);
  592. if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
  593. $check = $config['countdown'];
  594. $check -= 1;
  595. self::write('Config.countdown', $check);
  596. if (time() > ($time - ($sessionConfig['timeout'] * 60) + 2) || $check < 1) {
  597. self::renew();
  598. self::write('Config.countdown', self::$requestCountdown);
  599. }
  600. }
  601. self::$valid = true;
  602. } else {
  603. self::destroy();
  604. self::$valid = false;
  605. self::_setError(1, 'Session Highjacking Attempted !!!');
  606. }
  607. } else {
  608. self::write('Config.userAgent', self::$_userAgent);
  609. self::write('Config.time', self::$sessionTime);
  610. self::write('Config.countdown', self::$requestCountdown);
  611. self::$valid = true;
  612. }
  613. }
  614. /**
  615. * Restarts this session.
  616. *
  617. * @return void
  618. */
  619. public static function renew() {
  620. if (session_id()) {
  621. if (session_id() != '' || isset($_COOKIE[session_name()])) {
  622. setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
  623. }
  624. session_regenerate_id(true);
  625. }
  626. }
  627. /**
  628. * Helper method to set an internal error message.
  629. *
  630. * @param integer $errorNumber Number of the error
  631. * @param string $errorMessage Description of the error
  632. * @return void
  633. */
  634. protected static function _setError($errorNumber, $errorMessage) {
  635. if (self::$error === false) {
  636. self::$error = array();
  637. }
  638. self::$error[$errorNumber] = $errorMessage;
  639. self::$lastError = $errorNumber;
  640. }
  641. }
  642. /**
  643. * Interface for Session handlers. Custom session handler classes should implement
  644. * this interface as it allows CakeSession know how to map methods to session_set_save_handler()
  645. *
  646. * @package Cake.Model.Datasource
  647. */
  648. interface CakeSessionHandlerInterface {
  649. /**
  650. * Method called on open of a session.
  651. *
  652. * @return boolean Success
  653. */
  654. public function open();
  655. /**
  656. * Method called on close of a session.
  657. *
  658. * @return boolean Success
  659. */
  660. public function close();
  661. /**
  662. * Method used to read from a session.
  663. *
  664. * @param mixed $id The key of the value to read
  665. * @return mixed The value of the key or false if it does not exist
  666. */
  667. public function read($id);
  668. /**
  669. * Helper function called on write for sessions.
  670. *
  671. * @param integer $id ID that uniquely identifies session in database
  672. * @param mixed $data The value of the data to be saved.
  673. * @return boolean True for successful write, false otherwise.
  674. */
  675. public function write($id, $data);
  676. /**
  677. * Method called on the destruction of a session.
  678. *
  679. * @param integer $id ID that uniquely identifies session in database
  680. * @return boolean True for successful delete, false otherwise.
  681. */
  682. public function destroy($id);
  683. /**
  684. * Run the Garbage collection on the session storage. This method should vacuum all
  685. * expired or dead sessions.
  686. *
  687. * @param integer $expires Timestamp (defaults to current time)
  688. * @return boolean Success
  689. */
  690. public function gc($expires = null);
  691. }
  692. // Initialize the session
  693. CakeSession::init();