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;
42 protected $warn = true;
44 /** @var SessionManager|null */
47 /** @var BagOStuff|null */
50 /** @var LoggerInterface */
53 /** @var array Track original session fields for later modification check */
54 protected $sessionFieldCache = [];
56 protected function __construct( SessionManager
$manager ) {
57 $this->setEnableFlags(
58 \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' )
60 $manager->setupPHPSessionHandler( $this );
64 * Set $this->enable and $this->warn
66 * Separate just because there doesn't seem to be a good way to test it
69 * @param string $PHPSessionHandling See $wgPHPSessionHandling
71 private function setEnableFlags( $PHPSessionHandling ) {
72 switch ( $PHPSessionHandling ) {
84 $this->enable
= false;
91 * Test whether the handler is installed
94 public static function isInstalled() {
95 return (bool)self
::$instance;
99 * Test whether the handler is installed and enabled
102 public static function isEnabled() {
103 return self
::$instance && self
::$instance->enable
;
107 * Install a session handler for the current web request
108 * @param SessionManager $manager
110 public static function install( SessionManager
$manager ) {
111 if ( self
::$instance ) {
112 $manager->setupPHPSessionHandler( self
::$instance );
116 // @codeCoverageIgnoreStart
117 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
118 throw new \
BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
120 // @codeCoverageIgnoreEnd
122 self
::$instance = new self( $manager );
124 // Close any auto-started session, before we replace it
125 session_write_close();
128 \Wikimedia\
suppressWarnings();
130 // Tell PHP not to mess with cookies itself
131 ini_set( 'session.use_cookies', 0 );
132 ini_set( 'session.use_trans_sid', 0 );
134 // T124510: Disable automatic PHP session related cache headers.
135 // MediaWiki adds it's own headers and the default PHP behavior may
136 // set headers such as 'Pragma: no-cache' that cause problems with
138 session_cache_limiter( '' );
140 // Also set a sane serialization handler
141 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
143 // Register this as the save handler, and register an appropriate
144 // shutdown function.
145 session_set_save_handler( self
::$instance, true );
147 \Wikimedia\restoreWarnings
();
152 * Set the manager, store, and logger
153 * @private Use self::install().
154 * @param SessionManager $manager
155 * @param BagOStuff $store
156 * @param LoggerInterface $logger
158 public function setManager(
159 SessionManager
$manager, BagOStuff
$store, LoggerInterface
$logger
161 if ( $this->manager
!== $manager ) {
162 // Close any existing session before we change stores
163 if ( $this->manager
) {
164 session_write_close();
166 $this->manager
= $manager;
167 $this->store
= $store;
168 $this->logger
= $logger;
169 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
174 * Initialize the session (handler)
175 * @private For internal use only
176 * @param string $save_path Path used to store session files (ignored)
177 * @param string $session_name Session name (ignored)
180 public function open( $save_path, $session_name ) {
181 if ( self
::$instance !== $this ) {
182 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
184 if ( !$this->enable
) {
185 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
191 * Close the session (handler)
192 * @private For internal use only
195 public function close() {
196 if ( self
::$instance !== $this ) {
197 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
199 $this->sessionFieldCache
= [];
205 * @private For internal use only
206 * @param string $id Session id
207 * @return string Session data
209 public function read( $id ) {
210 if ( self
::$instance !== $this ) {
211 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
213 if ( !$this->enable
) {
214 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
217 $session = $this->manager
->getSessionById( $id, false );
223 $data = iterator_to_array( $session );
224 $this->sessionFieldCache
[$id] = $data;
225 return (string)\Wikimedia\PhpSessionSerializer
::encode( $data );
230 * @private For internal use only
231 * @param string $id Session id
232 * @param string $dataStr Session data. Not that you should ever call this
233 * directly, but note that this has the same issues with code injection
234 * via user-controlled data as does PHP's unserialize function.
237 public function write( $id, $dataStr ) {
238 if ( self
::$instance !== $this ) {
239 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
241 if ( !$this->enable
) {
242 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
245 $session = $this->manager
->getSessionById( $id, true );
247 // This can happen under normal circumstances, if the session exists but is
248 // invalid. Let's emit a log warning instead of a PHP warning.
249 $this->logger
->warning(
250 __METHOD__
. ': Session "{session}" cannot be loaded, skipping write.',
257 // First, decode the string PHP handed us
258 $data = \Wikimedia\PhpSessionSerializer
::decode( $dataStr );
259 if ( $data === null ) {
260 // @codeCoverageIgnoreStart
262 // @codeCoverageIgnoreEnd
265 // Now merge the data into the Session object.
267 $cache = $this->sessionFieldCache
[$id] ??
[];
268 foreach ( $data as $key => $value ) {
269 if ( !array_key_exists( $key, $cache ) ) {
270 if ( $session->exists( $key ) ) {
271 // New in both, so ignore and log
272 $this->logger
->warning(
273 __METHOD__
. ": Key \"$key\" added in both Session and \$_SESSION!"
276 // New in $_SESSION, keep it
277 $session->set( $key, $value );
280 } elseif ( $cache[$key] === $value ) {
281 // Unchanged in $_SESSION, so ignore it
282 } elseif ( !$session->exists( $key ) ) {
283 // Deleted in Session, keep but log
284 $this->logger
->warning(
285 __METHOD__
. ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
287 $session->set( $key, $value );
289 } elseif ( $cache[$key] === $session->get( $key ) ) {
290 // Unchanged in Session, so keep it
291 $session->set( $key, $value );
294 // Changed in both, so ignore and log
295 $this->logger
->warning(
296 __METHOD__
. ": Key \"$key\" changed in both Session and \$_SESSION!"
300 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
301 // (but not if $_SESSION can't represent it at all)
302 \Wikimedia\PhpSessionSerializer
::setLogger( new \Psr\Log\
NullLogger() );
303 foreach ( $cache as $key => $value ) {
304 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
305 \Wikimedia\PhpSessionSerializer
::encode( [ $key => true ] )
307 if ( $cache[$key] === $session->get( $key ) ) {
308 // Unchanged in Session, delete it
309 $session->remove( $key );
312 // Changed in Session, ignore deletion and log
313 $this->logger
->warning(
314 __METHOD__
. ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
319 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
321 // Save and update cache if anything changed
324 wfDeprecated( '$_SESSION', '1.27' );
325 $this->logger
->warning( 'Something wrote to $_SESSION!' );
329 $this->sessionFieldCache
[$id] = iterator_to_array( $session );
339 * @private For internal use only
340 * @param string $id Session id
343 public function destroy( $id ) {
344 if ( self
::$instance !== $this ) {
345 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
347 if ( !$this->enable
) {
348 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
350 $session = $this->manager
->getSessionById( $id, false );
358 * Execute garbage collection.
359 * @private For internal use only
360 * @param int $maxlifetime Maximum session life time (ignored)
362 * @codeCoverageIgnore See T135576
364 public function gc( $maxlifetime ) {
365 if ( self
::$instance !== $this ) {
366 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
368 $before = date( 'YmdHis', time() );
369 $this->store
->deleteObjectsExpiringBefore( $before );