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
31 * @todo Once we drop support for PHP < 5.4, use SessionHandlerInterface
32 * (should just be a matter of adding "implements SessionHandlerInterface" and
33 * changing the session_set_save_handler() call).
37 class PHPSessionHandler
{
38 /** @var PHPSessionHandler */
39 protected static $instance = null;
41 /** @var bool Whether PHP session handling is enabled */
42 protected $enable = false;
43 protected $warn = true;
45 /** @var SessionManager|null */
48 /** @var BagOStuff|null */
51 /** @var LoggerInterface */
54 /** @var array Track original session fields for later modification check */
55 protected $sessionFieldCache = array();
57 protected function __construct( SessionManager
$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 SessionManager $manager
111 public static function install( SessionManager
$manager ) {
112 if ( self
::$instance ) {
113 $manager->setupPHPSessionHandler( self
::$instance );
117 self
::$instance = new self( $manager );
119 // Close any auto-started session, before we replace it
120 session_write_close();
122 // Tell PHP not to mess with cookies itself
123 ini_set( 'session.use_cookies', 0 );
124 ini_set( 'session.use_trans_sid', 0 );
126 // T124510: Disable automatic PHP session related cache headers.
127 // MediaWiki adds it's own headers and the default PHP behavior may
128 // set headers such as 'Pragma: no-cache' that cause problems with
130 session_cache_limiter( '' );
132 // Also set a sane serialization handler
133 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
135 session_set_save_handler(
136 array( self
::$instance, 'open' ),
137 array( self
::$instance, 'close' ),
138 array( self
::$instance, 'read' ),
139 array( self
::$instance, 'write' ),
140 array( self
::$instance, 'destroy' ),
141 array( self
::$instance, 'gc' )
144 // It's necessary to register a shutdown function to call session_write_close(),
145 // because by the time the request shutdown function for the session module is
146 // called, other needed objects may have already been destroyed. Shutdown functions
147 // registered this way are called before object destruction.
148 register_shutdown_function( array( self
::$instance, 'handleShutdown' ) );
152 * Set the manager, store, and logger
153 * @private Use self::install().
154 * @param SessionManager $manager
155 * @param BagOStuff $store
156 * @param LoggerInterface $store
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)
178 * @return bool Success
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
193 * @return bool Success
195 public function close() {
196 if ( self
::$instance !== $this ) {
197 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
199 $this->sessionFieldCache
= array();
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.
235 * @return bool Success
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 = isset( $this->sessionFieldCache
[$id] ) ?
$this->sessionFieldCache
[$id] : array();
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( array( $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
341 * @return bool Success
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)
361 * @return bool Success
363 public function gc( $maxlifetime ) {
364 if ( self
::$instance !== $this ) {
365 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
367 $before = date( 'YmdHis', time() );
368 $this->store
->deleteObjectsExpiringBefore( $before );
375 * See the comment inside self::install for rationale.
376 * @codeCoverageIgnore
377 * @private For internal use only
379 public function handleShutdown() {
380 if ( $this->enable
) {
381 session_write_close();