Merge "SpecialWatchlist: Display 'wlnote' message even when showing "all" days"
[lhc/web/wiklou.git] / includes / session / CookieSessionProvider.php
1 <?php
2 /**
3 * MediaWiki cookie-based session provider interface
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 Config;
27 use User;
28 use WebRequest;
29
30 /**
31 * A CookieSessionProvider persists sessions using cookies
32 *
33 * @ingroup Session
34 * @since 1.27
35 */
36 class CookieSessionProvider extends SessionProvider {
37
38 protected $params = array();
39 protected $cookieOptions = array();
40
41 /**
42 * @param array $params Keys include:
43 * - priority: (required) Priority of the returned sessions
44 * - callUserSetCookiesHook: Whether to call the deprecated hook
45 * - sessionName: Session cookie name. Doesn't honor 'prefix'. Defaults to
46 * $wgSessionName, or $wgCookiePrefix . '_session' if that is unset.
47 * - cookieOptions: Options to pass to WebRequest::setCookie():
48 * - prefix: Cookie prefix, defaults to $wgCookiePrefix
49 * - path: Cookie path, defaults to $wgCookiePath
50 * - domain: Cookie domain, defaults to $wgCookieDomain
51 * - secure: Cookie secure flag, defaults to $wgCookieSecure
52 * - httpOnly: Cookie httpOnly flag, defaults to $wgCookieHttpOnly
53 */
54 public function __construct( $params = array() ) {
55 parent::__construct();
56
57 $params += array(
58 'cookieOptions' => array(),
59 // @codeCoverageIgnoreStart
60 );
61 // @codeCoverageIgnoreEnd
62
63 if ( !isset( $params['priority'] ) ) {
64 throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
65 }
66 if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
67 $params['priority'] > SessionInfo::MAX_PRIORITY
68 ) {
69 throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
70 }
71
72 if ( !is_array( $params['cookieOptions'] ) ) {
73 throw new \InvalidArgumentException( __METHOD__ . ': cookieOptions must be an array' );
74 }
75
76 $this->priority = $params['priority'];
77 $this->cookieOptions = $params['cookieOptions'];
78 $this->params = $params;
79 unset( $this->params['priority'] );
80 unset( $this->params['cookieOptions'] );
81 }
82
83 public function setConfig( Config $config ) {
84 parent::setConfig( $config );
85
86 // @codeCoverageIgnoreStart
87 $this->params += array(
88 // @codeCoverageIgnoreEnd
89 'callUserSetCookiesHook' => false,
90 'sessionName' =>
91 $config->get( 'SessionName' ) ?: $config->get( 'CookiePrefix' ) . '_session',
92 );
93
94 // @codeCoverageIgnoreStart
95 $this->cookieOptions += array(
96 // @codeCoverageIgnoreEnd
97 'prefix' => $config->get( 'CookiePrefix' ),
98 'path' => $config->get( 'CookiePath' ),
99 'domain' => $config->get( 'CookieDomain' ),
100 'secure' => $config->get( 'CookieSecure' ),
101 'httpOnly' => $config->get( 'CookieHttpOnly' ),
102 );
103 }
104
105 public function provideSessionInfo( WebRequest $request ) {
106 $info = array(
107 'id' => $this->getCookie( $request, $this->params['sessionName'], '' )
108 );
109 if ( !SessionManager::validateSessionId( $info['id'] ) ) {
110 unset( $info['id'] );
111 }
112
113 list( $userId, $userName, $token ) = $this->getUserInfoFromCookies( $request );
114 if ( $userId !== null ) {
115 try {
116 $userInfo = UserInfo::newFromId( $userId );
117 } catch ( \InvalidArgumentException $ex ) {
118 return null;
119 }
120
121 // Sanity check
122 if ( $userName !== null && $userInfo->getName() !== $userName ) {
123 return null;
124 }
125
126 if ( $token !== null ) {
127 if ( !hash_equals( $userInfo->getToken(), $token ) ) {
128 return null;
129 }
130 $info['userInfo'] = $userInfo->verified();
131 } elseif ( isset( $info['id'] ) ) { // No point if no session ID
132 $info['userInfo'] = $userInfo;
133 }
134 }
135
136 if ( !$info ) {
137 return null;
138 }
139
140 $info += array(
141 'provider' => $this,
142 'persisted' => isset( $info['id'] ),
143 'forceHTTPS' => $this->getCookie( $request, 'forceHTTPS', '', false )
144 );
145
146 return new SessionInfo( $this->priority, $info );
147 }
148
149 public function persistsSessionId() {
150 return true;
151 }
152
153 public function canChangeUser() {
154 return true;
155 }
156
157 public function persistSession( SessionBackend $session, WebRequest $request ) {
158 $response = $request->response();
159 if ( $response->headersSent() ) {
160 // Can't do anything now
161 $this->logger->debug( __METHOD__ . ': Headers already sent' );
162 return;
163 }
164
165 $user = $session->getUser();
166
167 $cookies = $this->cookieDataToExport( $user, $session->shouldRememberUser() );
168 $sessionData = $this->sessionDataToExport( $user );
169
170 // Legacy hook
171 if ( $this->params['callUserSetCookiesHook'] && !$user->isAnon() ) {
172 \Hooks::run( 'UserSetCookies', array( $user, &$sessionData, &$cookies ) );
173 }
174
175 $options = $this->cookieOptions;
176
177 $forceHTTPS = $session->shouldForceHTTPS() || $user->requiresHTTPS();
178 if ( $forceHTTPS ) {
179 $options['secure'] = true;
180 }
181
182 $response->setCookie( $this->params['sessionName'], $session->getId(), null,
183 array( 'prefix' => '' ) + $options
184 );
185
186 $extendedCookies = $this->config->get( 'ExtendedLoginCookies' );
187 $extendedExpiry = $this->config->get( 'ExtendedLoginCookieExpiration' );
188
189 foreach ( $cookies as $key => $value ) {
190 if ( $value === false ) {
191 $response->clearCookie( $key, $options );
192 } else {
193 if ( $extendedExpiry !== null && in_array( $key, $extendedCookies ) ) {
194 $expiry = time() + (int)$extendedExpiry;
195 } else {
196 $expiry = 0; // Default cookie expiration
197 }
198 $response->setCookie( $key, (string)$value, $expiry, $options );
199 }
200 }
201
202 $this->setForceHTTPSCookie( $forceHTTPS, $session, $request );
203 $this->setLoggedOutCookie( $session->getLoggedOutTimestamp(), $request );
204
205 if ( $sessionData ) {
206 $session->addData( $sessionData );
207 }
208 }
209
210 public function unpersistSession( WebRequest $request ) {
211 $response = $request->response();
212 if ( $response->headersSent() ) {
213 // Can't do anything now
214 $this->logger->debug( __METHOD__ . ': Headers already sent' );
215 return;
216 }
217
218 $cookies = array(
219 'UserID' => false,
220 'Token' => false,
221 );
222
223 $response->clearCookie(
224 $this->params['sessionName'], array( 'prefix' => '' ) + $this->cookieOptions
225 );
226
227 foreach ( $cookies as $key => $value ) {
228 $response->clearCookie( $key, $this->cookieOptions );
229 }
230
231 $this->setForceHTTPSCookie( false, null, $request );
232 }
233
234 /**
235 * Set the "forceHTTPS" cookie
236 * @param bool $set Whether the cookie should be set or not
237 * @param SessionBackend|null $backend
238 * @param WebRequest $request
239 */
240 protected function setForceHTTPSCookie(
241 $set, SessionBackend $backend = null, WebRequest $request
242 ) {
243 $response = $request->response();
244 if ( $set ) {
245 $response->setCookie( 'forceHTTPS', 'true', $backend->shouldRememberUser() ? 0 : null,
246 array( 'prefix' => '', 'secure' => false ) + $this->cookieOptions );
247 } else {
248 $response->clearCookie( 'forceHTTPS',
249 array( 'prefix' => '', 'secure' => false ) + $this->cookieOptions );
250 }
251 }
252
253 /**
254 * Set the "logged out" cookie
255 * @param int $loggedOut timestamp
256 * @param WebRequest $request
257 */
258 protected function setLoggedOutCookie( $loggedOut, WebRequest $request ) {
259 if ( $loggedOut + 86400 > time() &&
260 $loggedOut !== (int)$this->getCookie( $request, 'LoggedOut', $this->cookieOptions['prefix'] )
261 ) {
262 $request->response()->setCookie( 'LoggedOut', $loggedOut, $loggedOut + 86400,
263 $this->cookieOptions );
264 }
265 }
266
267 public function getVaryCookies() {
268 return array(
269 // Vary on token and session because those are the real authn
270 // determiners. UserID and UserName don't matter without those.
271 $this->cookieOptions['prefix'] . 'Token',
272 $this->cookieOptions['prefix'] . 'LoggedOut',
273 $this->params['sessionName'],
274 'forceHTTPS',
275 );
276 }
277
278 public function suggestLoginUsername( WebRequest $request ) {
279 $name = $this->getCookie( $request, 'UserName', $this->cookieOptions['prefix'] );
280 if ( $name !== null ) {
281 $name = User::getCanonicalName( $name, 'usable' );
282 }
283 return $name === false ? null : $name;
284 }
285
286 /**
287 * Fetch the user identity from cookies
288 * @param \WebRequest $request
289 * @return array (string|null $id, string|null $username, string|null $token)
290 */
291 protected function getUserInfoFromCookies( $request ) {
292 $prefix = $this->cookieOptions['prefix'];
293 return array(
294 $this->getCookie( $request, 'UserID', $prefix ),
295 $this->getCookie( $request, 'UserName', $prefix ),
296 $this->getCookie( $request, 'Token', $prefix ),
297 );
298 }
299
300 /**
301 * Get a cookie. Contains an auth-specific hack.
302 * @param \WebRequest $request
303 * @param string $key
304 * @param string $prefix
305 * @param mixed $default
306 * @return mixed
307 */
308 protected function getCookie( $request, $key, $prefix, $default = null ) {
309 $value = $request->getCookie( $key, $prefix, $default );
310 if ( $value === 'deleted' ) {
311 // PHP uses this value when deleting cookies. A legitimate cookie will never have
312 // this value (usernames start with uppercase, token is longer, other auth cookies
313 // are booleans or integers). Seeing this means that in a previous request we told the
314 // client to delete the cookie, but it has poor cookie handling. Pretend the cookie is
315 // not there to avoid invalidating the session.
316 return null;
317 }
318 return $value;
319 }
320
321 /**
322 * Return the data to store in cookies
323 * @param User $user
324 * @param bool $remember
325 * @return array $cookies Set value false to unset the cookie
326 */
327 protected function cookieDataToExport( $user, $remember ) {
328 if ( $user->isAnon() ) {
329 return array(
330 'UserID' => false,
331 'Token' => false,
332 );
333 } else {
334 return array(
335 'UserID' => $user->getId(),
336 'UserName' => $user->getName(),
337 'Token' => $remember ? (string)$user->getToken() : false,
338 );
339 }
340 }
341
342 /**
343 * Return extra data to store in the session
344 * @param User $user
345 * @return array $session
346 */
347 protected function sessionDataToExport( $user ) {
348 // If we're calling the legacy hook, we should populate $session
349 // like User::setCookies() did.
350 if ( !$user->isAnon() && $this->params['callUserSetCookiesHook'] ) {
351 return array(
352 'wsUserID' => $user->getId(),
353 'wsToken' => $user->getToken(),
354 'wsUserName' => $user->getName(),
355 );
356 }
357
358 return array();
359 }
360
361 public function whyNoSession() {
362 return wfMessage( 'sessionprovider-nocookies' );
363 }
364
365 }