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