Merge "Register a couple of test classes in autoloader"
[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 // Also set a sane serialization handler
127 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
128
129 session_set_save_handler(
130 array( self::$instance, 'open' ),
131 array( self::$instance, 'close' ),
132 array( self::$instance, 'read' ),
133 array( self::$instance, 'write' ),
134 array( self::$instance, 'destroy' ),
135 array( self::$instance, 'gc' )
136 );
137
138 // It's necessary to register a shutdown function to call session_write_close(),
139 // because by the time the request shutdown function for the session module is
140 // called, other needed objects may have already been destroyed. Shutdown functions
141 // registered this way are called before object destruction.
142 register_shutdown_function( array( self::$instance, 'handleShutdown' ) );
143 }
144
145 /**
146 * Set the manager, store, and logger
147 * @private Use self::install().
148 * @param SessionManager $manager
149 * @param BagOStuff $store
150 * @param LoggerInterface $store
151 */
152 public function setManager(
153 SessionManager $manager, BagOStuff $store, LoggerInterface $logger
154 ) {
155 if ( $this->manager !== $manager ) {
156 // Close any existing session before we change stores
157 if ( $this->manager ) {
158 session_write_close();
159 }
160 $this->manager = $manager;
161 $this->store = $store;
162 $this->logger = $logger;
163 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
164 }
165 }
166
167 /**
168 * Initialize the session (handler)
169 * @private For internal use only
170 * @param string $save_path Path used to store session files (ignored)
171 * @param string $session_name Session name (ignored)
172 * @return bool Success
173 */
174 public function open( $save_path, $session_name ) {
175 if ( self::$instance !== $this ) {
176 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
177 }
178 if ( !$this->enable ) {
179 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
180 }
181 return true;
182 }
183
184 /**
185 * Close the session (handler)
186 * @private For internal use only
187 * @return bool Success
188 */
189 public function close() {
190 if ( self::$instance !== $this ) {
191 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
192 }
193 $this->sessionFieldCache = array();
194 return true;
195 }
196
197 /**
198 * Read session data
199 * @private For internal use only
200 * @param string $id Session id
201 * @return string Session data
202 */
203 public function read( $id ) {
204 if ( self::$instance !== $this ) {
205 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
206 }
207 if ( !$this->enable ) {
208 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
209 }
210
211 $session = $this->manager->getSessionById( $id, false );
212 if ( !$session ) {
213 return '';
214 }
215 $session->persist();
216
217 $data = iterator_to_array( $session );
218 $this->sessionFieldCache[$id] = $data;
219 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
220 }
221
222 /**
223 * Write session data
224 * @private For internal use only
225 * @param string $id Session id
226 * @param string $dataStr Session data. Not that you should ever call this
227 * directly, but note that this has the same issues with code injection
228 * via user-controlled data as does PHP's unserialize function.
229 * @return bool Success
230 */
231 public function write( $id, $dataStr ) {
232 if ( self::$instance !== $this ) {
233 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
234 }
235 if ( !$this->enable ) {
236 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
237 }
238
239 $session = $this->manager->getSessionById( $id, true );
240 if ( !$session ) {
241 // This can happen under normal circumstances, if the session exists but is
242 // invalid. Let's emit a log warning instead of a PHP warning.
243 $this->logger->warning(
244 __METHOD__ . ": Session \"$id\" cannot be loaded, skipping write."
245 );
246 return true;
247 }
248
249 // First, decode the string PHP handed us
250 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
251 if ( $data === null ) {
252 // @codeCoverageIgnoreStart
253 return false;
254 // @codeCoverageIgnoreEnd
255 }
256
257 // Now merge the data into the Session object.
258 $changed = false;
259 $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : array();
260 foreach ( $data as $key => $value ) {
261 if ( !isset( $cache[$key] ) ) {
262 if ( $session->exists( $key ) ) {
263 // New in both, so ignore and log
264 $this->logger->warning(
265 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
266 );
267 } else {
268 // New in $_SESSION, keep it
269 $session->set( $key, $value );
270 $changed = true;
271 }
272 } elseif ( $cache[$key] === $value ) {
273 // Unchanged in $_SESSION, so ignore it
274 } elseif ( !$session->exists( $key ) ) {
275 // Deleted in Session, keep but log
276 $this->logger->warning(
277 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
278 );
279 $session->set( $key, $value );
280 $changed = true;
281 } elseif ( $cache[$key] === $session->get( $key ) ) {
282 // Unchanged in Session, so keep it
283 $session->set( $key, $value );
284 $changed = true;
285 } else {
286 // Changed in both, so ignore and log
287 $this->logger->warning(
288 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
289 );
290 }
291 }
292 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
293 // (but not if $_SESSION can't represent it at all)
294 \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
295 foreach ( $cache as $key => $value ) {
296 if ( !isset( $data[$key] ) && $session->exists( $key ) &&
297 \Wikimedia\PhpSessionSerializer::encode( array( $key => true ) )
298 ) {
299 if ( $cache[$key] === $session->get( $key ) ) {
300 // Unchanged in Session, delete it
301 $session->remove( $key );
302 $changed = true;
303 } else {
304 // Changed in Session, ignore deletion and log
305 $this->logger->warning(
306 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
307 );
308 }
309 }
310 }
311 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
312
313 // Save and update cache if anything changed
314 if ( $changed ) {
315 if ( $this->warn ) {
316 wfDeprecated( '$_SESSION', '1.27' );
317 $this->logger->warning( 'Something wrote to $_SESSION!' );
318 }
319
320 $session->save();
321 $this->sessionFieldCache[$id] = iterator_to_array( $session );
322 }
323
324 $session->persist();
325
326 return true;
327 }
328
329 /**
330 * Destroy a session
331 * @private For internal use only
332 * @param string $id Session id
333 * @return bool Success
334 */
335 public function destroy( $id ) {
336 if ( self::$instance !== $this ) {
337 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
338 }
339 if ( !$this->enable ) {
340 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
341 }
342 $session = $this->manager->getSessionById( $id, false );
343 if ( $session ) {
344 $session->clear();
345 }
346 return true;
347 }
348
349 /**
350 * Execute garbage collection.
351 * @private For internal use only
352 * @param int $maxlifetime Maximum session life time (ignored)
353 * @return bool Success
354 */
355 public function gc( $maxlifetime ) {
356 if ( self::$instance !== $this ) {
357 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
358 }
359 $before = date( 'YmdHis', time() );
360 $this->store->deleteObjectsExpiringBefore( $before );
361 return true;
362 }
363
364 /**
365 * Shutdown function.
366 *
367 * See the comment inside self::install for rationale.
368 * @codeCoverageIgnore
369 * @private For internal use only
370 */
371 public function handleShutdown() {
372 if ( $this->enable ) {
373 session_write_close();
374 }
375 }
376
377 }