Merge "MediaWikiTestCase: Centralise insertPage() logic from SearchEngineTest"
[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 * @var Config
68 */
69 private $config;
70
71 /**
72 * @var RequestContext
73 */
74 private static $instance = null;
75
76 /**
77 * Set the Config object
78 *
79 * @param Config $c
80 */
81 public function setConfig( Config $c ) {
82 $this->config = $c;
83 }
84
85 /**
86 * Get the Config object
87 *
88 * @return Config
89 */
90 public function getConfig() {
91 if ( $this->config === null ) {
92 // @todo In the future, we could move this to WebStart.php so
93 // the Config object is ready for when initialization happens
94 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
95 }
96
97 return $this->config;
98 }
99
100 /**
101 * Set the WebRequest object
102 *
103 * @param WebRequest $r
104 */
105 public function setRequest( WebRequest $r ) {
106 $this->request = $r;
107 }
108
109 /**
110 * Get the WebRequest object
111 *
112 * @return WebRequest
113 */
114 public function getRequest() {
115 if ( $this->request === null ) {
116 global $wgRequest; # fallback to $wg till we can improve this
117 $this->request = $wgRequest;
118 }
119
120 return $this->request;
121 }
122
123 /**
124 * Set the Title object
125 *
126 * @param Title $title
127 */
128 public function setTitle( Title $title ) {
129 $this->title = $title;
130 // Erase the WikiPage so a new one with the new title gets created.
131 $this->wikipage = null;
132 }
133
134 /**
135 * Get the Title object
136 *
137 * @return Title|null
138 */
139 public function getTitle() {
140 if ( $this->title === null ) {
141 global $wgTitle; # fallback to $wg till we can improve this
142 $this->title = $wgTitle;
143 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetCaller() . ' with no title set.' );
144 }
145
146 return $this->title;
147 }
148
149 /**
150 * Check whether a WikiPage object can be get with getWikiPage().
151 * Callers should expect that an exception is thrown from getWikiPage()
152 * if this method returns false.
153 *
154 * @since 1.19
155 * @return bool
156 */
157 public function canUseWikiPage() {
158 if ( $this->wikipage ) {
159 // If there's a WikiPage object set, we can for sure get it
160 return true;
161 }
162 // Only pages with legitimate titles can have WikiPages.
163 // That usually means pages in non-virtual namespaces.
164 $title = $this->getTitle();
165 return $title ? $title->canExist() : false;
166 }
167
168 /**
169 * Set the WikiPage object
170 *
171 * @since 1.19
172 * @param WikiPage $p
173 */
174 public function setWikiPage( WikiPage $p ) {
175 $contextTitle = $this->getTitle();
176 $pageTitle = $p->getTitle();
177 if ( !$contextTitle || !$pageTitle->equals( $contextTitle ) ) {
178 $this->setTitle( $pageTitle );
179 }
180 // Defer this to the end since setTitle sets it to null.
181 $this->wikipage = $p;
182 }
183
184 /**
185 * Get the WikiPage object.
186 * May throw an exception if there's no Title object set or the Title object
187 * belongs to a special namespace that doesn't have WikiPage, so use first
188 * canUseWikiPage() to check whether this method can be called safely.
189 *
190 * @since 1.19
191 * @throws MWException
192 * @return WikiPage
193 */
194 public function getWikiPage() {
195 if ( $this->wikipage === null ) {
196 $title = $this->getTitle();
197 if ( $title === null ) {
198 throw new MWException( __METHOD__ . ' called without Title object set' );
199 }
200 $this->wikipage = WikiPage::factory( $title );
201 }
202
203 return $this->wikipage;
204 }
205
206 /**
207 * @param OutputPage $o
208 */
209 public function setOutput( OutputPage $o ) {
210 $this->output = $o;
211 }
212
213 /**
214 * Get the OutputPage object
215 *
216 * @return OutputPage
217 */
218 public function getOutput() {
219 if ( $this->output === null ) {
220 $this->output = new OutputPage( $this );
221 }
222
223 return $this->output;
224 }
225
226 /**
227 * Set the User object
228 *
229 * @param User $u
230 */
231 public function setUser( User $u ) {
232 $this->user = $u;
233 }
234
235 /**
236 * Get the User object
237 *
238 * @return User
239 */
240 public function getUser() {
241 if ( $this->user === null ) {
242 $this->user = User::newFromSession( $this->getRequest() );
243 }
244
245 return $this->user;
246 }
247
248 /**
249 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
250 * code and replaces with $wgLanguageCode if not sane.
251 * @param string $code Language code
252 * @return string
253 */
254 public static function sanitizeLangCode( $code ) {
255 global $wgLanguageCode;
256
257 // BCP 47 - letter case MUST NOT carry meaning
258 $code = strtolower( $code );
259
260 # Validate $code
261 if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
262 wfDebug( "Invalid user language code\n" );
263 $code = $wgLanguageCode;
264 }
265
266 return $code;
267 }
268
269 /**
270 * Set the Language object
271 *
272 * @param Language|string $l Language instance or language code
273 * @throws MWException
274 * @since 1.19
275 */
276 public function setLanguage( $l ) {
277 if ( $l instanceof Language ) {
278 $this->lang = $l;
279 } elseif ( is_string( $l ) ) {
280 $l = self::sanitizeLangCode( $l );
281 $obj = Language::factory( $l );
282 $this->lang = $obj;
283 } else {
284 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
285 }
286 }
287
288 /**
289 * Get the Language object.
290 * Initialization of user or request objects can depend on this.
291 *
292 * @return Language
293 * @since 1.19
294 */
295 public function getLanguage() {
296 if ( isset( $this->recursion ) ) {
297 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
298 $e = new Exception;
299 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
300
301 $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
302 $this->lang = Language::factory( $code );
303 } elseif ( $this->lang === null ) {
304 $this->recursion = true;
305
306 global $wgContLang;
307
308 try {
309 $request = $this->getRequest();
310 $user = $this->getUser();
311
312 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
313 $code = self::sanitizeLangCode( $code );
314
315 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
316
317 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
318 $this->lang = $wgContLang;
319 } else {
320 $obj = Language::factory( $code );
321 $this->lang = $obj;
322 }
323
324 unset( $this->recursion );
325 }
326 catch ( Exception $ex ) {
327 unset( $this->recursion );
328 throw $ex;
329 }
330 }
331
332 return $this->lang;
333 }
334
335 /**
336 * Set the Skin object
337 *
338 * @param Skin $s
339 */
340 public function setSkin( Skin $s ) {
341 $this->skin = clone $s;
342 $this->skin->setContext( $this );
343 }
344
345 /**
346 * Get the Skin object
347 *
348 * @return Skin
349 */
350 public function getSkin() {
351 if ( $this->skin === null ) {
352 wfProfileIn( __METHOD__ . '-createskin' );
353
354 $skin = null;
355 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
356 $factory = SkinFactory::getDefaultInstance();
357
358 // If the hook worked try to set a skin from it
359 if ( $skin instanceof Skin ) {
360 $this->skin = $skin;
361 } elseif ( is_string( $skin ) ) {
362 // Normalize the key, just in case the hook did something weird.
363 $normalized = Skin::normalizeKey( $skin );
364 $this->skin = $factory->makeSkin( $normalized );
365 }
366
367 // If this is still null (the hook didn't run or didn't work)
368 // then go through the normal processing to load a skin
369 if ( $this->skin === null ) {
370 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
371 # get the user skin
372 $userSkin = $this->getUser()->getOption( 'skin' );
373 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
374 } else {
375 # if we're not allowing users to override, then use the default
376 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
377 }
378
379 // Normalize the key in case the user is passing gibberish
380 // or has old preferences (bug 69566).
381 $normalized = Skin::normalizeKey( $userSkin );
382
383 // Skin::normalizeKey will also validate it, so
384 // this won't throw an exception
385 $this->skin = $factory->makeSkin( $normalized );
386 }
387
388 // After all that set a context on whatever skin got created
389 $this->skin->setContext( $this );
390 wfProfileOut( __METHOD__ . '-createskin' );
391 }
392
393 return $this->skin;
394 }
395
396 /** Helpful methods **/
397
398 /**
399 * Get a Message object with context set
400 * Parameters are the same as wfMessage()
401 *
402 * @return Message
403 */
404 public function msg() {
405 $args = func_get_args();
406
407 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
408 }
409
410 /** Static methods **/
411
412 /**
413 * Get the RequestContext object associated with the main request
414 *
415 * @return RequestContext
416 */
417 public static function getMain() {
418 if ( self::$instance === null ) {
419 self::$instance = new self;
420 }
421
422 return self::$instance;
423 }
424
425 /**
426 * Get the RequestContext object associated with the main request
427 * and gives a warning to the log, to find places, where a context maybe is missing.
428 *
429 * @param string $func
430 * @return RequestContext
431 * @since 1.24
432 */
433 public static function getMainAndWarn( $func = __METHOD__ ) {
434 wfDebug( $func . ' called without context. ' .
435 "Using RequestContext::getMain() for sanity\n" );
436
437 return self::getMain();
438 }
439
440 /**
441 * Resets singleton returned by getMain(). Should be called only from unit tests.
442 */
443 public static function resetMain() {
444 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
445 throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
446 }
447 self::$instance = null;
448 }
449
450 /**
451 * Export the resolved user IP, HTTP headers, user ID, and session ID.
452 * The result will be reasonably sized to allow for serialization.
453 *
454 * @return array
455 * @since 1.21
456 */
457 public function exportSession() {
458 return array(
459 'ip' => $this->getRequest()->getIP(),
460 'headers' => $this->getRequest()->getAllHeaders(),
461 'sessionId' => session_id(),
462 'userId' => $this->getUser()->getId()
463 );
464 }
465
466 /**
467 * Import the resolved user IP, HTTP headers, user ID, and session ID.
468 * This sets the current session and sets $wgUser and $wgRequest.
469 * Once the return value falls out of scope, the old context is restored.
470 * This function can only be called within CLI mode scripts.
471 *
472 * This will setup the session from the given ID. This is useful when
473 * background scripts inherit context when acting on behalf of a user.
474 *
475 * @note suhosin.session.encrypt may interfere with this method.
476 *
477 * @param array $params Result of RequestContext::exportSession()
478 * @return ScopedCallback
479 * @throws MWException
480 * @since 1.21
481 */
482 public static function importScopedSession( array $params ) {
483 if ( PHP_SAPI !== 'cli' ) {
484 // Don't send random private cookies or turn $wgRequest into FauxRequest
485 throw new MWException( "Sessions can only be imported in cli mode." );
486 } elseif ( !strlen( $params['sessionId'] ) ) {
487 throw new MWException( "No session ID was specified." );
488 }
489
490 if ( $params['userId'] ) { // logged-in user
491 $user = User::newFromId( $params['userId'] );
492 $user->load();
493 if ( !$user->getId() ) {
494 throw new MWException( "No user with ID '{$params['userId']}'." );
495 }
496 } elseif ( !IP::isValid( $params['ip'] ) ) {
497 throw new MWException( "Could not load user '{$params['ip']}'." );
498 } else { // anon user
499 $user = User::newFromName( $params['ip'], false );
500 }
501
502 $importSessionFunction = function ( User $user, array $params ) {
503 global $wgRequest, $wgUser;
504
505 $context = RequestContext::getMain();
506 // Commit and close any current session
507 session_write_close(); // persist
508 session_id( '' ); // detach
509 $_SESSION = array(); // clear in-memory array
510 // Remove any user IP or agent information
511 $context->setRequest( new FauxRequest() );
512 $wgRequest = $context->getRequest(); // b/c
513 // Now that all private information is detached from the user, it should
514 // be safe to load the new user. If errors occur or an exception is thrown
515 // and caught (leaving the main context in a mixed state), there is no risk
516 // of the User object being attached to the wrong IP, headers, or session.
517 $context->setUser( $user );
518 $wgUser = $context->getUser(); // b/c
519 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
520 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
521 }
522 $request = new FauxRequest( array(), false, $_SESSION );
523 $request->setIP( $params['ip'] );
524 foreach ( $params['headers'] as $name => $value ) {
525 $request->setHeader( $name, $value );
526 }
527 // Set the current context to use the new WebRequest
528 $context->setRequest( $request );
529 $wgRequest = $context->getRequest(); // b/c
530 };
531
532 // Stash the old session and load in the new one
533 $oUser = self::getMain()->getUser();
534 $oParams = self::getMain()->exportSession();
535 $importSessionFunction( $user, $params );
536
537 // Set callback to save and close the new session and reload the old one
538 return new ScopedCallback( function () use ( $importSessionFunction, $oUser, $oParams ) {
539 $importSessionFunction( $oUser, $oParams );
540 } );
541 }
542
543 /**
544 * Create a new extraneous context. The context is filled with information
545 * external to the current session.
546 * - Title is specified by argument
547 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
548 * - User is an anonymous user, for separation IPv4 localhost is used
549 * - Language will be based on the anonymous user and request, may be content
550 * language or a uselang param in the fauxrequest data may change the lang
551 * - Skin will be based on the anonymous user, should be the wiki's default skin
552 *
553 * @param Title $title Title to use for the extraneous request
554 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
555 * @return RequestContext
556 */
557 public static function newExtraneousContext( Title $title, $request = array() ) {
558 $context = new self;
559 $context->setTitle( $title );
560 if ( $request instanceof WebRequest ) {
561 $context->setRequest( $request );
562 } else {
563 $context->setRequest( new FauxRequest( $request ) );
564 }
565 $context->user = User::newFromName( '127.0.0.1', false );
566
567 return $context;
568 }
569 }