Merge "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, MutableContext {
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 \Liuggio\StatsdClient\Factory\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->get( '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 $skin = null;
384 Hooks::run( 'RequestContextCreateSkin', array( $this, &$skin ) );
385 $factory = SkinFactory::getDefaultInstance();
386
387 // If the hook worked try to set a skin from it
388 if ( $skin instanceof Skin ) {
389 $this->skin = $skin;
390 } elseif ( is_string( $skin ) ) {
391 // Normalize the key, just in case the hook did something weird.
392 $normalized = Skin::normalizeKey( $skin );
393 $this->skin = $factory->makeSkin( $normalized );
394 }
395
396 // If this is still null (the hook didn't run or didn't work)
397 // then go through the normal processing to load a skin
398 if ( $this->skin === null ) {
399 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
400 # get the user skin
401 $userSkin = $this->getUser()->getOption( 'skin' );
402 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
403 } else {
404 # if we're not allowing users to override, then use the default
405 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
406 }
407
408 // Normalize the key in case the user is passing gibberish
409 // or has old preferences (bug 69566).
410 $normalized = Skin::normalizeKey( $userSkin );
411
412 // Skin::normalizeKey will also validate it, so
413 // this won't throw an exception
414 $this->skin = $factory->makeSkin( $normalized );
415 }
416
417 // After all that set a context on whatever skin got created
418 $this->skin->setContext( $this );
419 }
420
421 return $this->skin;
422 }
423
424 /** Helpful methods **/
425
426 /**
427 * Get a Message object with context set
428 * Parameters are the same as wfMessage()
429 *
430 * @param mixed ...
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, $wgUser, and $wgRequest from $params.
499 * Once the return value falls out of scope, the old context is restored.
500 * This method should only be called in contexts where there is no session
501 * ID or end user receiving the response (CLI or HTTP job runners). This
502 * is partly enforced, and is done so to avoid leaking cookies if certain
503 * error conditions arise.
504 *
505 * This is useful when background scripts inherit context when acting on
506 * behalf of a user. In general the 'sessionId' parameter should be set
507 * to an empty string unless session importing is *truly* needed. This
508 * feature is somewhat deprecated.
509 *
510 * @note suhosin.session.encrypt may interfere with this method.
511 *
512 * @param array $params Result of RequestContext::exportSession()
513 * @return ScopedCallback
514 * @throws MWException
515 * @since 1.21
516 */
517 public static function importScopedSession( array $params ) {
518 if ( session_id() != '' && strlen( $params['sessionId'] ) ) {
519 // Sanity check to avoid sending random cookies for the wrong users.
520 // This method should only called by CLI scripts or by HTTP job runners.
521 throw new MWException( "Sessions can only be imported when none is active." );
522 } elseif ( !IP::isValid( $params['ip'] ) ) {
523 throw new MWException( "Invalid client IP address '{$params['ip']}'." );
524 }
525
526 if ( $params['userId'] ) { // logged-in user
527 $user = User::newFromId( $params['userId'] );
528 $user->load();
529 if ( !$user->getId() ) {
530 throw new MWException( "No user with ID '{$params['userId']}'." );
531 }
532 } else { // anon user
533 $user = User::newFromName( $params['ip'], false );
534 }
535
536 $importSessionFunc = function ( User $user, array $params ) {
537 global $wgRequest, $wgUser;
538
539 $context = RequestContext::getMain();
540 // Commit and close any current session
541 session_write_close(); // persist
542 session_id( '' ); // detach
543 $_SESSION = array(); // clear in-memory array
544 // Remove any user IP or agent information
545 $context->setRequest( new FauxRequest() );
546 $wgRequest = $context->getRequest(); // b/c
547 // Now that all private information is detached from the user, it should
548 // be safe to load the new user. If errors occur or an exception is thrown
549 // and caught (leaving the main context in a mixed state), there is no risk
550 // of the User object being attached to the wrong IP, headers, or session.
551 $context->setUser( $user );
552 $wgUser = $context->getUser(); // b/c
553 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
554 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
555 }
556 $request = new FauxRequest( array(), false, $_SESSION );
557 $request->setIP( $params['ip'] );
558 foreach ( $params['headers'] as $name => $value ) {
559 $request->setHeader( $name, $value );
560 }
561 // Set the current context to use the new WebRequest
562 $context->setRequest( $request );
563 $wgRequest = $context->getRequest(); // b/c
564 };
565
566 // Stash the old session and load in the new one
567 $oUser = self::getMain()->getUser();
568 $oParams = self::getMain()->exportSession();
569 $oRequest = self::getMain()->getRequest();
570 $importSessionFunc( $user, $params );
571
572 // Set callback to save and close the new session and reload the old one
573 return new ScopedCallback(
574 function () use ( $importSessionFunc, $oUser, $oParams, $oRequest ) {
575 global $wgRequest;
576 $importSessionFunc( $oUser, $oParams );
577 // Restore the exact previous Request object (instead of leaving FauxRequest)
578 RequestContext::getMain()->setRequest( $oRequest );
579 $wgRequest = RequestContext::getMain()->getRequest(); // b/c
580 }
581 );
582 }
583
584 /**
585 * Create a new extraneous context. The context is filled with information
586 * external to the current session.
587 * - Title is specified by argument
588 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
589 * - User is an anonymous user, for separation IPv4 localhost is used
590 * - Language will be based on the anonymous user and request, may be content
591 * language or a uselang param in the fauxrequest data may change the lang
592 * - Skin will be based on the anonymous user, should be the wiki's default skin
593 *
594 * @param Title $title Title to use for the extraneous request
595 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
596 * @return RequestContext
597 */
598 public static function newExtraneousContext( Title $title, $request = array() ) {
599 $context = new self;
600 $context->setTitle( $title );
601 if ( $request instanceof WebRequest ) {
602 $context->setRequest( $request );
603 } else {
604 $context->setRequest( new FauxRequest( $request ) );
605 }
606 $context->user = User::newFromName( '127.0.0.1', false );
607
608 return $context;
609 }
610 }