3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Trevor Parscal
20 * @author Roan Kattouw
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
27 * Context object that contains information about the state of a specific
28 * ResourceLoader web request. Passed around to ResourceLoaderModule methods.
30 * @ingroup ResourceLoader
33 class ResourceLoaderContext
implements MessageLocalizer
{
34 const DEFAULT_LANG
= 'qqx';
35 const DEFAULT_SKIN
= 'fallback';
37 protected $resourceLoader;
41 // Module content vary
47 // Request vary (in addition to cache vary)
59 /** @var ResourceLoaderImage|false */
63 * @param ResourceLoader $resourceLoader
64 * @param WebRequest $request
66 public function __construct( ResourceLoader
$resourceLoader, WebRequest
$request ) {
67 $this->resourceLoader
= $resourceLoader;
68 $this->request
= $request;
69 $this->logger
= $resourceLoader->getLogger();
71 // Optimisation: Use WebRequest::getRawVal() instead of getVal(). We don't
72 // need the slow Language+UTF logic meant for user input here. (f303bb9360)
75 $modules = $request->getRawVal( 'modules' );
76 $this->modules
= $modules ? ResourceLoader
::expandModuleNames( $modules ) : [];
79 $this->user
= $request->getRawVal( 'user' );
80 $this->debug
= $request->getRawVal( 'debug' ) === 'true';
81 $this->only
= $request->getRawVal( 'only' );
82 $this->version
= $request->getRawVal( 'version' );
83 $this->raw
= $request->getFuzzyBool( 'raw' );
86 $this->image
= $request->getRawVal( 'image' );
87 $this->variant
= $request->getRawVal( 'variant' );
88 $this->format
= $request->getRawVal( 'format' );
90 $this->skin
= $request->getRawVal( 'skin' );
91 $skinnames = Skin
::getSkinNames();
92 if ( !$this->skin ||
!isset( $skinnames[$this->skin
] ) ) {
93 // The 'skin' parameter is required. (Not yet enforced.)
94 // For requests without a known skin specified,
95 // use MediaWiki's 'fallback' skin for skin-specific decisions.
96 $this->skin
= self
::DEFAULT_SKIN
;
101 * Return a dummy ResourceLoaderContext object suitable for passing into
102 * things that don't "really" need a context.
105 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
107 * @return ResourceLoaderContext
109 public static function newDummyContext() {
110 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
111 // but that's probably not needed. So once that moves into ServiceWiring, this'll
112 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
113 // is what this should've had originally. If this turns out to be untrue, change to:
114 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
115 return new self( new ResourceLoader(
116 MediaWikiServices
::getInstance()->getMainConfig(),
117 LoggerFactory
::getInstance( 'resourceloader' )
118 ), new FauxRequest( [] ) );
122 * @return ResourceLoader
124 public function getResourceLoader() {
125 return $this->resourceLoader
;
129 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
130 * inside module methods. Use ResourceLoader::getConfig elsewhere.
132 * @codeCoverageIgnore
134 public function getConfig() {
135 wfDeprecated( __METHOD__
, '1.34' );
136 return $this->getResourceLoader()->getConfig();
142 public function getRequest() {
143 return $this->request
;
147 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
148 * inside module methods. Use ResourceLoader::getLogger elsewhere.
150 * @return \Psr\Log\LoggerInterface
152 public function getLogger() {
153 return $this->logger
;
159 public function getModules() {
160 return $this->modules
;
166 public function getLanguage() {
167 if ( $this->language
=== null ) {
168 // Must be a valid language code after this point (T64849)
169 // Only support uselang values that follow built-in conventions (T102058)
170 $lang = $this->getRequest()->getRawVal( 'lang', '' );
171 // Stricter version of RequestContext::sanitizeLangCode()
172 if ( !Language
::isValidBuiltInCode( $lang ) ) {
173 // The 'lang' parameter is required. (Not yet enforced.)
174 // If omitted, localise with the dummy language code.
175 $lang = self
::DEFAULT_LANG
;
177 $this->language
= $lang;
179 return $this->language
;
185 public function getDirection() {
186 if ( $this->direction
=== null ) {
187 $direction = $this->getRequest()->getRawVal( 'dir' );
188 if ( $direction === 'ltr' ||
$direction === 'rtl' ) {
189 $this->direction
= $direction;
191 // Determine directionality based on user language (T8100)
192 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
195 return $this->direction
;
201 public function getSkin() {
206 * @return string|null
208 public function getUser() {
213 * Get a Message object with context set. See wfMessage for parameters.
216 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
217 * or a MessageSpecifier.
218 * @param mixed $args,...
219 * @suppress PhanCommentParamWithoutRealParam HHVM bug T228695#5450847
222 public function msg( $key ) {
223 return wfMessage( ...func_get_args() )
224 ->inLanguage( $this->getLanguage() )
225 // Use a dummy title because there is no real title
226 // for this endpoint, and the cache won't vary on it
228 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
232 * Get the possibly-cached User object for the specified username
237 public function getUserObj() {
238 if ( $this->userObj
=== null ) {
239 $username = $this->getUser();
241 // Use provided username if valid, fallback to anonymous user
242 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
245 $this->userObj
= new User
;
249 return $this->userObj
;
255 public function getDebug() {
260 * @return string|null
262 public function getOnly() {
267 * @see ResourceLoaderModule::getVersionHash
268 * @see ResourceLoaderClientHtml::makeLoad
269 * @return string|null
271 public function getVersion() {
272 return $this->version
;
278 public function getRaw() {
283 * @return string|null
285 public function getImage() {
290 * @return string|null
292 public function getVariant() {
293 return $this->variant
;
297 * @return string|null
299 public function getFormat() {
300 return $this->format
;
304 * If this is a request for an image, get the ResourceLoaderImage object.
307 * @return ResourceLoaderImage|bool false if a valid object cannot be created
309 public function getImageObj() {
310 if ( $this->imageObj
=== null ) {
311 $this->imageObj
= false;
313 if ( !$this->image
) {
314 return $this->imageObj
;
317 $modules = $this->getModules();
318 if ( count( $modules ) !== 1 ) {
319 return $this->imageObj
;
322 $module = $this->getResourceLoader()->getModule( $modules[0] );
323 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
324 return $this->imageObj
;
327 $image = $module->getImage( $this->image
, $this );
329 return $this->imageObj
;
332 $this->imageObj
= $image;
335 return $this->imageObj
;
339 * Return the replaced-content mapping callback
341 * When editing a page that's used to generate the scripts or styles of a
342 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
343 * the page rather than the current version in the database. A context
344 * supporting such previews should return a callback to return these
348 * @return callable|null Signature is `Content|null func( Title $t )`
350 public function getContentOverrideCallback() {
357 public function shouldIncludeScripts() {
358 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
364 public function shouldIncludeStyles() {
365 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
371 public function shouldIncludeMessages() {
372 return $this->getOnly() === null;
376 * All factors that uniquely identify this request, except 'modules'.
378 * The list of modules is excluded here for legacy reasons as most callers already
379 * split up handling of individual modules. Including it here would massively fragment
380 * the cache and decrease its usefulness.
382 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
386 public function getHash() {
387 if ( !isset( $this->hash
) ) {
388 $this->hash
= implode( '|', [
389 // Module content vary
390 $this->getLanguage(),
407 * Get the request base parameters, omitting any defaults.
409 * @internal For internal use by ResourceLoaderStartUpModule only
412 public function getReqBase() {
414 if ( $this->getLanguage() !== self
::DEFAULT_LANG
) {
415 $reqBase['lang'] = $this->getLanguage();
417 if ( $this->getSkin() !== self
::DEFAULT_SKIN
) {
418 $reqBase['skin'] = $this->getSkin();
420 if ( $this->getDebug() ) {
421 $reqBase['debug'] = 'true';