summaryrefslogtreecommitdiff
path: root/www/wiki/includes/session/PHPSessionHandler.php
blob: e1415df4d9603be80c14d786df3f22805bc6004d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<?php
/**
 * Session storage in object cache.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Session
 */

namespace MediaWiki\Session;

use Psr\Log\LoggerInterface;
use BagOStuff;

/**
 * Adapter for PHP's session handling
 * @ingroup Session
 * @since 1.27
 */
class PHPSessionHandler implements \SessionHandlerInterface {
	/** @var PHPSessionHandler */
	protected static $instance = null;

	/** @var bool Whether PHP session handling is enabled */
	protected $enable = false;
	protected $warn = true;

	/** @var SessionManager|null */
	protected $manager;

	/** @var BagOStuff|null */
	protected $store;

	/** @var LoggerInterface */
	protected $logger;

	/** @var array Track original session fields for later modification check */
	protected $sessionFieldCache = [];

	protected function __construct( SessionManager $manager ) {
		$this->setEnableFlags(
			\RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
		);
		$manager->setupPHPSessionHandler( $this );
	}

	/**
	 * Set $this->enable and $this->warn
	 *
	 * Separate just because there doesn't seem to be a good way to test it
	 * otherwise.
	 *
	 * @param string $PHPSessionHandling See $wgPHPSessionHandling
	 */
	private function setEnableFlags( $PHPSessionHandling ) {
		switch ( $PHPSessionHandling ) {
			case 'enable':
				$this->enable = true;
				$this->warn = false;
				break;

			case 'warn':
				$this->enable = true;
				$this->warn = true;
				break;

			case 'disable':
				$this->enable = false;
				$this->warn = false;
				break;
		}
	}

	/**
	 * Test whether the handler is installed
	 * @return bool
	 */
	public static function isInstalled() {
		return (bool)self::$instance;
	}

	/**
	 * Test whether the handler is installed and enabled
	 * @return bool
	 */
	public static function isEnabled() {
		return self::$instance && self::$instance->enable;
	}

	/**
	 * Install a session handler for the current web request
	 * @param SessionManager $manager
	 */
	public static function install( SessionManager $manager ) {
		if ( self::$instance ) {
			$manager->setupPHPSessionHandler( self::$instance );
			return;
		}

		// @codeCoverageIgnoreStart
		if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
			throw new \BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
		}
		// @codeCoverageIgnoreEnd

		self::$instance = new self( $manager );

		// Close any auto-started session, before we replace it
		session_write_close();

