MediaWiki REL1_30
PHPSessionHandler.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
26use Psr\Log\LoggerInterface;
27use BagOStuff;
28
34class PHPSessionHandler implements \SessionHandlerInterface {
36 protected static $instance = null;
37
39 protected $enable = false;
40 protected $warn = true;
41
43 protected $manager;
44
46 protected $store;
47
49 protected $logger;
50
52 protected $sessionFieldCache = [];
53
54 protected function __construct( SessionManager $manager ) {
55 $this->setEnableFlags(
56 \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
57 );
59 }
60
69 private function setEnableFlags( $PHPSessionHandling ) {
70 switch ( $PHPSessionHandling ) {
71 case 'enable':
72 $this->enable = true;
73 $this->warn = false;
74 break;
75
76 case 'warn':
77 $this->enable = true;
78 $this->warn = true;
79 break;
80
81 case 'disable':
82 $this->enable = false;
83 $this->warn = false;
84 break;
85 }
86 }
87
92 public static function isInstalled() {
93 return (bool)self::$instance;
94 }
95
100 public static function isEnabled() {
101 return self::$instance && self::$instance->enable;
102 }
103
108 public static function install( SessionManager $manager ) {
109 if ( self::$instance ) {
110 $manager->setupPHPSessionHandler( self::$instance );
111 return;
112 }
113
114 // @codeCoverageIgnoreStart
115 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
116 throw new \BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
117 }
118 // @codeCoverageIgnoreEnd
119
120 self::$instance = new self( $manager );
121
122 // Close any auto-started session, before we replace it
123 session_write_close();
124
125 // Tell PHP not to mess with cookies itself
126 ini_set( 'session.use_cookies', 0 );
127 ini_set( 'session.use_trans_sid', 0 );
128
129 // T124510: Disable automatic PHP session related cache headers.
130 // MediaWiki adds it's own headers and the default PHP behavior may
131 // set headers such as 'Pragma: no-cache' that cause problems with
132 // some user agents.
133 session_cache_limiter( '' );
134
135 // Also set a sane serialization handler
136 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
137
138 // Register this as the save handler, and register an appropriate
139 // shutdown function.
140 session_set_save_handler( self::$instance, true );
141 }
142
150 public function setManager(
152 ) {
153 if ( $this->manager !== $manager ) {
154 // Close any existing session before we change stores
155 if ( $this->manager ) {
156 session_write_close();
157 }
158 $this->manager = $manager;
159 $this->store = $store;
160 $this->logger = $logger;
161 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
162 }
163 }
164
178 protected static function returnSuccess() {
179 return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? true : 0;
180 }
181
188 protected static function returnFailure() {
189 return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? false : -1;
190 }
191
199 public function open( $save_path, $session_name ) {
200 if ( self::$instance !== $this ) {
201 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
202 }
203 if ( !$this->enable ) {
204 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
205 }
206 return self::returnSuccess();
207 }
208
214 public function close() {
215 if ( self::$instance !== $this ) {
216 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
217 }
218 $this->sessionFieldCache = [];
219 return self::returnSuccess();
220 }
221
228 public function read( $id ) {
229 if ( self::$instance !== $this ) {
230 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
231 }
232 if ( !$this->enable ) {
233 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
234 }
235
236 $session = $this->manager->getSessionById( $id, false );
237 if ( !$session ) {
238 return '';
239 }
240 $session->persist();
241
242 $data = iterator_to_array( $session );
243 $this->sessionFieldCache[$id] = $data;
244 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
245 }
246
256 public function write( $id, $dataStr ) {
257 if ( self::$instance !== $this ) {
258 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
259 }
260 if ( !$this->enable ) {
261 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
262 }
263
264 $session = $this->manager->getSessionById( $id, true );
265 if ( !$session ) {
266 // This can happen under normal circumstances, if the session exists but is
267 // invalid. Let's emit a log warning instead of a PHP warning.
268 $this->logger->warning(
269 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
270 [
271 'session' => $id,
272 ] );
273 return self::returnSuccess();
274 }
275
276 // First, decode the string PHP handed us
277 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
278 if ( $data === null ) {
279 // @codeCoverageIgnoreStart
280 return self::returnFailure();
281 // @codeCoverageIgnoreEnd
282 }
283
284 // Now merge the data into the Session object.
285 $changed = false;
286 $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : [];
287 foreach ( $data as $key => $value ) {
288 if ( !array_key_exists( $key, $cache ) ) {
289 if ( $session->exists( $key ) ) {
290 // New in both, so ignore and log
291 $this->logger->warning(
292 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
293 );
294 } else {
295 // New in $_SESSION, keep it
296 $session->set( $key, $value );
297 $changed = true;
298 }
299 } elseif ( $cache[$key] === $value ) {
300 // Unchanged in $_SESSION, so ignore it
301 } elseif ( !$session->exists( $key ) ) {
302 // Deleted in Session, keep but log
303 $this->logger->warning(
304 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
305 );
306 $session->set( $key, $value );
307 $changed = true;
308 } elseif ( $cache[$key] === $session->get( $key ) ) {
309 // Unchanged in Session, so keep it
310 $session->set( $key, $value );
311 $changed = true;
312 } else {
313 // Changed in both, so ignore and log
314 $this->logger->warning(
315 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
316 );
317 }
318 }
319 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
320 // (but not if $_SESSION can't represent it at all)
321 \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
322 foreach ( $cache as $key => $value ) {
323 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
324 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
325 ) {
326 if ( $cache[$key] === $session->get( $key ) ) {
327 // Unchanged in Session, delete it
328 $session->remove( $key );
329 $changed = true;
330 } else {
331 // Changed in Session, ignore deletion and log
332 $this->logger->warning(
333 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
334 );
335 }
336 }
337 }
338 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
339
340 // Save and update cache if anything changed
341 if ( $changed ) {
342 if ( $this->warn ) {
343 wfDeprecated( '$_SESSION', '1.27' );
344 $this->logger->warning( 'Something wrote to $_SESSION!' );
345 }
346
347 $session->save();
348 $this->sessionFieldCache[$id] = iterator_to_array( $session );
349 }
350
351 $session->persist();
352
353 return self::returnSuccess();
354 }
355
362 public function destroy( $id ) {
363 if ( self::$instance !== $this ) {
364 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
365 }
366 if ( !$this->enable ) {
367 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
368 }
369 $session = $this->manager->getSessionById( $id, false );
370 if ( $session ) {
371 $session->clear();
372 }
373 return self::returnSuccess();
374 }
375
383 public function gc( $maxlifetime ) {
384 if ( self::$instance !== $this ) {
385 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
386 }
387 $before = date( 'YmdHis', time() );
388 $this->store->deleteObjectsExpiringBefore( $before );
389 return self::returnSuccess();
390 }
391}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
interface is intended to be more or less compatible with the PHP memcached client.
Definition BagOStuff.php:47
Adapter for PHP's session handling.
gc( $maxlifetime)
Execute garbage collection.
write( $id, $dataStr)
Write session data.
static returnSuccess()
Workaround for PHP5 bug.
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.
setManager(SessionManager $manager, BagOStuff $store, LoggerInterface $logger)
Set the manager, store, and logger.
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.
static returnFailure()
Workaround for PHP5 bug.
This serves as the entry point to the MediaWiki session handling system.
setupPHPSessionHandler(PHPSessionHandler $handler)
Call setters on a PHPSessionHandler.
static getMain()
Static methods.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:1976
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
$cache
Definition mcc.php:33