Merge "resourceloader: Don't explicitly enqueue test libs on SpecialJavaScriptTest"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderContext.php
1 <?php
2 /**
3 * Context for ResourceLoader modules.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 use MediaWiki\Logger\LoggerFactory;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Object passed around to modules which contains information about the state
30 * of a specific loader request.
31 */
32 class ResourceLoaderContext implements MessageLocalizer {
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
60 /**
61 * @param ResourceLoader $resourceLoader
62 * @param WebRequest $request
63 */
64 public function __construct( ResourceLoader $resourceLoader, WebRequest $request ) {
65 $this->resourceLoader = $resourceLoader;
66 $this->request = $request;
67 $this->logger = $resourceLoader->getLogger();
68
69 // Future developers: Use WebRequest::getRawVal() instead of getVal().
70 // The getVal() method performs slow Language+UTF logic. (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
98 /**
99 * Reverse the process done by ResourceLoader::makePackedModulesString().
100 *
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
105 */
106 public static function expandModuleNames( $modules ) {
107 wfDeprecated( __METHOD__, '1.33' );
108 return ResourceLoader::expandModuleNames( $modules );
109 }
110
111 /**
112 * Return a dummy ResourceLoaderContext object suitable for passing into
113 * things that don't "really" need a context.
114 *
115 * Use cases:
116 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
117 *
118 * @return ResourceLoaderContext
119 */
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( [] ) );
130 }
131
132 /**
133 * @return ResourceLoader
134 */
135 public function getResourceLoader() {
136 return $this->resourceLoader;
137 }
138
139 /**
140 * @deprecated since 1.34 Use ResourceLoaderModule::getConfig instead
141 * inside module methods. Use ResourceLoader::getConfig elsewhere.
142 * @return Config
143 * @codeCoverageIgnore
144 */
145 public function getConfig() {
146 wfDeprecated( __METHOD__, '1.34' );
147 return $this->getResourceLoader()->getConfig();
148 }
149
150 /**
151 * @return WebRequest
152 */
153 public function getRequest() {
154 return $this->request;
155 }
156
157 /**
158 * @deprecated since 1.34 Use ResourceLoaderModule::getLogger instead
159 * inside module methods. Use ResourceLoader::getLogger elsewhere.
160 * @since 1.27
161 * @return \Psr\Log\LoggerInterface
162 */
163 public function getLogger() {
164 return $this->logger;
165 }
166
167 /**
168 * @return array
169 */
170 public function getModules() {
171 return $this->modules;
172 }
173
174 /**
175 * @return string
176 */
177 public function getLanguage() {
178 if ( $this->language === null ) {
179 // Must be a valid language code after this point (T64849)
180 // Only support uselang values that follow built-in conventions (T102058)
181 $lang = $this->getRequest()->getRawVal( 'lang', '' );
182 // Stricter version of RequestContext::sanitizeLangCode()
183 if ( !Language::isValidBuiltInCode( $lang ) ) {
184 // The 'lang' parameter is required. (Not yet enforced.)
185 // If omitted, localise with the dummy language code.
186 $lang = self::DEFAULT_LANG;
187 }
188 $this->language = $lang;
189 }
190 return $this->language;
191 }
192
193 /**
194 * @return string
195 */
196 public function getDirection() {
197 if ( $this->direction === null ) {
198 $direction = $this->getRequest()->getRawVal( 'dir' );
199 if ( $direction === 'ltr' || $direction === 'rtl' ) {
200 $this->direction = $direction;
201 } else {
202 // Determine directionality based on user language (T8100)
203 $this->direction = Language::factory( $this->getLanguage() )->getDir();
204 }
205 }
206 return $this->direction;
207 }
208
209 /**
210 * @return string
211 */
212 public function getSkin() {
213 return $this->skin;
214 }
215
216 /**
217 * @return string|null
218 */
219 public function getUser() {
220 return $this->user;
221 }
222
223 /**
224 * Get a Message object with context set. See wfMessage for parameters.
225 *
226 * @since 1.27
227 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
228 * or a MessageSpecifier.
229 * @param mixed $args,...
230 * @return Message
231 */
232 public function msg( $key ) {
233 return wfMessage( ...func_get_args() )
234 ->inLanguage( $this->getLanguage() )
235 // Use a dummy title because there is no real title
236 // for this endpoint, and the cache won't vary on it
237 // anyways.
238 ->title( Title::newFromText( 'Dwimmerlaik' ) );
239 }
240
241 /**
242 * Get the possibly-cached User object for the specified username
243 *
244 * @since 1.25
245 * @return User
246 */
247 public function getUserObj() {
248 if ( $this->userObj === null ) {
249 $username = $this->getUser();
250 if ( $username ) {
251 // Use provided username if valid, fallback to anonymous user
252 $this->userObj = User::newFromName( $username ) ?: new User;
253 } else {
254 // Anonymous user
255 $this->userObj = new User;
256 }
257 }
258
259 return $this->userObj;
260 }
261
262 /**
263 * @return bool
264 */
265 public function getDebug() {
266 return $this->debug;
267 }
268
269 /**
270 * @return string|null
271 */
272 public function getOnly() {
273 return $this->only;
274 }
275
276 /**
277 * @see ResourceLoaderModule::getVersionHash
278 * @see ResourceLoaderClientHtml::makeLoad
279 * @return string|null
280 */
281 public function getVersion() {
282 return $this->version;
283 }
284
285 /**
286 * @return bool
287 */
288 public function getRaw() {
289 return $this->raw;
290 }
291
292 /**
293 * @return string|null
294 */
295 public function getImage() {
296 return $this->image;
297 }
298
299 /**
300 * @return string|null
301 */
302 public function getVariant() {
303 return $this->variant;
304 }
305
306 /**
307 * @return string|null
308 */
309 public function getFormat() {
310 return $this->format;
311 }
312
313 /**
314 * If this is a request for an image, get the ResourceLoaderImage object.
315 *
316 * @since 1.25
317 * @return ResourceLoaderImage|bool false if a valid object cannot be created
318 */
319 public function getImageObj() {
320 if ( $this->imageObj === null ) {
321 $this->imageObj = false;
322
323 if ( !$this->image ) {
324 return $this->imageObj;
325 }
326
327 $modules = $this->getModules();
328 if ( count( $modules ) !== 1 ) {
329 return $this->imageObj;
330 }
331
332 $module = $this->getResourceLoader()->getModule( $modules[0] );
333 if ( !$module || !$module instanceof ResourceLoaderImageModule ) {
334 return $this->imageObj;
335 }
336
337 $image = $module->getImage( $this->image, $this );
338 if ( !$image ) {
339 return $this->imageObj;
340 }
341
342 $this->imageObj = $image;
343 }
344
345 return $this->imageObj;
346 }
347
348 /**
349 * Return the replaced-content mapping callback
350 *
351 * When editing a page that's used to generate the scripts or styles of a
352 * ResourceLoaderWikiModule, a preview should use the to-be-saved version of
353 * the page rather than the current version in the database. A context
354 * supporting such previews should return a callback to return these
355 * mappings here.
356 *
357 * @since 1.32
358 * @return callable|null Signature is `Content|null func( Title $t )`
359 */
360 public function getContentOverrideCallback() {
361 return null;
362 }
363
364 /**
365 * @return bool
366 */
367 public function shouldIncludeScripts() {
368 return $this->getOnly() === null || $this->getOnly() === 'scripts';
369 }
370
371 /**
372 * @return bool
373 */
374 public function shouldIncludeStyles() {
375 return $this->getOnly() === null || $this->getOnly() === 'styles';
376 }
377
378 /**
379 * @return bool
380 */
381 public function shouldIncludeMessages() {
382 return $this->getOnly() === null;
383 }
384
385 /**
386 * All factors that uniquely identify this request, except 'modules'.
387 *
388 * The list of modules is excluded here for legacy reasons as most callers already
389 * split up handling of individual modules. Including it here would massively fragment
390 * the cache and decrease its usefulness.
391 *
392 * E.g. Used by RequestFileCache to form a cache key for storing the reponse output.
393 *
394 * @return string
395 */
396 public function getHash() {
397 if ( !isset( $this->hash ) ) {
398 $this->hash = implode( '|', [
399 // Module content vary
400 $this->getLanguage(),
401 $this->getSkin(),
402 $this->getDebug(),
403 $this->getUser(),
404 // Request vary
405 $this->getOnly(),
406 $this->getVersion(),
407 $this->getRaw(),
408 $this->getImage(),
409 $this->getVariant(),
410 $this->getFormat(),
411 ] );
412 }
413 return $this->hash;
414 }
415
416 /**
417 * Get the request base parameters, omitting any defaults.
418 *
419 * @internal For internal use by ResourceLoaderStartUpModule only
420 * @return array
421 */
422 public function getReqBase() {
423 $reqBase = [];
424 if ( $this->getLanguage() !== self::DEFAULT_LANG ) {
425 $reqBase['lang'] = $this->getLanguage();
426 }
427 if ( $this->getSkin() !== self::DEFAULT_SKIN ) {
428 $reqBase['skin'] = $this->getSkin();
429 }
430 if ( $this->getDebug() ) {
431 $reqBase['debug'] = 'true';
432 }
433 return $reqBase;
434 }
435 }