		try {
			\Wikimedia\suppressWarnings();

			// Tell PHP not to mess with cookies itself
			ini_set( 'session.use_cookies', 0 );
			ini_set( 'session.use_trans_sid', 0 );

			// T124510: Disable automatic PHP session related cache headers.
			// MediaWiki adds it's own headers and the default PHP behavior may
			// set headers such as 'Pragma: no-cache' that cause problems with
			// some user agents.
			session_cache_limiter( '' );

			// Also set a sane serialization handler
			\Wikimedia\PhpSessionSerializer::setSerializeHandler();

			// Register this as the save handler, and register an appropriate
			// shutdown function.
			session_set_save_handler( self::$instance, true );
		} finally {
			\Wikimedia\restoreWarnings();
		}
	}

	/**
	 * Set the manager, store, and logger
	 * @private Use self::install().
	 * @param SessionManager $manager
	 * @param BagOStuff $store
	 * @param LoggerInterface $logger
	 */
	public function setManager(
		SessionManager $manager, BagOStuff $store, LoggerInterface $logger
	) {
		if ( $this->manager !== $manager ) {
			// Close any existing session before we change stores
			if ( $this->manager ) {
				session_write_close();
			}
			$this->manager = $manager;
			$this->store = $store;
			$this->logger = $logger;
			\Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
		}
	}

	/**
	 * Workaround for PHP5 bug
	 *
	 * PHP5 has a bug in handling boolean return values for
	 * SessionHandlerInterface methods, it expects 0 or -1 instead of true or
	 * false. See <https://wiki.php.net/rfc/session.user.return-value>.
	 *
	 * PHP7 and HHVM are not affected.
	 *
	 * @todo When we drop support for Zend PHP 5, this can be removed.
	 * @return bool|int
	 * @codeCoverageIgnore
	 */
	protected static function returnSuccess() {
		return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? true : 0;
	}

	/**
	 * Workaround for PHP5 bug
	 * @see self::returnSuccess()
	 * @return bool|int
	 * @codeCoverageIgnore
	 */
	protected static function returnFailure() {
		return defined( 'HHVM_VERSION' ) || version_compare( PHP_VERSION, '7.0.0', '>=' ) ? false : -1;
	}

	/**
	 * Initialize the session (handler)
	 * @private For internal use only
	 * @param string $save_path Path used to store session files (ignored)
	 * @param string $session_name Session name (ignored)
	 * @return bool|int Success (see self::returnSuccess())
	 */
	public function open( $save_path, $session_name ) {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		if ( !$this->enable ) {
			throw new \BadMethodCallException( 'Attempt to use PHP session management' );
		}
		return self::returnSuccess();
	}

	/**
	 * Close the session (handler)
	 * @private For internal use only
	 * @return bool|int Success (see self::returnSuccess())
	 */
	public function close() {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		$this->sessionFieldCache = [];
		return self::returnSuccess();
	}

	/**
	 * Read session data
	 * @private For internal use only
	 * @param string $id Session id
	 * @return string Session data
	 */
	public function read( $id ) {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		if ( !$this->enable ) {
			throw new \BadMethodCallException( 'Attempt to use PHP session management' );
		}

		$session = $this->manager->getSessionById( $id, false );
		if ( !$session ) {
			return '';
		}
		$session->persist();

		$data = iterator_to_array( $session );
		$this->sessionFieldCache[$id] = $data;
		return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
	}

	/**
	 * Write session data
	 * @private For internal use only
	 * @param string $id Session id
	 * @param string $dataStr Session data. Not that you should ever call this
	 *   directly, but note that this has the same issues with code injection
	 *   via user-controlled data as does PHP's unserialize function.
	 * @return bool|int Success (see self::returnSuccess())
	 */
	public function write( $id, $dataStr ) {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		if ( !$this->enable ) {
			throw new \BadMethodCallException( 'Attempt to use PHP session management' );
		}

		$session = $this->manager->getSessionById( $id, true );
		if ( !$session ) {
			// This can happen under normal circumstances, if the session exists but is
			// invalid. Let's emit a log warning instead of a PHP warning.
			$this->logger->warning(
				__METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
				[
					'session' => $id,
			] );
			return self::returnSuccess();
		}

		// First, decode the string PHP handed us
		$data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
		if ( $data === null ) {
			// @codeCoverageIgnoreStart
			return self::returnFailure();
			// @codeCoverageIgnoreEnd
		}

		// Now merge the data into the Session object.
		$changed = false;
		$cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : [];
		foreach ( $data as $key => $value ) {
			if ( !array_key_exists( $key, $cache ) ) {
				if ( $session->exists( $key ) ) {
					// New in both, so ignore and log
					$this->logger->warning(
						__METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
					);
				} else {
					// New in $_SESSION, keep it
					$session->set( $key, $value );
					$changed = true;
				}
			} elseif ( $cache[$key] === $value ) {
				// Unchanged in $_SESSION, so ignore it
			} elseif ( !$session->exists( $key ) ) {
				// Deleted in Session, keep but log
				$this->logger->warning(
					__METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
				);
				$session->set( $key, $value );
				$changed = true;
			} elseif ( $cache[$key] === $session->get( $key ) ) {
				// Unchanged in Session, so keep it
				$session->set( $key, $value );
				$changed = true;
			} else {
				// Changed in both, so ignore and log
				$this->logger->warning(
					__METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
				);
			}
		}
		// Anything deleted in $_SESSION and unchanged in Session should be deleted too
		// (but not if $_SESSION can't represent it at all)
		\Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
		foreach ( $cache as $key => $value ) {
			if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
				\Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
			) {
				if ( $cache[$key] === $session->get( $key ) ) {
					// Unchanged in Session, delete it
					$session->remove( $key );
					$changed = true;
				} else {
					// Changed in Session, ignore deletion and log
					$this->logger->warning(
						__METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
					);
				}
			}
		}
		\Wikimedia\PhpSessionSerializer::setLogger( $this->logger );

		// Save and update cache if anything changed
		if ( $changed ) {
			if ( $this->warn ) {
				wfDeprecated( '$_SESSION', '1.27' );
				$this->logger->warning( 'Something wrote to $_SESSION!' );
			}

			$session->save();
			$this->sessionFieldCache[$id] = iterator_to_array( $session );
		}

		$session->persist();

		return self::returnSuccess();
	}

	/**
	 * Destroy a session
	 * @private For internal use only
	 * @param string $id Session id
	 * @return bool|int Success (see self::returnSuccess())
	 */
	public function destroy( $id ) {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		if ( !$this->enable ) {
			throw new \BadMethodCallException( 'Attempt to use PHP session management' );
		}
		$session = $this->manager->getSessionById( $id, false );
		if ( $session ) {
			$session->clear();
		}
		return self::returnSuccess();
	}

	/**
	 * Execute garbage collection.
	 * @private For internal use only
	 * @param int $maxlifetime Maximum session life time (ignored)
	 * @return bool|int Success (see self::returnSuccess())
	 * @codeCoverageIgnore See T135576
	 */
	public function gc( $maxlifetime ) {
		if ( self::$instance !== $this ) {
			throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
		}
		$before = date( 'YmdHis', time() );
		$this->store->deleteObjectsExpiringBefore( $before );
		return self::returnSuccess();
	}
}