MediaWiki  1.32.0
PHPSessionHandler.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Psr\Log\LoggerInterface;
28 
34 class 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 
178  public function open( $save_path, $session_name ) {
179  if ( self::$instance !== $this ) {
180  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
181  }
182  if ( !$this->enable ) {
183  throw new \BadMethodCallException( 'Attempt to use PHP session management' );
184  }
185  return true;
186  }
187 
193  public function close() {
194  if ( self::$instance !== $this ) {
195  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
196  }
197  $this->sessionFieldCache = [];
198  return true;
199  }
200 
207  public function read( $id ) {
208  if ( self::$instance !== $this ) {
209  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
210  }
211  if ( !$this->enable ) {
212  throw new \BadMethodCallException( 'Attempt to use PHP session management' );
213  }
214 
215  $session = $this->manager->getSessionById( $id, false );
216  if ( !$session ) {
217  return '';
218  }
219  $session->persist();
220 
221  $data = iterator_to_array( $session );
222  $this->sessionFieldCache[$id] = $data;
223  return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
224  }
225 
235  public function write( $id, $dataStr ) {
236  if ( self::$instance !== $this ) {
237  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
238  }
239  if ( !$this->enable ) {
240  throw new \BadMethodCallException( 'Attempt to use PHP session management' );
241  }
242 
243  $session = $this->manager->getSessionById( $id, true );
244  if ( !$session ) {
245  // This can happen under normal circumstances, if the session exists but is
246  // invalid. Let's emit a log warning instead of a PHP warning.
247  $this->logger->warning(
248  __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
249  [
250  'session' => $id,
251  ] );
252  return true;
253  }
254 
255  // First, decode the string PHP handed us
256  $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
257  if ( $data === null ) {
258  // @codeCoverageIgnoreStart
259  return false;
260  // @codeCoverageIgnoreEnd
261  }
262 
263  // Now merge the data into the Session object.
264  $changed = false;
265  $cache = $this->sessionFieldCache[$id] ?? [];
266  foreach ( $data as $key => $value ) {
267  if ( !array_key_exists( $key, $cache ) ) {
268  if ( $session->exists( $key ) ) {
269  // New in both, so ignore and log
270  $this->logger->warning(
271  __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
272  );
273  } else {
274  // New in $_SESSION, keep it
275  $session->set( $key, $value );
276  $changed = true;
277  }
278  } elseif ( $cache[$key] === $value ) {
279  // Unchanged in $_SESSION, so ignore it
280  } elseif ( !$session->exists( $key ) ) {
281  // Deleted in Session, keep but log
282  $this->logger->warning(
283  __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
284  );
285  $session->set( $key, $value );
286  $changed = true;
287  } elseif ( $cache[$key] === $session->get( $key ) ) {
288  // Unchanged in Session, so keep it
289  $session->set( $key, $value );
290  $changed = true;
291  } else {
292  // Changed in both, so ignore and log
293  $this->logger->warning(
294  __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
295  );
296  }
297  }
298  // Anything deleted in $_SESSION and unchanged in Session should be deleted too
299  // (but not if $_SESSION can't represent it at all)
300  \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
301  foreach ( $cache as $key => $value ) {
302  if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
303  \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
304  ) {
305  if ( $cache[$key] === $session->get( $key ) ) {
306  // Unchanged in Session, delete it
307  $session->remove( $key );
308  $changed = true;
309  } else {
310  // Changed in Session, ignore deletion and log
311  $this->logger->warning(
312  __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
313  );
314  }
315  }
316  }
317  \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
318 
319  // Save and update cache if anything changed
320  if ( $changed ) {
321  if ( $this->warn ) {
322  wfDeprecated( '$_SESSION', '1.27' );
323  $this->logger->warning( 'Something wrote to $_SESSION!' );
324  }
325 
326  $session->save();
327  $this->sessionFieldCache[$id] = iterator_to_array( $session );
328  }
329 
330  $session->persist();
331 
332  return true;
333  }
334 
341  public function destroy( $id ) {
342  if ( self::$instance !== $this ) {
343  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
344  }
345  if ( !$this->enable ) {
346  throw new \BadMethodCallException( 'Attempt to use PHP session management' );
347  }
348  $session = $this->manager->getSessionById( $id, false );
349  if ( $session ) {
350  $session->clear();
351  }
352  return true;
353  }
354 
362  public function gc( $maxlifetime ) {
363  if ( self::$instance !== $this ) {
364  throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
365  }
366  $before = date( 'YmdHis', time() );
367  $this->store->deleteObjectsExpiringBefore( $before );
368  return true;
369  }
370 }
MediaWiki\Session\PHPSessionHandler\$warn
$warn
Definition: PHPSessionHandler.php:40
MediaWiki\Session\PHPSessionHandler\install
static install(SessionManager $manager)
Install a session handler for the current web request.
Definition: PHPSessionHandler.php:108
MediaWiki\Session\PHPSessionHandler\$instance
static PHPSessionHandler $instance
Definition: PHPSessionHandler.php:36
MediaWiki\Session\PHPSessionHandler\setManager
setManager(SessionManager $manager, BagOStuff $store, LoggerInterface $logger)
Set the manager, store, and logger.
Definition: PHPSessionHandler.php:156
MediaWiki\Session\SessionManager\setupPHPSessionHandler
setupPHPSessionHandler(PHPSessionHandler $handler)
Call setters on a PHPSessionHandler.
Definition: SessionManager.php:948
MediaWiki\Session\PHPSessionHandler\$sessionFieldCache
array $sessionFieldCache
Track original session fields for later modification check.
Definition: PHPSessionHandler.php:52
MediaWiki\Session\PHPSessionHandler\isEnabled
static isEnabled()
Test whether the handler is installed and enabled.
Definition: PHPSessionHandler.php:100
MediaWiki\Session\PHPSessionHandler\$logger
LoggerInterface $logger
Definition: PHPSessionHandler.php:49
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
MediaWiki\Session\PHPSessionHandler\gc
gc( $maxlifetime)
Execute garbage collection.
Definition: PHPSessionHandler.php:362
MediaWiki\Session\PHPSessionHandler\open
open( $save_path, $session_name)
Initialize the session (handler)
Definition: PHPSessionHandler.php:178
MediaWiki\Session\PHPSessionHandler\$enable
bool $enable
Whether PHP session handling is enabled.
Definition: PHPSessionHandler.php:39
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1118
store
MediaWiki s SiteStore can be cached and stored in a flat in a json format If the SiteStore is frequently the file cache may provide a performance benefit over a database store
Definition: sitescache.txt:1
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MediaWiki\Session
Definition: BotPasswordSessionProvider.php:24
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
MediaWiki\Session\PHPSessionHandler
Adapter for PHP's session handling.
Definition: PHPSessionHandler.php:34
$value
$value
Definition: styleTest.css.php:49
MediaWiki\Session\PHPSessionHandler\destroy
destroy( $id)
Destroy a session.
Definition: PHPSessionHandler.php:341
MediaWiki\Session\PHPSessionHandler\close
close()
Close the session (handler)
Definition: PHPSessionHandler.php:193
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
MediaWiki\Session\PHPSessionHandler\setEnableFlags
setEnableFlags( $PHPSessionHandling)
Set $this->enable and $this->warn.
Definition: PHPSessionHandler.php:69
MediaWiki\Session\PHPSessionHandler\$store
BagOStuff null $store
Definition: PHPSessionHandler.php:46
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:432
MediaWiki\Session\PHPSessionHandler\write
write( $id, $dataStr)
Write session data.
Definition: PHPSessionHandler.php:235
$cache
$cache
Definition: mcc.php:33
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MediaWiki\Session\PHPSessionHandler\__construct
__construct(SessionManager $manager)
Definition: PHPSessionHandler.php:54
MediaWiki\Session\PHPSessionHandler\isInstalled
static isInstalled()
Test whether the handler is installed.
Definition: PHPSessionHandler.php:92
MediaWiki\Session\PHPSessionHandler\$manager
SessionManager null $manager
Definition: PHPSessionHandler.php:43
MediaWiki\Session\PHPSessionHandler\read
read( $id)
Read session data.
Definition: PHPSessionHandler.php:207