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
31 * @todo Once we drop support for PHP < 5.4, use SessionHandlerInterface
32 * (should just be a matter of adding "implements SessionHandlerInterface" and
33 * changing the session_set_save_handler() call).
37 class PHPSessionHandler
{
38 /** @var PHPSessionHandler */
39 protected static $instance = null;
41 /** @var bool Whether PHP session handling is enabled */
42 protected $enable = false;
43 protected $warn = true;
45 /** @var SessionManager|null */
48 /** @var BagOStuff|null */
51 /** @var LoggerInterface */
54 /** @var array Track original session fields for later modification check */
55 protected $sessionFieldCache = array();
57 protected function __construct( SessionManager
$manager ) {
58 $this->setEnableFlags(
59 \RequestContext
::getMain()->getConfig()->get( 'PHPSessionHandling' )
61 $manager->setupPHPSessionHandler( $this );
65 * Set $this->enable and $this->warn
67 * Separate just because there doesn't seem to be a good way to test it
70 * @param string $PHPSessionHandling See $wgPHPSessionHandling
72 private function setEnableFlags( $PHPSessionHandling ) {
73 switch ( $PHPSessionHandling ) {
85 $this->enable
= false;
92 * Test whether the handler is installed
95 public static function isInstalled() {
96 return (bool)self
::$instance;
100 * Test whether the handler is installed and enabled
103 public static function isEnabled() {
104 return self
::$instance && self
::$instance->enable
;
108 * Install a session handler for the current web request
109 * @param SessionManager $manager
111 public static function install( SessionManager
$manager ) {
112 if ( self
::$instance ) {
113 $manager->setupPHPSessionHandler( self
::$instance );
117 self
::$instance = new self( $manager );
119 // Close any auto-started session, before we replace it
120 session_write_close();
122 // Tell PHP not to mess with cookies itself
123 ini_set( 'session.use_cookies', 0 );
124 ini_set( 'session.use_trans_sid', 0 );
126 // Also set a sane serialization handler
127 \Wikimedia\PhpSessionSerializer
::setSerializeHandler();
129 session_set_save_handler(
130 array( self
::$instance, 'open' ),
131 array( self
::$instance, 'close' ),
132 array( self
::$instance, 'read' ),
133 array( self
::$instance, 'write' ),
134 array( self
::$instance, 'destroy' ),
135 array( self
::$instance, 'gc' )
138 // It's necessary to register a shutdown function to call session_write_close(),
139 // because by the time the request shutdown function for the session module is
140 // called, other needed objects may have already been destroyed. Shutdown functions
141 // registered this way are called before object destruction.
142 register_shutdown_function( array( self
::$instance, 'handleShutdown' ) );
146 * Set the manager, store, and logger
147 * @private Use self::install().
148 * @param SessionManager $manager
149 * @param BagOStuff $store
150 * @param LoggerInterface $store
152 public function setManager(
153 SessionManager
$manager, BagOStuff
$store, LoggerInterface
$logger
155 if ( $this->manager
!== $manager ) {
156 // Close any existing session before we change stores
157 if ( $this->manager
) {
158 session_write_close();
160 $this->manager
= $manager;
161 $this->store
= $store;
162 $this->logger
= $logger;
163 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
168 * Initialize the session (handler)
169 * @private For internal use only
170 * @param string $save_path Path used to store session files (ignored)
171 * @param string $session_name Session name (ignored)
172 * @return bool Success
174 public function open( $save_path, $session_name ) {
175 if ( self
::$instance !== $this ) {
176 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
178 if ( !$this->enable
) {
179 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
185 * Close the session (handler)
186 * @private For internal use only
187 * @return bool Success
189 public function close() {
190 if ( self
::$instance !== $this ) {
191 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
193 $this->sessionFieldCache
= array();
199 * @private For internal use only
200 * @param string $id Session id
201 * @return string Session data
203 public function read( $id ) {
204 if ( self
::$instance !== $this ) {
205 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
207 if ( !$this->enable
) {
208 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
211 $session = $this->manager
->getSessionById( $id, true );
217 $data = iterator_to_array( $session );
218 $this->sessionFieldCache
[$id] = $data;
219 return (string)\Wikimedia\PhpSessionSerializer
::encode( $data );
224 * @private For internal use only
225 * @param string $id Session id
226 * @param string $dataStr Session data. Not that you should ever call this
227 * directly, but note that this has the same issues with code injection
228 * via user-controlled data as does PHP's unserialize function.
229 * @return bool Success
231 public function write( $id, $dataStr ) {
232 if ( self
::$instance !== $this ) {
233 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
235 if ( !$this->enable
) {
236 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
239 $session = $this->manager
->getSessionById( $id );
241 // First, decode the string PHP handed us
242 $data = \Wikimedia\PhpSessionSerializer
::decode( $dataStr );
243 if ( $data === null ) {
244 // @codeCoverageIgnoreStart
246 // @codeCoverageIgnoreEnd
249 // Now merge the data into the Session object.
251 $cache = isset( $this->sessionFieldCache
[$id] ) ?
$this->sessionFieldCache
[$id] : array();
252 foreach ( $data as $key => $value ) {
253 if ( !isset( $cache[$key] ) ) {
254 if ( $session->exists( $key ) ) {
255 // New in both, so ignore and log
256 $this->logger
->warning(
257 __METHOD__
. ": Key \"$key\" added in both Session and \$_SESSION!"
260 // New in $_SESSION, keep it
261 $session->set( $key, $value );
264 } elseif ( $cache[$key] === $value ) {
265 // Unchanged in $_SESSION, so ignore it
266 } elseif ( !$session->exists( $key ) ) {
267 // Deleted in Session, keep but log
268 $this->logger
->warning(
269 __METHOD__
. ": Key \"$key\" deleted in Session and changed in \$_SESSION!"
271 $session->set( $key, $value );
273 } elseif ( $cache[$key] === $session->get( $key ) ) {
274 // Unchanged in Session, so keep it
275 $session->set( $key, $value );
278 // Changed in both, so ignore and log
279 $this->logger
->warning(
280 __METHOD__
. ": Key \"$key\" changed in both Session and \$_SESSION!"
284 // Anything deleted in $_SESSION and unchanged in Session should be deleted too
285 // (but not if $_SESSION can't represent it at all)
286 \Wikimedia\PhpSessionSerializer
::setLogger( new \Psr\Log\
NullLogger() );
287 foreach ( $cache as $key => $value ) {
288 if ( !isset( $data[$key] ) && $session->exists( $key ) &&
289 \Wikimedia\PhpSessionSerializer
::encode( array( $key => true ) )
291 if ( $cache[$key] === $session->get( $key ) ) {
292 // Unchanged in Session, delete it
293 $session->remove( $key );
296 // Changed in Session, ignore deletion and log
297 $this->logger
->warning(
298 __METHOD__
. ": Key \"$key\" changed in Session and deleted in \$_SESSION!"
303 \Wikimedia\PhpSessionSerializer
::setLogger( $this->logger
);
305 // Save and update cache if anything changed
308 wfDeprecated( '$_SESSION', '1.27' );
309 $this->logger
->warning( 'Something wrote to $_SESSION!' );
313 $this->sessionFieldCache
[$id] = iterator_to_array( $session );
323 * @private For internal use only
324 * @param string $id Session id
325 * @return bool Success
327 public function destroy( $id ) {
328 if ( self
::$instance !== $this ) {
329 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
331 if ( !$this->enable
) {
332 throw new \
BadMethodCallException( 'Attempt to use PHP session management' );
334 $session = $this->manager
->getSessionById( $id, true );
342 * Execute garbage collection.
343 * @private For internal use only
344 * @param int $maxlifetime Maximum session life time (ignored)
345 * @return bool Success
347 public function gc( $maxlifetime ) {
348 if ( self
::$instance !== $this ) {
349 throw new \
UnexpectedValueException( __METHOD__
. ': Wrong instance called!' );
351 $before = date( 'YmdHis', time() );
352 $this->store
->deleteObjectsExpiringBefore( $before );
359 * See the comment inside self::install for rationale.
360 * @codeCoverageIgnore
361 * @private For internal use only
363 public function handleShutdown() {
364 if ( $this->enable
) {
365 session_write_close();