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