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