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