21db609090fef2d0b70532dfcd1ab4f548d6a0e0
[lhc/web/wiklou.git] / includes / session / Session.php
1 <?php
2 /**
3 * MediaWiki session
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Session
22 */
23
24 namespace MediaWiki\Session;
25
26 use Psr\Log\LoggerInterface;
27 use User;
28 use WebRequest;
29
30 /**
31 * Manages data for an an authenticated session
32 *
33 * A Session represents the fact that the current HTTP request is part of a
34 * session. There are two broad types of Sessions, based on whether they
35 * return true or false from self::canSetUser():
36 * * When true (mutable), the Session identifies multiple requests as part of
37 * a session generically, with no tie to a particular user.
38 * * When false (immutable), the Session identifies multiple requests as part
39 * of a session by identifying and authenticating the request itself as
40 * belonging to a particular user.
41 *
42 * The Session object also serves as a replacement for PHP's $_SESSION,
43 * managing access to per-session data.
44 *
45 * @ingroup Session
46 * @since 1.27
47 */
48 final class Session implements \Countable, \Iterator, \ArrayAccess {
49 /** @var SessionBackend Session backend */
50 private $backend;
51
52 /** @var int Session index */
53 private $index;
54
55 /** @var LoggerInterface */
56 private $logger;
57
58 /**
59 * @param SessionBackend $backend
60 * @param int $index
61 * @param LoggerInterface $logger
62 */
63 public function __construct( SessionBackend $backend, $index, LoggerInterface $logger ) {
64 $this->backend = $backend;
65 $this->index = $index;
66 $this->logger = $logger;
67 }
68
69 public function __destruct() {
70 $this->backend->deregisterSession( $this->index );
71 }
72
73 /**
74 * Returns the session ID
75 * @return string
76 */
77 public function getId() {
78 return $this->backend->getId();
79 }
80
81 /**
82 * Returns the SessionId object
83 * @private For internal use by WebRequest
84 * @return SessionId
85 */
86 public function getSessionId() {
87 return $this->backend->getSessionId();
88 }
89
90 /**
91 * Changes the session ID
92 * @return string New ID (might be the same as the old)
93 */
94 public function resetId() {
95 return $this->backend->resetId();
96 }
97
98 /**
99 * Fetch the SessionProvider for this session
100 * @return SessionProviderInterface
101 */
102 public function getProvider() {
103 return $this->backend->getProvider();
104 }
105
106 /**
107 * Indicate whether this session is persisted across requests
108 *
109 * For example, if cookies are set.
110 *
111 * @return bool
112 */
113 public function isPersistent() {
114 return $this->backend->isPersistent();
115 }
116
117 /**
118 * Make this session persisted across requests
119 *
120 * If the session is already persistent, equivalent to calling
121 * $this->renew().
122 */
123 public function persist() {
124 $this->backend->persist();
125 }
126
127 /**
128 * Make this session not be persisted across requests
129 */
130 public function unpersist() {
131 $this->backend->unpersist();
132 }
133
134 /**
135 * Indicate whether the user should be remembered independently of the
136 * session ID.
137 * @return bool
138 */
139 public function shouldRememberUser() {
140 return $this->backend->shouldRememberUser();
141 }
142
143 /**
144 * Set whether the user should be remembered independently of the session
145 * ID.
146 * @param bool $remember
147 */
148 public function setRememberUser( $remember ) {
149 $this->backend->setRememberUser( $remember );
150 }
151
152 /**
153 * Returns the request associated with this session
154 * @return WebRequest
155 */
156 public function getRequest() {
157 return $this->backend->getRequest( $this->index );
158 }
159
160 /**
161 * Returns the authenticated user for this session
162 * @return User
163 */
164 public function getUser() {
165 return $this->backend->getUser();
166 }
167
168 /**
169 * Fetch the rights allowed the user when this session is active.
170 * @return null|string[] Allowed user rights, or null to allow all.
171 */
172 public function getAllowedUserRights() {
173 return $this->backend->getAllowedUserRights();
174 }
175
176 /**
177 * Indicate whether the session user info can be changed
178 * @return bool
179 */
180 public function canSetUser() {
181 return $this->backend->canSetUser();
182 }
183
184 /**
185 * Set a new user for this session
186 * @note This should only be called when the user has been authenticated
187 * @param User $user User to set on the session.
188 * This may become a "UserValue" in the future, or User may be refactored
189 * into such.
190 */
191 public function setUser( $user ) {
192 $this->backend->setUser( $user );
193 }
194
195 /**
196 * Get a suggested username for the login form
197 * @return string|null
198 */
199 public function suggestLoginUsername() {
200 return $this->backend->suggestLoginUsername( $this->index );
201 }
202
203 /**
204 * Whether HTTPS should be forced
205 * @return bool
206 */
207 public function shouldForceHTTPS() {
208 return $this->backend->shouldForceHTTPS();
209 }
210
211 /**
212 * Set whether HTTPS should be forced
213 * @param bool $force
214 */
215 public function setForceHTTPS( $force ) {
216 $this->backend->setForceHTTPS( $force );
217 }
218
219 /**
220 * Fetch the "logged out" timestamp
221 * @return int
222 */
223 public function getLoggedOutTimestamp() {
224 return $this->backend->getLoggedOutTimestamp();
225 }
226
227 /**
228 * Set the "logged out" timestamp
229 * @param int $ts
230 */
231 public function setLoggedOutTimestamp( $ts ) {
232 $this->backend->setLoggedOutTimestamp( $ts );
233 }
234
235 /**
236 * Fetch provider metadata
237 * @protected For use by SessionProvider subclasses only
238 * @return mixed
239 */
240 public function getProviderMetadata() {
241 return $this->backend->getProviderMetadata();
242 }
243
244 /**
245 * Delete all session data and clear the user (if possible)
246 */
247 public function clear() {
248 $data = &$this->backend->getData();
249 if ( $data ) {
250 $data = [];
251 $this->backend->dirty();
252 }
253 if ( $this->backend->canSetUser() ) {
254 $this->backend->setUser( new User );
255 }
256 $this->backend->save();
257 }
258
259 /**
260 * Renew the session
261 *
262 * Resets the TTL in the backend store if the session is near expiring, and
263 * re-persists the session to any active WebRequests if persistent.
264 */
265 public function renew() {
266 $this->backend->renew();
267 }
268
269 /**
270 * Fetch a copy of this session attached to an alternative WebRequest
271 *
272 * Actions on the copy will affect this session too, and vice versa.
273 *
274 * @param WebRequest $request Any existing session associated with this
275 * WebRequest object will be overwritten.
276 * @return Session
277 */
278 public function sessionWithRequest( WebRequest $request ) {
279 $request->setSessionId( $this->backend->getSessionId() );
280 return $this->backend->getSession( $request );
281 }
282
283 /**
284 * Fetch a value from the session
285 * @param string|int $key
286 * @param mixed $default Returned if $this->exists( $key ) would be false
287 * @return mixed
288 */
289 public function get( $key, $default = null ) {
290 $data = &$this->backend->getData();
291 return array_key_exists( $key, $data ) ? $data[$key] : $default;
292 }
293
294 /**
295 * Test if a value exists in the session
296 * @note Unlike isset(), null values are considered to exist.
297 * @param string|int $key
298 * @return bool
299 */
300 public function exists( $key ) {
301 $data = &$this->backend->getData();
302 return array_key_exists( $key, $data );
303 }
304
305 /**
306 * Set a value in the session
307 * @param string|int $key
308 * @param mixed $value
309 */
310 public function set( $key, $value ) {
311 $data = &$this->backend->getData();
312 if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
313 $data[$key] = $value;
314 $this->backend->dirty();
315 }
316 }
317
318 /**
319 * Remove a value from the session
320 * @param string|int $key
321 */
322 public function remove( $key ) {
323 $data = &$this->backend->getData();
324 if ( array_key_exists( $key, $data ) ) {
325 unset( $data[$key] );
326 $this->backend->dirty();
327 }
328 }
329
330 /**
331 * Fetch a CSRF token from the session
332 *
333 * Note that this does not persist the session, which you'll probably want
334 * to do if you want the token to actually be useful.
335 *
336 * @param string|string[] $salt Token salt
337 * @param string $key Token key
338 * @return MediaWiki\\Session\\SessionToken
339 */
340 public function getToken( $salt = '', $key = 'default' ) {
341 $new = false;
342 $secrets = $this->get( 'wsTokenSecrets' );
343 if ( !is_array( $secrets ) ) {
344 $secrets = [];
345 }
346 if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
347 $secret = $secrets[$key];
348 } else {
349 $secret = \MWCryptRand::generateHex( 32 );
350 $secrets[$key] = $secret;
351 $this->set( 'wsTokenSecrets', $secrets );
352 $new = true;
353 }
354 if ( is_array( $salt ) ) {
355 $salt = join( '|', $salt );
356 }
357 return new Token( $secret, (string)$salt, $new );
358 }
359
360 /**
361 * Remove a CSRF token from the session
362 *
363 * The next call to self::getToken() with $key will generate a new secret.
364 *
365 * @param string $key Token key
366 */
367 public function resetToken( $key = 'default' ) {
368 $secrets = $this->get( 'wsTokenSecrets' );
369 if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
370 unset( $secrets[$key] );
371 $this->set( 'wsTokenSecrets', $secrets );
372 }
373 }
374
375 /**
376 * Remove all CSRF tokens from the session
377 */
378 public function resetAllTokens() {
379 $this->remove( 'wsTokenSecrets' );
380 }
381
382 /**
383 * Delay automatic saving while multiple updates are being made
384 *
385 * Calls to save() or clear() will not be delayed.
386 *
387 * @return \ScopedCallback When this goes out of scope, a save will be triggered
388 */
389 public function delaySave() {
390 return $this->backend->delaySave();
391 }
392
393 /**
394 * Save the session
395 */
396 public function save() {
397 $this->backend->save();
398 }
399
400 /**
401 * @name Interface methods
402 * @{
403 */
404
405 public function count() {
406 $data = &$this->backend->getData();
407 return count( $data );
408 }
409
410 public function current() {
411 $data = &$this->backend->getData();
412 return current( $data );
413 }
414
415 public function key() {
416 $data = &$this->backend->getData();
417 return key( $data );
418 }
419
420 public function next() {
421 $data = &$this->backend->getData();
422 next( $data );
423 }
424
425 public function rewind() {
426 $data = &$this->backend->getData();
427 reset( $data );
428 }
429
430 public function valid() {
431 $data = &$this->backend->getData();
432 return key( $data ) !== null;
433 }
434
435 /**
436 * @note Despite the name, this seems to be intended to implement isset()
437 * rather than array_key_exists(). So do that.
438 */
439 public function offsetExists( $offset ) {
440 $data = &$this->backend->getData();
441 return isset( $data[$offset] );
442 }
443
444 /**
445 * @note This supports indirect modifications but can't mark the session
446 * dirty when those happen. SessionBackend::save() checks the hash of the
447 * data to detect such changes.
448 * @note Accessing a nonexistent key via this mechanism causes that key to
449 * be created with a null value, and does not raise a PHP warning.
450 */
451 public function &offsetGet( $offset ) {
452 $data = &$this->backend->getData();
453 if ( !array_key_exists( $offset, $data ) ) {
454 $ex = new \Exception( "Undefined index (auto-adds to session with a null value): $offset" );
455 $this->logger->debug( $ex->getMessage(), [ 'exception' => $ex ] );
456 }
457 return $data[$offset];
458 }
459
460 public function offsetSet( $offset, $value ) {
461 $this->set( $offset, $value );
462 }
463
464 public function offsetUnset( $offset ) {
465 $this->remove( $offset );
466 }
467
468 /**@}*/
469
470 }