Debian Codegraph @

includes/session/PHPSessionHandler.php

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