Merge "Stop using SiteConfiguration::isLocalVHost()"
[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 * Indicate whether the user should be remembered independently of the
129 * session ID.
130 * @return bool
131 */
132 public function shouldRememberUser() {
133 return $this->backend->shouldRememberUser();
134 }
135
136 /**
137 * Set whether the user should be remembered independently of the session
138 * ID.
139 * @param bool $remember
140 */
141 public function setRememberUser( $remember ) {
142 $this->backend->setRememberUser( $remember );
143 }
144
145 /**
146 * Returns the request associated with this session
147 * @return WebRequest
148 */
149 public function getRequest() {
150 return $this->backend->getRequest( $this->index );
151 }
152
153 /**
154 * Returns the authenticated user for this session
155 * @return User
156 */
157 public function getUser() {
158 return $this->backend->getUser();
159 }
160
161 /**
162 * Fetch the rights allowed the user when this session is active.
163 * @return null|string[] Allowed user rights, or null to allow all.
164 */
165 public function getAllowedUserRights() {
166 return $this->backend->getAllowedUserRights();
167 }
168
169 /**
170 * Indicate whether the session user info can be changed
171 * @return bool
172 */
173 public function canSetUser() {
174 return $this->backend->canSetUser();
175 }
176
177 /**
178 * Set a new user for this session
179 * @note This should only be called when the user has been authenticated
180 * @param User $user User to set on the session.
181 * This may become a "UserValue" in the future, or User may be refactored
182 * into such.
183 */
184 public function setUser( $user ) {
185 $this->backend->setUser( $user );
186 }
187
188 /**
189 * Get a suggested username for the login form
190 * @return string|null
191 */
192 public function suggestLoginUsername() {
193 return $this->backend->suggestLoginUsername( $this->index );
194 }
195
196 /**
197 * Whether HTTPS should be forced
198 * @return bool
199 */
200 public function shouldForceHTTPS() {
201 return $this->backend->shouldForceHTTPS();
202 }
203
204 /**
205 * Set whether HTTPS should be forced
206 * @param bool $force
207 */
208 public function setForceHTTPS( $force ) {
209 $this->backend->setForceHTTPS( $force );
210 }
211
212 /**
213 * Fetch the "logged out" timestamp
214 * @return int
215 */
216 public function getLoggedOutTimestamp() {
217 return $this->backend->getLoggedOutTimestamp();
218 }
219
220 /**
221 * Set the "logged out" timestamp
222 * @param int $ts
223 */
224 public function setLoggedOutTimestamp( $ts ) {
225 $this->backend->setLoggedOutTimestamp( $ts );
226 }
227
228 /**
229 * Fetch provider metadata
230 * @protected For use by SessionProvider subclasses only
231 * @return mixed
232 */
233 public function getProviderMetadata() {
234 return $this->backend->getProviderMetadata();
235 }
236
237 /**
238 * Delete all session data and clear the user (if possible)
239 */
240 public function clear() {
241 $data = &$this->backend->getData();
242 if ( $data ) {
243 $data = array();
244 $this->backend->dirty();
245 }
246 if ( $this->backend->canSetUser() ) {
247 $this->backend->setUser( new User );
248 }
249 $this->backend->save();
250 }
251
252 /**
253 * Renew the session
254 *
255 * Resets the TTL in the backend store if the session is near expiring, and
256 * re-persists the session to any active WebRequests if persistent.
257 */
258 public function renew() {
259 $this->backend->renew();
260 }
261
262 /**
263 * Fetch a copy of this session attached to an alternative WebRequest
264 *
265 * Actions on the copy will affect this session too, and vice versa.
266 *
267 * @param WebRequest $request Any existing session associated with this
268 * WebRequest object will be overwritten.
269 * @return Session
270 */
271 public function sessionWithRequest( WebRequest $request ) {
272 $request->setSessionId( $this->backend->getSessionId() );
273 return $this->backend->getSession( $request );
274 }
275
276 /**
277 * Fetch a value from the session
278 * @param string|int $key
279 * @param mixed $default Returned if $this->exists( $key ) would be false
280 * @return mixed
281 */
282 public function get( $key, $default = null ) {
283 $data = &$this->backend->getData();
284 return array_key_exists( $key, $data ) ? $data[$key] : $default;
285 }
286
287 /**
288 * Test if a value exists in the session
289 * @note Unlike isset(), null values are considered to exist.
290 * @param string|int $key
291 * @return bool
292 */
293 public function exists( $key ) {
294 $data = &$this->backend->getData();
295 return array_key_exists( $key, $data );
296 }
297
298 /**
299 * Set a value in the session
300 * @param string|int $key
301 * @param mixed $value
302 */
303 public function set( $key, $value ) {
304 $data = &$this->backend->getData();
305 if ( !array_key_exists( $key, $data ) || $data[$key] !== $value ) {
306 $data[$key] = $value;
307 $this->backend->dirty();
308 }
309 }
310
311 /**
312 * Remove a value from the session
313 * @param string|int $key
314 */
315 public function remove( $key ) {
316 $data = &$this->backend->getData();
317 if ( array_key_exists( $key, $data ) ) {
318 unset( $data[$key] );
319 $this->backend->dirty();
320 }
321 }
322
323 /**
324 * Fetch a CSRF token from the session
325 *
326 * Note that this does not persist the session, which you'll probably want
327 * to do if you want the token to actually be useful.
328 *
329 * @param string|string[] $salt Token salt
330 * @param string $key Token key
331 * @return MediaWiki\\Session\\SessionToken
332 */
333 public function getToken( $salt = '', $key = 'default' ) {
334 $new = false;
335 $secrets = $this->get( 'wsTokenSecrets' );
336 if ( !is_array( $secrets ) ) {
337 $secrets = array();
338 }
339 if ( isset( $secrets[$key] ) && is_string( $secrets[$key] ) ) {
340 $secret = $secrets[$key];
341 } else {
342 $secret = \MWCryptRand::generateHex( 32 );
343 $secrets[$key] = $secret;
344 $this->set( 'wsTokenSecrets', $secrets );
345 $new = true;
346 }
347 if ( is_array( $salt ) ) {
348 $salt = join( '|', $salt );
349 }
350 return new Token( $secret, (string)$salt, $new );
351 }
352
353 /**
354 * Remove a CSRF token from the session
355 *
356 * The next call to self::getToken() with $key will generate a new secret.
357 *
358 * @param string $key Token key
359 */
360 public function resetToken( $key = 'default' ) {
361 $secrets = $this->get( 'wsTokenSecrets' );
362 if ( is_array( $secrets ) && isset( $secrets[$key] ) ) {
363 unset( $secrets[$key] );
364 $this->set( 'wsTokenSecrets', $secrets );
365 }
366 }
367
368 /**
369 * Remove all CSRF tokens from the session
370 */
371 public function resetAllTokens() {
372 $this->remove( 'wsTokenSecrets' );
373 }
374
375 /**
376 * Delay automatic saving while multiple updates are being made
377 *
378 * Calls to save() or clear() will not be delayed.
379 *
380 * @return \ScopedCallback When this goes out of scope, a save will be triggered
381 */
382 public function delaySave() {
383 return $this->backend->delaySave();
384 }
385
386 /**
387 * Save the session
388 */
389 public function save() {
390 $this->backend->save();
391 }
392
393 /**
394 * @name Interface methods
395 * @{
396 */
397
398 public function count() {
399 $data = &$this->backend->getData();
400 return count( $data );
401 }
402
403 public function current() {
404 $data = &$this->backend->getData();
405 return current( $data );
406 }
407
408 public function key() {
409 $data = &$this->backend->getData();
410 return key( $data );
411 }
412
413 public function next() {
414 $data = &$this->backend->getData();
415 next( $data );
416 }
417
418 public function rewind() {
419 $data = &$this->backend->getData();
420 reset( $data );
421 }
422
423 public function valid() {
424 $data = &$this->backend->getData();
425 return key( $data ) !== null;
426 }
427
428 /**
429 * @note Despite the name, this seems to be intended to implement isset()
430 * rather than array_key_exists(). So do that.
431 */
432 public function offsetExists( $offset ) {
433 $data = &$this->backend->getData();
434 return isset( $data[$offset] );
435 }
436
437 /**
438 * @note This supports indirect modifications but can't mark the session
439 * dirty when those happen. SessionBackend::save() checks the hash of the
440 * data to detect such changes.
441 * @note Accessing a nonexistent key via this mechanism causes that key to
442 * be created with a null value, and does not raise a PHP warning.
443 */
444 public function &offsetGet( $offset ) {
445 $data = &$this->backend->getData();
446 if ( !array_key_exists( $offset, $data ) ) {
447 $ex = new \Exception( "Undefined index (auto-adds to session with a null value): $offset" );
448 $this->logger->debug( $ex->getMessage(), array( 'exception' => $ex ) );
449 }
450 return $data[$offset];
451 }
452
453 public function offsetSet( $offset, $value ) {
454 $this->set( $offset, $value );
455 }
456
457 public function offsetUnset( $offset ) {
458 $this->remove( $offset );
459 }
460
461 /**@}*/
462
463 }