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 ? self
::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 no skin is specified, or we don't recognize the skin, use the default skin
88 if ( !$this->skin ||
!isset( $skinnames[$this->skin
] ) ) {
89 $this->skin
= $this->getConfig()->get( 'DefaultSkin' );
94 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
95 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
96 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
98 * This process is reversed by ResourceLoader::makePackedModulesString().
100 * @param string $modules Packed module name list
101 * @return array Array of module names
103 public static function expandModuleNames( $modules ) {
105 $exploded = explode( '|', $modules );
106 foreach ( $exploded as $group ) {
107 if ( strpos( $group, ',' ) === false ) {
108 // This is not a set of modules in foo.bar,baz notation
109 // but a single module
112 // This is a set of modules in foo.bar,baz notation
113 $pos = strrpos( $group, '.' );
114 if ( $pos === false ) {
115 // Prefixless modules, i.e. without dots
116 $retval = array_merge( $retval, explode( ',', $group ) );
118 // We have a prefix and a bunch of suffixes
119 $prefix = substr( $group, 0, $pos ); // 'foo'
120 $suffixes = explode( ',', substr( $group, $pos +
1 ) ); // [ 'bar', 'baz' ]
121 foreach ( $suffixes as $suffix ) {
122 $retval[] = "$prefix.$suffix";
131 * Return a dummy ResourceLoaderContext object suitable for passing into
132 * things that don't "really" need a context.
135 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
137 * @return ResourceLoaderContext
139 public static function newDummyContext() {
140 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
141 // but that's probably not needed. So once that moves into ServiceWiring, this'll
142 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
143 // is what this should've had originally. If this turns out to be untrue, change to:
144 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
145 return new self( new ResourceLoader(
146 MediaWikiServices
::getInstance()->getMainConfig(),
147 LoggerFactory
::getInstance( 'resourceloader' )
148 ), new FauxRequest( [] ) );
152 * @return ResourceLoader
154 public function getResourceLoader() {
155 return $this->resourceLoader
;
161 public function getConfig() {
162 return $this->getResourceLoader()->getConfig();
168 public function getRequest() {
169 return $this->request
;
174 * @return \Psr\Log\LoggerInterface
176 public function getLogger() {
177 return $this->logger
;
183 public function getModules() {
184 return $this->modules
;
190 public function getLanguage() {
191 if ( $this->language
=== null ) {
192 // Must be a valid language code after this point (T64849)
193 // Only support uselang values that follow built-in conventions (T102058)
194 $lang = $this->getRequest()->getRawVal( 'lang', '' );
195 // Stricter version of RequestContext::sanitizeLangCode()
196 if ( !Language
::isValidBuiltInCode( $lang ) ) {
197 $lang = $this->getConfig()->get( 'LanguageCode' );
199 $this->language
= $lang;
201 return $this->language
;
207 public function getDirection() {
208 if ( $this->direction
=== null ) {
209 $this->direction
= $this->getRequest()->getRawVal( 'dir' );
210 if ( !$this->direction
) {
211 // Determine directionality based on user language (T8100)
212 $this->direction
= Language
::factory( $this->getLanguage() )->getDir();
215 return $this->direction
;
221 public function getSkin() {
226 * @return string|null
228 public function getUser() {
233 * Get a Message object with context set. See wfMessage for parameters.
236 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
237 * or a MessageSpecifier.
238 * @param mixed $args,...
241 public function msg( $key ) {
242 return wfMessage( ...func_get_args() )
243 ->inLanguage( $this->getLanguage() )
244 // Use a dummy title because there is no real title
245 // for this endpoint, and the cache won't vary on it
247 ->title( Title
::newFromText( 'Dwimmerlaik' ) );
251 * Get the possibly-cached User object for the specified username
256 public function getUserObj() {
257 if ( $this->userObj
=== null ) {
258 $username = $this->getUser();
260 // Use provided username if valid, fallback to anonymous user
261 $this->userObj
= User
::newFromName( $username ) ?
: new User
;
264 $this->userObj
= new User
;
268 return $this->userObj
;
274 public function getDebug() {
279 * @return string|null
281 public function getOnly() {
286 * @see ResourceLoaderModule::getVersionHash
287 * @see ResourceLoaderClientHtml::makeLoad
288 * @return string|null
290 public function getVersion() {
291 return $this->version
;
297 public function getRaw() {
302 * @return string|null
304 public function getImage() {
309 * @return string|null
311 public function getVariant() {
312 return $this->variant
;
316 * @return string|null
318 public function getFormat() {
319 return $this->format
;
323 * If this is a request for an image, get the ResourceLoaderImage object.
326 * @return ResourceLoaderImage|bool false if a valid object cannot be created
328 public function getImageObj() {
329 if ( $this->imageObj
=== null ) {
330 $this->imageObj
= false;
332 if ( !$this->image
) {
333 return $this->imageObj
;
336 $modules = $this->getModules();
337 if ( count( $modules ) !== 1 ) {
338 return $this->imageObj
;
341 $module = $this->getResourceLoader()->getModule( $modules[0] );
342 if ( !$module ||
!$module instanceof ResourceLoaderImageModule
) {
343 return $this->imageObj
;
346 $image = $module->getImage( $this->image
, $this );
348 return $this->imageObj
;
351 $this->imageObj
= $image;
354 return $this->imageObj
;
358 * Return the replaced-content mapping callback
360 * When editing a page that's used to generate the scripts or styles of a
361 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
362 * the page rather than the current version in the database. A context
363 * supporting such previews should return a callback to return these
367 * @return callable|null Signature is `Content|null func( Title $t )`
369 public function getContentOverrideCallback() {
376 public function shouldIncludeScripts() {
377 return $this->getOnly() === null ||
$this->getOnly() === 'scripts';
383 public function shouldIncludeStyles() {
384 return $this->getOnly() === null ||
$this->getOnly() === 'styles';
390 public function shouldIncludeMessages() {
391 return $this->getOnly() === null;
395 * All factors that uniquely identify this request, except 'modules'.
397 * The list of modules is excluded here for legacy reasons as most callers already
398 * split up handling of individual modules. Including it here would massively fragment
399 * the cache and decrease its usefulness.
401 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
405 public function getHash() {
406 if ( !isset( $this->hash
) ) {
407 $this->hash
= implode( '|', [
408 // Module content vary
409 $this->getLanguage(),