Merge "Add .pipeline/ with dev image variant"
[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 use Psr\Log\NullLogger;
29
30 /**
31 * Adapter for PHP's session handling
32 * @ingroup Session
33 * @since 1.27
34 */
35 class PHPSessionHandler implements \SessionHandlerInterface {
36 /** @var PHPSessionHandler */
37 protected static $instance = null;
38
39 /** @var bool Whether PHP session handling is enabled */
40 protected $enable = false;
41
42 /** @var bool */
43 protected $warn = true;
44
45 /** @var SessionManagerInterface|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 = [];
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 // @codeCoverageIgnoreStart
118 if ( defined( 'MW_NO_SESSION_HANDLER' ) ) {
119 throw new \BadMethodCallException( 'MW_NO_SESSION_HANDLER is defined' );
120 }
121 // @codeCoverageIgnoreEnd
122
123 self::$instance = new self( $manager );
124
125 // Close any auto-started session, before we replace it
126 session_write_close();
127
128 try {
129 \Wikimedia\suppressWarnings();
130
131 // Tell PHP not to mess with cookies itself
132 ini_set( 'session.use_cookies', 0 );
133 ini_set( 'session.use_trans_sid', 0 );
134
135 // T124510: Disable automatic PHP session related cache headers.
136 // MediaWiki adds it's own headers and the default PHP behavior may
137 // set headers such as 'Pragma: no-cache' that cause problems with
138 // some user agents.
139 session_cache_limiter( '' );
140
141 // Also set a sane serialization handler
142 \Wikimedia\PhpSessionSerializer::setSerializeHandler();
143
144 // Register this as the save handler, and register an appropriate
145 // shutdown function.
146 session_set_save_handler( self::$instance, true );
147 } finally {
148 \Wikimedia\restoreWarnings();
149 }
150 }
151
152 /**
153 * Set the manager, store, and logger
154 * @private Use self::install().
155 * @param SessionManagerInterface $manager
156 * @param BagOStuff $store
157 * @param LoggerInterface $logger
158 */
159 public function setManager(
160 SessionManagerInterface $manager, BagOStuff $store, LoggerInterface $logger
161 ) {
162 if ( $this->manager !== $manager ) {
163 // Close any existing session before we change stores
164 if ( $this->manager ) {
165 session_write_close();
166 }
167 $this->manager = $manager;
168 $this->store = $store;
169 $this->logger = $logger;
170 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
171 }
172 }
173
174 /**
175 * Initialize the session (handler)
176 * @private For internal use only
177 * @param string $save_path Path used to store session files (ignored)
178 * @param string $session_name Session name (ignored)
179 * @return true
180 */
181 public function open( $save_path, $session_name ) {
182 if ( self::$instance !== $this ) {
183 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
184 }
185 if ( !$this->enable ) {
186 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
187 }
188 return true;
189 }
190
191 /**
192 * Close the session (handler)
193 * @private For internal use only
194 * @return true
195 */
196 public function close() {
197 if ( self::$instance !== $this ) {
198 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
199 }
200 $this->sessionFieldCache = [];
201 return true;
202 }
203
204 /**
205 * Read session data
206 * @private For internal use only
207 * @param string $id Session id
208 * @return string Session data
209 */
210 public function read( $id ) {
211 if ( self::$instance !== $this ) {
212 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
213 }
214 if ( !$this->enable ) {
215 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
216 }
217
218 $session = $this->manager->getSessionById( $id, false );
219 if ( !$session ) {
220 return '';
221 }
222 $session->persist();
223
224 $data = iterator_to_array( $session );
225 $this->sessionFieldCache[$id] = $data;
226 return (string)\Wikimedia\PhpSessionSerializer::encode( $data );
227 }
228
229 /**
230 * Write session data
231 * @private For internal use only
232 * @param string $id Session id
233 * @param string $dataStr Session data. Not that you should ever call this
234 * directly, but note that this has the same issues with code injection
235 * via user-controlled data as does PHP's unserialize function.
236 * @return bool
237 */
238 public function write( $id, $dataStr ) {
239 if ( self::$instance !== $this ) {
240 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
241 }
242 if ( !$this->enable ) {
243 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
244 }
245
246 $session = $this->manager->getSessionById( $id, true );
247 if ( !$session ) {
248 // This can happen under normal circumstances, if the session exists but is
249 // invalid. Let's emit a log warning instead of a PHP warning.
250 $this->logger->warning(
251 __METHOD__ . ': Session "{session}" cannot be loaded, skipping write.',
252 [
253 'session' => $id,
254 ] );
255 return true;
256 }
257
258 // First, decode the string PHP handed us
259 $data = \Wikimedia\PhpSessionSerializer::decode( $dataStr );
260 if ( $data === null ) {
261 // @codeCoverageIgnoreStart
262 return false;
263 // @codeCoverageIgnoreEnd
264 }
265
266 // Now merge the data into the Session object.
267 $changed = false;
268 $cache = $this->sessionFieldCache[$id] ?? [];
269 foreach ( $data as $key => $value ) {
270 if ( !array_key_exists( $key, $cache ) ) {
271 if ( $session->exists( $key ) ) {
272 // New in both, so ignore and log
273 $this->logger->warning(
274 __METHOD__ . ": Key \"$key\" added in both Session and \$_SESSION!"
275 );
276 } else {
277 // New in $_SESSION, keep it
278 $session->set( $key, $value );
279 $changed = true;
280 }
281 } elseif ( $cache[$key] === $value ) {
282 // Unchanged in $_SESSION, so ignore it
283 } elseif ( !$session->exists( $key ) ) {
284 // Deleted in Session, keep but log
285 $this->logger->warning(
286 __METHOD__ . ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
287 );
288 $session->set( $key, $value );
289 $changed = true;
290 } elseif ( $cache[$key] === $session->get( $key ) ) {
291 // Unchanged in Session, so keep it
292 $session->set( $key, $value );
293 $changed = true;
294 } else {
295 // Changed in both, so ignore and log
296 $this->logger->warning(
297 __METHOD__ . ": Key \"$key\" changed in both Session and \$_SESSION!"
298 );
299 }
300 }
301 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
302 // (but not if $_SESSION can't represent it at all)
303 \Wikimedia\PhpSessionSerializer::setLogger( new NullLogger() );
304 foreach ( $cache as $key => $value ) {
305 if ( !array_key_exists( $key, $data ) && $session->exists( $key ) &&
306 \Wikimedia\PhpSessionSerializer::encode( [ $key => true ] )
307 ) {
308 if ( $cache[$key] === $session->get( $key ) ) {
309 // Unchanged in Session, delete it
310 $session->remove( $key );
311 $changed = true;
312 } else {
313 // Changed in Session, ignore deletion and log
314 $this->logger->warning(
315 __METHOD__ . ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
316 );
317 }
318 }
319 }
320 \Wikimedia\PhpSessionSerializer::setLogger( $this->logger );
321
322 // Save and update cache if anything changed
323 if ( $changed ) {
324 if ( $this->warn ) {
325 wfDeprecated( '$_SESSION', '1.27' );
326 $this->logger->warning( 'Something wrote to $_SESSION!' );
327 }
328
329 $session->save();
330 $this->sessionFieldCache[$id] = iterator_to_array( $session );
331 }
332
333 $session->persist();
334
335 return true;
336 }
337
338 /**
339 * Destroy a session
340 * @private For internal use only
341 * @param string $id Session id
342 * @return true
343 */
344 public function destroy( $id ) {
345 if ( self::$instance !== $this ) {
346 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
347 }
348 if ( !$this->enable ) {
349 throw new \BadMethodCallException( 'Attempt to use PHP session management' );
350 }
351 $session = $this->manager->getSessionById( $id, false );
352 if ( $session ) {
353 $session->clear();
354 }
355 return true;
356 }
357
358 /**
359 * Execute garbage collection.
360 * @private For internal use only
361 * @param int $maxlifetime Maximum session life time (ignored)
362 * @return true
363 * @codeCoverageIgnore See T135576
364 */
365 public function gc( $maxlifetime ) {
366 if ( self::$instance !== $this ) {
367 throw new \UnexpectedValueException( __METHOD__ . ': Wrong instance called!' );
368 }
369 $before = date( 'YmdHis', time() );
370 $this->store->deleteObjectsExpiringBefore( $before );
371 return true;
372 }
373 }