MediaWiki REL1_34
PHPSessionHandler.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
26use Psr\Log\LoggerInterface;
27use BagOStuff;
28use Psr\Log\NullLogger;
29
35class PHPSessionHandler implements \SessionHandlerInterface {
37 protected static $instance = null;
38
40 protected $enable = false;
41
43 protected $warn = true;
44
46 protected $manager;
47
49 protected $store;
50
52 protected $logger;
53
55 protected $sessionFieldCache = [];
56
57 protected function __construct( SessionManager $manager ) {
58 $this->setEnableFlags(
59 \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
60 );
61 $manager->setupPHPSessionHandler( $this );
62 }
63
72 private function setEnableFlags( $PHPSessionHandling ) {
73 switch ( $PHPSessionHandling ) {
74 case 'enable':
75 $this->enable = true;
76 $this->warn = false;
77 break;
78
79 case 'warn':
80 $this->enable = true;
81 $this->warn = true;
82 break;
83
84 case 'disable':
85 $this->enable = false;
86 $this->warn = false;
87 break;
88 }
89 }
90
95 public static function isInstalled() {
96 return (bool)self::$instance;
97 }
98
103 public static function isEnabled() {
104 return self::$instance && self::$instance->enable;
105 }
106
111 public static function install( SessionManager $manager ) {
112 if ( self::$instance ) {
113 $manager->setupPHPSessionHandler( self::$instance );
114 return;
115 }
116
117 // @codeCoverageIgnoreStart
118 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
119 throw new \BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
120 }
121 // @codeCoverageIgnoreEnd
122
123 self::$instance = new self( $manager );
124
125 // Close any auto-started session, before we replace it
126 session_write_close();
127
128 try {
129 \Wikimedia\suppressWarnings();
130
131 // Tell PHP not to mess with cookies itself
132 ini_set( 'session.use_cookies', 0 );
133 ini_set( 'session.use_trans_sid', 0 );
134
135 // T124510: Disable automatic PHP session related cache headers.
136 // MediaWiki adds it's own headers and the default PHP behavior may
137 // set headers such as 'Pragma: no-cache' that cause problems with
138 // some user agents.
139 session_cache_limiter( '' );
140
141 // Also set a sane serialization handler
142 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
143
144 // Register this as the save handler, and register an appropriate
145 // shutdown function.
146 session_set_save_handler( self::$instance, true );
147 } finally {
148 \Wikimedia\restoreWarnings();
149 }
150 }
151
159 public function setManager(
161 ) {
162 if ( $this->manager !== $manager ) {
163 // Close any existing session before we change stores
164 if ( $this->manager ) {
165 session_write_close();
166 }
167 $this->manager = $manager;
168 $this->store = $store;
169 $this->logger = $logger;
170 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
171 }
172 }
173
181 public function open( $save_path, $session_name ) {
182 if ( self::$instance !== $this ) {
183 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
184 }
185 if ( !$this->enable ) {
186 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
187 }
188 return true;
189 }
190
196 public function close() {
197 if ( self::$instance !== $this ) {
198 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
199 }
200 $this->sessionFieldCache = [];
201 return true;
202 }
203
210 public function read( $id ) {
211 if ( self::$instance !== $this ) {
212 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
213 }
214 if ( !$this->enable ) {
215 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
216 }
217
218 $session = $this->manager->getSessionById( $id, false );
219 if ( !$session ) {
220 return '';
221 }
222 $session->persist();
223
224 $data = iterator_to_array( $session );
225 $this->sessionFieldCache[$id] = $data;
226 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
227 }
228
238 public function write( $id, $dataStr ) {
239 if ( self::$instance !== $this ) {
240 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
241 }
242 if ( !$this->enable ) {
243 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
244 }
245
246 $session = $this->manager->getSessionById( $id, true );
247 if ( !$session ) {
248 // This can happen under normal circumstances, if the session exists but is
249 // invalid. Let's emit a log warning instead of a PHP warning.
250 $this->logger->warning(
251 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
252 [
253 'session' => $id,
254 ] );
255 return true;
256 }
257
258 // First, decode the string PHP handed us
259 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
260 if ( $data === null ) {
261 // @codeCoverageIgnoreStart
262 return false;
263 // @codeCoverageIgnoreEnd
264 }
265
266 // Now merge the data into the Session object.
267 $changed = false;
268 $cache = $this->sessionFieldCache[$id] ?? [];
269 foreach ( $data as $key => $value ) {
270 if ( !array_key_exists( $key, $cache ) ) {
271 if ( $session->exists( $key ) ) {
272 // New in both, so ignore and log
273 $this->logger->warning(
274 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
275 );
276 } else {
277 // New in $_SESSION, keep it
278 $session->set( $key, $value );
279 $changed = true;
280 }
281 } elseif ( $cache[$key] === $value ) {
282 // Unchanged in $_SESSION, so ignore it
283 } elseif ( !$session->exists( $key ) ) {
284 // Deleted in Session, keep but log
285 $this->logger->warning(
286 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
287 );
288 $session->set( $key, $value );
289 $changed = true;
290 } elseif ( $cache[$key] === $session->get( $key ) ) {
291 // Unchanged in Session, so keep it
292 $session->set( $key, $value );
293 $changed = true;
294 } else {
295 // Changed in both, so ignore and log
296 $this->logger->warning(
297 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
298 );
299 }
300 }
301 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
302 // (but not if $_SESSION can't represent it at all)
303 \Wikimedia\PhpSessionSerializer::setLogger( new NullLogger() );
304 foreach ( $cache as $key => $value ) {
305 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
306 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
307 ) {
308 if ( $cache[$key] === $session->get( $key ) ) {
309 // Unchanged in Session, delete it
310 $session->remove( $key );
311 $changed = true;
312 } else {
313 // Changed in Session, ignore deletion and log
314 $this->logger->warning(
315 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
316 );
317 }
318 }
319 }
320 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
321
322 // Save and update cache if anything changed
323 if ( $changed ) {
324 if ( $this->warn ) {
325 wfDeprecated( '$_SESSION', '1.27' );
326 $this->logger->warning( 'Something wrote to $_SESSION!' );
327 }
328
329 $session->save();
330 $this->sessionFieldCache[$id] = iterator_to_array( $session );
331 }
332
333 $session->persist();
334
335 return true;
336 }
337
344 public function destroy( $id ) {
345 if ( self::$instance !== $this ) {
346 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
347 }
348 if ( !$this->enable ) {
349 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
350 }
351 $session = $this->manager->getSessionById( $id, false );
352 if ( $session ) {
353 $session->clear();
354 }
355 return true;
356 }
357
365 public function gc( $maxlifetime ) {
366 if ( self::$instance !== $this ) {
367 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
368 }
369 $before = date( 'YmdHis', time() );
370 $this->store->deleteObjectsExpiringBefore( $before );
371 return true;
372 }
373}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:63
Adapter for PHP's session handling.
gc( $maxlifetime)
Execute garbage collection.
write( $id, $dataStr)
Write session data.
setEnableFlags( $PHPSessionHandling)
Set $this->enable and $this->warn.
static isInstalled()
Test whether the handler is installed.
static isEnabled()
Test whether the handler is installed and enabled.
SessionManagerInterface null $manager
close()
Close the session (handler)
array $sessionFieldCache
Track original session fields for later modification check.
open( $save_path, $session_name)
Initialize the session (handler)
static install(SessionManager $manager)
Install a session handler for the current web request.
bool $enable
Whether PHP session handling is enabled.
setManager(SessionManagerInterface $manager, BagOStuff $store, LoggerInterface $logger)
Set the manager, store, and logger.
This serves as the entry point to the MediaWiki session handling system.
This exists to make IDEs happy, so they don't see the internal-but-required-to-be-public methods on S...
$cache
Definition mcc.php:33
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...