MediaWiki  master
ResourceLoaderContext.php
Go to the documentation of this file.
1 <?php
27 
33  const DEFAULT_LANG = 'qqx';
34  const DEFAULT_SKIN = 'fallback';
35 
36  protected $resourceLoader;
37  protected $request;
38  protected $logger;
39 
40  // Module content vary
41  protected $skin;
42  protected $language;
43  protected $debug;
44  protected $user;
45 
46  // Request vary (in addition to cache vary)
47  protected $modules;
48  protected $only;
49  protected $version;
50  protected $raw;
51  protected $image;
52  protected $variant;
53  protected $format;
54 
55  protected $direction;
56  protected $hash;
57  protected $userObj;
58  protected $imageObj;
59 
65  $this->resourceLoader = $resourceLoader;
66  $this->request = $request;
67  $this->logger = $resourceLoader->getLogger();
68 
69  // Optimisation: Use WebRequest::getRawVal() instead of getVal(). We don't
70  // need the slow Language+UTF logic meant for user input here. (f303bb9360)
71 
72  // List of modules
73  $modules = $request->getRawVal( 'modules' );
74  $this->modules = $modules ? ResourceLoader::expandModuleNames( $modules ) : [];
75 
76  // Various parameters
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' );
82 
83  // Image requests
84  $this->image = $request->getRawVal( 'image' );
85  $this->variant = $request->getRawVal( 'variant' );
86  $this->format = $request->getRawVal( 'format' );
87 
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;
95  }
96  }
97 
107  public static function newDummyContext() {
108  // This currently creates a non-empty instance of ResourceLoader (all modules registered),
109  // but that's probably not needed. So once that moves into ServiceWiring, this'll
110  // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
111  // is what this should've had originally. If this turns out to be untrue, change to:
112  // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
113  return new self( new ResourceLoader(
114  MediaWikiServices::getInstance()->getMainConfig(),
115  LoggerFactory::getInstance( 'resourceloader' )
116  ), new FauxRequest( [] ) );
117  }
118 
122  public function getResourceLoader() {
123  return $this->resourceLoader;
124  }
125 
132  public function getConfig() {
133  wfDeprecated( __METHOD__, '1.34' );
134  return $this->getResourceLoader()->getConfig();
135  }
136 
140  public function getRequest() {
141  return $this->request;
142  }
143 
150  public function getLogger() {
151  return $this->logger;
152  }
153 
157  public function getModules() {
158  return $this->modules;
159  }
160 
164  public function getLanguage() {
165  if ( $this->language === null ) {
166  // Must be a valid language code after this point (T64849)
167  // Only support uselang values that follow built-in conventions (T102058)
168  $lang = $this->getRequest()->getRawVal( 'lang', '' );
169  // Stricter version of RequestContext::sanitizeLangCode()
171  // The 'lang' parameter is required. (Not yet enforced.)
172  // If omitted, localise with the dummy language code.
173  $lang = self::DEFAULT_LANG;
174  }
175  $this->language = $lang;
176  }
177  return $this->language;
178  }
179 
183  public function getDirection() {
184  if ( $this->direction === null ) {
185  $direction = $this->getRequest()->getRawVal( 'dir' );
186  if ( $direction === 'ltr' || $direction === 'rtl' ) {
187  $this->direction = $direction;
188  } else {
189  // Determine directionality based on user language (T8100)
190  $this->direction = Language::factory( $this->getLanguage() )->getDir();
191  }
192  }
193  return $this->direction;
194  }
195 
199  public function getSkin() {
200  return $this->skin;
201  }
202 
206  public function getUser() {
207  return $this->user;
208  }
209 
219  public function msg( $key ) {
220  return wfMessage( ...func_get_args() )
221  ->inLanguage( $this->getLanguage() )
222  // Use a dummy title because there is no real title
223  // for this endpoint, and the cache won't vary on it
224  // anyways.
225  ->title( Title::newFromText( 'Dwimmerlaik' ) );
226  }
227 
234  public function getUserObj() {
235  if ( $this->userObj === null ) {
236  $username = $this->getUser();
237  if ( $username ) {
238  // Use provided username if valid, fallback to anonymous user
239  $this->userObj = User::newFromName( $username ) ?: new User;
240  } else {
241  // Anonymous user
242  $this->userObj = new User;
243  }
244  }
245 
246  return $this->userObj;
247  }
248 
252  public function getDebug() {
253  return $this->debug;
254  }
255 
259  public function getOnly() {
260  return $this->only;
261  }
262 
268  public function getVersion() {
269  return $this->version;
270  }
271 
275  public function getRaw() {
276  return $this->raw;
277  }
278 
282  public function getImage() {
283  return $this->image;
284  }
285 
289  public function getVariant() {
290  return $this->variant;
291  }
292 
296  public function getFormat() {
297  return $this->format;
298  }
299 
306  public function getImageObj() {
307  if ( $this->imageObj === null ) {
308  $this->imageObj = false;
309 
310  if ( !$this->image ) {
311  return $this->imageObj;
312  }
313 
314  $modules = $this->getModules();
315  if ( count( $modules ) !== 1 ) {
316  return $this->imageObj;
317  }
318 
319  $module = $this->getResourceLoader()->getModule( $modules[0] );
320  if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
321  return $this->imageObj;
322  }
323 
324  $image = $module->getImage( $this->image, $this );
325  if ( !$image ) {
326  return $this->imageObj;
327  }
328 
329  $this->imageObj = $image;
330  }
331 
332  return $this->imageObj;
333  }
334 
347  public function getContentOverrideCallback() {
348  return null;
349  }
350 
354  public function shouldIncludeScripts() {
355  return $this->getOnly() === null || $this->getOnly() === 'scripts';
356  }
357 
361  public function shouldIncludeStyles() {
362  return $this->getOnly() === null || $this->getOnly() === 'styles';
363  }
364 
368  public function shouldIncludeMessages() {
369  return $this->getOnly() === null;
370  }
371 
383  public function getHash() {
384  if ( !isset( $this->hash ) ) {
385  $this->hash = implode( '|', [
386  // Module content vary
387  $this->getLanguage(),
388  $this->getSkin(),
389  $this->getDebug(),
390  $this->getUser(),
391  // Request vary
392  $this->getOnly(),
393  $this->getVersion(),
394  $this->getRaw(),
395  $this->getImage(),
396  $this->getVariant(),
397  $this->getFormat(),
398  ] );
399  }
400  return $this->hash;
401  }
402 
409  public function getReqBase() {
410  $reqBase = [];
411  if ( $this->getLanguage() !== self::DEFAULT_LANG ) {
412  $reqBase['lang'] = $this->getLanguage();
413  }
414  if ( $this->getSkin() !== self::DEFAULT_SKIN ) {
415  $reqBase['skin'] = $this->getSkin();
416  }
417  if ( $this->getDebug() ) {
418  $reqBase['debug'] = 'true';
419  }
420  return $reqBase;
421  }
422 }
getRawVal( $name, $default=null)
Fetch a scalar from the input without normalization, or return $default if it&#39;s not set...
Definition: WebRequest.php:424
ResourceLoader module for generated and embedded images.
static newDummyContext()
Return a dummy ResourceLoaderContext object suitable for passing into things that don&#39;t "really" need...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(!isset( $args[0])) $lang
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:57
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static isValidBuiltInCode( $code)
Returns true if a language code is of a valid form for the purposes of internal customisation of Medi...
Definition: Language.php:413
Prior to version
Definition: maintenance.txt:1
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
getReqBase()
Get the request base parameters, omitting any defaults.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
getContentOverrideCallback()
Return the replaced-content mapping callback.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
getFuzzyBool( $name, $default=false)
Fetch a boolean value from the input or return $default if not set.
Definition: WebRequest.php:589
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:216
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging a wrapping ErrorException create2 Corresponds to logging log_action database field and which is displayed in the UI similar to $comment or false if none Defaults to false if not set multiOccurrence Can this option be passed multiple times Defaults to false if not set this hook should only be used to add variables that depend on the current page request
Definition: hooks.txt:2153
getUserObj()
Get the possibly-cached User object for the specified username.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:773
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static expandModuleNames( $modules)
Expand a string of the form jquery.foo,bar|jquery.ui.baz,quux to an array of module names like `[ &#39;jq...
msg( $key)
Get a Message object with context set.
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
getHash()
All factors that uniquely identify this request, except &#39;modules&#39;.
__construct(ResourceLoader $resourceLoader, WebRequest $request)
getImageObj()
If this is a request for an image, get the ResourceLoaderImage object.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
if the prop value should be in the metadata multi language array format
Definition: hooks.txt:1629
Object passed around to modules which contains information about the state of a specific loader reque...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322