PageRenderTime 62ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/cake_session.php

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