PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/cake_session.php

https://github.com/msadouni/cakephp2x
PHP | 791 lines | 607 code | 25 blank | 159 comment | 42 complexity | 113048784950f9b7e84c810737a3c97a 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 Version 5.x
  11. *
  12. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  13. * Copyright 2005-2009, 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-2009, 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 extends Object {
  35. /**
  36. * True if the Session is still valid
  37. *
  38. * @var boolean
  39. * @access public
  40. */
  41. public $valid = false;
  42. /**
  43. * Error messages for this session
  44. *
  45. * @var array
  46. * @access public
  47. */
  48. public $error = false;
  49. /**
  50. * User agent string
  51. *
  52. * @var string
  53. * @access protected
  54. */
  55. protected $_userAgent = '';
  56. /**
  57. * Path to where the session is active.
  58. *
  59. * @var string
  60. * @access public
  61. */
  62. public $path = '/';
  63. /**
  64. * Error number of last occurred error
  65. *
  66. * @var integer
  67. * @access public
  68. */
  69. public $lastError = null;
  70. /**
  71. * 'Security.level' setting, "high", "medium", or "low".
  72. *
  73. * @var string
  74. * @access public
  75. */
  76. public $security = null;
  77. /**
  78. * Start time for this session.
  79. *
  80. * @var integer
  81. * @access public
  82. */
  83. public $time = false;
  84. /**
  85. * Time when this session becomes invalid.
  86. *
  87. * @var integer
  88. * @access public
  89. */
  90. public $sessionTime = false;
  91. /**
  92. * Keeps track of keys to watch for writes on
  93. *
  94. * @var array
  95. * @access public
  96. */
  97. public $watchKeys = array();
  98. /**
  99. * Current Session id
  100. *
  101. * @var string
  102. * @access public
  103. */
  104. public $id = null;
  105. /**
  106. * Constructor.
  107. *
  108. * @param string $base The base path for the Session
  109. * @param boolean $start Should session be started right now
  110. * @access public
  111. */
  112. function __construct($base = null, $start = true) {
  113. App::import('Core', 'Set', 'Security');
  114. $this->time = time();
  115. if (Configure::read('Session.checkAgent') === true || Configure::read('Session.checkAgent') === null) {
  116. if (env('HTTP_USER_AGENT') != null) {
  117. $this->_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
  118. }
  119. }
  120. if (Configure::read('Session.save') === 'database') {
  121. $modelName = Configure::read('Session.model');
  122. $database = Configure::read('Session.database');
  123. $table = Configure::read('Session.table');
  124. if (empty($database)) {
  125. $database = 'default';
  126. }
  127. if (empty($modelName)) {
  128. ClassRegistry::init(array(
  129. 'class' => Inflector::classify($table),
  130. 'alias' => 'Session'
  131. ));
  132. } else {
  133. ClassRegistry::init(array(
  134. 'class' => $modelName,
  135. 'alias' => 'Session'
  136. ));
  137. }
  138. }
  139. if ($start === true) {
  140. if (!empty($base)) {
  141. $this->path = $base;
  142. if (strpos($base, 'index.php') !== false) {
  143. $this->path = str_replace('index.php', '', $base);
  144. }
  145. if (strpos($base, '?') !== false) {
  146. $this->path = str_replace('?', '', $base);
  147. }
  148. }
  149. $this->host = env('HTTP_HOST');
  150. if (strpos($this->host, ':') !== false) {
  151. $this->host = substr($this->host, 0, strpos($this->host, ':'));
  152. }
  153. }
  154. if (isset($_SESSION) || $start === true) {
  155. if (!class_exists('Security')) {
  156. App::import('Core', 'Security');
  157. }
  158. $this->sessionTime = $this->time + (Security::inactiveMins() * Configure::read('Session.timeout'));
  159. $this->security = Configure::read('Security.level');
  160. }
  161. parent::__construct();
  162. }
  163. /**
  164. * Starts the Session.
  165. *
  166. * @param string $name Variable name to check for
  167. * @return boolean True if variable is there
  168. * @access public
  169. */
  170. public function start() {
  171. if (function_exists('session_write_close')) {
  172. session_write_close();
  173. }
  174. $this->__initSession();
  175. return $this->__startSession();
  176. }
  177. /**
  178. * Determine if Session has been started.
  179. *
  180. * @access public
  181. * @return boolean True if session has been started.
  182. */
  183. public function started() {
  184. if (isset($_SESSION)) {
  185. return true;
  186. }
  187. return false;
  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. * @access public
  195. */
  196. public function check($name) {
  197. if (empty($name)) {
  198. return false;
  199. }
  200. $result = Set::classicExtract($_SESSION, $name);
  201. return isset($result);
  202. }
  203. /**
  204. * Returns the Session id
  205. *
  206. * @param id $name string
  207. * @return string Session id
  208. * @access public
  209. */
  210. public function id($id = null) {
  211. if ($id) {
  212. $this->id = $id;
  213. session_id($this->id);
  214. }
  215. if (isset($_SESSION)) {
  216. return session_id();
  217. } else {
  218. return $this->id;
  219. }
  220. }
  221. /**
  222. * Removes a variable from session.
  223. *
  224. * @param string $name Session variable to remove
  225. * @return boolean Success
  226. * @access public
  227. */
  228. public function delete($name) {
  229. if ($this->check($name)) {
  230. if (in_array($name, $this->watchKeys)) {
  231. trigger_error('Deleting session key {' . $name . '}', E_USER_NOTICE);
  232. }
  233. $this->__overwrite($_SESSION, Set::remove($_SESSION, $name));
  234. return ($this->check($name) == false);
  235. }
  236. $this->__setError(2, "$name doesn't exist");
  237. return false;
  238. }
  239. /**
  240. * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
  241. *
  242. * @param array $old Set of old variables => values
  243. * @param array $new New set of variable => value
  244. * @access private
  245. */
  246. private function __overwrite(&$old, $new) {
  247. if (!empty($old)) {
  248. foreach ($old as $key => $var) {
  249. if (!isset($new[$key])) {
  250. unset($old[$key]);
  251. }
  252. }
  253. }
  254. foreach ($new as $key => $var) {
  255. $old[$key] = $var;
  256. }
  257. }
  258. /**
  259. * Return error description for given error number.
  260. *
  261. * @param integer $errorNumber Error to set
  262. * @return string Error as string
  263. * @access private
  264. */
  265. private function __error($errorNumber) {
  266. if (!is_array($this->error) || !array_key_exists($errorNumber, $this->error)) {
  267. return false;
  268. } else {
  269. return $this->error[$errorNumber];
  270. }
  271. }
  272. /**
  273. * Returns last occurred error as a string, if any.
  274. *
  275. * @return mixed Error description as a string, or false.
  276. * @access public
  277. */
  278. public function error() {
  279. if ($this->lastError) {
  280. return $this->__error($this->lastError);
  281. } else {
  282. return false;
  283. }
  284. }
  285. /**
  286. * Returns true if session is valid.
  287. *
  288. * @return boolean Success
  289. * @access public
  290. */
  291. public function valid() {
  292. if ($this->read('Config')) {
  293. if ((Configure::read('Session.checkAgent') === false || $this->_userAgent == $this->read('Config.userAgent')) && $this->time <= $this->read('Config.time')) {
  294. if ($this->error === false) {
  295. $this->valid = true;
  296. }
  297. } else {
  298. $this->valid = false;
  299. $this->__setError(1, 'Session Highjacking Attempted !!!');
  300. }
  301. }
  302. return $this->valid;
  303. }
  304. /**
  305. * Returns given session variable, or all of them, if no parameters given.
  306. *
  307. * @param mixed $name The name of the session variable (or a path as sent to Set.extract)
  308. * @return mixed The value of the session variable
  309. * @access public
  310. */
  311. public function read($name = null) {
  312. if (is_null($name)) {
  313. return $this->__returnSessionVars();
  314. }
  315. if (empty($name)) {
  316. return false;
  317. }
  318. $result = Set::classicExtract($_SESSION, $name);
  319. if (!is_null($result)) {
  320. return $result;
  321. }
  322. $this->__setError(2, "$name doesn't exist");
  323. return null;
  324. }
  325. /**
  326. * Returns all session variables.
  327. *
  328. * @return mixed Full $_SESSION array, or false on error.
  329. * @access private
  330. */
  331. private function __returnSessionVars() {
  332. if (!empty($_SESSION)) {
  333. return $_SESSION;
  334. }
  335. $this->__setError(2, "No Session vars set");
  336. return false;
  337. }
  338. /**
  339. * Tells Session to write a notification when a certain session path or subpath is written to
  340. *
  341. * @param mixed $var The variable path to watch
  342. * @return void
  343. * @access public
  344. */
  345. public function watch($var) {
  346. if (empty($var)) {
  347. return false;
  348. }
  349. if (!in_array($var, $this->watchKeys, true)) {
  350. $this->watchKeys[] = $var;
  351. }
  352. }
  353. /**
  354. * Tells Session to stop watching a given key path
  355. *
  356. * @param mixed $var The variable path to watch
  357. * @return void
  358. * @access public
  359. */
  360. public function ignore($var) {
  361. if (!in_array($var, $this->watchKeys)) {
  362. return;
  363. }
  364. foreach ($this->watchKeys as $i => $key) {
  365. if ($key == $var) {
  366. unset($this->watchKeys[$i]);
  367. $this->watchKeys = array_values($this->watchKeys);
  368. return;
  369. }
  370. }
  371. }
  372. /**
  373. * Writes value to given session variable name.
  374. *
  375. * @param mixed $name Name of variable
  376. * @param string $value Value to write
  377. * @return boolean True if the write was successful, false if the write failed
  378. * @access public
  379. */
  380. public function write($name, $value) {
  381. if (empty($name)) {
  382. return false;
  383. }
  384. if (in_array($name, $this->watchKeys)) {
  385. trigger_error('Writing session key {' . $name . '}: ' . Debugger::exportVar($value), E_USER_NOTICE);
  386. }
  387. $this->__overwrite($_SESSION, Set::insert($_SESSION, $name, $value));
  388. return (Set::classicExtract($_SESSION, $name) === $value);
  389. }
  390. /**
  391. * Helper method to destroy invalid sessions.
  392. *
  393. * @return void
  394. * @access public
  395. */
  396. public function destroy() {
  397. $_SESSION = array();
  398. $this->__construct($this->path);
  399. $this->start();
  400. $this->renew();
  401. $this->_checkValid();
  402. }
  403. /**
  404. * Helper method to initialize a session, based on Cake core settings.
  405. *
  406. * @access private
  407. */
  408. private function __initSession() {
  409. $iniSet = function_exists('ini_set');
  410. if ($iniSet && env('HTTPS')) {
  411. ini_set('session.cookie_secure', 1);
  412. }
  413. switch ($this->security) {
  414. case 'high':
  415. $this->cookieLifeTime = 0;
  416. if ($iniSet) {
  417. ini_set('session.referer_check', $this->host);
  418. }
  419. break;
  420. case 'medium':
  421. $this->cookieLifeTime = 7 * 86400;
  422. if ($iniSet) {
  423. ini_set('session.referer_check', $this->host);
  424. }
  425. break;
  426. case 'low':
  427. default:
  428. $this->cookieLifeTime = 788940000;
  429. break;
  430. }
  431. switch (Configure::read('Session.save')) {
  432. case 'cake':
  433. if (empty($_SESSION)) {
  434. if ($iniSet) {
  435. ini_set('session.use_trans_sid', 0);
  436. ini_set('url_rewriter.tags', '');
  437. ini_set('session.serialize_handler', 'php');
  438. ini_set('session.use_cookies', 1);
  439. ini_set('session.name', Configure::read('Session.cookie'));
  440. ini_set('session.cookie_lifetime', $this->cookieLifeTime);
  441. ini_set('session.cookie_path', $this->path);
  442. ini_set('session.auto_start', 0);
  443. ini_set('session.save_path', TMP . 'sessions');
  444. }
  445. }
  446. break;
  447. case 'database':
  448. if (empty($_SESSION)) {
  449. if (Configure::read('Session.table') === null) {
  450. trigger_error(__("You must set the all Configure::write('Session.*') in core.php to use database storage"), E_USER_WARNING);
  451. exit();
  452. } elseif (Configure::read('Session.database') === null) {
  453. Configure::write('Session.database', 'default');
  454. }
  455. if ($iniSet) {
  456. ini_set('session.use_trans_sid', 0);
  457. ini_set('url_rewriter.tags', '');
  458. ini_set('session.save_handler', 'user');
  459. ini_set('session.serialize_handler', 'php');
  460. ini_set('session.use_cookies', 1);
  461. ini_set('session.name', Configure::read('Session.cookie'));
  462. ini_set('session.cookie_lifetime', $this->cookieLifeTime);
  463. ini_set('session.cookie_path', $this->path);
  464. ini_set('session.auto_start', 0);
  465. }
  466. }
  467. session_set_save_handler(
  468. array('CakeSession','__open'),
  469. array('CakeSession', '__close'),
  470. array('CakeSession', '__read'),
  471. array('CakeSession', '__write'),
  472. array('CakeSession', '__destroy'),
  473. array('CakeSession', '__gc')
  474. );
  475. break;
  476. case 'php':
  477. if (empty($_SESSION)) {
  478. if ($iniSet) {
  479. ini_set('session.use_trans_sid', 0);
  480. ini_set('session.name', Configure::read('Session.cookie'));
  481. ini_set('session.cookie_lifetime', $this->cookieLifeTime);
  482. ini_set('session.cookie_path', $this->path);
  483. }
  484. }
  485. break;
  486. case 'cache':
  487. if (empty($_SESSION)) {
  488. if (!class_exists('Cache')) {
  489. require LIBS . 'cache.php';
  490. }
  491. if ($iniSet) {
  492. ini_set('session.use_trans_sid', 0);
  493. ini_set('url_rewriter.tags', '');
  494. ini_set('session.save_handler', 'user');
  495. ini_set('session.use_cookies', 1);
  496. ini_set('session.name', Configure::read('Session.cookie'));
  497. ini_set('session.cookie_lifetime', $this->cookieLifeTime);
  498. ini_set('session.cookie_path', $this->path);
  499. }
  500. }
  501. session_set_save_handler(
  502. array('CakeSession','__open'),
  503. array('CakeSession', '__close'),
  504. array('Cache', 'read'),
  505. array('Cache', 'write'),
  506. array('Cache', 'delete'),
  507. array('Cache', 'gc')
  508. );
  509. break;
  510. default:
  511. if (empty($_SESSION)) {
  512. $config = CONFIGS . Configure::read('Session.save') . '.php';
  513. if (is_file($config)) {
  514. require($config);
  515. }
  516. }
  517. break;
  518. }
  519. }
  520. /**
  521. * Helper method to start a session
  522. *
  523. * @access private
  524. */
  525. private function __startSession() {
  526. if (headers_sent()) {
  527. if (empty($_SESSION)) {
  528. $_SESSION = array();
  529. }
  530. return false;
  531. } elseif (!isset($_SESSION)) {
  532. session_cache_limiter ("must-revalidate");
  533. session_start();
  534. header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
  535. return true;
  536. } else {
  537. session_start();
  538. return true;
  539. }
  540. }
  541. /**
  542. * Helper method to create a new session.
  543. *
  544. * @return void
  545. * @access protected
  546. */
  547. protected function _checkValid() {
  548. if ($this->read('Config')) {
  549. if ((Configure::read('Session.checkAgent') === false || $this->_userAgent == $this->read('Config.userAgent')) && $this->time <= $this->read('Config.time')) {
  550. $time = $this->read('Config.time');
  551. $this->write('Config.time', $this->sessionTime);
  552. if (Configure::read('Security.level') === 'high') {
  553. $check = $this->read('Config.timeout');
  554. $check = $check - 1;
  555. $this->write('Config.timeout', $check);
  556. if (time() > ($time - (Security::inactiveMins() * Configure::read('Session.timeout')) + 2) || $check < 1) {
  557. $this->renew();
  558. $this->write('Config.timeout', 10);
  559. }
  560. }
  561. $this->valid = true;
  562. } else {
  563. $this->destroy();
  564. $this->valid = false;
  565. $this->__setError(1, 'Session Highjacking Attempted !!!');
  566. }
  567. } else {
  568. $this->write('Config.userAgent', $this->_userAgent);
  569. $this->write('Config.time', $this->sessionTime);
  570. $this->write('Config.timeout', 10);
  571. $this->valid = true;
  572. $this->__setError(1, 'Session is valid');
  573. }
  574. }
  575. /**
  576. * Helper method to restart a session.
  577. *
  578. * @return void
  579. * @access private
  580. */
  581. private function __regenerateId() {
  582. $oldSessionId = session_id();
  583. if ($oldSessionId) {
  584. if (session_id() != ''|| isset($_COOKIE[session_name()])) {
  585. setcookie(Configure::read('Session.cookie'), '', time() - 42000, $this->path);
  586. }
  587. session_regenerate_id(true);
  588. if (PHP_VERSION < 5.1) {
  589. $sessionPath = session_save_path();
  590. if (empty($sessionPath)) {
  591. $sessionPath = '/tmp';
  592. }
  593. $newSessid = session_id();
  594. if (function_exists('session_write_close')) {
  595. session_write_close();
  596. }
  597. $this->__initSession();
  598. session_id($oldSessionId);
  599. session_start();
  600. session_destroy();
  601. $file = $sessionPath . DS . 'sess_' . $oldSessionId;
  602. @unlink($file);
  603. $this->__initSession();
  604. session_id($newSessid);
  605. session_start();
  606. }
  607. }
  608. }
  609. /**
  610. * Restarts this session.
  611. *
  612. * @access public
  613. */
  614. public function renew() {
  615. $this->__regenerateId();
  616. }
  617. /**
  618. * Helper method to set an internal error message.
  619. *
  620. * @param integer $errorNumber Number of the error
  621. * @param string $errorMessage Description of the error
  622. * @return void
  623. * @access private
  624. */
  625. private function __setError($errorNumber, $errorMessage) {
  626. if ($this->error === false) {
  627. $this->error = array();
  628. }
  629. $this->error[$errorNumber] = $errorMessage;
  630. $this->lastError = $errorNumber;
  631. }
  632. /**
  633. * Method called on open of a database session.
  634. *
  635. * @return boolean Success
  636. * @access private
  637. */
  638. private function __open() {
  639. return true;
  640. }
  641. /**
  642. * Method called on close of a database session.
  643. *
  644. * @return boolean Success
  645. * @access private
  646. */
  647. private function __close() {
  648. $probability = mt_rand(1, 150);
  649. if ($probability <= 3) {
  650. switch (Configure::read('Session.save')) {
  651. case 'cache':
  652. Cache::gc();
  653. break;
  654. default:
  655. CakeSession::__gc();
  656. break;
  657. }
  658. }
  659. return true;
  660. }
  661. /**
  662. * Method used to read from a database 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. * @access private
  667. */
  668. private function __read($id) {
  669. $model = ClassRegistry::getObject('Session');
  670. $row = $model->find('first', array(
  671. 'conditions' => array($model->primaryKey => $id)
  672. ));
  673. if (empty($row[$model->alias]['data'])) {
  674. return false;
  675. }
  676. return $row[$model->alias]['data'];
  677. }
  678. /**
  679. * Helper function called on write for database sessions.
  680. *
  681. * @param integer $id ID that uniquely identifies session in database
  682. * @param mixed $data The value of the the data to be saved.
  683. * @return boolean True for successful write, false otherwise.
  684. * @access private
  685. */
  686. public function __write($id, $data) {
  687. switch (Configure::read('Security.level')) {
  688. case 'medium':
  689. $factor = 100;
  690. break;
  691. case 'low':
  692. $factor = 300;
  693. break;
  694. case 'high':
  695. default:
  696. $factor = 10;
  697. break;
  698. }
  699. $expires = time() + Configure::read('Session.timeout') * $factor;
  700. $model = ClassRegistry::getObject('Session');
  701. $return = $model->save(compact('id', 'data', 'expires'));
  702. return $return;
  703. }
  704. /**
  705. * Method called on the destruction of a database session.
  706. *
  707. * @param integer $id ID that uniquely identifies session in database
  708. * @return boolean True for successful delete, false otherwise.
  709. * @access private
  710. */
  711. private function __destroy($id) {
  712. $model = ClassRegistry::getObject('Session');
  713. $return = $model->delete($id);
  714. return $return;
  715. }
  716. /**
  717. * Helper function called on gc for database sessions.
  718. *
  719. * @param integer $expires Timestamp (defaults to current time)
  720. * @return boolean Success
  721. * @access private
  722. */
  723. private function __gc($expires = null) {
  724. $model = ClassRegistry::getObject('Session');
  725. if (!$expires) {
  726. $expires = time();
  727. }
  728. $return = $model->deleteAll(array($model->alias . ".expires <" => $expires), false, false);
  729. return $return;
  730. }
  731. }
  732. ?>