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