Merge "Add support for Laki"
[lhc/web/wiklou.git] / includes / session / PHPSessionHandler.php
1 <?php
2 /**
3 * Session storage in object cache.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Session
22 */
23
24 namespace MediaWiki\Session;
25
26 use Psr\Log\LoggerInterface;
27 use BagOStuff;
28
29 /**
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).
34 * @ingroup Session
35 * @since 1.27
36 */
37 class PHPSessionHandler {
38 /** @var PHPSessionHandler */
39 protected static $instance = null;
40
41 /** @var bool Whether PHP session handling is enabled */
42 protected $enable = false;
43 protected $warn = true;
44
45 /** @var SessionManager|null */
46 protected $manager;
47
48 /** @var BagOStuff|null */
49 protected $store;
50
51 /** @var LoggerInterface */
52 protected $logger;
53
54 /** @var array Track original session fields for later modification check */
55 protected $sessionFieldCache = array();
56
57 protected function __construct( SessionManager $manager ) {
58 $this->setEnableFlags(
59 \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
60 );
61 $manager->setupPHPSessionHandler( $this );
62 }
63
64 /**
65 * Set $this->enable and $this->warn
66 *
67 * Separate just because there doesn't seem to be a good way to test it
68 * otherwise.
69 *
70 * @param string $PHPSessionHandling See $wgPHPSessionHandling
71 */
72 private function setEnableFlags( $PHPSessionHandling ) {
73 switch ( $PHPSessionHandling ) {
74 case 'enable':
75 $this->enable = true;
76 $this->warn = false;
77 break;
78
79 case 'warn':
80 $this->enable = true;
81 $this->warn = true;
82 break;
83
84 case 'disable':
85 $this->enable = false;
86 $this->warn = false;
87 break;
88 }
89 }
90
91 /**
92 * Test whether the handler is installed
93 * @return bool
94 */
95 public static function isInstalled() {
96 return (bool)self::$instance;
97 }
98
99 /**
100 * Test whether the handler is installed and enabled
101 * @return bool
102 */
103 public static function isEnabled() {
104 return self::$instance && self::$instance->enable;
105 }
106
107 /**
108 * Install a session handler for the current web request
109 * @param SessionManager $manager
110 */
111 public static function install( SessionManager $manager ) {
112 if ( self::$instance ) {
113 $manager->setupPHPSessionHandler( self::$instance );
114 return;
115 }
116
117 self::$instance = new self( $manager );
118
119 // Close any auto-started session, before we replace it
120 session_write_close();
121
122 // Tell PHP not to mess with cookies itself
123 ini_set( 'session.use_cookies', 0 );
124 ini_set( 'session.use_trans_sid', 0 );
125
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
129 // some user agents.
130 session_cache_limiter( '' );
131
132 // Also set a sane serialization handler
133 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
134
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' )
142 );
143
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' ) );
149 }
150
151 /**
152 * Set the manager, store, and logger
153 * @private Use self::install().
154 * @param SessionManager $manager
155 * @param BagOStuff $store
156 * @param LoggerInterface $store
157 */
158 public function setManager(
159 SessionManager $manager, BagOStuff $store, LoggerInterface $logger
160 ) {
161 if ( $this->manager !== $manager ) {
162 // Close any existing session before we change stores
163 if ( $this->manager ) {
164 session_write_close();
165 }
166 $this->manager = $manager;
167 $this->store = $store;
168 $this->logger = $logger;
169 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
170 }
171 }
172
173 /**
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
179 */
180 public function open( $save_path, $session_name ) {
181 if ( self::$instance !== $this ) {
182 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
183 }
184 if ( !$this->enable ) {
185 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
186 }
187 return true;
188 }
189
190 /**
191 * Close the session (handler)
192 * @private For internal use only
193 * @return bool Success
194 */
195 public function close() {
196 if ( self::$instance !== $this ) {
197 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
198 }
199 $this->sessionFieldCache = array();
200 return true;
201 }
202
203 /**
204 * Read session data
205 * @private For internal use only
206 * @param string $id Session id
207 * @return string Session data
208 */
209 public function read( $id ) {
210 if ( self::$instance !== $this ) {
211 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
212 }
213 if ( !$this->enable ) {
214 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
215 }
216
217 $session = $this->manager->getSessionById( $id, false );
218 if ( !$session ) {
219 return '';
220 }
221 $session->persist();
222
223 $data = iterator_to_array( $session );
224 $this->sessionFieldCache[$id] = $data;
225 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
226 }
227
228 /**
229 * Write session 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
236 */
237 public function write( $id, $dataStr ) {
238 if ( self::$instance !== $this ) {
239 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
240 }
241 if ( !$this->enable ) {
242 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
243 }
244
245 $session = $this->manager->getSessionById( $id, true );
246 if ( !$session ) {
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.',
251 array(
252 'session' => $id,
253 ) );
254 return true;
255 }
256
257 // First, decode the string PHP handed us
258 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
259 if ( $data === null ) {
260 // @codeCoverageIgnoreStart
261 return false;
262 // @codeCoverageIgnoreEnd
263 }
264
265 // Now merge the data into the Session object.
266 $changed = false;
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!"
274 );
275 } else {
276 // New in $_SESSION, keep it
277 $session->set( $key, $value );
278 $changed = true;
279 }
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!"
286 );
287 $session->set( $key, $value );
288 $changed = true;
289 } elseif ( $cache[$key] === $session->get( $key ) ) {
290 // Unchanged in Session, so keep it
291 $session->set( $key, $value );
292 $changed = true;
293 } else {
294 // Changed in both, so ignore and log
295 $this->logger->warning(
296 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
297 );
298 }
299 }
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 ) )
306 ) {
307 if ( $cache[$key] === $session->get( $key ) ) {
308 // Unchanged in Session, delete it
309 $session->remove( $key );
310 $changed = true;
311 } else {
312 // Changed in Session, ignore deletion and log
313 $this->logger->warning(
314 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
315 );
316 }
317 }
318 }
319 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
320
321 // Save and update cache if anything changed
322 if ( $changed ) {
323 if ( $this->warn ) {
324 wfDeprecated( '$_SESSION', '1.27' );
325 $this->logger->warning( 'Something wrote to $_SESSION!' );
326 }
327
328 $session->save();
329 $this->sessionFieldCache[$id] = iterator_to_array( $session );
330 }
331
332 $session->persist();
333
334 return true;
335 }
336
337 /**
338 * Destroy a session
339 * @private For internal use only
340 * @param string $id Session id
341 * @return bool Success
342 */
343 public function destroy( $id ) {
344 if ( self::$instance !== $this ) {
345 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
346 }
347 if ( !$this->enable ) {
348 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
349 }
350 $session = $this->manager->getSessionById( $id, false );
351 if ( $session ) {
352 $session->clear();
353 }
354 return true;
355 }
356
357 /**
358 * Execute garbage collection.
359 * @private For internal use only
360 * @param int $maxlifetime Maximum session life time (ignored)
361 * @return bool Success
362 */
363 public function gc( $maxlifetime ) {
364 if ( self::$instance !== $this ) {
365 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
366 }
367 $before = date( 'YmdHis', time() );
368 $this->store->deleteObjectsExpiringBefore( $before );
369 return true;
370 }
371
372 /**
373 * Shutdown function.
374 *
375 * See the comment inside self::install for rationale.
376 * @codeCoverageIgnore
377 * @private For internal use only
378 */
379 public function handleShutdown() {
380 if ( $this->enable ) {
381 session_write_close();
382 }
383 }
384
385 }