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
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
30 * Adapter for PHP's session handling
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 */
45 /** @var BagOStuff|null */
48 /** @var LoggerInterface */
51 /** @var array Track original session fields for later modification check */
52 protected $sessionFieldCache = array();
54 protected function __construct( SessionManager
$manager ) {
55 $this->setEnableFlags(
56 \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' )
58 $manager->setupPHPSessionHandler( $this );
62 * Set $this->enable and $this->warn
64 * Separate just because there doesn't seem to be a good way to test it
67 * @param string $PHPSessionHandling See $wgPHPSessionHandling
69 private function setEnableFlags( $PHPSessionHandling ) {
70 switch ( $PHPSessionHandling ) {
82 $this->enable
= false;
89 * Test whether the handler is installed
92 public static function isInstalled() {
93 return (bool)self
::$instance;
97 * Test whether the handler is installed and enabled
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 );
114 self
::$instance = new self( $manager );
116 // Close any auto-started session, before we replace it
117 session_write_close();
119 // Tell PHP not to mess with cookies itself
120 ini_set( 'session.use_cookies', 0 );
121 ini_set( 'session.use_trans_sid', 0 );
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
127 session_cache_limiter( '' );
129 // Also set a sane serialization handler
130 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
132 // Register this as the save handler, and register an appropriate
133 // shutdown function.
134 session_set_save_handler( self
::$instance, true );
138 * Set the manager, store, and logger
139 * @private Use self::install().
140 * @param SessionManager $manager
141 * @param BagOStuff $store
142 * @param LoggerInterface $store
144 public function setManager(
145 SessionManager
$manager, BagOStuff
$store, LoggerInterface
$logger
147 if ( $this->manager
!== $manager ) {
148 // Close any existing session before we change stores
149 if ( $this->manager
) {
150 session_write_close();
152 $this->manager
= $manager;
153 $this->store
= $store;
154 $this->logger
= $logger;
155 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
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
166 public function open( $save_path, $session_name ) {
167 if ( self
::$instance !== $this ) {
168 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
170 if ( !$this->enable
) {
171 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
177 * Close the session (handler)
178 * @private For internal use only
179 * @return bool Success
181 public function close() {
182 if ( self
::$instance !== $this ) {
183 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
185 $this->sessionFieldCache
= array();
191 * @private For internal use only
192 * @param string $id Session id
193 * @return string Session data
195 public function read( $id ) {
196 if ( self
::$instance !== $this ) {
197 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
199 if ( !$this->enable
) {
200 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
203 $session = $this->manager
->getSessionById( $id, false );
209 $data = iterator_to_array( $session );
210 $this->sessionFieldCache
[$id] = $data;
211 return (string)\Wikimedia\PhpSessionSerializer
::encode( $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
223 public function write( $id, $dataStr ) {
224 if ( self
::$instance !== $this ) {
225 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
227 if ( !$this->enable
) {
228 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
231 $session = $this->manager
->getSessionById( $id, true );
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.',
243 // First, decode the string PHP handed us
244 $data = \Wikimedia\PhpSessionSerializer
::decode( $dataStr );
245 if ( $data === null ) {
246 // @codeCoverageIgnoreStart
248 // @codeCoverageIgnoreEnd
251 // Now merge the data into the Session object.
253 $cache = isset( $this->sessionFieldCache
[$id] ) ?
$this->sessionFieldCache
[$id] : array();
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!"
262 // New in $_SESSION, keep it
263 $session->set( $key, $value );
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!"
273 $session->set( $key, $value );
275 } elseif ( $cache[$key] === $session->get( $key ) ) {
276 // Unchanged in Session, so keep it
277 $session->set( $key, $value );
280 // Changed in both, so ignore and log
281 $this->logger
->warning(
282 __METHOD__
. ": Key \"$key\" changed in both Session and \$_SESSION!"
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( array( $key => true ) )
293 if ( $cache[$key] === $session->get( $key ) ) {
294 // Unchanged in Session, delete it
295 $session->remove( $key );
298 // Changed in Session, ignore deletion and log
299 $this->logger
->warning(
300 __METHOD__
. ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
305 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
307 // Save and update cache if anything changed
310 wfDeprecated( '$_SESSION', '1.27' );
311 $this->logger
->warning( 'Something wrote to $_SESSION!' );
315 $this->sessionFieldCache
[$id] = iterator_to_array( $session );
325 * @private For internal use only
326 * @param string $id Session id
327 * @return bool Success
329 public function destroy( $id ) {
330 if ( self
::$instance !== $this ) {
331 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
333 if ( !$this->enable
) {
334 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
336 $session = $this->manager
->getSessionById( $id, false );
344 * Execute garbage collection.
345 * @private For internal use only
346 * @param int $maxlifetime Maximum session life time (ignored)
347 * @return bool Success
349 public function gc( $maxlifetime ) {
350 if ( self
::$instance !== $this ) {
351 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
353 $before = date( 'YmdHis', time() );
354 $this->store
->deleteObjectsExpiringBefore( $before );