PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / session / Session.php
blob4ad69ae802d6a819285f014541e9719cd578182e
1 <?php
2 /**
3 * MediaWiki session
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Session
24 namespace MediaWiki\Session;
26 use User;
27 use WebRequest;
29 /**
30 * Manages data for an an authenticated session
32 * A Session represents the fact that the current HTTP request is part of a
33 * session. There are two broad types of Sessions, based on whether they
34 * return true or false from self::canSetUser():
35 * * When true (mutable), the Session identifies multiple requests as part of
36 * a session generically, with no tie to a particular user.
37 * * When false (immutable), the Session identifies multiple requests as part
38 * of a session by identifying and authenticating the request itself as
39 * belonging to a particular user.
41 * The Session object also serves as a replacement for PHP's $_SESSION,
42 * managing access to per-session data.
44 * @todo Once we drop support for PHP 5.3.3, implementing ArrayAccess would be nice.
45 * @ingroup Session
46 * @since 1.27
48 final class Session implements \Countable, \Iterator {
49 /** @var SessionBackend Session backend */
50 private $backend;
52 /** @var int Session index */
53 private $index;
55 /**
56 * @param SessionBackend $backend
57 * @param int $index
59 public function __construct( SessionBackend $backend, $index ) {
60 $this->backend = $backend;
61 $this->index = $index;
64 public function __destruct() {
65 $this->backend->deregisterSession( $this->index );
68 /**
69 * Returns the session ID
70 * @return string
72 public function getId() {
73 return $this->backend->getId();
76 /**
77 * Returns the SessionId object
78 * @private For internal use by WebRequest
79 * @return SessionId
81 public function getSessionId() {
82 return $this->backend->getSessionId();
85 /**
86 * Changes the session ID
87 * @return string New ID (might be the same as the old)
89 public function resetId() {
90 return $this->backend->resetId();
93 /**
94 * Fetch the SessionProvider for this session
95 * @return SessionProviderInterface
97 public function getProvider() {
98 return $this->backend->getProvider();
102 * Indicate whether this session is persisted across requests
104 * For example, if cookies are set.
106 * @return bool
108 public function isPersistent() {
109 return $this->backend->isPersistent();
113 * Make this session persisted across requests
115 * If the session is already persistent, equivalent to calling
116 * $this->renew().
118 public function persist() {
119 $this->backend->persist();
123 * Indicate whether the user should be remembered independently of the
124 * session ID.
125 * @return bool
127 public function shouldRememberUser() {
128 return $this->backend->shouldRememberUser();
132 * Set whether the user should be remembered independently of the session
133 * ID.
134 * @param bool $remember
136 public function setRememberUser( $remember ) {
137 $this->backend->setRememberUser( $remember );
141 * Returns the request associated with this session
142 * @return WebRequest
144 public function getRequest() {
145 return $this->backend->getRequest( $this->index );
149 * Returns the authenticated user for this session
150 * @return User
152 public function getUser() {
153 return $this->backend->getUser();
157 * Fetch the rights allowed the user when this session is active.
158 * @return null|string[] Allowed user rights, or null to allow all.
160 public function getAllowedUserRights() {
161 return $this->backend->getAllowedUserRights();
165 * Indicate whether the session user info can be changed
166 * @return bool
168 public function canSetUser() {
169 return $this->backend->canSetUser();
173 * Set a new user for this session
174 * @note This should only be called when the user has been authenticated
175 * @param User $user User to set on the session.
176 * This may become a "UserValue" in the future, or User may be refactored
177 * into such.
179 public function setUser( $user ) {
180 $this->backend->setUser( $user );
184 * Get a suggested username for the login form
185 * @return string|null
187 public function suggestLoginUsername() {
188 return $this->backend->suggestLoginUsername( $this->index );
192 * Whether HTTPS should be forced
193 * @return bool
195 public function shouldForceHTTPS() {
196 return $this->backend->shouldForceHTTPS();
200 * Set whether HTTPS should be forced
201 * @param bool $force
203 public function setForceHTTPS( $force ) {
204 $this->backend->setForceHTTPS( $force );
208 * Fetch the "logged out" timestamp
209 * @return int
211 public function getLoggedOutTimestamp() {
212 return $this->backend->getLoggedOutTimestamp();
216 * Set the "logged out" timestamp
217 * @param int $ts
219 public function setLoggedOutTimestamp( $ts ) {
220 $this->backend->setLoggedOutTimestamp( $ts );
224 * Fetch provider metadata
225 * @protected For use by SessionProvider subclasses only
226 * @return mixed
228 public function getProviderMetadata() {
229 return $this->backend->getProviderMetadata();
233 * Delete all session data and clear the user (if possible)
235 public function clear() {
236 $data = &$this->backend->getData();
237 if ( $data ) {
238 $data = array();
239 $this->backend->dirty();
241 if ( $this->backend->canSetUser() ) {
242 $this->backend->setUser( new User );
244 $this->backend->save();
248 * Renew the session
250 * Resets the TTL in the backend store if the session is near expiring, and
251 * re-persists the session to any active WebRequests if persistent.
253 public function renew() {
254 $this->backend->renew();
258 * Fetch a copy of this session attached to an alternative WebRequest
260 * Actions on the copy will affect this session too, and vice versa.
262 * @param WebRequest $request Any existing session associated with this
263 * WebRequest object will be overwritten.
264 * @return Session
266 public function sessionWithRequest( WebRequest $request ) {
267 $request->setSessionId( $this->backend->getSessionId() );
268 return $this->backend->getSession( $request );
272 * Fetch a value from the session
273 * @param string|int $key
274 * @param mixed $default
275 * @return mixed
277 public function get( $key, $default = null ) {
278 $data = &$this->backend->getData();
279 return array_key_exists( $key, $data ) ? $data[$key] : $default;
283 * Test if a value exists in the session
284 * @param string|int $key
285 * @return bool
287 public function exists( $key ) {
288 $data = &$this->backend->getData();
289 return array_key_exists( $key, $data );
293 * Set a value in the session
294 * @param string|int $key
295 * @param mixed $value
297 public function set( $key, $value ) {
298 $data = &$this->backend->getData();
299 if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
300 $data[$key] = $value;
301 $this->backend->dirty();
306 * Remove a value from the session
307 * @param string|int $key
309 public function remove( $key ) {
310 $data = &$this->backend->getData();
311 if ( array_key_exists( $key, $data ) ) {
312 unset( $data[$key] );
313 $this->backend->dirty();
318 * Fetch a CSRF token from the session
320 * Note that this does not persist the session, which you'll probably want
321 * to do if you want the token to actually be useful.
323 * @param string|string[] $salt Token salt
324 * @param string $key Token key
325 * @return MediaWiki\\Session\\SessionToken
327 public function getToken( $salt = '', $key = 'default' ) {
328 $new = false;
329 $secrets = $this->get( 'wsTokenSecrets' );
330 if ( !is_array( $secrets ) ) {
331 $secrets = array();
333 if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
334 $secret = $secrets[$key];
335 } else {
336 $secret = \MWCryptRand::generateHex( 32 );
337 $secrets[$key] = $secret;
338 $this->set( 'wsTokenSecrets', $secrets );
339 $new = true;
341 if ( is_array( $salt ) ) {
342 $salt = join( '|', $salt );
344 return new Token( $secret, (string)$salt, $new );
348 * Remove a CSRF token from the session
350 * The next call to self::getToken() with $key will generate a new secret.
352 * @param string $key Token key
354 public function resetToken( $key = 'default' ) {
355 $secrets = $this->get( 'wsTokenSecrets' );
356 if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
357 unset( $secrets[$key] );
358 $this->set( 'wsTokenSecrets', $secrets );
363 * Remove all CSRF tokens from the session
365 public function resetAllTokens() {
366 $this->remove( 'wsTokenSecrets' );
370 * Delay automatic saving while multiple updates are being made
372 * Calls to save() or clear() will not be delayed.
374 * @return \ScopedCallback When this goes out of scope, a save will be triggered
376 public function delaySave() {
377 return $this->backend->delaySave();
381 * Save the session
383 public function save() {
384 $this->backend->save();
388 * @name Interface methods
389 * @{
392 public function count() {
393 $data = &$this->backend->getData();
394 return count( $data );
397 public function current() {
398 $data = &$this->backend->getData();
399 return current( $data );
402 public function key() {
403 $data = &$this->backend->getData();
404 return key( $data );
407 public function next() {
408 $data = &$this->backend->getData();
409 next( $data );
412 public function rewind() {
413 $data = &$this->backend->getData();
414 reset( $data );
417 public function valid() {
418 $data = &$this->backend->getData();
419 return key( $data ) !== null;
422 /**@}*/