MediaWiki REL1_31
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 try {
126 \Wikimedia\suppressWarnings();
127
128 // Tell PHP not to mess with cookies itself
129 ini_set( 'session.use_cookies', 0 );
130 ini_set( 'session.use_trans_sid', 0 );
131
132 // T124510: Disable automatic PHP session related cache headers.
133 // MediaWiki adds it's own headers and the default PHP behavior may
134 // set headers such as 'Pragma: no-cache' that cause problems with
135 // some user agents.
136 session_cache_limiter( '' );
137
138 // Also set a sane serialization handler
139 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
140
141 // Register this as the save handler, and register an appropriate
142 // shutdown function.
143 session_set_save_handler( self::$instance, true );
144 } finally {
145 \Wikimedia\restoreWarnings();
146 }
147 }
148
156 public function setManager(
158 ) {
159 if ( $this->manager !== $manager ) {
160 // Close any existing session before we change stores
161 if ( $this->manager ) {
162 session_write_close();
163 }
164 $this->manager = $manager;
165 $this->store = $store;
166 $this->logger = $logger;
167 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
168 }
169 }
170
184 protected static function returnSuccess() {
185 return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? true : 0;
186 }
187
194 protected static function returnFailure() {
195 return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? false : -1;
196 }
197
205 public function open( $save_path, $session_name ) {
206 if ( self::$instance !== $this ) {
207 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
208 }
209 if ( !$this->enable ) {
210 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
211 }
212 return self::returnSuccess();
213 }
214
220 public function close() {
221 if ( self::$instance !== $this ) {
222 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
223 }
224 $this->sessionFieldCache = [];
225 return self::returnSuccess();
226 }
227
234 public function read( $id ) {
235 if ( self::$instance !== $this ) {
236 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
237 }
238 if ( !$this->enable ) {
239 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
240 }
241
242 $session = $this->manager->getSessionById( $id, false );
243 if ( !$session ) {
244 return '';
245 }
246 $session->persist();
247
248 $data = iterator_to_array( $session );
249 $this->sessionFieldCache[$id] = $data;
250 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
251 }
252
262 public function write( $id, $dataStr ) {
263 if ( self::$instance !== $this ) {
264 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
265 }
266 if ( !$this->enable ) {
267 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
268 }
269
270 $session = $this->manager->getSessionById( $id, true );
271 if ( !$session ) {
272 // This can happen under normal circumstances, if the session exists but is
273 // invalid. Let's emit a log warning instead of a PHP warning.
274 $this->logger->warning(
275 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
276 [
277 'session' => $id,
278 ] );
279 return self::returnSuccess();
280 }
281
282 // First, decode the string PHP handed us
283 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
284 if ( $data === null ) {
285 // @codeCoverageIgnoreStart
286 return self::returnFailure();
287 // @codeCoverageIgnoreEnd
288 }
289
290 // Now merge the data into the Session object.
291 $changed = false;
292 $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : [];
293 foreach ( $data as $key => $value ) {
294 if ( !array_key_exists( $key, $cache ) ) {
295 if ( $session->exists( $key ) ) {
296 // New in both, so ignore and log
297 $this->logger->warning(
298 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
299 );
300 } else {
301 // New in $_SESSION, keep it
302 $session->set( $key, $value );
303 $changed = true;
304 }
305 } elseif ( $cache[$key] === $value ) {
306 // Unchanged in $_SESSION, so ignore it
307 } elseif ( !$session->exists( $key ) ) {
308 // Deleted in Session, keep but log
309 $this->logger->warning(
310 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
311 );
312 $session->set( $key, $value );
313 $changed = true;
314 } elseif ( $cache[$key] === $session->get( $key ) ) {
315 // Unchanged in Session, so keep it
316 $session->set( $key, $value );
317 $changed = true;
318 } else {
319 // Changed in both, so ignore and log
320 $this->logger->warning(
321 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
322 );
323 }
324 }
325 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
326 // (but not if $_SESSION can't represent it at all)
327 \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
328 foreach ( $cache as $key => $value ) {
329 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
330 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
331 ) {
332 if ( $cache[$key] === $session->get( $key ) ) {
333 // Unchanged in Session, delete it
334 $session->remove( $key );
335 $changed = true;
336 } else {
337 // Changed in Session, ignore deletion and log
338 $this->logger->warning(
339 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
340 );
341 }
342 }
343 }
344 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
345
346 // Save and update cache if anything changed
347 if ( $changed ) {
348 if ( $this->warn ) {
349 wfDeprecated( '$_SESSION', '1.27' );
350 $this->logger->warning( 'Something wrote to $_SESSION!' );
351 }
352
353 $session->save();
354 $this->sessionFieldCache[$id] = iterator_to_array( $session );
355 }
356
357 $session->persist();
358
359 return self::returnSuccess();
360 }
361
368 public function destroy( $id ) {
369 if ( self::$instance !== $this ) {
370 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
371 }
372 if ( !$this->enable ) {
373 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
374 }
375 $session = $this->manager->getSessionById( $id, false );
376 if ( $session ) {
377 $session->clear();
378 }
379 return self::returnSuccess();
380 }
381
389 public function gc( $maxlifetime ) {
390 if ( self::$instance !== $this ) {
391 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
392 }
393 $before = date( 'YmdHis', time() );
394 $this->store->deleteObjectsExpiringBefore( $before );
395 return self::returnSuccess();
396 }
397}
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()
Get the RequestContext object associated with the main request.
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:2006
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
$cache
Definition mcc.php:33