3 * Session storage in object cache.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
30 * Adapter for PHP's session handling
34 class PHPSessionHandler
implements \SessionHandlerInterface
{
35 /** @var PHPSessionHandler */
36 protected static $instance = null;
38 /** @var bool Whether PHP session handling is enabled */
39 protected $enable = false;
40 protected $warn = true;
42 /** @var SessionManager|null */
45 /** @var BagOStuff|null */
48 /** @var LoggerInterface */
51 /** @var array Track original session fields for later modification check */
52 protected $sessionFieldCache = [];
54 protected function __construct( SessionManager
$manager ) {
55 $this->setEnableFlags(
56 \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' )
58 $manager->setupPHPSessionHandler( $this );
62 * Set $this->enable and $this->warn
64 * Separate just because there doesn't seem to be a good way to test it
67 * @param string $PHPSessionHandling See $wgPHPSessionHandling
69 private function setEnableFlags( $PHPSessionHandling ) {
70 switch ( $PHPSessionHandling ) {
82 $this->enable
= false;
89 * Test whether the handler is installed
92 public static function isInstalled() {
93 return (bool)self
::$instance;
97 * Test whether the handler is installed and enabled
100 public static function isEnabled() {
101 return self
::$instance && self
::$instance->enable
;
105 * Install a session handler for the current web request
106 * @param SessionManager $manager
108 public static function install( SessionManager
$manager ) {
109 if ( self
::$instance ) {
110 $manager->setupPHPSessionHandler( self
::$instance );
114 // @codeCoverageIgnoreStart
115 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
116 throw new \
BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
118 // @codeCoverageIgnoreEnd
120 self
::$instance = new self( $manager );
122 // Close any auto-started session, before we replace it
123 session_write_close();
126 \Wikimedia\
suppressWarnings();
128 // Tell PHP not to mess with cookies itself
129 ini_set( 'session.use_cookies', 0 );
130 ini_set( 'session.use_trans_sid', 0 );
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
136 session_cache_limiter( '' );
138 // Also set a sane serialization handler
139 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
141 // Register this as the save handler, and register an appropriate
142 // shutdown function.
143 session_set_save_handler( self
::$instance, true );
145 \Wikimedia\restoreWarnings
();
150 * Set the manager, store, and logger
151 * @private Use self::install().
152 * @param SessionManager $manager
153 * @param BagOStuff $store
154 * @param LoggerInterface $logger
156 public function setManager(
157 SessionManager
$manager, BagOStuff
$store, LoggerInterface
$logger
159 if ( $this->manager
!== $manager ) {
160 // Close any existing session before we change stores
161 if ( $this->manager
) {
162 session_write_close();
164 $this->manager
= $manager;
165 $this->store
= $store;
166 $this->logger
= $logger;
167 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
172 * Initialize the session (handler)
173 * @private For internal use only
174 * @param string $save_path Path used to store session files (ignored)
175 * @param string $session_name Session name (ignored)
178 public function open( $save_path, $session_name ) {
179 if ( self
::$instance !== $this ) {
180 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
182 if ( !$this->enable
) {
183 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
189 * Close the session (handler)
190 * @private For internal use only
193 public function close() {
194 if ( self
::$instance !== $this ) {
195 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
197 $this->sessionFieldCache
= [];
203 * @private For internal use only
204 * @param string $id Session id
205 * @return string Session data
207 public function read( $id ) {
208 if ( self
::$instance !== $this ) {
209 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
211 if ( !$this->enable
) {
212 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
215 $session = $this->manager
->getSessionById( $id, false );
221 $data = iterator_to_array( $session );
222 $this->sessionFieldCache
[$id] = $data;
223 return (string)\Wikimedia\PhpSessionSerializer
::encode( $data );
228 * @private For internal use only
229 * @param string $id Session id
230 * @param string $dataStr Session data. Not that you should ever call this
231 * directly, but note that this has the same issues with code injection
232 * via user-controlled data as does PHP's unserialize function.
235 public function write( $id, $dataStr ) {
236 if ( self
::$instance !== $this ) {
237 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
239 if ( !$this->enable
) {
240 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
243 $session = $this->manager
->getSessionById( $id, true );
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.',
255 // First, decode the string PHP handed us
256 $data = \Wikimedia\PhpSessionSerializer
::decode( $dataStr );
257 if ( $data === null ) {
258 // @codeCoverageIgnoreStart
260 // @codeCoverageIgnoreEnd
263 // Now merge the data into the Session object.
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!"
274 // New in $_SESSION, keep it
275 $session->set( $key, $value );
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!"
285 $session->set( $key, $value );
287 } elseif ( $cache[$key] === $session->get( $key ) ) {
288 // Unchanged in Session, so keep it
289 $session->set( $key, $value );
292 // Changed in both, so ignore and log
293 $this->logger
->warning(
294 __METHOD__
. ": Key \"$key\" changed in both Session and \$_SESSION!"
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 ] )
305 if ( $cache[$key] === $session->get( $key ) ) {
306 // Unchanged in Session, delete it
307 $session->remove( $key );
310 // Changed in Session, ignore deletion and log
311 $this->logger
->warning(
312 __METHOD__
. ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
317 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
319 // Save and update cache if anything changed
322 wfDeprecated( '$_SESSION', '1.27' );
323 $this->logger
->warning( 'Something wrote to $_SESSION!' );
327 $this->sessionFieldCache
[$id] = iterator_to_array( $session );
337 * @private For internal use only
338 * @param string $id Session id
341 public function destroy( $id ) {
342 if ( self
::$instance !== $this ) {
343 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
345 if ( !$this->enable
) {
346 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
348 $session = $this->manager
->getSessionById( $id, false );
356 * Execute garbage collection.
357 * @private For internal use only
358 * @param int $maxlifetime Maximum session life time (ignored)
360 * @codeCoverageIgnore See T135576
362 public function gc( $maxlifetime ) {
363 if ( self
::$instance !== $this ) {
364 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
366 $before = date( 'YmdHis', time() );
367 $this->store
->deleteObjectsExpiringBefore( $before );