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