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.
144 public function getConfig() {
145 return $this->getResourceLoader()->getConfig();
151 public function getRequest() {
152 return $this->request
;
156 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
157 * inside module methods. Use ResourceLoader::getLogger elsewhere.
159 * @return \Psr\Log\LoggerInterface
161 public function getLogger() {
162 return $this->logger
;
168 public function getModules() {
169 return $this->modules
;
175 public function getLanguage() {
176 if ( $this->language
=== null ) {
177 // Must be a valid language code after this point (T64849)
178 // Only support uselang values that follow built-in conventions (T102058)
179 $lang = $this->getRequest()->getRawVal( 'lang', '' );
180 // Stricter version of RequestContext::sanitizeLangCode()
181 if ( !Language
::isValidBuiltInCode( $lang ) ) {
182 // The 'lang' parameter is required. (Not yet enforced.)
183 // If omitted, localise with the dummy language code.
184 $lang = self
::DEFAULT_LANG
;
186 $this->language
= $lang;
188 return $this->language
;
194 public function getDirection() {
195 if ( $this->direction
=== null ) {
196 $direction = $this->getRequest()->getRawVal( 'dir' );
197 if ( $direction === 'ltr' ||
$direction === 'rtl' ) {
198 $this->direction
= $direction;
200 // Determine directionality based on user language (T8100)
201 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
204 return $this->direction
;
210 public function getSkin() {
215 * @return string|null
217 public function getUser() {
222 * Get a Message object with context set. See wfMessage for parameters.
225 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
226 * or a MessageSpecifier.
227 * @param mixed $args,...
230 public function msg( $key ) {
231 return wfMessage( ...func_get_args() )
232 ->inLanguage( $this->getLanguage() )
233 // Use a dummy title because there is no real title
234 // for this endpoint, and the cache won't vary on it
236 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
240 * Get the possibly-cached User object for the specified username
245 public function getUserObj() {
246 if ( $this->userObj
=== null ) {
247 $username = $this->getUser();
249 // Use provided username if valid, fallback to anonymous user
250 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
253 $this->userObj
= new User
;
257 return $this->userObj
;
263 public function getDebug() {
268 * @return string|null
270 public function getOnly() {
275 * @see ResourceLoaderModule::getVersionHash
276 * @see ResourceLoaderClientHtml::makeLoad
277 * @return string|null
279 public function getVersion() {
280 return $this->version
;
286 public function getRaw() {
291 * @return string|null
293 public function getImage() {
298 * @return string|null
300 public function getVariant() {
301 return $this->variant
;
305 * @return string|null
307 public function getFormat() {
308 return $this->format
;
312 * If this is a request for an image, get the ResourceLoaderImage object.
315 * @return ResourceLoaderImage|bool false if a valid object cannot be created
317 public function getImageObj() {
318 if ( $this->imageObj
=== null ) {
319 $this->imageObj
= false;
321 if ( !$this->image
) {
322 return $this->imageObj
;
325 $modules = $this->getModules();
326 if ( count( $modules ) !== 1 ) {
327 return $this->imageObj
;
330 $module = $this->getResourceLoader()->getModule( $modules[0] );
331 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
332 return $this->imageObj
;
335 $image = $module->getImage( $this->image
, $this );
337 return $this->imageObj
;
340 $this->imageObj
= $image;
343 return $this->imageObj
;
347 * Return the replaced-content mapping callback
349 * When editing a page that's used to generate the scripts or styles of a
350 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
351 * the page rather than the current version in the database. A context
352 * supporting such previews should return a callback to return these
356 * @return callable|null Signature is `Content|null func( Title $t )`
358 public function getContentOverrideCallback() {
365 public function shouldIncludeScripts() {
366 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
372 public function shouldIncludeStyles() {
373 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
379 public function shouldIncludeMessages() {
380 return $this->getOnly() === null;
384 * All factors that uniquely identify this request, except 'modules'.
386 * The list of modules is excluded here for legacy reasons as most callers already
387 * split up handling of individual modules. Including it here would massively fragment
388 * the cache and decrease its usefulness.
390 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
394 public function getHash() {
395 if ( !isset( $this->hash
) ) {
396 $this->hash
= implode( '|', [
397 // Module content vary
398 $this->getLanguage(),
415 * Get the request base parameters, omitting any defaults.
417 * @internal For internal use by ResourceLoaderStartUpModule only
420 public function getReqBase() {
422 if ( $this->getLanguage() !== self
::DEFAULT_LANG
) {
423 $reqBase['lang'] = $this->getLanguage();
425 if ( $this->getSkin() !== self
::DEFAULT_SKIN
) {
426 $reqBase['skin'] = $this->getSkin();
428 if ( $this->getDebug() ) {
429 $reqBase['debug'] = 'true';