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)
58 /** @var ResourceLoaderImage|false */
62 * @param ResourceLoader $resourceLoader
63 * @param WebRequest $request
65 public function __construct( ResourceLoader
$resourceLoader, WebRequest
$request ) {
66 $this->resourceLoader
= $resourceLoader;
67 $this->request
= $request;
68 $this->logger
= $resourceLoader->getLogger();
70 // Optimisation: Use WebRequest::getRawVal() instead of getVal(). We don't
71 // need the slow Language+UTF logic meant for user input here. (f303bb9360)
74 $modules = $request->getRawVal( 'modules' );
75 $this->modules
= $modules ? ResourceLoader
::expandModuleNames( $modules ) : [];
78 $this->user
= $request->getRawVal( 'user' );
79 $this->debug
= $request->getRawVal( 'debug' ) === 'true';
80 $this->only
= $request->getRawVal( 'only' );
81 $this->version
= $request->getRawVal( 'version' );
82 $this->raw
= $request->getFuzzyBool( 'raw' );
85 $this->image
= $request->getRawVal( 'image' );
86 $this->variant
= $request->getRawVal( 'variant' );
87 $this->format
= $request->getRawVal( 'format' );
89 $this->skin
= $request->getRawVal( 'skin' );
90 $skinnames = Skin
::getSkinNames();
91 if ( !$this->skin ||
!isset( $skinnames[$this->skin
] ) ) {
92 // The 'skin' parameter is required. (Not yet enforced.)
93 // For requests without a known skin specified,
94 // use MediaWiki's 'fallback' skin for skin-specific decisions.
95 $this->skin
= self
::DEFAULT_SKIN
;
100 * Return a dummy ResourceLoaderContext object suitable for passing into
101 * things that don't "really" need a context.
104 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
106 * @return ResourceLoaderContext
108 public static function newDummyContext() {
109 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
110 // but that's probably not needed. So once that moves into ServiceWiring, this'll
111 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
112 // is what this should've had originally. If this turns out to be untrue, change to:
113 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
114 return new self( new ResourceLoader(
115 MediaWikiServices
::getInstance()->getMainConfig(),
116 LoggerFactory
::getInstance( 'resourceloader' )
117 ), new FauxRequest( [] ) );
121 * @return ResourceLoader
123 public function getResourceLoader() {
124 return $this->resourceLoader
;
128 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
129 * inside module methods. Use ResourceLoader::getConfig elsewhere.
131 * @codeCoverageIgnore
133 public function getConfig() {
134 wfDeprecated( __METHOD__
, '1.34' );
135 return $this->getResourceLoader()->getConfig();
141 public function getRequest() {
142 return $this->request
;
146 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
147 * inside module methods. Use ResourceLoader::getLogger elsewhere.
149 * @return \Psr\Log\LoggerInterface
151 public function getLogger() {
152 return $this->logger
;
158 public function getModules() {
159 return $this->modules
;
165 public function getLanguage() {
166 if ( $this->language
=== null ) {
167 // Must be a valid language code after this point (T64849)
168 // Only support uselang values that follow built-in conventions (T102058)
169 $lang = $this->getRequest()->getRawVal( 'lang', '' );
170 // Stricter version of RequestContext::sanitizeLangCode()
171 if ( !Language
::isValidBuiltInCode( $lang ) ) {
172 // The 'lang' parameter is required. (Not yet enforced.)
173 // If omitted, localise with the dummy language code.
174 $lang = self
::DEFAULT_LANG
;
176 $this->language
= $lang;
178 return $this->language
;
184 public function getDirection() {
185 if ( $this->direction
=== null ) {
186 $direction = $this->getRequest()->getRawVal( 'dir' );
187 if ( $direction === 'ltr' ||
$direction === 'rtl' ) {
188 $this->direction
= $direction;
190 // Determine directionality based on user language (T8100)
191 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
194 return $this->direction
;
200 public function getSkin() {
205 * @return string|null
207 public function getUser() {
212 * Get a Message object with context set. See wfMessage for parameters.
215 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
216 * or a MessageSpecifier.
217 * @param mixed $args,...
218 * @suppress PhanCommentParamWithoutRealParam HHVM bug T228695#5450847
221 public function msg( $key ) {
222 return wfMessage( ...func_get_args() )
223 ->inLanguage( $this->getLanguage() )
224 // Use a dummy title because there is no real title
225 // for this endpoint, and the cache won't vary on it
227 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
231 * Get the possibly-cached User object for the specified username
236 public function getUserObj() {
237 if ( $this->userObj
=== null ) {
238 $username = $this->getUser();
240 // Use provided username if valid, fallback to anonymous user
241 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
244 $this->userObj
= new User
;
248 return $this->userObj
;
254 public function getDebug() {
259 * @return string|null
261 public function getOnly() {
266 * @see ResourceLoaderModule::getVersionHash
267 * @see ResourceLoaderClientHtml::makeLoad
268 * @return string|null
270 public function getVersion() {
271 return $this->version
;
277 public function getRaw() {
282 * @return string|null
284 public function getImage() {
289 * @return string|null
291 public function getVariant() {
292 return $this->variant
;
296 * @return string|null
298 public function getFormat() {
299 return $this->format
;
303 * If this is a request for an image, get the ResourceLoaderImage object.
306 * @return ResourceLoaderImage|bool false if a valid object cannot be created
308 public function getImageObj() {
309 if ( $this->imageObj
=== null ) {
310 $this->imageObj
= false;
312 if ( !$this->image
) {
313 return $this->imageObj
;
316 $modules = $this->getModules();
317 if ( count( $modules ) !== 1 ) {
318 return $this->imageObj
;
321 $module = $this->getResourceLoader()->getModule( $modules[0] );
322 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
323 return $this->imageObj
;
326 $image = $module->getImage( $this->image
, $this );
328 return $this->imageObj
;
331 $this->imageObj
= $image;
334 return $this->imageObj
;
338 * Return the replaced-content mapping callback
340 * When editing a page that's used to generate the scripts or styles of a
341 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
342 * the page rather than the current version in the database. A context
343 * supporting such previews should return a callback to return these
347 * @return callable|null Signature is `Content|null func( Title $t )`
349 public function getContentOverrideCallback() {
356 public function shouldIncludeScripts() {
357 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
363 public function shouldIncludeStyles() {
364 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
370 public function shouldIncludeMessages() {
371 return $this->getOnly() === null;
375 * All factors that uniquely identify this request, except 'modules'.
377 * The list of modules is excluded here for legacy reasons as most callers already
378 * split up handling of individual modules. Including it here would massively fragment
379 * the cache and decrease its usefulness.
381 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
385 public function getHash() {
386 if ( !isset( $this->hash
) ) {
387 $this->hash
= implode( '|', [
388 // Module content vary
389 $this->getLanguage(),
406 * Get the request base parameters, omitting any defaults.
408 * @internal For internal use by ResourceLoaderStartUpModule only
411 public function getReqBase() {
413 if ( $this->getLanguage() !== self
::DEFAULT_LANG
) {
414 $reqBase['lang'] = $this->getLanguage();
416 if ( $this->getSkin() !== self
::DEFAULT_SKIN
) {
417 $reqBase['skin'] = $this->getSkin();
419 if ( $this->getDebug() ) {
420 $reqBase['debug'] = 'true';