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