Merge "Accessibility: Make the collapsible sidebar screen reader friendly"
[lhc/web/wiklou.git] / includes / context / RequestContext.php
1 <?php
2 /**
3 * Request-dependant objects containers.
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 * @since 1.18
21 *
22 * @author Alexandre Emsenhuber
23 * @author Daniel Friesen
24 * @file
25 */
26
27 /**
28 * Group all the pieces relevant to the context of a request into one instance
29 */
30 class RequestContext implements IContextSource {
31 /**
32 * @var WebRequest
33 */
34 private $request;
35
36 /**
37 * @var Title
38 */
39 private $title;
40
41 /**
42 * @var WikiPage
43 */
44 private $wikipage;
45
46 /**
47 * @var OutputPage
48 */
49 private $output;
50
51 /**
52 * @var User
53 */
54 private $user;
55
56 /**
57 * @var Language
58 */
59 private $lang;
60
61 /**
62 * @var Skin
63 */
64 private $skin;
65
66 /**
67 * Set the WebRequest object
68 *
69 * @param WebRequest $r
70 */
71 public function setRequest( WebRequest $r ) {
72 $this->request = $r;
73 }
74
75 /**
76 * Get the WebRequest object
77 *
78 * @return WebRequest
79 */
80 public function getRequest() {
81 if ( $this->request === null ) {
82 global $wgRequest; # fallback to $wg till we can improve this
83 $this->request = $wgRequest;
84 }
85 return $this->request;
86 }
87
88 /**
89 * Set the Title object
90 *
91 * @param Title $t
92 */
93 public function setTitle( $t ) {
94 if ( $t !== null && !$t instanceof Title ) {
95 throw new MWException( __METHOD__ . " expects an instance of Title" );
96 }
97 $this->title = $t;
98 // Erase the WikiPage so a new one with the new title gets created.
99 $this->wikipage = null;
100 }
101
102 /**
103 * Get the Title object
104 *
105 * @return Title
106 */
107 public function getTitle() {
108 if ( $this->title === null ) {
109 global $wgTitle; # fallback to $wg till we can improve this
110 $this->title = $wgTitle;
111 }
112 return $this->title;
113 }
114
115 /**
116 * Check whether a WikiPage object can be get with getWikiPage().
117 * Callers should expect that an exception is thrown from getWikiPage()
118 * if this method returns false.
119 *
120 * @since 1.19
121 * @return bool
122 */
123 public function canUseWikiPage() {
124 if ( $this->wikipage !== null ) {
125 # If there's a WikiPage object set, we can for sure get it
126 return true;
127 }
128 $title = $this->getTitle();
129 if ( $title === null ) {
130 # No Title, no WikiPage
131 return false;
132 } else {
133 # Only namespaces whose pages are stored in the database can have WikiPage
134 return $title->canExist();
135 }
136 }
137
138 /**
139 * Set the WikiPage object
140 *
141 * @since 1.19
142 * @param WikiPage $p
143 */
144 public function setWikiPage( WikiPage $p ) {
145 $contextTitle = $this->getTitle();
146 $pageTitle = $p->getTitle();
147 if ( !$contextTitle || !$pageTitle->equals( $contextTitle ) ) {
148 $this->setTitle( $pageTitle );
149 }
150 // Defer this to the end since setTitle sets it to null.
151 $this->wikipage = $p;
152 }
153
154 /**
155 * Get the WikiPage object.
156 * May throw an exception if there's no Title object set or the Title object
157 * belongs to a special namespace that doesn't have WikiPage, so use first
158 * canUseWikiPage() to check whether this method can be called safely.
159 *
160 * @since 1.19
161 * @throws MWException
162 * @return WikiPage
163 */
164 public function getWikiPage() {
165 if ( $this->wikipage === null ) {
166 $title = $this->getTitle();
167 if ( $title === null ) {
168 throw new MWException( __METHOD__ . ' called without Title object set' );
169 }
170 $this->wikipage = WikiPage::factory( $title );
171 }
172 return $this->wikipage;
173 }
174
175 /**
176 * @param $o OutputPage
177 */
178 public function setOutput( OutputPage $o ) {
179 $this->output = $o;
180 }
181
182 /**
183 * Get the OutputPage object
184 *
185 * @return OutputPage
186 */
187 public function getOutput() {
188 if ( $this->output === null ) {
189 $this->output = new OutputPage( $this );
190 }
191 return $this->output;
192 }
193
194 /**
195 * Set the User object
196 *
197 * @param User $u
198 */
199 public function setUser( User $u ) {
200 $this->user = $u;
201 }
202
203 /**
204 * Get the User object
205 *
206 * @return User
207 */
208 public function getUser() {
209 if ( $this->user === null ) {
210 $this->user = User::newFromSession( $this->getRequest() );
211 }
212 return $this->user;
213 }
214
215 /**
216 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
217 * code and replaces with $wgLanguageCode if not sane.
218 * @param string $code Language code
219 * @return string
220 */
221 public static function sanitizeLangCode( $code ) {
222 global $wgLanguageCode;
223
224 // BCP 47 - letter case MUST NOT carry meaning
225 $code = strtolower( $code );
226
227 # Validate $code
228 if ( empty( $code ) || !Language::isValidCode( $code ) || ( $code === 'qqq' ) ) {
229 wfDebug( "Invalid user language code\n" );
230 $code = $wgLanguageCode;
231 }
232
233 return $code;
234 }
235
236 /**
237 * Set the Language object
238 *
239 * @deprecated since 1.19 Use setLanguage instead
240 * @param Language|string $l Language instance or language code
241 */
242 public function setLang( $l ) {
243 wfDeprecated( __METHOD__, '1.19' );
244 $this->setLanguage( $l );
245 }
246
247 /**
248 * Set the Language object
249 *
250 * @param Language|string $l Language instance or language code
251 * @throws MWException
252 * @since 1.19
253 */
254 public function setLanguage( $l ) {
255 if ( $l instanceof Language ) {
256 $this->lang = $l;
257 } elseif ( is_string( $l ) ) {
258 $l = self::sanitizeLangCode( $l );
259 $obj = Language::factory( $l );
260 $this->lang = $obj;
261 } else {
262 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
263 }
264 }
265
266 /**
267 * @deprecated since 1.19 Use getLanguage instead
268 * @return Language
269 */
270 public function getLang() {
271 wfDeprecated( __METHOD__, '1.19' );
272 return $this->getLanguage();
273 }
274
275 /**
276 * Get the Language object.
277 * Initialization of user or request objects can depend on this.
278 *
279 * @return Language
280 * @since 1.19
281 */
282 public function getLanguage() {
283 if ( isset( $this->recursion ) ) {
284 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
285 $e = new Exception;
286 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
287
288 global $wgLanguageCode;
289 $code = ( $wgLanguageCode ) ? $wgLanguageCode : 'en';
290 $this->lang = Language::factory( $code );
291 } elseif ( $this->lang === null ) {
292 $this->recursion = true;
293
294 global $wgLanguageCode, $wgContLang;
295
296 $request = $this->getRequest();
297 $user = $this->getUser();
298
299 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
300 $code = self::sanitizeLangCode( $code );
301
302 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
303
304 if ( $code === $wgLanguageCode ) {
305 $this->lang = $wgContLang;
306 } else {
307 $obj = Language::factory( $code );
308 $this->lang = $obj;
309 }
310
311 unset( $this->recursion );
312 }
313
314 return $this->lang;
315 }
316
317 /**
318 * Set the Skin object
319 *
320 * @param Skin $s
321 */
322 public function setSkin( Skin $s ) {
323 $this->skin = clone $s;
324 $this->skin->setContext( $this );
325 }
326
327 /**
328 * Get the Skin object
329 *
330 * @return Skin
331 */
332 public function getSkin() {
333 if ( $this->skin === null ) {
334 wfProfileIn( __METHOD__ . '-createskin' );
335
336 $skin = null;
337 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
338
339 // If the hook worked try to set a skin from it
340 if ( $skin instanceof Skin ) {
341 $this->skin = $skin;
342 } elseif ( is_string( $skin ) ) {
343 $this->skin = Skin::newFromKey( $skin );
344 }
345
346 // If this is still null (the hook didn't run or didn't work)
347 // then go through the normal processing to load a skin
348 if ( $this->skin === null ) {
349 global $wgHiddenPrefs;
350 if ( !in_array( 'skin', $wgHiddenPrefs ) ) {
351 # get the user skin
352 $userSkin = $this->getUser()->getOption( 'skin' );
353 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
354 } else {
355 # if we're not allowing users to override, then use the default
356 global $wgDefaultSkin;
357 $userSkin = $wgDefaultSkin;
358 }
359
360 $this->skin = Skin::newFromKey( $userSkin );
361 }
362
363 // After all that set a context on whatever skin got created
364 $this->skin->setContext( $this );
365 wfProfileOut( __METHOD__ . '-createskin' );
366 }
367 return $this->skin;
368 }
369
370 /** Helpful methods **/
371
372 /**
373 * Get a Message object with context set
374 * Parameters are the same as wfMessage()
375 *
376 * @return Message
377 */
378 public function msg() {
379 $args = func_get_args();
380 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
381 }
382
383 /** Static methods **/
384
385 /**
386 * Get the RequestContext object associated with the main request
387 *
388 * @return RequestContext
389 */
390 public static function getMain() {
391 static $instance = null;
392 if ( $instance === null ) {
393 $instance = new self;
394 }
395 return $instance;
396 }
397
398 /**
399 * Export the resolved user IP, HTTP headers, user ID, and session ID.
400 * The result will be reasonably sized to allow for serialization.
401 *
402 * @return Array
403 * @since 1.21
404 */
405 public function exportSession() {
406 return array(
407 'ip' => $this->getRequest()->getIP(),
408 'headers' => $this->getRequest()->getAllHeaders(),
409 'sessionId' => session_id(),
410 'userId' => $this->getUser()->getId()
411 );
412 }
413
414 /**
415 * Import the resolved user IP, HTTP headers, user ID, and session ID.
416 * This sets the current session and sets $wgUser and $wgRequest.
417 * Once the return value falls out of scope, the old context is restored.
418 * This function can only be called within CLI mode scripts.
419 *
420 * This will setup the session from the given ID. This is useful when
421 * background scripts inherit context when acting on behalf of a user.
422 *
423 * @note suhosin.session.encrypt may interfere with this method.
424 *
425 * @param array $params Result of RequestContext::exportSession()
426 * @return ScopedCallback
427 * @throws MWException
428 * @since 1.21
429 */
430 public static function importScopedSession( array $params ) {
431 if ( PHP_SAPI !== 'cli' ) {
432 // Don't send random private cookies or turn $wgRequest into FauxRequest
433 throw new MWException( "Sessions can only be imported in cli mode." );
434 } elseif ( !strlen( $params['sessionId'] ) ) {
435 throw new MWException( "No session ID was specified." );
436 }
437
438 if ( $params['userId'] ) { // logged-in user
439 $user = User::newFromId( $params['userId'] );
440 if ( !$user ) {
441 throw new MWException( "No user with ID '{$params['userId']}'." );
442 }
443 } elseif ( !IP::isValid( $params['ip'] ) ) {
444 throw new MWException( "Could not load user '{$params['ip']}'." );
445 } else { // anon user
446 $user = User::newFromName( $params['ip'], false );
447 }
448
449 $importSessionFunction = function( User $user, array $params ) {
450 global $wgRequest, $wgUser;
451
452 $context = RequestContext::getMain();
453 // Commit and close any current session
454 session_write_close(); // persist
455 session_id( '' ); // detach
456 $_SESSION = array(); // clear in-memory array
457 // Remove any user IP or agent information
458 $context->setRequest( new FauxRequest() );
459 $wgRequest = $context->getRequest(); // b/c
460 // Now that all private information is detached from the user, it should
461 // be safe to load the new user. If errors occur or an exception is thrown
462 // and caught (leaving the main context in a mixed state), there is no risk
463 // of the User object being attached to the wrong IP, headers, or session.
464 $context->setUser( $user );
465 $wgUser = $context->getUser(); // b/c
466 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
467 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
468 }
469 $request = new FauxRequest( array(), false, $_SESSION );
470 $request->setIP( $params['ip'] );
471 foreach ( $params['headers'] as $name => $value ) {
472 $request->setHeader( $name, $value );
473 }
474 // Set the current context to use the new WebRequest
475 $context->setRequest( $request );
476 $wgRequest = $context->getRequest(); // b/c
477 };
478
479 // Stash the old session and load in the new one
480 $oUser = self::getMain()->getUser();
481 $oParams = self::getMain()->exportSession();
482 $importSessionFunction( $user, $params );
483
484 // Set callback to save and close the new session and reload the old one
485 return new ScopedCallback( function() use ( $importSessionFunction, $oUser, $oParams ) {
486 $importSessionFunction( $oUser, $oParams );
487 } );
488 }
489
490 /**
491 * Create a new extraneous context. The context is filled with information
492 * external to the current session.
493 * - Title is specified by argument
494 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
495 * - User is an anonymous user, for separation IPv4 localhost is used
496 * - Language will be based on the anonymous user and request, may be content
497 * language or a uselang param in the fauxrequest data may change the lang
498 * - Skin will be based on the anonymous user, should be the wiki's default skin
499 *
500 * @param Title $title Title to use for the extraneous request
501 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
502 * @return RequestContext
503 */
504 public static function newExtraneousContext( Title $title, $request = array() ) {
505 $context = new self;
506 $context->setTitle( $title );
507 if ( $request instanceof WebRequest ) {
508 $context->setRequest( $request );
509 } else {
510 $context->setRequest( new FauxRequest( $request ) );
511 }
512 $context->user = User::newFromName( '127.0.0.1', false );
513 return $context;
514 }
515 }