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