3 * Context for ResourceLoader modules.
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.
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.
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
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
29 * Object passed around to modules which contains information about the state
30 * of a specific loader request.
32 class ResourceLoaderContext
implements MessageLocalizer
{
33 const DEFAULT_LANG
= 'qqx';
34 const DEFAULT_SKIN
= 'fallback';
36 protected $resourceLoader;
40 // Module content vary
46 // Request vary (in addition to cache vary)
61 * @param ResourceLoader $resourceLoader
62 * @param WebRequest $request
64 public function __construct( ResourceLoader
$resourceLoader, WebRequest
$request ) {
65 $this->resourceLoader
= $resourceLoader;
66 $this->request
= $request;
67 $this->logger
= $resourceLoader->getLogger();
69 // Future developers: Use WebRequest::getRawVal() instead of getVal().
70 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
73 $modules = $request->getRawVal( 'modules' );
74 $this->modules
= $modules ? ResourceLoader
::expandModuleNames( $modules ) : [];
77 $this->user
= $request->getRawVal( 'user' );
78 $this->debug
= $request->getRawVal( 'debug' ) === 'true';
79 $this->only
= $request->getRawVal( 'only', null );
80 $this->version
= $request->getRawVal( 'version', null );
81 $this->raw
= $request->getFuzzyBool( 'raw' );
84 $this->image
= $request->getRawVal( 'image' );
85 $this->variant
= $request->getRawVal( 'variant' );
86 $this->format
= $request->getRawVal( 'format' );
88 $this->skin
= $request->getRawVal( 'skin' );
89 $skinnames = Skin
::getSkinNames();
90 if ( !$this->skin ||
!isset( $skinnames[$this->skin
] ) ) {
91 // The 'skin' parameter is required. (Not yet enforced.)
92 // For requests without a known skin specified,
93 // use MediaWiki's 'fallback' skin for skin-specific decisions.
94 $this->skin
= self
::DEFAULT_SKIN
;
99 * Reverse the process done by ResourceLoader::makePackedModulesString().
101 * @deprecated since 1.33 Use ResourceLoader::expandModuleNames instead.
102 * @param string $modules Packed module name list
103 * @return array Array of module names
104 * @codeCoverageIgnore
106 public static function expandModuleNames( $modules ) {
107 wfDeprecated( __METHOD__
, '1.33' );
108 return ResourceLoader
::expandModuleNames( $modules );
112 * Return a dummy ResourceLoaderContext object suitable for passing into
113 * things that don't "really" need a context.
116 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
118 * @return ResourceLoaderContext
120 public static function newDummyContext() {
121 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
122 // but that's probably not needed. So once that moves into ServiceWiring, this'll
123 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
124 // is what this should've had originally. If this turns out to be untrue, change to:
125 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
126 return new self( new ResourceLoader(
127 MediaWikiServices
::getInstance()->getMainConfig(),
128 LoggerFactory
::getInstance( 'resourceloader' )
129 ), new FauxRequest( [] ) );
133 * @return ResourceLoader
135 public function getResourceLoader() {
136 return $this->resourceLoader
;
140 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
141 * inside module methods. Use ResourceLoader::getConfig elsewhere.
143 * @codeCoverageIgnore
145 public function getConfig() {
146 wfDeprecated( __METHOD__
, '1.34' );
147 return $this->getResourceLoader()->getConfig();
153 public function getRequest() {
154 return $this->request
;
158 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
159 * inside module methods. Use ResourceLoader::getLogger elsewhere.
161 * @return \Psr\Log\LoggerInterface
163 public function getLogger() {
164 return $this->logger
;
170 public function getModules() {
171 return $this->modules
;
177 public function getLanguage() {
178 if ( $this->language
=== null ) {
179 // Must be a valid language code after this point (T64849)
180 // Only support uselang values that follow built-in conventions (T102058)
181 $lang = $this->getRequest()->getRawVal( 'lang', '' );
182 // Stricter version of RequestContext::sanitizeLangCode()
183 if ( !Language
::isValidBuiltInCode( $lang ) ) {
184 // The 'lang' parameter is required. (Not yet enforced.)
185 // If omitted, localise with the dummy language code.
186 $lang = self
::DEFAULT_LANG
;
188 $this->language
= $lang;
190 return $this->language
;
196 public function getDirection() {
197 if ( $this->direction
=== null ) {
198 $direction = $this->getRequest()->getRawVal( 'dir' );
199 if ( $direction === 'ltr' ||
$direction === 'rtl' ) {
200 $this->direction
= $direction;
202 // Determine directionality based on user language (T8100)
203 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
206 return $this->direction
;
212 public function getSkin() {
217 * @return string|null
219 public function getUser() {
224 * Get a Message object with context set. See wfMessage for parameters.
227 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
228 * or a MessageSpecifier.
229 * @param mixed $args,...
232 public function msg( $key ) {
233 return wfMessage( ...func_get_args() )
234 ->inLanguage( $this->getLanguage() )
235 // Use a dummy title because there is no real title
236 // for this endpoint, and the cache won't vary on it
238 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
242 * Get the possibly-cached User object for the specified username
247 public function getUserObj() {
248 if ( $this->userObj
=== null ) {
249 $username = $this->getUser();
251 // Use provided username if valid, fallback to anonymous user
252 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
255 $this->userObj
= new User
;
259 return $this->userObj
;
265 public function getDebug() {
270 * @return string|null
272 public function getOnly() {
277 * @see ResourceLoaderModule::getVersionHash
278 * @see ResourceLoaderClientHtml::makeLoad
279 * @return string|null
281 public function getVersion() {
282 return $this->version
;
288 public function getRaw() {
293 * @return string|null
295 public function getImage() {
300 * @return string|null
302 public function getVariant() {
303 return $this->variant
;
307 * @return string|null
309 public function getFormat() {
310 return $this->format
;
314 * If this is a request for an image, get the ResourceLoaderImage object.
317 * @return ResourceLoaderImage|bool false if a valid object cannot be created
319 public function getImageObj() {
320 if ( $this->imageObj
=== null ) {
321 $this->imageObj
= false;
323 if ( !$this->image
) {
324 return $this->imageObj
;
327 $modules = $this->getModules();
328 if ( count( $modules ) !== 1 ) {
329 return $this->imageObj
;
332 $module = $this->getResourceLoader()->getModule( $modules[0] );
333 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
334 return $this->imageObj
;
337 $image = $module->getImage( $this->image
, $this );
339 return $this->imageObj
;
342 $this->imageObj
= $image;
345 return $this->imageObj
;
349 * Return the replaced-content mapping callback
351 * When editing a page that's used to generate the scripts or styles of a
352 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
353 * the page rather than the current version in the database. A context
354 * supporting such previews should return a callback to return these
358 * @return callable|null Signature is `Content|null func( Title $t )`
360 public function getContentOverrideCallback() {
367 public function shouldIncludeScripts() {
368 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
374 public function shouldIncludeStyles() {
375 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
381 public function shouldIncludeMessages() {
382 return $this->getOnly() === null;
386 * All factors that uniquely identify this request, except 'modules'.
388 * The list of modules is excluded here for legacy reasons as most callers already
389 * split up handling of individual modules. Including it here would massively fragment
390 * the cache and decrease its usefulness.
392 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
396 public function getHash() {
397 if ( !isset( $this->hash
) ) {
398 $this->hash
= implode( '|', [
399 // Module content vary
400 $this->getLanguage(),
417 * Get the request base parameters, omitting any defaults.
419 * @internal For internal use by ResourceLoaderStartUpModule only
422 public function getReqBase() {
424 if ( $this->getLanguage() !== self
::DEFAULT_LANG
) {
425 $reqBase['lang'] = $this->getLanguage();
427 if ( $this->getSkin() !== self
::DEFAULT_SKIN
) {
428 $reqBase['skin'] = $this->getSkin();
430 if ( $this->getDebug() ) {
431 $reqBase['debug'] = 'true';