| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- * @link http://cakephp.org CakePHP(tm) Project
- * @since 0.10.0
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Network;
- use Cake\Core\App;
- use Cake\Core\Configure;
- use Cake\Error;
- use Cake\Utility\Hash;
- use SessionHandlerInterface;
- /**
- * This class is a wrapper for the native PHP session functions. It provides
- * with several defaults for the most common use cases for utilizing the session
- * via external handlers and helps with using session in cli without any warnings.
- *
- * Sessions can be created out of defaults using `Session::create()` or you can get
- * an instance of a new session by just instantiating this class and passing the full
- * options you want to use.
- *
- * When specific options are omitted, this class will take its defaults from the configuration
- * values from the `session.*` directives in php.ini. This class will also alter such
- * directives when configuration values are provided.
- */
- class Session {
- /**
- * The Session handler instace used as an engine for persisting the session data.
- *
- * @var SessionHandlerInterface
- */
- protected $_engine;
- /**
- * Indicates whether the sessions has already started
- *
- * @var boolean
- */
- protected $_started;
- /**
- * The time in seconds the session will be valid for
- *
- * @var int
- */
- protected $_lifetime;
- /**
- * Returns a new instance of a session after building a configuration bundle for it.
- * This function allows an options array which will be used for configuring the session
- * and the handler to be used. The most important key in the configuration array is
- * `defaults`, which indicates the set of configurations to inherit from, the possible
- * defaults are:
- *
- * - php: just use session as configured in php.ini
- * - cache: Use the CakePHP caching system as an storage for the session, you will need
- * to pass the `config` key with the name of an already configured Cache engine.
- * - database: Use the CakePHP ORM to persist and manage sessions. By default this requires
- * a table in your database named `sessions` or a `model` key in the configuration
- * to indicate which Table object to use.
- * - cake: Use files for storing the sessions, but let CakePHP manage them and decide
- * where to store them.
- *
- * The full list of options follows:
- *
- * - defaults: either 'php', 'database', 'cache' or 'cake' as explained above.
- * - handler: An array containing the handler configuration
- * - ini: A list of php.ini directives to set before the session starts.
- * - timeout: The time in minutes the session should stay active
- *
- * @param array $sessionConfig
- * @return Cake\Network\Session
- * @see Session::__construct()
- */
- public static function create($sessionConfig = []) {
- if (isset($sessionConfig['defaults'])) {
- $defaults = static::_defaultConfig($sessionConfig['defaults']);
- if ($defaults) {
- $sessionConfig = Hash::merge($defaults, $sessionConfig);
- }
- }
- if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
- $sessionConfig['ini']['session.cookie_secure'] = 1;
- }
- if (!isset($sessionConfig['ini']['session.name'])) {
- $sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
- }
- if (!empty($sessionConfig['handler'])) {
- $sessionConfig['ini']['session.save_handler'] = 'user';
- }
- if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
- $sessionConfig['ini']['session.cookie_httponly'] = 1;
- }
- return new static($sessionConfig);
- }
- /**
- * Get one of the prebaked default session configurations.
- *
- * @param string $name
- * @return bool|array
- */
- protected static function _defaultConfig($name) {
- $defaults = array(
- 'php' => array(
- 'checkAgent' => false,
- 'cookie' => 'CAKEPHP',
- 'ini' => array(
- 'session.use_trans_sid' => 0,
- )
- ),
- 'cake' => array(
- 'checkAgent' => false,
- 'cookie' => 'CAKEPHP',
- 'ini' => array(
- 'session.use_trans_sid' => 0,
- 'url_rewriter.tags' => '',
- 'session.serialize_handler' => 'php',
- 'session.use_cookies' => 1,
- 'session.save_path' => TMP . 'sessions',
- 'session.save_handler' => 'files'
- )
- ),
- 'cache' => array(
- 'checkAgent' => false,
- 'cookie' => 'CAKEPHP',
- 'ini' => array(
- 'session.use_trans_sid' => 0,
- 'url_rewriter.tags' => '',
- 'session.use_cookies' => 1,
- 'session.save_handler' => 'user',
- ),
- 'handler' => array(
- 'engine' => 'CacheSession',
- 'config' => 'default'
- )
- ),
- 'database' => array(
- 'checkAgent' => false,
- 'cookie' => 'CAKEPHP',
- 'ini' => array(
- 'session.use_trans_sid' => 0,
- 'url_rewriter.tags' => '',
- 'session.use_cookies' => 1,
- 'session.save_handler' => 'user',
- 'session.serialize_handler' => 'php',
- ),
- 'handler' => array(
- 'engine' => 'DatabaseSession'
- )
- )
- );
- if (isset($defaults[$name])) {
- return $defaults[$name];
- }
- return false;
- }
- /**
- * Constructor.
- *
- * ### Configuration:
- *
- * - timeout: The time in minutes the session should be valid for
- * - ini: A list of ini directives to change before the session start.
- * - handler: An array containing at least the `class` key. To be used as the session
- * engine for persisting data. The rest of the keys in the array will be passed as
- * the configuration array for the engine. You can set the `class` key to an already
- * instantiated session handler object.
- *
- * @param array The Configuration to apply to this session object
- */
- public function __construct(array $config = []) {
- if (isset($config['timeout'])) {
- $config['ini']['session.cookie_lifetime'] = 60 * $config['timeout'];
- $config['ini']['session.gc_maxlifetime'] = 60 * $config['timeout'];
- }
- if (!empty($config['ini']) && is_array($config['ini'])) {
- $this->options($config['ini']);
- }
- if (!empty($config['handler']['engine'])) {
- $class = $config['handler']['engine'];
- unset($config['handler']['engine']);
- session_set_save_handler($this->engine($class, $config['handler']), false);
- }
- $this->_lifetime = ini_get('session.gc_maxlifetime');
- session_register_shutdown();
- }
- /**
- * Sets the session handler instance to use for this session.
- * If a string is passed for the first argument, it will be treated as the
- * class name and the second argument will be passed as the first argument
- * in the constructor.
- *
- * If an instance of a SessionHandlerInterface is provided as the first argument,
- * the handler will be set to it.
- *
- * If no arguments are passed it will return the currently configured handler instance
- * or null if none exists.
- *
- * @param string|\SessionHandlerInterface $class The session handler to use
- * @param array $options the options to pass to the SessionHandler constructor
- * @return \SessionHandlerInterface|null
- * @throws \InvalidArgumentException
- */
- public function engine($class = null, $options = []) {
- if ($class instanceof SessionHandlerInterface) {
- return $this->_engine = $class;
- }
- if ($class === null) {
- return $this->_engine;
- }
- $class = App::className($class, 'Network/Session');
- if (!class_exists($class)) {
- throw new \InvalidArgumentException(sprintf('The class %s does not exist.', $class));
- }
- $handler = new $class($options);
- if (!($handler instanceof SessionHandlerInterface)) {
- throw new \InvalidArgumentException(
- 'Chosen SessionHandler does not implement SessionHandlerInterface, it cannot be used with an engine key.'
- );
- }
- return $this->_engine = $handler;
- }
- /**
- * Calls ini_set for each of the keys in `$options` and set them
- * to the respective value in the passed array.
- *
- * ### Example:
- *
- * `$session->options(['session.use_cookies' => 1]);`
- *
- * @return void
- * @throws \RuntimeException if any directive could not be set
- */
- public function options(array $options) {
- if (session_status() === \PHP_SESSION_ACTIVE) {
- return;
- }
- foreach ($options as $setting => $value) {
- if (ini_set($setting, $value) === false) {
- throw new \RuntimeException(sprintf(
- sprintf('Unable to configure the session, setting %s failed.'),
- $setting
- ));
- }
- }
- }
- /**
- * Starts the Session.
- *
- * @return bool True if session was started
- * @throws \RuntimeException if the session was already started or headers were already
- * sent
- */
- public function start() {
- if ($this->_started) {
- return true;
- }
- if (php_sapi_name() === 'cli') {
- $_SESSION = [];
- return $this->_started = true;
- }
- if (session_status() === \PHP_SESSION_ACTIVE) {
- throw new \RuntimeException('Session was already started');
- }
- if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
- throw new \RuntimeException(
- sprintf('Cannot start session, headers already sent in "%s" at line %d', $file, $line)
- );
- }
- if (!session_start()) {
- throw new \RuntimeException('Could not start the session');
- }
-
- $this->_started = true;
- if ($this->_timedOut()) {
- $this->destroy();
- return $this->start();
- }
- return $this->_started;
- }
- /**
- * Determine if Session has already been started.
- *
- * @return bool True if session has been started.
- */
- public function started() {
- return $this->_started || session_status() === \PHP_SESSION_ACTIVE;
- }
- /**
- * Returns true if given variable name is set in session.
- *
- * @param string $name Variable name to check for
- * @return bool True if variable is there
- */
- public function check($name = null) {
- if (empty($name)) {
- return false;
- }
- if ($this->_hasSession() && !$this->started()) {
- $this->start();
- }
- return Hash::get($_SESSION, $name) !== null;
- }
- /**
- * Returns given session variable, or all of them, if no parameters given.
- *
- * @param string|array $name The name of the session variable (or a path as sent to Set.extract)
- * @return mixed The value of the session variable, null if session not available,
- * session not started, or provided name not found in the session.
- */
- public function read($name = null) {
- if (empty($name) && $name !== null) {
- return null;
- }
- if ($this->_hasSession() && !$this->started()) {
- $this->start();
- }
- if (!isset($_SESSION)) {
- return null;
- }
- if ($name === null) {
- return isset($_SESSION) ? $_SESSION : [];
- }
- return Hash::get($_SESSION, $name);
- }
- /**
- * Writes value to given session variable name.
- *
- * @param string|array $name Name of variable
- * @param string $value Value to write
- * @return bool True if the write was successful, false if the write failed
- */
- public function write($name, $value = null) {
- if (empty($name)) {
- return;
- }
- if (!$this->started()) {
- $this->start();
- }
- $write = $name;
- if (!is_array($name)) {
- $write = array($name => $value);
- }
- $data = $_SESSION ?: [];
- foreach ($write as $key => $val) {
- $data = Hash::insert($data, $key, $val);
- }
- $this->_overwrite($_SESSION, $data);
- }
- /**
- * Returns the session id.
- * Calling this method will not auto start the session. You might have to manually
- * assert a started session.
- *
- * Passing an id into it, you can also replace the session id if the session
- * has not already been started.
- * Note that depending on the session handler, not all characters are allowed
- * within the session id. For example, the file session handler only allows
- * characters in the range a-z A-Z 0-9 , (comma) and - (minus).
- *
- * @param string $id Id to replace the current session id
- * @return string Session id
- */
- public function id($id = null) {
- if ($id !== null) {
- session_id($id);
- }
- return session_id();
- }
- /**
- * Removes a variable from session.
- *
- * @param string $name Session variable to remove
- * @return bool Success
- */
- public function delete($name) {
- if ($this->check($name)) {
- $this->_overwrite($_SESSION, Hash::remove($_SESSION, $name));
- }
- }
- /**
- * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
- *
- * @param array $old Set of old variables => values
- * @param array $new New set of variable => value
- * @return void
- */
- protected function _overwrite(&$old, $new) {
- if (!empty($old)) {
- foreach ($old as $key => $var) {
- if (!isset($new[$key])) {
- unset($old[$key]);
- }
- }
- }
- foreach ($new as $key => $var) {
- $old[$key] = $var;
- }
- }
- /**
- * Helper method to destroy invalid sessions.
- *
- * @return void
- */
- public function destroy() {
- if ($this->_hasSession() && !$this->started()) {
- $this->start();
- }
- if (php_sapi_name() !== 'cli') {
- session_destroy();
- }
- $_SESSION = [];
- $this->_started = false;
- }
- /**
- * Clears the session, the session id, and renews the session.
- *
- * @return void
- */
- public function clear() {
- $_SESSION = [];
- $this->renew();
- }
- /**
- * Returns whether a session exists
- * @return bool
- */
- protected function _hasSession() {
- return !ini_get('session.use_cookies') || isset($_COOKIE[session_name()]);
- }
- /**
- * Restarts this session.
- *
- * @return void
- */
- public function renew() {
- if (!$this->_hasSession()) {
- return;
- }
- $params = session_get_cookie_params();
- setcookie(
- session_name(), '', time() - 42000,
- $params['path'], $params['domain'],
- $params['secure'], $params['httponly']
- );
- session_regenerate_id(true);
- }
- /**
- * Stores a single string under the "Message.flash" session key. This is useful
- * for persisting messages from one request to another that should be displayed
- * to the user.
- *
- * The options array accepts `key`, this is is useful for assigning a domain
- * to the flash message since you can only store one per domain.
- *
- * ### Example
- *
- * {{{
- * $session->flash('Welcome, Mark', 'success');
- * $session->flash('This is a message in a different domain', 'info', ['key' => 'another']);
- * }}}
- *
- * @param string $message the message to display to persist
- * @param string $type the type of message
- * @param array $options A list of extra options to persist related to this message
- * @return void
- */
- public function flash($message, $type = 'info', $options = []) {
- $options += ['key' => 'flash'];
- $key = $options['key'];
- unset($options['key']);
- $this->write("Message.$key", [
- 'message' => $message,
- 'type' => $type,
- 'params' => $options
- ]);
- }
- /**
- * Returns the flash message stored in the given key if exists.
- *
- * @param string $key the message domain
- * @return array|null
- */
- public function readFlash($key = 'flash') {
- return $this->read("Message.$key");
- }
- /**
- * Deletes the flash message stored in the given key
- *
- * @param string $key the message domain
- * @return void
- */
- public function deleteFlash($key = 'flash') {
- $this->delete("Message.$key");
- }
- /**
- * Returns true if the session is no longer valid because the last time it was
- * accessed was after the configured timeout.
- *
- * @return boolean
- */
- protected function _timedOut() {
- $time = $this->read('Config.time');
- $result = false;
- $checkTime = $time !== null && $this->_lifetime > 0;
- if ($checkTime && (time() - $time > $this->_lifetime)) {
- $result = true;
- }
- $this->write('Config.time', time());
- return $result;
- }
- }
|