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