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 protected $resourceLoader;
37 // Module content vary
43 // Request vary (in addition to cache vary)
58 * @param ResourceLoader $resourceLoader
59 * @param WebRequest $request
61 public function __construct( ResourceLoader
$resourceLoader, WebRequest
$request ) {
62 $this->resourceLoader
= $resourceLoader;
63 $this->request
= $request;
64 $this->logger
= $resourceLoader->getLogger();
66 // Future developers: Use WebRequest::getRawVal() instead of getVal().
67 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
70 $modules = $request->getRawVal( 'modules' );
71 $this->modules
= $modules ? ResourceLoader
::expandModuleNames( $modules ) : [];
74 $this->user
= $request->getRawVal( 'user' );
75 $this->debug
= $request->getRawVal( 'debug' ) === 'true';
76 $this->only
= $request->getRawVal( 'only', null );
77 $this->version
= $request->getRawVal( 'version', null );
78 $this->raw
= $request->getFuzzyBool( 'raw' );
81 $this->image
= $request->getRawVal( 'image' );
82 $this->variant
= $request->getRawVal( 'variant' );
83 $this->format
= $request->getRawVal( 'format' );
85 $this->skin
= $request->getRawVal( 'skin' );
86 $skinnames = Skin
::getSkinNames();
87 if ( !$this->skin ||
!isset( $skinnames[$this->skin
] ) ) {
88 // The 'skin' parameter is required. (Not yet enforced.)
89 // For requests without a known skin specified,
90 // use MediaWiki's 'fallback' skin for skin-specific decisions.
91 $this->skin
= 'fallback';
96 * Reverse the process done by ResourceLoader::makePackedModulesString().
98 * @deprecated since 1.33 Use ResourceLoader::expandModuleNames instead.
99 * @param string $modules Packed module name list
100 * @return array Array of module names
101 * @codeCoverageIgnore
103 public static function expandModuleNames( $modules ) {
104 wfDeprecated( __METHOD__
, '1.33' );
105 return ResourceLoader
::expandModuleNames( $modules );
109 * Return a dummy ResourceLoaderContext object suitable for passing into
110 * things that don't "really" need a context.
113 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
115 * @return ResourceLoaderContext
117 public static function newDummyContext() {
118 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
119 // but that's probably not needed. So once that moves into ServiceWiring, this'll
120 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
121 // is what this should've had originally. If this turns out to be untrue, change to:
122 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
123 return new self( new ResourceLoader(
124 MediaWikiServices
::getInstance()->getMainConfig(),
125 LoggerFactory
::getInstance( 'resourceloader' )
126 ), new FauxRequest( [] ) );
130 * @return ResourceLoader
132 public function getResourceLoader() {
133 return $this->resourceLoader
;
137 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
138 * inside module methods. Use ResourceLoader::getConfig elsewhere.
141 public function getConfig() {
142 return $this->getResourceLoader()->getConfig();
148 public function getRequest() {
149 return $this->request
;
153 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
154 * inside module methods. Use ResourceLoader::getLogger elsewhere.
156 * @return \Psr\Log\LoggerInterface
158 public function getLogger() {
159 return $this->logger
;
165 public function getModules() {
166 return $this->modules
;
172 public function getLanguage() {
173 if ( $this->language
=== null ) {
174 // Must be a valid language code after this point (T64849)
175 // Only support uselang values that follow built-in conventions (T102058)
176 $lang = $this->getRequest()->getRawVal( 'lang', '' );
177 // Stricter version of RequestContext::sanitizeLangCode()
178 if ( !Language
::isValidBuiltInCode( $lang ) ) {
179 // The 'lang' parameter is required. (Not yet enforced.)
180 // If omitted, localise with the dummy language code.
183 $this->language
= $lang;
185 return $this->language
;
191 public function getDirection() {
192 if ( $this->direction
=== null ) {
193 $direction = $this->getRequest()->getRawVal( 'dir' );
194 if ( $direction === 'ltr' ||
$direction === 'rtl' ) {
195 $this->direction
= $direction;
197 // Determine directionality based on user language (T8100)
198 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
201 return $this->direction
;
207 public function getSkin() {
212 * @return string|null
214 public function getUser() {
219 * Get a Message object with context set. See wfMessage for parameters.
222 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
223 * or a MessageSpecifier.
224 * @param mixed $args,...
227 public function msg( $key ) {
228 return wfMessage( ...func_get_args() )
229 ->inLanguage( $this->getLanguage() )
230 // Use a dummy title because there is no real title
231 // for this endpoint, and the cache won't vary on it
233 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
237 * Get the possibly-cached User object for the specified username
242 public function getUserObj() {
243 if ( $this->userObj
=== null ) {
244 $username = $this->getUser();
246 // Use provided username if valid, fallback to anonymous user
247 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
250 $this->userObj
= new User
;
254 return $this->userObj
;
260 public function getDebug() {
265 * @return string|null
267 public function getOnly() {
272 * @see ResourceLoaderModule::getVersionHash
273 * @see ResourceLoaderClientHtml::makeLoad
274 * @return string|null
276 public function getVersion() {
277 return $this->version
;
283 public function getRaw() {
288 * @return string|null
290 public function getImage() {
295 * @return string|null
297 public function getVariant() {
298 return $this->variant
;
302 * @return string|null
304 public function getFormat() {
305 return $this->format
;
309 * If this is a request for an image, get the ResourceLoaderImage object.
312 * @return ResourceLoaderImage|bool false if a valid object cannot be created
314 public function getImageObj() {
315 if ( $this->imageObj
=== null ) {
316 $this->imageObj
= false;
318 if ( !$this->image
) {
319 return $this->imageObj
;
322 $modules = $this->getModules();
323 if ( count( $modules ) !== 1 ) {
324 return $this->imageObj
;
327 $module = $this->getResourceLoader()->getModule( $modules[0] );
328 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
329 return $this->imageObj
;
332 $image = $module->getImage( $this->image
, $this );
334 return $this->imageObj
;
337 $this->imageObj
= $image;
340 return $this->imageObj
;
344 * Return the replaced-content mapping callback
346 * When editing a page that's used to generate the scripts or styles of a
347 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
348 * the page rather than the current version in the database. A context
349 * supporting such previews should return a callback to return these
353 * @return callable|null Signature is `Content|null func( Title $t )`
355 public function getContentOverrideCallback() {
362 public function shouldIncludeScripts() {
363 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
369 public function shouldIncludeStyles() {
370 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
376 public function shouldIncludeMessages() {
377 return $this->getOnly() === null;
381 * All factors that uniquely identify this request, except 'modules'.
383 * The list of modules is excluded here for legacy reasons as most callers already
384 * split up handling of individual modules. Including it here would massively fragment
385 * the cache and decrease its usefulness.
387 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
391 public function getHash() {
392 if ( !isset( $this->hash
) ) {
393 $this->hash
= implode( '|', [
394 // Module content vary
395 $this->getLanguage(),