PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/joomla/session/session.php

https://bitbucket.org/organicdevelopment/joomla-2.5
PHP | 919 lines | 733 code | 32 blank | 154 comment | 8 complexity | 3ac4024686edbcbf9fe456d2be08871a MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, MIT, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * @package Joomla.Platform
  4. * @subpackage Session
  5. *
  6. * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
  7. * @license GNU General Public License version 2 or later; see LICENSE
  8. */
  9. defined('JPATH_PLATFORM') or die;
  10. jimport('joomla.environment.request');
  11. /**
  12. * Class for managing HTTP sessions
  13. *
  14. * Provides access to session-state values as well as session-level
  15. * settings and lifetime management methods.
  16. * Based on the standard PHP session handling mechanism it provides
  17. * more advanced features such as expire timeouts.
  18. *
  19. * @package Joomla.Platform
  20. * @subpackage Session
  21. * @since 11.1
  22. */
  23. class JSession extends JObject
  24. {
  25. /**
  26. * Internal state.
  27. * One of 'active'|'expired'|'destroyed'|'error'
  28. *
  29. * @var string
  30. * @see getState()
  31. * @since 11.1
  32. */
  33. protected $_state = 'active';
  34. /**
  35. * Maximum age of unused session in minutes
  36. *
  37. * @var string
  38. * @since 11.1
  39. */
  40. protected $_expire = 15;
  41. /**
  42. * The session store object.
  43. *
  44. * @var JSessionStorage
  45. * @since 11.1
  46. */
  47. protected $_store = null;
  48. /**
  49. * Security policy.
  50. * List of checks that will be done.
  51. *
  52. * Default values:
  53. * - fix_browser
  54. * - fix_adress
  55. *
  56. * @var array
  57. * @since 11.1
  58. */
  59. protected $_security = array('fix_browser');
  60. /**
  61. * Force cookies to be SSL only
  62. * Default false
  63. *
  64. * @var boolean
  65. * @since 11.1
  66. */
  67. protected $_force_ssl = false;
  68. /**
  69. * @var JSession JSession instances container.
  70. * @since 11.3
  71. */
  72. protected static $instance;
  73. /**
  74. * Constructor
  75. *
  76. * @param string $store The type of storage for the session.
  77. * @param array $options Optional parameters
  78. *
  79. * @since 11.1
  80. */
  81. public function __construct($store = 'none', $options = array())
  82. {
  83. // Need to destroy any existing sessions started with session.auto_start
  84. if (session_id())
  85. {
  86. session_unset();
  87. session_destroy();
  88. }
  89. // Set default sessios save handler
  90. ini_set('session.save_handler', 'files');
  91. // Disable transparent sid support
  92. ini_set('session.use_trans_sid', '0');
  93. // Create handler
  94. $this->_store = JSessionStorage::getInstance($store, $options);
  95. // Set options
  96. $this->_setOptions($options);
  97. $this->_setCookieParams();
  98. // Load the session
  99. $this->_start();
  100. // Initialise the session
  101. $this->_setCounter();
  102. $this->_setTimers();
  103. $this->_state = 'active';
  104. // Perform security checks
  105. $this->_validate();
  106. }
  107. /**
  108. * Session object destructor
  109. *
  110. * @since 11.1
  111. */
  112. public function __destruct()
  113. {
  114. $this->close();
  115. }
  116. /**
  117. * Returns the global Session object, only creating it
  118. * if it doesn't already exist.
  119. *
  120. * @param string $handler The type of session handler.
  121. * @param array $options An array of configuration options.
  122. *
  123. * @return JSession The Session object.
  124. *
  125. * @since 11.1
  126. */
  127. public static function getInstance($handler, $options)
  128. {
  129. if (!is_object(self::$instance))
  130. {
  131. self::$instance = new JSession($handler, $options);
  132. }
  133. return self::$instance;
  134. }
  135. /**
  136. * Get current state of session
  137. *
  138. * @return string The session state
  139. *
  140. * @since 11.1
  141. */
  142. public function getState()
  143. {
  144. return $this->_state;
  145. }
  146. /**
  147. * Get expiration time in minutes
  148. *
  149. * @return integer The session expiration time in minutes
  150. *
  151. * @since 11.1
  152. */
  153. public function getExpire()
  154. {
  155. return $this->_expire;
  156. }
  157. /**
  158. * Get a session token, if a token isn't set yet one will be generated.
  159. *
  160. * Tokens are used to secure forms from spamming attacks. Once a token
  161. * has been generated the system will check the post request to see if
  162. * it is present, if not it will invalidate the session.
  163. *
  164. * @param boolean $forceNew If true, force a new token to be created
  165. *
  166. * @return string The session token
  167. *
  168. * @since 11.1
  169. */
  170. public function getToken($forceNew = false)
  171. {
  172. $token = $this->get('session.token');
  173. // Create a token
  174. if ($token === null || $forceNew)
  175. {
  176. $token = $this->_createToken(12);
  177. $this->set('session.token', $token);
  178. }
  179. return $token;
  180. }
  181. /**
  182. * Method to determine if a token exists in the session. If not the
  183. * session will be set to expired
  184. *
  185. * @param string $tCheck Hashed token to be verified
  186. * @param boolean $forceExpire If true, expires the session
  187. *
  188. * @return boolean
  189. *
  190. * @since 11.1
  191. */
  192. public function hasToken($tCheck, $forceExpire = true)
  193. {
  194. // Check if a token exists in the session
  195. $tStored = $this->get('session.token');
  196. // Check token
  197. if (($tStored !== $tCheck))
  198. {
  199. if ($forceExpire)
  200. {
  201. $this->_state = 'expired';
  202. }
  203. return false;
  204. }
  205. return true;
  206. }
  207. /**
  208. * Method to determine a hash for anti-spoofing variable names
  209. *
  210. * @param boolean $forceNew If true, force a new token to be created
  211. *
  212. * @return string Hashed var name
  213. *
  214. * @since 11.1
  215. */
  216. public static function getFormToken($forceNew = false)
  217. {
  218. $user = JFactory::getUser();
  219. $session = JFactory::getSession();
  220. $hash = JApplication::getHash($user->get('id', 0) . $session->getToken($forceNew));
  221. return $hash;
  222. }
  223. /**
  224. * Checks for a form token in the request.
  225. *
  226. * Use in conjunction with JHtml::_('form.token') or JSession::getFormToken.
  227. *
  228. * @param string $method The request method in which to look for the token key.
  229. *
  230. * @return boolean True if found and valid, false otherwise.
  231. *
  232. * @since 12.1
  233. */
  234. public static function checkToken($method = 'post')
  235. {
  236. if ($method == 'default')
  237. {
  238. trigger_error("JSession::checkToken() doesn't support 'default' for the method parameter.", E_USER_ERROR);
  239. return false;
  240. }
  241. $token = self::getFormToken();
  242. $app = JFactory::getApplication();
  243. if (!JRequest::getVar($token, '', $method, 'alnum'))
  244. {
  245. $session = JFactory::getSession();
  246. if ($session->isNew())
  247. {
  248. // Redirect to login screen.
  249. $app->redirect(JRoute::_('index.php'), JText::_('JLIB_ENVIRONMENT_SESSION_EXPIRED'));
  250. $app->close();
  251. }
  252. else
  253. {
  254. return false;
  255. }
  256. }
  257. else
  258. {
  259. return true;
  260. }
  261. }
  262. /**
  263. * Get session name
  264. *
  265. * @return string The session name
  266. *
  267. * @since 11.1
  268. */
  269. public function getName()
  270. {
  271. if ($this->_state === 'destroyed')
  272. {
  273. // @TODO : raise error
  274. return null;
  275. }
  276. return session_name();
  277. }
  278. /**
  279. * Get session id
  280. *
  281. * @return string The session name
  282. *
  283. * @since 11.1
  284. */
  285. public function getId()
  286. {
  287. if ($this->_state === 'destroyed')
  288. {
  289. // @TODO : raise error
  290. return null;
  291. }
  292. return session_id();
  293. }
  294. /**
  295. * Get the session handlers
  296. *
  297. * @return array An array of available session handlers
  298. *
  299. * @since 11.1
  300. */
  301. public static function getStores()
  302. {
  303. jimport('joomla.filesystem.folder');
  304. $handlers = JFolder::files(dirname(__FILE__) . '/storage', '.php$');
  305. $names = array();
  306. foreach ($handlers as $handler)
  307. {
  308. $name = substr($handler, 0, strrpos($handler, '.'));
  309. $class = 'JSessionStorage' . ucfirst($name);
  310. // Load the class only if needed
  311. if (!class_exists($class))
  312. {
  313. require_once dirname(__FILE__) . '/storage/' . $name . '.php';
  314. }
  315. if (call_user_func_array(array(trim($class), 'test'), array()))
  316. {
  317. $names[] = $name;
  318. }
  319. }
  320. return $names;
  321. }
  322. /**
  323. * Check whether this session is currently created
  324. *
  325. * @return boolean True on success.
  326. *
  327. * @since 11.1
  328. */
  329. public function isNew()
  330. {
  331. $counter = $this->get('session.counter');
  332. if ($counter === 1)
  333. {
  334. return true;
  335. }
  336. return false;
  337. }
  338. /**
  339. * Get data from the session store
  340. *
  341. * @param string $name Name of a variable
  342. * @param mixed $default Default value of a variable if not set
  343. * @param string $namespace Namespace to use, default to 'default'
  344. *
  345. * @return mixed Value of a variable
  346. *
  347. * @since 11.1
  348. */
  349. public function get($name, $default = null, $namespace = 'default')
  350. {
  351. // Add prefix to namespace to avoid collisions
  352. $namespace = '__' . $namespace;
  353. if ($this->_state !== 'active' && $this->_state !== 'expired')
  354. {
  355. // @TODO :: generated error here
  356. $error = null;
  357. return $error;
  358. }
  359. if (isset($_SESSION[$namespace][$name]))
  360. {
  361. return $_SESSION[$namespace][$name];
  362. }
  363. return $default;
  364. }
  365. /**
  366. * Set data into the session store.
  367. *
  368. * @param string $name Name of a variable.
  369. * @param mixed $value Value of a variable.
  370. * @param string $namespace Namespace to use, default to 'default'.
  371. *
  372. * @return mixed Old value of a variable.
  373. *
  374. * @since 11.1
  375. */
  376. public function set($name, $value = null, $namespace = 'default')
  377. {
  378. // Add prefix to namespace to avoid collisions
  379. $namespace = '__' . $namespace;
  380. if ($this->_state !== 'active')
  381. {
  382. // @TODO :: generated error here
  383. return null;
  384. }
  385. $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null;
  386. if (null === $value)
  387. {
  388. unset($_SESSION[$namespace][$name]);
  389. }
  390. else
  391. {
  392. $_SESSION[$namespace][$name] = $value;
  393. }
  394. return $old;
  395. }
  396. /**
  397. * Check whether data exists in the session store
  398. *
  399. * @param string $name Name of variable
  400. * @param string $namespace Namespace to use, default to 'default'
  401. *
  402. * @return boolean True if the variable exists
  403. *
  404. * @since 11.1
  405. */
  406. public function has($name, $namespace = 'default')
  407. {
  408. // Add prefix to namespace to avoid collisions.
  409. $namespace = '__' . $namespace;
  410. if ($this->_state !== 'active')
  411. {
  412. // @TODO :: generated error here
  413. return null;
  414. }
  415. return isset($_SESSION[$namespace][$name]);
  416. }
  417. /**
  418. * Unset data from the session store
  419. *
  420. * @param string $name Name of variable
  421. * @param string $namespace Namespace to use, default to 'default'
  422. *
  423. * @return mixed The value from session or NULL if not set
  424. *
  425. * @since 11.1
  426. */
  427. public function clear($name, $namespace = 'default')
  428. {
  429. // Add prefix to namespace to avoid collisions
  430. $namespace = '__' . $namespace;
  431. if ($this->_state !== 'active')
  432. {
  433. // @TODO :: generated error here
  434. return null;
  435. }
  436. $value = null;
  437. if (isset($_SESSION[$namespace][$name]))
  438. {
  439. $value = $_SESSION[$namespace][$name];
  440. unset($_SESSION[$namespace][$name]);
  441. }
  442. return $value;
  443. }
  444. /**
  445. * Start a session.
  446. *
  447. * Creates a session (or resumes the current one based on the state of the session)
  448. *
  449. * @return boolean true on success
  450. *
  451. * @since 11.1
  452. */
  453. protected function _start()
  454. {
  455. // Start session if not started
  456. if ($this->_state == 'restart')
  457. {
  458. session_id($this->_createId());
  459. }
  460. else
  461. {
  462. $session_name = session_name();
  463. if (!JRequest::getVar($session_name, false, 'COOKIE'))
  464. {
  465. if (JRequest::getVar($session_name))
  466. {
  467. session_id(JRequest::getVar($session_name));
  468. setcookie($session_name, '', time() - 3600);
  469. }
  470. }
  471. }
  472. session_cache_limiter('none');
  473. session_start();
  474. return true;
  475. }
  476. /**
  477. * Frees all session variables and destroys all data registered to a session
  478. *
  479. * This method resets the $_SESSION variable and destroys all of the data associated
  480. * with the current session in its storage (file or DB). It forces new session to be
  481. * started after this method is called. It does not unset the session cookie.
  482. *
  483. * @return boolean True on success
  484. *
  485. * @see session_destroy()
  486. * @see session_unset()
  487. * @since 11.1
  488. */
  489. public function destroy()
  490. {
  491. // Session was already destroyed
  492. if ($this->_state === 'destroyed')
  493. {
  494. return true;
  495. }
  496. /*
  497. * In order to kill the session altogether, such as to log the user out, the session id
  498. * must also be unset. If a cookie is used to propagate the session id (default behavior),
  499. * then the session cookie must be deleted.
  500. */
  501. if (isset($_COOKIE[session_name()]))
  502. {
  503. $config = JFactory::getConfig();
  504. $cookie_domain = $config->get('cookie_domain', '');
  505. $cookie_path = $config->get('cookie_path', '/');
  506. setcookie(session_name(), '', time() - 42000, $cookie_path, $cookie_domain);
  507. }
  508. session_unset();
  509. session_destroy();
  510. $this->_state = 'destroyed';
  511. return true;
  512. }
  513. /**
  514. * Restart an expired or locked session.
  515. *
  516. * @return boolean True on success
  517. *
  518. * @see destroy
  519. * @since 11.1
  520. */
  521. public function restart()
  522. {
  523. $this->destroy();
  524. if ($this->_state !== 'destroyed')
  525. {
  526. // @TODO :: generated error here
  527. return false;
  528. }
  529. // Re-register the session handler after a session has been destroyed, to avoid PHP bug
  530. $this->_store->register();
  531. $this->_state = 'restart';
  532. // Regenerate session id
  533. $id = $this->_createId();
  534. session_id($id);
  535. $this->_start();
  536. $this->_state = 'active';
  537. $this->_validate();
  538. $this->_setCounter();
  539. return true;
  540. }
  541. /**
  542. * Create a new session and copy variables from the old one
  543. *
  544. * @return boolean $result true on success
  545. *
  546. * @since 11.1
  547. */
  548. public function fork()
  549. {
  550. if ($this->_state !== 'active')
  551. {
  552. // @TODO :: generated error here
  553. return false;
  554. }
  555. // Save values
  556. $values = $_SESSION;
  557. // Keep session config
  558. $trans = ini_get('session.use_trans_sid');
  559. if ($trans)
  560. {
  561. ini_set('session.use_trans_sid', 0);
  562. }
  563. $cookie = session_get_cookie_params();
  564. // Create new session id
  565. $id = $this->_createId();
  566. // Kill session
  567. session_destroy();
  568. // Re-register the session store after a session has been destroyed, to avoid PHP bug
  569. $this->_store->register();
  570. // Restore config
  571. ini_set('session.use_trans_sid', $trans);
  572. session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure']);
  573. // Restart session with new id
  574. session_id($id);
  575. session_start();
  576. return true;
  577. }
  578. /**
  579. * Writes session data and ends session
  580. *
  581. * Session data is usually stored after your script terminated without the need
  582. * to call JSession::close(), but as session data is locked to prevent concurrent
  583. * writes only one script may operate on a session at any time. When using
  584. * framesets together with sessions you will experience the frames loading one
  585. * by one due to this locking. You can reduce the time needed to load all the
  586. * frames by ending the session as soon as all changes to session variables are
  587. * done.
  588. *
  589. * @return void
  590. *
  591. * @see session_write_close()
  592. * @since 11.1
  593. */
  594. public function close()
  595. {
  596. session_write_close();
  597. }
  598. /**
  599. * Create a session id
  600. *
  601. * @return string Session ID
  602. *
  603. * @since 11.1
  604. */
  605. protected function _createId()
  606. {
  607. $id = 0;
  608. while (strlen($id) < 32)
  609. {
  610. $id .= mt_rand(0, mt_getrandmax());
  611. }
  612. $id = md5(uniqid($id, true));
  613. return $id;
  614. }
  615. /**
  616. * Set session cookie parameters
  617. *
  618. * @return void
  619. *
  620. * @since 11.1
  621. */
  622. protected function _setCookieParams()
  623. {
  624. $cookie = session_get_cookie_params();
  625. if ($this->_force_ssl)
  626. {
  627. $cookie['secure'] = true;
  628. }
  629. $config = JFactory::getConfig();
  630. if ($config->get('cookie_domain', '') != '')
  631. {
  632. $cookie['domain'] = $config->get('cookie_domain');
  633. }
  634. if ($config->get('cookie_path', '') != '')
  635. {
  636. $cookie['path'] = $config->get('cookie_path');
  637. }
  638. session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure']);
  639. }
  640. /**
  641. * Create a token-string
  642. *
  643. * @param integer $length Length of string
  644. *
  645. * @return string Generated token
  646. *
  647. * @since 11.1
  648. */
  649. protected function _createToken($length = 32)
  650. {
  651. static $chars = '0123456789abcdef';
  652. $max = strlen($chars) - 1;
  653. $token = '';
  654. $name = session_name();
  655. for ($i = 0; $i < $length; ++$i)
  656. {
  657. $token .= $chars[(rand(0, $max))];
  658. }
  659. return md5($token . $name);
  660. }
  661. /**
  662. * Set counter of session usage
  663. *
  664. * @return boolean True on success
  665. *
  666. * @since 11.1
  667. */
  668. protected function _setCounter()
  669. {
  670. $counter = $this->get('session.counter', 0);
  671. ++$counter;
  672. $this->set('session.counter', $counter);
  673. return true;
  674. }
  675. /**
  676. * Set the session timers
  677. *
  678. * @return boolean True on success
  679. *
  680. * @since 11.1
  681. */
  682. protected function _setTimers()
  683. {
  684. if (!$this->has('session.timer.start'))
  685. {
  686. $start = time();
  687. $this->set('session.timer.start', $start);
  688. $this->set('session.timer.last', $start);
  689. $this->set('session.timer.now', $start);
  690. }
  691. $this->set('session.timer.last', $this->get('session.timer.now'));
  692. $this->set('session.timer.now', time());
  693. return true;
  694. }
  695. /**
  696. * Set additional session options
  697. *
  698. * @param array &$options List of parameter
  699. *
  700. * @return boolean True on success
  701. *
  702. * @since 11.1
  703. */
  704. protected function _setOptions(&$options)
  705. {
  706. // Set name
  707. if (isset($options['name']))
  708. {
  709. session_name(md5($options['name']));
  710. }
  711. // Set id
  712. if (isset($options['id']))
  713. {
  714. session_id($options['id']);
  715. }
  716. // Set expire time
  717. if (isset($options['expire']))
  718. {
  719. $this->_expire = $options['expire'];
  720. }
  721. // Get security options
  722. if (isset($options['security']))
  723. {
  724. $this->_security = explode(',', $options['security']);
  725. }
  726. if (isset($options['force_ssl']))
  727. {
  728. $this->_force_ssl = (bool) $options['force_ssl'];
  729. }
  730. // Sync the session maxlifetime
  731. ini_set('session.gc_maxlifetime', $this->_expire);
  732. return true;
  733. }
  734. /**
  735. * Do some checks for security reason
  736. *
  737. * - timeout check (expire)
  738. * - ip-fixiation
  739. * - browser-fixiation
  740. *
  741. * If one check failed, session data has to be cleaned.
  742. *
  743. * @param boolean $restart Reactivate session
  744. *
  745. * @return boolean True on success
  746. *
  747. * @see http://shiflett.org/articles/the-truth-about-sessions
  748. * @since 11.1
  749. */
  750. protected function _validate($restart = false)
  751. {
  752. // Allow to restart a session
  753. if ($restart)
  754. {
  755. $this->_state = 'active';
  756. $this->set('session.client.address', null);
  757. $this->set('session.client.forwarded', null);
  758. $this->set('session.client.browser', null);
  759. $this->set('session.token', null);
  760. }
  761. // Check if session has expired
  762. if ($this->_expire)
  763. {
  764. $curTime = $this->get('session.timer.now', 0);
  765. $maxTime = $this->get('session.timer.last', 0) + $this->_expire;
  766. // Empty session variables
  767. if ($maxTime < $curTime)
  768. {
  769. $this->_state = 'expired';
  770. return false;
  771. }
  772. }
  773. // Record proxy forwarded for in the session in case we need it later
  774. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  775. {
  776. $this->set('session.client.forwarded', $_SERVER['HTTP_X_FORWARDED_FOR']);
  777. }
  778. // Check for client address
  779. if (in_array('fix_adress', $this->_security) && isset($_SERVER['REMOTE_ADDR']))
  780. {
  781. $ip = $this->get('session.client.address');
  782. if ($ip === null)
  783. {
  784. $this->set('session.client.address', $_SERVER['REMOTE_ADDR']);
  785. }
  786. elseif ($_SERVER['REMOTE_ADDR'] !== $ip)
  787. {
  788. $this->_state = 'error';
  789. return false;
  790. }
  791. }
  792. // Check for clients browser
  793. if (in_array('fix_browser', $this->_security) && isset($_SERVER['HTTP_USER_AGENT']))
  794. {
  795. $browser = $this->get('session.client.browser');
  796. if ($browser === null)
  797. {
  798. $this->set('session.client.browser', $_SERVER['HTTP_USER_AGENT']);
  799. }
  800. elseif ($_SERVER['HTTP_USER_AGENT'] !== $browser)
  801. {
  802. // @todo remove code: $this->_state = 'error';
  803. // @todo remove code: return false;
  804. }
  805. }
  806. return true;
  807. }
  808. }