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