MediaWiki REL1_37
PHPSessionHandler.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
26use BagOStuff;
27use Psr\Log\LoggerInterface;
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 #[\ReturnTypeWillChange]
182 public function open( $save_path, $session_name ) {
183 if ( self::$instance !== $this ) {
184 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
185 }
186 if ( !$this->enable ) {
187 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
188 }
189 return true;
190 }
191
197 #[\ReturnTypeWillChange]
198 public function close() {
199 if ( self::$instance !== $this ) {
200 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
201 }
202 $this->sessionFieldCache = [];
203 return true;
204 }
205
212 #[\ReturnTypeWillChange]
213 public function read( $id ) {
214 if ( self::$instance !== $this ) {
215 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
216 }
217 if ( !$this->enable ) {
218 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
219 }
220
221 $session = $this->manager->getSessionById( $id, false );
222 if ( !$session ) {
223 return '';
224 }
225 $session->persist();
226
227 $data = iterator_to_array( $session );
228 $this->sessionFieldCache[$id] = $data;
229 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
230 }
231
241 #[\ReturnTypeWillChange]
242 public function write( $id, $dataStr ) {
243 if ( self::$instance !== $this ) {
244 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
245 }
246 if ( !$this->enable ) {
247 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
248 }
249
250 $session = $this->manager->getSessionById( $id, true );
251 if ( !$session ) {
252 // This can happen under normal circumstances, if the session exists but is
253 // invalid. Let's emit a log warning instead of a PHP warning.
254 $this->logger->warning(
255 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
256 [
257 'session' => $id,
258 ] );
259 return true;
260 }
261
262 // First, decode the string PHP handed us
263 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
264 if ( $data === null ) {
265 // @codeCoverageIgnoreStart
266 return false;
267 // @codeCoverageIgnoreEnd
268 }
269
270 // Now merge the data into the Session object.
271 $changed = false;
272 $cache = $this->sessionFieldCache[$id] ?? [];
273 foreach ( $data as $key => $value ) {
274 if ( !array_key_exists( $key, $cache ) ) {
275 if ( $session->exists( $key ) ) {
276 // New in both, so ignore and log
277 $this->logger->warning(
278 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
279 );
280 } else {
281 // New in $_SESSION, keep it
282 $session->set( $key, $value );
283 $changed = true;
284 }
285 } elseif ( $cache[$key] === $value ) {
286 // Unchanged in $_SESSION, so ignore it
287 } elseif ( !$session->exists( $key ) ) {
288 // Deleted in Session, keep but log
289 $this->logger->warning(
290 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
291 );
292 $session->set( $key, $value );
293 $changed = true;
294 } elseif ( $cache[$key] === $session->get( $key ) ) {
295 // Unchanged in Session, so keep it
296 $session->set( $key, $value );
297 $changed = true;
298 } else {
299 // Changed in both, so ignore and log
300 $this->logger->warning(
301 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
302 );
303 }
304 }
305 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
306 // (but not if $_SESSION can't represent it at all)
307 \Wikimedia\PhpSessionSerializer::setLogger( new NullLogger() );
308 foreach ( $cache as $key => $value ) {
309 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
310 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
311 ) {
312 if ( $value === $session->get( $key ) ) {
313 // Unchanged in Session, delete it
314 $session->remove( $key );
315 $changed = true;
316 } else {
317 // Changed in Session, ignore deletion and log
318 $this->logger->warning(
319 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
320 );
321 }
322 }
323 }
324 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
325
326 // Save and update cache if anything changed
327 if ( $changed ) {
328 if ( $this->warn ) {
329 wfDeprecated( '$_SESSION', '1.27' );
330 $this->logger->warning( 'Something wrote to $_SESSION!' );
331 }
332
333 $session->save();
334 $this->sessionFieldCache[$id] = iterator_to_array( $session );
335 }
336
337 $session->persist();
338
339 return true;
340 }
341
348 #[\ReturnTypeWillChange]
349 public function destroy( $id ) {
350 if ( self::$instance !== $this ) {
351 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
352 }
353 if ( !$this->enable ) {
354 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
355 }
356 $session = $this->manager->getSessionById( $id, false );
357 if ( $session ) {
358 $session->clear();
359 }
360 return true;
361 }
362
370 #[\ReturnTypeWillChange]
371 public function gc( $maxlifetime ) {
372 if ( self::$instance !== $this ) {
373 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
374 }
375 $before = date( 'YmdHis', time() );
376 $this->store->deleteObjectsExpiringBefore( $before );
377 return true;
378 }
379}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:86
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...