Debian Codegraph @

includes/ResourceLoader/Context.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 namespace MediaWiki\ResourceLoader;
24
25 use MediaWiki\Logger\LoggerFactory;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Message\Message;
28 use MediaWiki\Page\PageReferenceValue;
29 use MediaWiki\Request\FauxRequest;
30 use MediaWiki\Request\WebRequest;
31 use MediaWiki\User\User;
32 use MediaWiki\User\UserIdentity;
33 use MediaWiki\User\UserRigorOptions;
34 use MessageLocalizer;
35 use Psr\Log\LoggerInterface;
36 use Wikimedia\Message\MessageSpecifier;
37
38 /**
39 * Context object that contains information about the state of a specific
40 * ResourceLoader web request. Passed around to Module methods.
41 *
42 * @ingroup ResourceLoader
43 * @since 1.17
44 */
45 class Context implements MessageLocalizer {
46 public const DEFAULT_LANG = 'qqx';
47 public const DEFAULT_SKIN = 'fallback';
48
49 /** @internal For use in ResourceLoader classes. */
50 public const DEBUG_OFF = 0;
51 /** @internal For use in ResourceLoader classes. */
52 public const DEBUG_LEGACY = 1;
53 /** @internal For use in SpecialJavaScriptTest. */
54 public const DEBUG_MAIN = 2;
55
56 /** @var ResourceLoader */
57 protected $resourceLoader;
58 /** @var WebRequest */
59 protected $request;
60 /** @var LoggerInterface */
61 protected $logger;
62
63 // Module content vary
64 /** @var string */
65 protected $skin;
66 /** @var string */
67 protected $language;
68 /** @var int */
69 protected $debug;
70 /** @var string|null */
71 protected $user;
72
73 // Request vary (in addition to cache vary)
74 /** @var string[] */
75 protected $modules;
76 /** @var string|null */
77 protected $only;
78 /** @var string|null */
79 protected $version;
80 /** @var bool */
81 protected $raw;
82 /** @var bool */
83 protected $sourcemap;
84 /** @var string|null */
85 protected $image;
86 /** @var string|null */
87 protected $variant;
88 /** @var string|null */
89 protected $format;
90
91 /** @var string|null */
92 protected $direction;
93 /** @var string|null */
94 protected $hash;
95 /** @var User|null */
96 protected $userObj;
97 /** @var UserIdentity|null|false */
98 protected $userIdentity = false;
99 /** @var Image|false */
100 protected $imageObj;
101
102 /**
103 * @param ResourceLoader $resourceLoader
104 * @param WebRequest $request
105 * @param string[]|null $validSkins List of valid skin names. If not passed,
106 * any skin name is considered valid. Invalid skins are replaced by the default.
107 */
108 public function __construct(
109 ResourceLoader $resourceLoader, WebRequest $request, $validSkins = null
110 ) {
111 $this->resourceLoader = $resourceLoader;
112 $this->request = $request;
113 $this->logger = $resourceLoader->getLogger();
114
115 // Optimisation: Use WebRequest::getRawVal() instead of getVal(). We don't
116 // need the slow Language+UTF logic meant for user input here. (f303bb9360)
117
118 // List of modules
119 $modules = $request->getRawVal( 'modules' );
120 $this->modules = $modules ? ResourceLoader::expandModuleNames( $modules ) : [];
121
122 // Various parameters
123 $this->user = $request->getRawVal( 'user' );
124 $this->debug = self::debugFromString( $request->getRawVal( 'debug' ) );
125 $this->only = $request->getRawVal( 'only' );
126 $this->version = $request->getRawVal( 'version' );
127 $this->raw = $request->getFuzzyBool( 'raw' );
128 $this->sourcemap = $request->getFuzzyBool( 'sourcemap' );
129
130 // Image requests
131 $this->image = $request->getRawVal( 'image' );
132 $this->variant = $request->getRawVal( 'variant' );
133 $this->format = $request->getRawVal( 'format' );
134
135 $skin = $request->getRawVal( 'skin' );
136 if (
137 $skin === null
138 || ( is_array( $validSkins ) && !in_array( $skin, $validSkins ) )
139 ) {
140 // For requests without a known skin specified,
141 // use MediaWiki's 'fallback' skin for any skin-specific decisions.
142 $skin = self::DEFAULT_SKIN;
143 }
144 $this->skin = $skin;
145 }
146
147 /**
148 * @internal For use in ResourceLoader::inDebugMode
149 * @param string|null $debug
150 * @return int
151 */
152 public static function debugFromString( ?string $debug ): int {
153 // The canonical way to enable debug mode is via debug=true
154 // This continues to map to v1 until v2 is ready (T85805).
155 if ( $debug === 'true' || $debug === '1' ) {
156 $ret = self::DEBUG_LEGACY;
157 } elseif ( $debug === '2' ) {
158 $ret = self::DEBUG_MAIN;
159 } else {
160 $ret = self::DEBUG_OFF;
161 }
162
163 return $ret;
164 }
165
166 /**
167 * Return a dummy Context object suitable for passing into
168 * things that don't "really" need a context.
169 *
170 * Use cases:
171 * - Unit tests (deprecated, create empty instance directly or use RLTestCase).
172 *
173 * @return Context
174 */
175 public static function newDummyContext(): Context {
176 // This currently creates a non-empty instance of ResourceLoader (all modules registered),
177 // but that's probably not needed. So once that moves into ServiceWiring, this'll
178 // become more like the EmptyResourceLoader class we have in PHPUnit tests, which
179 // is what this should've had originally. If this turns out to be untrue, change to:
180 // `MediaWikiServices::getInstance()->getResourceLoader()` instead.
181 return new self( new ResourceLoader(
182 MediaWikiServices::getInstance()->getMainConfig(),
183 LoggerFactory::getInstance( 'resourceloader' )
184 ), new FauxRequest( [] ) );
185 }
186
187 public function getResourceLoader(): ResourceLoader {
188 return $this->resourceLoader;
189 }
190
191 public function getRequest(): WebRequest {
192 return $this->request;
193 }
194
195 /**
196 * @deprecated since 1.34 Use Module::getLogger instead
197 * inside module methods. Use ResourceLoader::getLogger elsewhere.
198 * @since 1.27
199 * @return LoggerInterface
200 */
201 public function getLogger() {
202 return $this->logger;
203 }
204
205 public function getModules(): array {
206 return $this->modules;
207 }
208
209 public function getLanguage(): string {
210 if ( $this->language === null ) {
211 // Must be a valid language code after this point (T64849)
212 // Only support uselang values that follow built-in conventions (T102058)
213 $lang = $this->getRequest()->getRawVal( 'lang' ) ?? '';
214 // Stricter version of RequestContext::sanitizeLangCode()
215 $validBuiltinCode = MediaWikiServices::getInstance()->getLanguageNameUtils()
216 ->isValidBuiltInCode( $lang );
217 if ( !$validBuiltinCode ) {
218 // The 'lang' parameter is required. (Not yet enforced.)
219 // If omitted, localise with the dummy language code.
220 $lang = self::DEFAULT_LANG;
221 }
222 $this->language = $lang;
223 }
224 return $this->language;
225 }
226
227 public function getDirection(): string {
228 if ( $this->direction === null ) {
229 $direction = $this->getRequest()->getRawVal( 'dir' );
230 if ( $direction === 'ltr' || $direction === 'rtl' ) {
231 $this->direction = $direction;
232 } else {
233 // Determine directionality based on user language (T8100)
234 $this->direction = MediaWikiServices::getInstance()->getLanguageFactory()
235 ->getLanguage( $this->getLanguage() )->getDir();
236 }
237 }
238 return $this->direction;
239 }
240
241 public function getSkin(): string {
242 return $this->skin;
243 }
244
245 /**
246 * @return string|null
247 */
248 public function getUser(): ?string {
249 return $this->user;
250 }
251
252 /**
253 * Get a Message object with context set. See wfMessage for parameters.
254 *
255 * @since 1.27
256 * @param string|string[]|MessageSpecifier $key Message key, or array of keys,
257 * or a MessageSpecifier.
258 * @param mixed ...$params
259 * @return Message
260 */
261 public function msg( $key, ...$params ): Message {
262 return wfMessage( $key, ...$params )
263 // Do not use MediaWiki user language from session. Use the provided one instead.
264 ->inLanguage( $this->getLanguage() )
265 // inLanguage() clears the interface flag, so we need re-enable it. (T291601)
266 ->setInterfaceMessageFlag( true )
267 // Use a dummy title because there is no real title for this endpoint, and the cache won't
268 // vary on it anyways.
269 ->page( PageReferenceValue::localReference( NS_SPECIAL, 'Badtitle/ResourceLoaderContext' ) );
270 }
271
272 /**
273 * Get the possibly-cached UserIdentity object for the specified username
274 *
275 * This will be null on most requests,
276 * except for load.php requests that have a 'user' parameter set.
277 *
278 * @since 1.38
279 * @return UserIdentity|null
280 */
281 public function getUserIdentity(): ?UserIdentity {
282 if ( $this->userIdentity === false ) {
283 $username = $this->getUser();
284 if ( $username === null ) {
285 // Anonymous user
286 $this->userIdentity = null;
287 } else {
288 // Use provided username if valid
289 $this->userIdentity = MediaWikiServices::getInstance()
290 ->getUserFactory()
291 ->newFromName( $username, UserRigorOptions::RIGOR_VALID );
292 }
293 }
294 return $this->userIdentity;
295 }
296
297 /**
298 * Get the possibly-cached User object for the specified username
299 *
300 * @since 1.25
301 * @return User
302 */
303 public function getUserObj(): User {
304 if ( $this->userObj === null ) {
305 $username = $this->getUser();
306 $userFactory = MediaWikiServices::getInstance()->getUserFactory();
307 if ( $username ) {
308 // Use provided username if valid, fallback to anonymous user
309 $this->userObj = $userFactory->newFromName( $username, UserRigorOptions::RIGOR_VALID );
310 }
311 // Anonymous user
312 $this->userObj ??= $userFactory->newAnonymous();
313 }
314
315 return $this->userObj;
316 }
317
318 public function getDebug(): int {
319 return $this->debug;
320 }
321
322 /**
323 * @return string|null
324 */
325 public function getOnly(): ?string {
326 return $this->only;
327 }
328
329 /**
330 * @see Module::getVersionHash
331 * @see ClientHtml::makeLoad
332 * @return string|null
333 */
334 public function getVersion(): ?string {
335 return $this->version;
336 }
337
338 public function getRaw(): bool {
339 return $this->raw;
340 }
341
342 /**
343 * @since 1.41
344 * @return bool
345 */
346 public function isSourceMap(): bool {
347 return $this->sourcemap;
348 }
349
350 /**
351 * @return string|null
352 */
353 public function getImage(): ?string {
354 return $this->image;
355 }
356
357 /**
358 * @return string|null
359 */
360 public function getVariant(): ?string {
361 return $this->variant;
362 }
363
364 /**
365 * @return string|null
366 */
367 public function getFormat(): ?string {
368 return $this->format;
369 }
370
371 /**
372 * If this is a request for an image, get the Image object.
373 *
374 * @since 1.25
375 * @return Image|false false if a valid object cannot be created
376 */
377 public function getImageObj() {
378 if ( $this->imageObj === null ) {
379 $this->imageObj = false;
380
381 if ( !$this->image ) {
382 return $this->imageObj;
383 }
384
385 $modules = $this->getModules();
386 if ( count( $modules ) !== 1 ) {
387 return $this->imageObj;
388 }
389
390 $module = $this->getResourceLoader()->getModule( $modules[0] );
391 if ( !$module || !$module instanceof ImageModule ) {
392 return $this->imageObj;
393 }
394
395 $image = $module->getImage( $this->image, $this );
396 if ( !$image ) {
397 return $this->imageObj;
398 }
399
400 $this->imageObj = $image;
401 }
402
403 return $this->imageObj;
404 }
405
406 /**
407 * Return the replaced-content mapping callback
408 *
409 * When editing a page that's used to generate the scripts or styles of a
410 * WikiModule, a preview should use the to-be-saved version of
411 * the page rather than the current version in the database. A context
412 * supporting such previews should return a callback to return these
413 * mappings here.
414 *
415 * @since 1.32
416 * @return callable|null Signature is `Content|null func( Title $t )`
417 */
418 public function getContentOverrideCallback() {
419 return null;
420 }
421
422 public function shouldIncludeScripts(): bool {
423 return $this->getOnly() === null || $this->getOnly() === 'scripts';
424 }
425
426 public function shouldIncludeStyles(): bool {
427 return $this->getOnly() === null || $this->getOnly() === 'styles';
428 }
429
430 public function shouldIncludeMessages(): bool {
431 return $this->getOnly() === null;
432 }
433
434 /**
435 * All factors that uniquely identify this request, except 'modules'.
436 *
437 * The list of modules is excluded here for legacy reasons as most callers already
438 * split up handling of individual modules. Including it here would massively fragment
439 * the cache and decrease its usefulness.
440 *
441 * E.g. Used by RequestFileCache to form a cache key for storing the response output.
442 *
443 * @return string
444 */
445 public function getHash(): string {
446 if ( $this->hash === null ) {
447 $this->hash = implode( '|', [
448 // Module content vary
449 $this->getLanguage(),
450 $this->getSkin(),
451 (string)$this->getDebug(),
452 $this->getUser() ?? '',
453 // Request vary
454 $this->getOnly() ?? '',
455 $this->getVersion() ?? '',
456 (string)$this->getRaw(),
457 $this->getImage() ?? '',
458 $this->getVariant() ?? '',
459 $this->getFormat() ?? '',
460 ] );
461 }
462 return $this->hash;
463 }
464
465 /**
466 * Get the request base parameters, omitting any defaults.
467 *
468 * @internal For use by StartUpModule only
469 * @return string[]
470 */
471 public function getReqBase(): array {
472 $reqBase = [];
473 $lang = $this->getLanguage();
474 if ( $lang !== self::DEFAULT_LANG ) {
475 $reqBase['lang'] = $lang;
476 }
477 $skin = $this->getSkin();
478 if ( $skin !== self::DEFAULT_SKIN ) {
479 $reqBase['skin'] = $skin;
480 }
481 $debug = $this->getDebug();
482 if ( $debug !== self::DEBUG_OFF ) {
483 $reqBase['debug'] = strval( $debug );
484 }
485 return $reqBase;
486 }
487
488 /**
489 * Wrapper around json_encode that avoids needless escapes,
490 * and pretty-prints in debug mode.
491 *
492 * @since 1.34
493 * @param mixed $data
494 * @return string|false JSON string, false on error
495 */
496 public function encodeJson( $data ) {
497 // Keep output as small as possible by disabling needless escape modes
498 // that PHP uses by default.
499 // However, while most module scripts are only served on HTTP responses
500 // for JavaScript, some modules can also be embedded in the HTML as inline
501 // scripts. This, and the fact that we sometimes need to export strings
502 // containing user-generated content and labels that may genuinely contain
503 // a sequences like "</script>", we need to encode either '/' or '<'.
504 // By default PHP escapes '/'. Let's escape '<' instead which is less common
505 // and allows URLs to mostly remain readable.
506 $jsonFlags = JSON_UNESCAPED_SLASHES |
507 JSON_UNESCAPED_UNICODE |
508 JSON_PARTIAL_OUTPUT_ON_ERROR |
509 JSON_HEX_TAG |
510 JSON_HEX_AMP;
511 if ( $this->getDebug() ) {
512 $jsonFlags |= JSON_PRETTY_PRINT;
513 }
514 $json = json_encode( $data, $jsonFlags );
515 if ( json_last_error() !== JSON_ERROR_NONE ) {
516 trigger_error( __METHOD__ . ' partially failed: ' . json_last_error_msg(), E_USER_WARNING );
517 }
518 return $json;
519 }
520 }