PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / session / PHPSessionHandler.php
blob7d7e1cb77e880d8738a2e3653e5058ad1cc052a5
1 <?php
2 /**
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
20 * @file
21 * @ingroup Session
24 namespace MediaWiki\Session;
26 use Psr\Log\LoggerInterface;
27 use BagOStuff;
29 /**
30 * Adapter for PHP's session handling
31 * @ingroup Session
32 * @since 1.27
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 */
43 protected $manager;
45 /** @var BagOStuff|null */
46 protected $store;
48 /** @var LoggerInterface */
49 protected $logger;
51 /** @var array Track original session fields for later modification check */
52 protected $sessionFieldCache = array();
54 protected function __construct( SessionManager $manager ) {
55 $this->setEnableFlags(
56 \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
58 $manager->setupPHPSessionHandler( $this );
61 /**
62 * Set $this->enable and $this->warn
64 * Separate just because there doesn't seem to be a good way to test it
65 * otherwise.
67 * @param string $PHPSessionHandling See $wgPHPSessionHandling
69 private function setEnableFlags( $PHPSessionHandling ) {
70 switch ( $PHPSessionHandling ) {
71 case 'enable':
72 $this->enable = true;
73 $this->warn = false;
74 break;
76 case 'warn':
77 $this->enable = true;
78 $this->warn = true;
79 break;
81 case 'disable':
82 $this->enable = false;
83 $this->warn = false;
84 break;
88 /**
89 * Test whether the handler is installed
90 * @return bool
92 public static function isInstalled() {
93 return (bool)self::$instance;
96 /**
97 * Test whether the handler is installed and enabled
98 * @return bool
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 );
111 return;
114 self::$instance = new self( $manager );
116 // Close any auto-started session, before we replace it
117 session_write_close();
119 // Tell PHP not to mess with cookies itself
120 ini_set( 'session.use_cookies', 0 );
121 ini_set( 'session.use_trans_sid', 0 );
123 // T124510: Disable automatic PHP session related cache headers.
124 // MediaWiki adds it's own headers and the default PHP behavior may
125 // set headers such as 'Pragma: no-cache' that cause problems with
126 // some user agents.
127 session_cache_limiter( '' );
129 // Also set a sane serialization handler
130 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
132 // Register this as the save handler, and register an appropriate
133 // shutdown function.
134 session_set_save_handler( self::$instance, true );
138 * Set the manager, store, and logger
139 * @private Use self::install().
140 * @param SessionManager $manager
141 * @param BagOStuff $store
142 * @param LoggerInterface $store
144 public function setManager(
145 SessionManager $manager, BagOStuff $store, LoggerInterface $logger
147 if ( $this->manager !== $manager ) {
148 // Close any existing session before we change stores
149 if ( $this->manager ) {
150 session_write_close();
152 $this->manager = $manager;
153 $this->store = $store;
154 $this->logger = $logger;
155 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
160 * Initialize the session (handler)
161 * @private For internal use only
162 * @param string $save_path Path used to store session files (ignored)
163 * @param string $session_name Session name (ignored)
164 * @return bool Success
166 public function open( $save_path, $session_name ) {
167 if ( self::$instance !== $this ) {
168 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
170 if ( !$this->enable ) {
171 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
173 return true;
177 * Close the session (handler)
178 * @private For internal use only
179 * @return bool Success
181 public function close() {
182 if ( self::$instance !== $this ) {
183 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
185 $this->sessionFieldCache = array();
186 return true;
190 * Read session data
191 * @private For internal use only
192 * @param string $id Session id
193 * @return string Session data
195 public function read( $id ) {
196 if ( self::$instance !== $this ) {
197 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
199 if ( !$this->enable ) {
200 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
203 $session = $this->manager->getSessionById( $id, false );
204 if ( !$session ) {
205 return '';
207 $session->persist();
209 $data = iterator_to_array( $session );
210 $this->sessionFieldCache[$id] = $data;
211 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
215 * Write session data
216 * @private For internal use only
217 * @param string $id Session id
218 * @param string $dataStr Session data. Not that you should ever call this
219 * directly, but note that this has the same issues with code injection
220 * via user-controlled data as does PHP's unserialize function.
221 * @return bool Success
223 public function write( $id, $dataStr ) {
224 if ( self::$instance !== $this ) {
225 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
227 if ( !$this->enable ) {
228 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
231 $session = $this->manager->getSessionById( $id, true );
232 if ( !$session ) {
233 // This can happen under normal circumstances, if the session exists but is
234 // invalid. Let's emit a log warning instead of a PHP warning.
235 $this->logger->warning(
236 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
237 array(
238 'session' => $id,
239 ) );
240 return true;
243 // First, decode the string PHP handed us
244 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
245 if ( $data === null ) {
246 // @codeCoverageIgnoreStart
247 return false;
248 // @codeCoverageIgnoreEnd
251 // Now merge the data into the Session object.
252 $changed = false;
253 $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : array();
254 foreach ( $data as $key => $value ) {
255 if ( !array_key_exists( $key, $cache ) ) {
256 if ( $session->exists( $key ) ) {
257 // New in both, so ignore and log
258 $this->logger->warning(
259 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
261 } else {
262 // New in $_SESSION, keep it
263 $session->set( $key, $value );
264 $changed = true;
266 } elseif ( $cache[$key] === $value ) {
267 // Unchanged in $_SESSION, so ignore it
268 } elseif ( !$session->exists( $key ) ) {
269 // Deleted in Session, keep but log
270 $this->logger->warning(
271 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
273 $session->set( $key, $value );
274 $changed = true;
275 } elseif ( $cache[$key] === $session->get( $key ) ) {
276 // Unchanged in Session, so keep it
277 $session->set( $key, $value );
278 $changed = true;
279 } else {
280 // Changed in both, so ignore and log
281 $this->logger->warning(
282 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
286 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
287 // (but not if $_SESSION can't represent it at all)
288 \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
289 foreach ( $cache as $key => $value ) {
290 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
291 \Wikimedia\PhpSessionSerializer::encode( array( $key => true ) )
293 if ( $cache[$key] === $session->get( $key ) ) {
294 // Unchanged in Session, delete it
295 $session->remove( $key );
296 $changed = true;
297 } else {
298 // Changed in Session, ignore deletion and log
299 $this->logger->warning(
300 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
305 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
307 // Save and update cache if anything changed
308 if ( $changed ) {
309 if ( $this->warn ) {
310 wfDeprecated( '$_SESSION', '1.27' );
311 $this->logger->warning( 'Something wrote to $_SESSION!' );
314 $session->save();
315 $this->sessionFieldCache[$id] = iterator_to_array( $session );
318 $session->persist();
320 return true;
324 * Destroy a session
325 * @private For internal use only
326 * @param string $id Session id
327 * @return bool Success
329 public function destroy( $id ) {
330 if ( self::$instance !== $this ) {
331 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
333 if ( !$this->enable ) {
334 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
336 $session = $this->manager->getSessionById( $id, false );
337 if ( $session ) {
338 $session->clear();
340 return true;
344 * Execute garbage collection.
345 * @private For internal use only
346 * @param int $maxlifetime Maximum session life time (ignored)
347 * @return bool Success
349 public function gc( $maxlifetime ) {
350 if ( self::$instance !== $this ) {
351 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
353 $before = date( 'YmdHis', time() );
354 $this->store->deleteObjectsExpiringBefore( $before );
355 return true;