Merge "Fix resource path check when ResourceBasePath is an empty string"
[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 * @ingroup Session
32 * @since 1.27
33 */
34 class PHPSessionHandler implements \SessionHandlerInterface {
35 /** @var PHPSessionHandler */
36 protected static $instance = null;
37
38 /** @var bool Whether PHP session handling is enabled */
39 protected $enable = false;
40 protected $warn = true;
41
42 /** @var SessionManager|null */
43 protected $manager;
44
45 /** @var BagOStuff|null */
46 protected $store;
47
48 /** @var LoggerInterface */
49 protected $logger;
50
51 /** @var array Track original session fields for later modification check */
52 protected $sessionFieldCache = [];
53
54 protected function __construct( SessionManager $manager ) {
55 $this->setEnableFlags(
56 \RequestContext::getMain()->getConfig()->get( 'PHPSessionHandling' )
57 );
58 $manager->setupPHPSessionHandler( $this );
59 }
60
61 /**
62 * Set $this->enable and $this->warn
63 *
64 * Separate just because there doesn't seem to be a good way to test it
65 * otherwise.
66 *
67 * @param string $PHPSessionHandling See $wgPHPSessionHandling
68 */
69 private function setEnableFlags( $PHPSessionHandling ) {
70 switch ( $PHPSessionHandling ) {
71 case 'enable':
72 $this->enable = true;
73 $this->warn = false;
74 break;
75
76 case 'warn':
77 $this->enable = true;
78 $this->warn = true;
79 break;
80
81 case 'disable':
82 $this->enable = false;
83 $this->warn = false;
84 break;
85 }
86 }
87
88 /**
89 * Test whether the handler is installed
90 * @return bool
91 */
92 public static function isInstalled() {
93 return (bool)self::$instance;
94 }
95
96 /**
97 * Test whether the handler is installed and enabled
98 * @return bool
99 */
100 public static function isEnabled() {
101 return self::$instance && self::$instance->enable;
102 }
103
104 /**
105 * Install a session handler for the current web request
106 * @param SessionManager $manager
107 */
108 public static function install( SessionManager $manager ) {
109 if ( self::$instance ) {
110 $manager->setupPHPSessionHandler( self::$instance );
111 return;
112 }
113
114 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
115 throw new \BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
116 }
117
118 self::$instance = new self( $manager );
119
120 // Close any auto-started session, before we replace it
121 session_write_close();
122
123 // Tell PHP not to mess with cookies itself
124 ini_set( 'session.use_cookies', 0 );
125 ini_set( 'session.use_trans_sid', 0 );
126
127 // T124510: Disable automatic PHP session related cache headers.
128 // MediaWiki adds it's own headers and the default PHP behavior may
129 // set headers such as 'Pragma: no-cache' that cause problems with
130 // some user agents.
131 session_cache_limiter( '' );
132
133 // Also set a sane serialization handler
134 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
135
136 // Register this as the save handler, and register an appropriate
137 // shutdown function.
138 session_set_save_handler( self::$instance, true );
139 }
140
141 /**
142 * Set the manager, store, and logger
143 * @private Use self::install().
144 * @param SessionManager $manager
145 * @param BagOStuff $store
146 * @param LoggerInterface $store
147 */
148 public function setManager(
149 SessionManager $manager, BagOStuff $store, LoggerInterface $logger
150 ) {
151 if ( $this->manager !== $manager ) {
152 // Close any existing session before we change stores
153 if ( $this->manager ) {
154 session_write_close();
155 }
156 $this->manager = $manager;
157 $this->store = $store;
158 $this->logger = $logger;
159 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
160 }
161 }
162
163 /**
164 * Initialize the session (handler)
165 * @private For internal use only
166 * @param string $save_path Path used to store session files (ignored)
167 * @param string $session_name Session name (ignored)
168 * @return bool Success
169 */
170 public function open( $save_path, $session_name ) {
171 if ( self::$instance !== $this ) {
172 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
173 }
174 if ( !$this->enable ) {
175 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
176 }
177 return true;
178 }
179
180 /**
181 * Close the session (handler)
182 * @private For internal use only
183 * @return bool Success
184 */
185 public function close() {
186 if ( self::$instance !== $this ) {
187 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
188 }
189 $this->sessionFieldCache = [];
190 return true;
191 }
192
193 /**
194 * Read session data
195 * @private For internal use only
196 * @param string $id Session id
197 * @return string Session data
198 */
199 public function read( $id ) {
200 if ( self::$instance !== $this ) {
201 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
202 }
203 if ( !$this->enable ) {
204 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
205 }
206
207 $session = $this->manager->getSessionById( $id, false );
208 if ( !$session ) {
209 return '';
210 }
211 $session->persist();
212
213 $data = iterator_to_array( $session );
214 $this->sessionFieldCache[$id] = $data;
215 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
216 }
217
218 /**
219 * Write session data
220 * @private For internal use only
221 * @param string $id Session id
222 * @param string $dataStr Session data. Not that you should ever call this
223 * directly, but note that this has the same issues with code injection
224 * via user-controlled data as does PHP's unserialize function.
225 * @return bool Success
226 */
227 public function write( $id, $dataStr ) {
228 if ( self::$instance !== $this ) {
229 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
230 }
231 if ( !$this->enable ) {
232 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
233 }
234
235 $session = $this->manager->getSessionById( $id, true );
236 if ( !$session ) {
237 // This can happen under normal circumstances, if the session exists but is
238 // invalid. Let's emit a log warning instead of a PHP warning.
239 $this->logger->warning(
240 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
241 [
242 'session' => $id,
243 ] );
244 return true;
245 }
246
247 // First, decode the string PHP handed us
248 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
249 if ( $data === null ) {
250 // @codeCoverageIgnoreStart
251 return false;
252 // @codeCoverageIgnoreEnd
253 }
254
255 // Now merge the data into the Session object.
256 $changed = false;
257 $cache = isset( $this->sessionFieldCache[$id] ) ? $this->sessionFieldCache[$id] : [];
258 foreach ( $data as $key => $value ) {
259 if ( !array_key_exists( $key, $cache ) ) {
260 if ( $session->exists( $key ) ) {
261 // New in both, so ignore and log
262 $this->logger->warning(
263 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
264 );
265 } else {
266 // New in $_SESSION, keep it
267 $session->set( $key, $value );
268 $changed = true;
269 }
270 } elseif ( $cache[$key] === $value ) {
271 // Unchanged in $_SESSION, so ignore it
272 } elseif ( !$session->exists( $key ) ) {
273 // Deleted in Session, keep but log
274 $this->logger->warning(
275 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
276 );
277 $session->set( $key, $value );
278 $changed = true;
279 } elseif ( $cache[$key] === $session->get( $key ) ) {
280 // Unchanged in Session, so keep it
281 $session->set( $key, $value );
282 $changed = true;
283 } else {
284 // Changed in both, so ignore and log
285 $this->logger->warning(
286 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
287 );
288 }
289 }
290 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
291 // (but not if $_SESSION can't represent it at all)
292 \Wikimedia\PhpSessionSerializer::setLogger( new \Psr\Log\NullLogger() );
293 foreach ( $cache as $key => $value ) {
294 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
295 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
296 ) {
297 if ( $cache[$key] === $session->get( $key ) ) {
298 // Unchanged in Session, delete it
299 $session->remove( $key );
300 $changed = true;
301 } else {
302 // Changed in Session, ignore deletion and log
303 $this->logger->warning(
304 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
305 );
306 }
307 }
308 }
309 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
310
311 // Save and update cache if anything changed
312 if ( $changed ) {
313 if ( $this->warn ) {
314 wfDeprecated( '$_SESSION', '1.27' );
315 $this->logger->warning( 'Something wrote to $_SESSION!' );
316 }
317
318 $session->save();
319 $this->sessionFieldCache[$id] = iterator_to_array( $session );
320 }
321
322 $session->persist();
323
324 return true;
325 }
326
327 /**
328 * Destroy a session
329 * @private For internal use only
330 * @param string $id Session id
331 * @return bool Success
332 */
333 public function destroy( $id ) {
334 if ( self::$instance !== $this ) {
335 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
336 }
337 if ( !$this->enable ) {
338 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
339 }
340 $session = $this->manager->getSessionById( $id, false );
341 if ( $session ) {
342 $session->clear();
343 }
344 return true;
345 }
346
347 /**
348 * Execute garbage collection.
349 * @private For internal use only
350 * @param int $maxlifetime Maximum session life time (ignored)
351 * @return bool Success
352 */
353 public function gc( $maxlifetime ) {
354 if ( self::$instance !== $this ) {
355 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
356 }
357 $before = date( 'YmdHis', time() );
358 $this->store->deleteObjectsExpiringBefore( $before );
359 return true;
360 }
361 }