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