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
;
28 use Psr\Log\NullLogger
;
31 * Adapter for PHP's session handling
35 class PHPSessionHandler
implements \SessionHandlerInterface
{
36 /** @var PHPSessionHandler */
37 protected static $instance = null;
39 /** @var bool Whether PHP session handling is enabled */
40 protected $enable = false;
43 protected $warn = true;
45 /** @var SessionManagerInterface|null */
48 /** @var BagOStuff|null */
51 /** @var LoggerInterface */
54 /** @var array Track original session fields for later modification check */
55 protected $sessionFieldCache = [];
57 protected function __construct( SessionManagerInterface
$manager ) {
58 $this->setEnableFlags(
59 \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' )
61 $manager->setupPHPSessionHandler( $this );
65 * Set $this->enable and $this->warn
67 * Separate just because there doesn't seem to be a good way to test it
70 * @param string $PHPSessionHandling See $wgPHPSessionHandling
72 private function setEnableFlags( $PHPSessionHandling ) {
73 switch ( $PHPSessionHandling ) {
85 $this->enable
= false;
92 * Test whether the handler is installed
95 public static function isInstalled() {
96 return (bool)self
::$instance;
100 * Test whether the handler is installed and enabled
103 public static function isEnabled() {
104 return self
::$instance && self
::$instance->enable
;
108 * Install a session handler for the current web request
109 * @param SessionManagerInterface $manager
111 public static function install( SessionManagerInterface
$manager ) {
112 if ( self
::$instance ) {
113 $manager->setupPHPSessionHandler( self
::$instance );
117 // @codeCoverageIgnoreStart
118 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
119 throw new \
BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
121 // @codeCoverageIgnoreEnd
123 self
::$instance = new self( $manager );
125 // Close any auto-started session, before we replace it
126 session_write_close();
129 \Wikimedia\
suppressWarnings();
131 // Tell PHP not to mess with cookies itself
132 ini_set( 'session.use_cookies', 0 );
133 ini_set( 'session.use_trans_sid', 0 );
135 // T124510: Disable automatic PHP session related cache headers.
136 // MediaWiki adds it's own headers and the default PHP behavior may
137 // set headers such as 'Pragma: no-cache' that cause problems with
139 session_cache_limiter( '' );
141 // Also set a sane serialization handler
142 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
144 // Register this as the save handler, and register an appropriate
145 // shutdown function.
146 session_set_save_handler( self
::$instance, true );
148 \Wikimedia\restoreWarnings
();
153 * Set the manager, store, and logger
154 * @private Use self::install().
155 * @param SessionManagerInterface $manager
156 * @param BagOStuff $store
157 * @param LoggerInterface $logger
159 public function setManager(
160 SessionManagerInterface
$manager, BagOStuff
$store, LoggerInterface
$logger
162 if ( $this->manager
!== $manager ) {
163 // Close any existing session before we change stores
164 if ( $this->manager
) {
165 session_write_close();
167 $this->manager
= $manager;
168 $this->store
= $store;
169 $this->logger
= $logger;
170 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
175 * Initialize the session (handler)
176 * @private For internal use only
177 * @param string $save_path Path used to store session files (ignored)
178 * @param string $session_name Session name (ignored)
181 public function open( $save_path, $session_name ) {
182 if ( self
::$instance !== $this ) {
183 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
185 if ( !$this->enable
) {
186 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
192 * Close the session (handler)
193 * @private For internal use only
196 public function close() {
197 if ( self
::$instance !== $this ) {
198 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
200 $this->sessionFieldCache
= [];
206 * @private For internal use only
207 * @param string $id Session id
208 * @return string Session data
210 public function read( $id ) {
211 if ( self
::$instance !== $this ) {
212 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
214 if ( !$this->enable
) {
215 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
218 $session = $this->manager
->getSessionById( $id, false );
224 $data = iterator_to_array( $session );
225 $this->sessionFieldCache
[$id] = $data;
226 return (string)\Wikimedia\PhpSessionSerializer
::encode( $data );
231 * @private For internal use only
232 * @param string $id Session id
233 * @param string $dataStr Session data. Not that you should ever call this
234 * directly, but note that this has the same issues with code injection
235 * via user-controlled data as does PHP's unserialize function.
238 public function write( $id, $dataStr ) {
239 if ( self
::$instance !== $this ) {
240 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
242 if ( !$this->enable
) {
243 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
246 $session = $this->manager
->getSessionById( $id, true );
248 // This can happen under normal circumstances, if the session exists but is
249 // invalid. Let's emit a log warning instead of a PHP warning.
250 $this->logger
->warning(
251 __METHOD__
. ': Session "{session}" cannot be loaded, skipping write.',
258 // First, decode the string PHP handed us
259 $data = \Wikimedia\PhpSessionSerializer
::decode( $dataStr );
260 if ( $data === null ) {
261 // @codeCoverageIgnoreStart
263 // @codeCoverageIgnoreEnd
266 // Now merge the data into the Session object.
268 $cache = $this->sessionFieldCache
[$id] ??
[];
269 foreach ( $data as $key => $value ) {
270 if ( !array_key_exists( $key, $cache ) ) {
271 if ( $session->exists( $key ) ) {
272 // New in both, so ignore and log
273 $this->logger
->warning(
274 __METHOD__
. ": Key \"$key\" added in both Session and \$_SESSION!"
277 // New in $_SESSION, keep it
278 $session->set( $key, $value );
281 } elseif ( $cache[$key] === $value ) {
282 // Unchanged in $_SESSION, so ignore it
283 } elseif ( !$session->exists( $key ) ) {
284 // Deleted in Session, keep but log
285 $this->logger
->warning(
286 __METHOD__
. ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
288 $session->set( $key, $value );
290 } elseif ( $cache[$key] === $session->get( $key ) ) {
291 // Unchanged in Session, so keep it
292 $session->set( $key, $value );
295 // Changed in both, so ignore and log
296 $this->logger
->warning(
297 __METHOD__
. ": Key \"$key\" changed in both Session and \$_SESSION!"
301 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
302 // (but not if $_SESSION can't represent it at all)
303 \Wikimedia\PhpSessionSerializer
::setLogger( new NullLogger() );
304 foreach ( $cache as $key => $value ) {
305 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
306 \Wikimedia\PhpSessionSerializer
::encode( [ $key => true ] )
308 if ( $cache[$key] === $session->get( $key ) ) {
309 // Unchanged in Session, delete it
310 $session->remove( $key );
313 // Changed in Session, ignore deletion and log
314 $this->logger
->warning(
315 __METHOD__
. ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
320 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
322 // Save and update cache if anything changed
325 wfDeprecated( '$_SESSION', '1.27' );
326 $this->logger
->warning( 'Something wrote to $_SESSION!' );
330 $this->sessionFieldCache
[$id] = iterator_to_array( $session );
340 * @private For internal use only
341 * @param string $id Session id
344 public function destroy( $id ) {
345 if ( self
::$instance !== $this ) {
346 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
348 if ( !$this->enable
) {
349 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
351 $session = $this->manager
->getSessionById( $id, false );
359 * Execute garbage collection.
360 * @private For internal use only
361 * @param int $maxlifetime Maximum session life time (ignored)
363 * @codeCoverageIgnore See T135576
365 public function gc( $maxlifetime ) {
366 if ( self
::$instance !== $this ) {
367 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
369 $before = date( 'YmdHis', time() );
370 $this->store
->deleteObjectsExpiringBefore( $before );