Don't check namespace in SpecialWantedtemplates
[lhc/web/wiklou.git] / includes / context / RequestContext.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @since 1.18
19 *
20 * @author Alexandre Emsenhuber
21 * @author Daniel Friesen
22 * @file
23 */
24
25 /**
26 * Group all the pieces relevant to the context of a request into one instance
27 */
28 class RequestContext implements IContextSource {
29 /**
30 * @var WebRequest
31 */
32 private $request;
33
34 /**
35 * @var Title
36 */
37 private $title;
38
39 /**
40 * @var WikiPage
41 */
42 private $wikipage;
43
44 /**
45 * @var OutputPage
46 */
47 private $output;
48
49 /**
50 * @var User
51 */
52 private $user;
53
54 /**
55 * @var Language
56 */
57 private $lang;
58
59 /**
60 * @var Skin
61 */
62 private $skin;
63
64 /**
65 * @var StatsdDataFactory
66 */
67 private $stats;
68
69 /**
70 * @var Config
71 */
72 private $config;
73
74 /**
75 * @var RequestContext
76 */
77 private static $instance = null;
78
79 /**
80 * Set the Config object
81 *
82 * @param Config $c
83 */
84 public function setConfig( Config $c ) {
85 $this->config = $c;
86 }
87
88 /**
89 * Get the Config object
90 *
91 * @return Config
92 */
93 public function getConfig() {
94 if ( $this->config === null ) {
95 // @todo In the future, we could move this to WebStart.php so
96 // the Config object is ready for when initialization happens
97 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
98 }
99
100 return $this->config;
101 }
102
103 /**
104 * Set the WebRequest object
105 *
106 * @param WebRequest $r
107 */
108 public function setRequest( WebRequest $r ) {
109 $this->request = $r;
110 }
111
112 /**
113 * Get the WebRequest object
114 *
115 * @return WebRequest
116 */
117 public function getRequest() {
118 if ( $this->request === null ) {
119 global $wgRequest; # fallback to $wg till we can improve this
120 $this->request = $wgRequest;
121 }
122
123 return $this->request;
124 }
125
126 /**
127 * Get the Stats object
128 *
129 * @return BufferingStatsdDataFactory
130 */
131 public function getStats() {
132 if ( $this->stats === null ) {
133 $config = $this->getConfig();
134 $prefix = $config->has( 'StatsdMetricPrefix' )
135 ? rtrim( $config->get( 'StatsdMetricPrefix' ), '.' )
136 : 'MediaWiki';
137 $this->stats = new BufferingStatsdDataFactory( $prefix );
138 }
139 return $this->stats;
140 }
141
142 /**
143 * Set the Title object
144 *
145 * @param Title $title
146 */
147 public function setTitle( Title $title ) {
148 $this->title = $title;
149 // Erase the WikiPage so a new one with the new title gets created.
150 $this->wikipage = null;
151 }
152
153 /**
154 * Get the Title object
155 *
156 * @return Title|null
157 */
158 public function getTitle() {
159 if ( $this->title === null ) {
160 global $wgTitle; # fallback to $wg till we can improve this
161 $this->title = $wgTitle;
162 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
163 }
164
165 return $this->title;
166 }
167
168 /**
169 * Check, if a Title object is set
170 *
171 * @since 1.25
172 * @return bool
173 */
174 public function hasTitle() {
175 return $this->title !== null;
176 }
177
178 /**
179 * Check whether a WikiPage object can be get with getWikiPage().
180 * Callers should expect that an exception is thrown from getWikiPage()
181 * if this method returns false.
182 *
183 * @since 1.19
184 * @return bool
185 */
186 public function canUseWikiPage() {
187 if ( $this->wikipage ) {
188 // If there's a WikiPage object set, we can for sure get it
189 return true;
190 }
191 // Only pages with legitimate titles can have WikiPages.
192 // That usually means pages in non-virtual namespaces.
193 $title = $this->getTitle();
194 return $title ? $title->canExist() : false;
195 }
196
197 /**
198 * Set the WikiPage object
199 *
200 * @since 1.19
201 * @param WikiPage $p
202 */
203 public function setWikiPage( WikiPage $p ) {
204 $pageTitle = $p->getTitle();
205 if ( !$this->hasTitle() || !$pageTitle->equals( $this->getTitle() ) ) {
206 $this->setTitle( $pageTitle );
207 }
208 // Defer this to the end since setTitle sets it to null.
209 $this->wikipage = $p;
210 }
211
212 /**
213 * Get the WikiPage object.
214 * May throw an exception if there's no Title object set or the Title object
215 * belongs to a special namespace that doesn't have WikiPage, so use first
216 * canUseWikiPage() to check whether this method can be called safely.
217 *
218 * @since 1.19
219 * @throws MWException
220 * @return WikiPage
221 */
222 public function getWikiPage() {
223 if ( $this->wikipage === null ) {
224 $title = $this->getTitle();
225 if ( $title === null ) {
226 throw new MWException( __METHOD__ . ' called without Title object set' );
227 }
228 $this->wikipage = WikiPage::factory( $title );
229 }
230
231 return $this->wikipage;
232 }
233
234 /**
235 * @param OutputPage $o
236 */
237 public function setOutput( OutputPage $o ) {
238 $this->output = $o;
239 }
240
241 /**
242 * Get the OutputPage object
243 *
244 * @return OutputPage
245 */
246 public function getOutput() {
247 if ( $this->output === null ) {
248 $this->output = new OutputPage( $this );
249 }
250
251 return $this->output;
252 }
253
254 /**
255 * Set the User object
256 *
257 * @param User $u
258 */
259 public function setUser( User $u ) {
260 $this->user = $u;
261 }
262
263 /**
264 * Get the User object
265 *
266 * @return User
267 */
268 public function getUser() {
269 if ( $this->user === null ) {
270 $this->user = User::newFromSession( $this->getRequest() );
271 }
272
273 return $this->user;
274 }
275
276 /**
277 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
278 * code and replaces with $wgLanguageCode if not sane.
279 * @param string $code Language code
280 * @return string
281 */
282 public static function sanitizeLangCode( $code ) {
283 global $wgLanguageCode;
284
285 // BCP 47 - letter case MUST NOT carry meaning
286 $code = strtolower( $code );
287
288 # Validate $code
289 if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
290 wfDebug( "Invalid user language code\n" );
291 $code = $wgLanguageCode;
292 }
293
294 return $code;
295 }
296
297 /**
298 * Set the Language object
299 *
300 * @param Language|string $l Language instance or language code
301 * @throws MWException
302 * @since 1.19
303 */
304 public function setLanguage( $l ) {
305 if ( $l instanceof Language ) {
306 $this->lang = $l;
307 } elseif ( is_string( $l ) ) {
308 $l = self::sanitizeLangCode( $l );
309 $obj = Language::factory( $l );
310 $this->lang = $obj;
311 } else {
312 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
313 }
314 }
315
316 /**
317 * Get the Language object.
318 * Initialization of user or request objects can depend on this.
319 * @return Language
320 * @throws Exception
321 * @since 1.19
322 */
323 public function getLanguage() {
324 if ( isset( $this->recursion ) ) {
325 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
326 $e = new Exception;
327 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
328
329 $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
330 $this->lang = Language::factory( $code );
331 } elseif ( $this->lang === null ) {
332 $this->recursion = true;
333
334 global $wgContLang;
335
336 try {
337 $request = $this->getRequest();
338 $user = $this->getUser();
339
340 $code = $request->getVal( 'uselang', 'user' );
341 if ( $code === 'user' ) {
342 $code = $user->getOption( 'language' );
343 }
344 $code = self::sanitizeLangCode( $code );
345
346 Hooks::run( 'UserGetLanguageObject', array( $user, &$code, $this ) );
347
348 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
349 $this->lang = $wgContLang;
350 } else {
351 $obj = Language::factory( $code );
352 $this->lang = $obj;
353 }
354
355 unset( $this->recursion );
356 }
357 catch ( Exception $ex ) {
358 unset( $this->recursion );
359 throw $ex;
360 }
361 }
362
363 return $this->lang;
364 }
365
366 /**
367 * Set the Skin object
368 *
369 * @param Skin $s
370 */
371 public function setSkin( Skin $s ) {
372 $this->skin = clone $s;
373 $this->skin->setContext( $this );
374 }
375
376 /**
377 * Get the Skin object
378 *
379 * @return Skin
380 */
381 public function getSkin() {
382 if ( $this->skin === null ) {
383
384 $skin = null;
385 Hooks::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
386 $factory = SkinFactory::getDefaultInstance();
387
388 // If the hook worked try to set a skin from it
389 if ( $skin instanceof Skin ) {
390 $this->skin = $skin;
391 } elseif ( is_string( $skin ) ) {
392 // Normalize the key, just in case the hook did something weird.
393 $normalized = Skin::normalizeKey( $skin );
394 $this->skin = $factory->makeSkin( $normalized );
395 }
396
397 // If this is still null (the hook didn't run or didn't work)
398 // then go through the normal processing to load a skin
399 if ( $this->skin === null ) {
400 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
401 # get the user skin
402 $userSkin = $this->getUser()->getOption( 'skin' );
403 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
404 } else {
405 # if we're not allowing users to override, then use the default
406 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
407 }
408
409 // Normalize the key in case the user is passing gibberish
410 // or has old preferences (bug 69566).
411 $normalized = Skin::normalizeKey( $userSkin );
412
413 // Skin::normalizeKey will also validate it, so
414 // this won't throw an exception
415 $this->skin = $factory->makeSkin( $normalized );
416 }
417
418 // After all that set a context on whatever skin got created
419 $this->skin->setContext( $this );
420 }
421
422 return $this->skin;
423 }
424
425 /** Helpful methods **/
426
427 /**
428 * Get a Message object with context set
429 * Parameters are the same as wfMessage()
430 *
431 * @return Message
432 */
433 public function msg() {
434 $args = func_get_args();
435
436 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
437 }
438
439 /** Static methods **/
440
441 /**
442 * Get the RequestContext object associated with the main request
443 *
444 * @return RequestContext
445 */
446 public static function getMain() {
447 if ( self::$instance === null ) {
448 self::$instance = new self;
449 }
450
451 return self::$instance;
452 }
453
454 /**
455 * Get the RequestContext object associated with the main request
456 * and gives a warning to the log, to find places, where a context maybe is missing.
457 *
458 * @param string $func
459 * @return RequestContext
460 * @since 1.24
461 */
462 public static function getMainAndWarn( $func = __METHOD__ ) {
463 wfDebug( $func . ' called without context. ' .
464 "Using RequestContext::getMain() for sanity\n" );
465
466 return self::getMain();
467 }
468
469 /**
470 * Resets singleton returned by getMain(). Should be called only from unit tests.
471 */
472 public static function resetMain() {
473 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
474 throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
475 }
476 self::$instance = null;
477 }
478
479 /**
480 * Export the resolved user IP, HTTP headers, user ID, and session ID.
481 * The result will be reasonably sized to allow for serialization.
482 *
483 * @return array
484 * @since 1.21
485 */
486 public function exportSession() {
487 return array(
488 'ip' => $this->getRequest()->getIP(),
489 'headers' => $this->getRequest()->getAllHeaders(),
490 'sessionId' => session_id(),
491 'userId' => $this->getUser()->getId()
492 );
493 }
494
495 /**
496 * Import an client IP address, HTTP headers, user ID, and session ID
497 *
498 * This sets the current session and sets $wgUser and $wgRequest.
499 * Once the return value falls out of scope, the old context is restored.
500 * This method should only be called in contexts (CLI or HTTP job runners)
501 * where there is no session ID or end user receiving the response. This
502 * is partly enforced, and is done so to avoid leaking cookies if certain
503 * error conditions arise.
504 *
505 * This will setup the session from the given ID. This is useful when
506 * background scripts inherit context when acting on behalf of a user.
507 *
508 * @note suhosin.session.encrypt may interfere with this method.
509 *
510 * @param array $params Result of RequestContext::exportSession()
511 * @return ScopedCallback
512 * @throws MWException
513 * @since 1.21
514 */
515 public static function importScopedSession( array $params ) {
516 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
517 // Sanity check to avoid sending random cookies for the wrong users.
518 // This method should only called by CLI scripts or by HTTP job runners.
519 throw new MWException( "Sessions can only be imported when none is active." );
520 } elseif ( !IP::isValid( $params['ip'] ) ) {
521 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
522 }
523
524 if ( $params['userId'] ) { // logged-in user
525 $user = User::newFromId( $params['userId'] );
526 $user->load();
527 if ( !$user->getId() ) {
528 throw new MWException( "No user with ID '{$params['userId']}'." );
529 }
530 } else { // anon user
531 $user = User::newFromName( $params['ip'], false );
532 }
533
534 $importSessionFunc = function ( User $user, array $params ) {
535 global $wgRequest, $wgUser;
536
537 $context = RequestContext::getMain();
538 // Commit and close any current session
539 session_write_close(); // persist
540 session_id( '' ); // detach
541 $_SESSION = array(); // clear in-memory array
542 // Remove any user IP or agent information
543 $context->setRequest( new FauxRequest() );
544 $wgRequest = $context->getRequest(); // b/c
545 // Now that all private information is detached from the user, it should
546 // be safe to load the new user. If errors occur or an exception is thrown
547 // and caught (leaving the main context in a mixed state), there is no risk
548 // of the User object being attached to the wrong IP, headers, or session.
549 $context->setUser( $user );
550 $wgUser = $context->getUser(); // b/c
551 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
552 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
553 }
554 $request = new FauxRequest( array(), false, $_SESSION );
555 $request->setIP( $params['ip'] );
556 foreach ( $params['headers'] as $name => $value ) {
557 $request->setHeader( $name, $value );
558 }
559 // Set the current context to use the new WebRequest
560 $context->setRequest( $request );
561 $wgRequest = $context->getRequest(); // b/c
562 };
563
564 // Stash the old session and load in the new one
565 $oUser = self::getMain()->getUser();
566 $oParams = self::getMain()->exportSession();
567 $oRequest = self::getMain()->getRequest();
568 $importSessionFunc( $user, $params );
569
570 // Set callback to save and close the new session and reload the old one
571 return new ScopedCallback(
572 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
573 global $wgRequest;
574 $importSessionFunc( $oUser, $oParams );
575 // Restore the exact previous Request object (instead of leaving FauxRequest)
576 RequestContext::getMain()->setRequest( $oRequest );
577 $wgRequest = RequestContext::getMain()->getRequest(); // b/c
578 }
579 );
580 }
581
582 /**
583 * Create a new extraneous context. The context is filled with information
584 * external to the current session.
585 * - Title is specified by argument
586 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
587 * - User is an anonymous user, for separation IPv4 localhost is used
588 * - Language will be based on the anonymous user and request, may be content
589 * language or a uselang param in the fauxrequest data may change the lang
590 * - Skin will be based on the anonymous user, should be the wiki's default skin
591 *
592 * @param Title $title Title to use for the extraneous request
593 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
594 * @return RequestContext
595 */
596 public static function newExtraneousContext( Title $title, $request = array() ) {
597 $context = new self;
598 $context->setTitle( $title );
599 if ( $request instanceof WebRequest ) {
600 $context->setRequest( $request );
601 } else {
602 $context->setRequest( new FauxRequest( $request ) );
603 }
604 $context->user = User::newFromName( '127.0.0.1', false );
605
606 return $context;
607 }
608 }