Debian Codegraph @

includes/ResourceLoader/Module.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 Exception;
26 use FileContentsHasher;
27 use LogicException;
28 use MediaWiki\Config\Config;
29 use MediaWiki\HookContainer\HookContainer;
30 use MediaWiki\MainConfigNames;
31 use MediaWiki\MediaWikiServices;
32 use Peast\Peast;
33 use Peast\Syntax\Exception as PeastSyntaxException;
34 use Psr\Log\LoggerAwareInterface;
35 use Psr\Log\LoggerInterface;
36 use Psr\Log\NullLogger;
37 use RuntimeException;
38 use Wikimedia\RelPath;
39 use Wikimedia\RequestTimeout\TimeoutException;
40
41 /**
42 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
43 *
44 * @see $wgResourceModules for the available options when registering a module.
45 * @stable to extend
46 * @ingroup ResourceLoader
47 * @since 1.17
48 */
49 abstract class Module implements LoggerAwareInterface {
50 /** @var Config */
51 protected $config;
52 /** @var LoggerInterface */
53 protected $logger;
54
55 /**
56 * Script and style modules form a hierarchy of trustworthiness, with core modules
57 * like skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
58 * limit the types of scripts and styles we allow to load on, say, sensitive special
59 * pages like Special:UserLogin and Special:Preferences
60 * @var int
61 */
62 protected $origin = self::ORIGIN_CORE_SITEWIDE;
63
64 /** @var string|null Module name */
65 protected $name = null;
66 /** @var string[]|null Skin names */
67 protected $skins = null;
68
69 /** @var array Map of (variant => indirect file dependencies) */
70 protected $fileDeps = [];
71 /** @var array Map of (language => in-object cache for message blob) */
72 protected $msgBlobs = [];
73 /** @var array Map of (context hash => cached module version hash) */
74 protected $versionHash = [];
75 /** @var array Map of (context hash => cached module content) */
76 protected $contents = [];
77
78 /** @var HookRunner|null */
79 private $hookRunner;
80
81 /** @var callback Function of (module name, variant) to get indirect file dependencies */
82 private $depLoadCallback;
83 /** @var callback Function of (module name, variant) to get indirect file dependencies */
84 private $depSaveCallback;
85
86 /** @var string|bool Deprecation string or true if deprecated; false otherwise */
87 protected $deprecated = false;
88
89 /** @var string Scripts only */
90 public const TYPE_SCRIPTS = 'scripts';
91 /** @var string Styles only */
92 public const TYPE_STYLES = 'styles';
93 /** @var string Scripts and styles */
94 public const TYPE_COMBINED = 'combined';
95
96 /** @var string */
97 public const GROUP_SITE = 'site';
98 /** @var string */
99 public const GROUP_USER = 'user';
100 /** @var string */
101 public const GROUP_PRIVATE = 'private';
102 /** @var string */
103 public const GROUP_NOSCRIPT = 'noscript';
104
105 /** @var string Module only has styles (loaded via <style> or <link rel=stylesheet>) */
106 public const LOAD_STYLES = 'styles';
107 /** @var string Module may have other resources (loaded via mw.loader from a script) */
108 public const LOAD_GENERAL = 'general';
109
110 /** @var int An constant to represent no module loading; make sure this is kept as the smallest number in this group */
111 public const ORIGIN_NONE = 0;
112
113 /** @var int Sitewide core module like a skin file or jQuery component */
114 public const ORIGIN_CORE_SITEWIDE = 1;
115 /** @var int Per-user module generated by the software */
116 public const ORIGIN_CORE_INDIVIDUAL = 2;
117 /**
118 * Sitewide module generated from user-editable files, like MediaWiki:Common.js,
119 * or modules accessible to multiple users, such as those generated by the Gadgets extension.
120 * @var int
121 */
122 public const ORIGIN_USER_SITEWIDE = 3;
123 /** @var int Per-user module generated from user-editable files, like User:Me/vector.js */
124 public const ORIGIN_USER_INDIVIDUAL = 4;
125 /** @var int An access constant; make sure this is kept as the largest number in this group */
126 public const ORIGIN_ALL = 10;
127
128 /** @var int Cache version for user-script JS validation errors from validateScriptFile(). */
129 private const USERJSPARSE_CACHE_VERSION = 3;
130
131 /**
132 * Get this module's name. This is set when the module is registered
133 * with ResourceLoader::register()
134 *
135 * @return string|null Name (string) or null if no name was set
136 */
137 public function getName() {
138 return $this->name;
139 }
140
141 /**
142 * Set this module's name. This is called by ResourceLoader::register()
143 * when registering the module. Other code should not call this.
144 *
145 * @param string $name
146 */
147 public function setName( $name ) {
148 $this->name = $name;
149 }
150
151 /**
152 * Provide overrides for skinStyles to modules that support that.
153 *
154 * This MUST be called after self::setName().
155 *
156 * @since 1.37
157 * @see $wgResourceModuleSkinStyles
158 * @param array $moduleSkinStyles
159 */
160 public function setSkinStylesOverride( array $moduleSkinStyles ): void {
161 // Stub, only supported by FileModule currently.
162 }
163
164 /**
165 * Inject the functions that load/save the indirect file path dependency list from storage
166 *
167 * @param callable $loadCallback Function of (module name, variant)
168 * @param callable $saveCallback Function of (module name, variant, current paths, stored paths)
169 * @since 1.35
170 */
171 public function setDependencyAccessCallbacks( callable $loadCallback, callable $saveCallback ) {
172 $this->depLoadCallback = $loadCallback;
173 $this->depSaveCallback = $saveCallback;
174 }
175
176 /**
177 * Get this module's origin. This is set when the module is registered
178 * with ResourceLoader::register()
179 *
180 * @return int Module class constant, the subclass default if not set manually
181 */
182 public function getOrigin() {
183 return $this->origin;
184 }
185
186 /**
187 * @param Context $context
188 * @return bool
189 */
190 public function getFlip( Context $context ) {
191 return MediaWikiServices::getInstance()->getContentLanguage()->getDir() !==
192 $context->getDirection();
193 }
194
195 /**
196 * Get JS representing deprecation information for the current module if available
197 *
198 * @deprecated since 1.41 use getDeprecationWarning()
199 *
200 * @param Context $context
201 * @return string JavaScript code
202 */
203 public function getDeprecationInformation( Context $context ) {
204 wfDeprecated( __METHOD__, '1.41' );
205 $warning = $this->getDeprecationWarning();
206 if ( $warning === null ) {
207 return '';
208 }
209 return 'mw.log.warn(' . $context->encodeJson( $warning ) . ');';
210 }
211
212 /**
213 * Get the deprecation warning, if any
214 *
215 * @since 1.41
216 * @return string|null
217 */
218 public function getDeprecationWarning() {
219 if ( !$this->deprecated ) {
220 return null;
221 }
222 $name = $this->getName();
223 $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
224 if ( is_string( $this->deprecated ) ) {
225 $warning .= "\n" . $this->deprecated;
226 }
227 return $warning;
228 }
229
230 /**
231 * Get all JS for this module for a given language and skin.
232 * Includes all relevant JS except loader scripts.
233 *
234 * For multi-file modules where require() is used to load one file from
235 * another file, this should return an array structured as follows:
236 * [
237 * 'files' => [
238 * 'file1.js' => [ 'type' => 'script', 'content' => 'JS code' ],
239 * 'file2.js' => [ 'type' => 'script', 'content' => 'JS code' ],
240 * 'data.json' => [ 'type' => 'data', 'content' => array ]
241 * ],
242 * 'main' => 'file1.js'
243 * ]
244 *
245 * For plain concatenated scripts, this can either return a string, or an
246 * associative array similar to the one used for package files:
247 * [
248 * 'plainScripts' => [
249 * [ 'content' => 'JS code' ],
250 * [ 'content' => 'JS code' ],
251 * ],
252 * ]
253 *
254 * @stable to override
255 * @param Context $context
256 * @return string|array JavaScript code (string), or multi-file array with the
257 * following keys:
258 * - files: An associative array mapping file name to file info structure
259 * - main: The name of the main script, a key in the files array
260 * - plainScripts: An array of file info structures to be concatenated and
261 * executed when the module is loaded.
262 * Each file info structure has the following keys:
263 * - type: May be "script", "script-vue" or "data". Optional, default "script".
264 * - content: The string content of the file
265 * - filePath: A FilePath object describing the location of the source file.
266 * This will be used to construct the source map during minification.
267 */
268 public function getScript( Context $context ) {
269 // Stub, override expected
270 return '';
271 }
272
273 /**
274 * Takes named templates by the module and returns an array mapping.
275 *
276 * @stable to override
277 * @return string[] Array of templates mapping template alias to content
278 */
279 public function getTemplates() {
280 // Stub, override expected.
281 return [];
282 }
283
284 /**
285 * @return Config
286 * @since 1.24
287 */
288 public function getConfig() {
289 if ( $this->config === null ) {
290 throw new RuntimeException( 'Config accessed before it is set' );
291 }
292
293 return $this->config;
294 }
295
296 /**
297 * @param Config $config
298 * @since 1.24
299 */
300 public function setConfig( Config $config ) {
301 $this->config = $config;
302 }
303
304 /**
305 * @since 1.27
306 * @param LoggerInterface $logger
307 */
308 public function setLogger( LoggerInterface $logger ) {
309 $this->logger = $logger;
310 }
311
312 /**
313 * @since 1.27
314 * @return LoggerInterface
315 */
316 protected function getLogger() {
317 if ( !$this->logger ) {
318 $this->logger = new NullLogger();
319 }
320 return $this->logger;
321 }
322
323 /**
324 * @internal For use only by ResourceLoader::getModule
325 * @param HookContainer $hookContainer
326 */
327 public function setHookContainer( HookContainer $hookContainer ): void {
328 $this->hookRunner = new HookRunner( $hookContainer );
329 }
330
331 /**
332 * Get a HookRunner for running core hooks.
333 *
334 * @internal For use only within core Module subclasses. Hook interfaces may be removed
335 * without notice.
336 * @return HookRunner
337 */
338 protected function getHookRunner(): HookRunner {
339 return $this->hookRunner;
340 }
341
342 /**
343 * Get alternative script URLs for legacy debug mode.
344 *
345 * The default behavior is to return a `load.php?only=scripts&module=<name>` URL.
346 *
347 * Module classes that merely wrap one or more other script files in production mode, may
348 * override this method to return an array of raw URLs for those underlying scripts,
349 * if those are individually web-accessible.
350 *
351 * The mw.loader client will load and execute each URL consecutively. This has the caveat of
352 * executing legacy debug scripts in the global scope, which is why non-package file modules
353 * tend to use file closures (T50886).
354 *
355 * This function MUST NOT be called, unless all the following are true:
356 *
357 * 1. We're in debug mode,
358 * 2. There is no `only=` parameter in the context,
359 * 3. self::supportsURLLoading() has returned true.
360 *
361 * Point 2 prevents an infinite loop since we use the `only=` mechanism in the return value.
362 * Overrides must similarly return with `only`, or return or a non-load.php URL.
363 *
364 * @stable to override
365 * @param Context $context
366 * @return string[]
367 */
368 public function getScriptURLsForDebug( Context $context ) {
369 $rl = $context->getResourceLoader();
370 $derivative = new DerivativeContext( $context );
371 $derivative->setModules( [ $this->getName() ] );
372 $derivative->setOnly( 'scripts' );
373
374 $url = $rl->createLoaderURL(
375 $this->getSource(),
376 $derivative
377 );
378
379 // Expand debug URL in case we are another wiki's module source (T255367)
380 $url = $rl->expandUrl( $this->getConfig()->get( MainConfigNames::Server ), $url );
381
382 return [ $url ];
383 }
384
385 /**
386 * Whether this module supports URL loading. If this function returns false,
387 * getScript() will be used even in cases (debug mode, no only param) where
388 * getScriptURLsForDebug() would normally be used instead.
389 *
390 * @stable to override
391 * @return bool
392 */
393 public function supportsURLLoading() {
394 return true;
395 }
396
397 /**
398 * Get all CSS for this module for a given skin.
399 *
400 * @stable to override
401 * @param Context $context
402 * @return array List of CSS strings or array of CSS strings keyed by media type.
403 * like [ 'screen' => '.foo { width: 0 }' ];
404 * or [ 'screen' => [ '.foo { width: 0 }' ] ];
405 */
406 public function getStyles( Context $context ) {
407 // Stub, override expected
408 return [];
409 }
410
411 /**
412 * Get the URL or URLs to load for this module's CSS in debug mode.
413 * The default behavior is to return a load.php?only=styles URL for
414 * the module, but file-based modules will want to override this to
415 * load the files directly
416 *
417 * This function must only be called when:
418 *
419 * 1. We're in debug mode,
420 * 2. There is no `only=` parameter and,
421 * 3. self::supportsURLLoading() returns true.
422 *
423 * See also getScriptURLsForDebug().
424 *
425 * @stable to override
426 * @param Context $context
427 * @return array [ mediaType => [ URL1, URL2, ... ], ... ]
428 */
429 public function getStyleURLsForDebug( Context $context ) {
430 $resourceLoader = $context->getResourceLoader();
431 $derivative = new DerivativeContext( $context );
432 $derivative->setModules( [ $this->getName() ] );
433 $derivative->setOnly( 'styles' );
434
435 $url = $resourceLoader->createLoaderURL(
436 $this->getSource(),
437 $derivative
438 );
439
440 return [ 'all' => [ $url ] ];
441 }
442
443 /**
444 * Get the messages needed for this module.
445 *
446 * To get a JSON blob with messages, use MessageBlobStore::get()
447 *
448 * @stable to override
449 * @return string[] List of message keys. Keys may occur more than once
450 */
451 public function getMessages() {
452 // Stub, override expected
453 return [];
454 }
455
456 /**
457 * Specifies the group this module is in.
458 *
459 * Return one of the Module::GROUP_ constants for reserved group names with special behavior,
460 * or a freeform string.
461 * Refer to https://www.mediawiki.org/wiki/ResourceLoader/Architecture#Groups for documentation.
462 *
463 * @stable to override
464 * @return string|null Group name
465 */
466 public function getGroup() {
467 // Stub, override expected
468 return null;
469 }
470
471 /**
472 * Get the source of this module. Should only be overridden for foreign modules.
473 *
474 * @stable to override
475 * @return string Source name, 'local' for local modules
476 */
477 public function getSource() {
478 // Stub, override expected
479 return 'local';
480 }
481
482 /**
483 * Get a list of modules this module depends on.
484 *
485 * Dependency information is taken into account when loading a module
486 * on the client side.
487 *
488 * Note: It is expected that $context will be made non-optional in the near
489 * future.
490 *
491 * @stable to override
492 * @param Context|null $context
493 * @return string[] List of module names as strings
494 */
495 public function getDependencies( ?Context $context = null ) {
496 // Stub, override expected
497 return [];
498 }
499
500 /**
501 * Get list of skins for which this module must be available to load.
502 *
503 * By default, modules are available to all skins.
504 *
505 * This information may be used by the startup module to optimise registrations
506 * based on the current skin.
507 *
508 * @stable to override
509 * @since 1.39
510 * @return string[]|null
511 */
512 public function getSkins(): ?array {
513 return $this->skins;
514 }
515
516 /**
517 * Get the module's load type.
518 *
519 * @stable to override
520 * @since 1.28
521 * @return string Module LOAD_* constant
522 */
523 public function getType() {
524 return self::LOAD_GENERAL;
525 }
526
527 /**
528 * Get the skip function.
529 *
530 * Modules that provide fallback functionality can provide a "skip function". This
531 * function, if provided, will be passed along to the module registry on the client.
532 * When this module is loaded (either directly or as a dependency of another module),
533 * then this function is executed first. If the function returns true, the module will
534 * instantly be considered "ready" without requesting the associated module resources.
535 *
536 * The value returned here must be valid javascript for execution in a private function.
537 * It must not contain the "function () {" and "}" wrapper though.
538 *
539 * @stable to override
540 * @return string|null A JavaScript function body returning a boolean value, or null
541 */
542 public function getSkipFunction() {
543 return null;
544 }
545
546 /**
547 * Whether the module requires ES6 support in the client.
548 *
549 * If the client does not support ES6, attempting to load a module that requires ES6 will
550 * result in an error.
551 *
552 * @deprecated since 1.41, ignored by ResourceLoader
553 * @since 1.36
554 * @return bool
555 */
556 public function requiresES6() {
557 return true;
558 }
559
560 /**
561 * Get the indirect dependencies for this module pursuant to the skin/language context
562 *
563 * These are only image files referenced by the module's stylesheet
564 *
565 * If neither setFileDependencies() nor setDependencyAccessCallbacks() was called,
566 * this will simply return a placeholder with an empty file list
567 *
568 * @see Module::setFileDependencies()
569 * @see Module::saveFileDependencies()
570 * @param Context $context
571 * @return string[] List of absolute file paths
572 */
573 protected function getFileDependencies( Context $context ) {
574 $variant = self::getVary( $context );
575
576 if ( !isset( $this->fileDeps[$variant] ) ) {
577 if ( $this->depLoadCallback ) {
578 $this->fileDeps[$variant] =
579 call_user_func( $this->depLoadCallback, $this->getName(), $variant );
580 } else {
581 $this->getLogger()->info( __METHOD__ . ": no callback registered" );
582 $this->fileDeps[$variant] = [];
583 }
584 }
585
586 return $this->fileDeps[$variant];
587 }
588
589 /**
590 * Set the indirect dependencies for this module pursuant to the skin/language context
591 *
592 * These are only image files referenced by the module's stylesheet
593 *
594 * @see Module::getFileDependencies()
595 * @see Module::saveFileDependencies()
596 * @param Context $context
597 * @param string[] $paths List of absolute file paths
598 */
599 public function setFileDependencies( Context $context, array $paths ) {
600 $variant = self::getVary( $context );
601 $this->fileDeps[$variant] = $paths;
602 }
603
604 /**
605 * Save the indirect dependencies for this module pursuant to the skin/language context
606 *
607 * @param Context $context
608 * @param string[] $curFileRefs List of newly computed indirect file dependencies
609 * @since 1.27
610 */
611 protected function saveFileDependencies( Context $context, array $curFileRefs ) {
612 if ( !$this->depSaveCallback ) {
613 $this->getLogger()->info( __METHOD__ . ": no callback registered" );
614
615 return;
616 }
617
618 try {
619 // Pitfalls and performance considerations:
620 // 1. Don't keep updating the tracked paths due to duplicates or sorting.
621 // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
622 // 3. Don't needlessly replace tracked paths with the same value
623 // just because $IP changed (e.g. when upgrading a wiki).
624 // 4. Don't create an endless replace loop on every request for this
625 // module when '../' is used anywhere. Even though both are expanded
626 // (one expanded by getFileDependencies from the DB, the other is
627 // still raw as originally read by RL), the latter has not
628 // been normalized yet.
629 call_user_func(
630 $this->depSaveCallback,
631 $this->getName(),
632 self::getVary( $context ),
633 self::getRelativePaths( $curFileRefs ),
634 self::getRelativePaths( $this->getFileDependencies( $context ) )
635 );
636 } catch ( TimeoutException $e ) {
637 throw $e;
638 } catch ( Exception $e ) {
639 $this->getLogger()->warning(
640 __METHOD__ . ": failed to update dependencies: {$e->getMessage()}",
641 [ 'exception' => $e ]
642 );
643 }
644 }
645
646 /**
647 * Make file paths relative to MediaWiki directory.
648 *
649 * This is used to make file paths safe for storing in a database without the paths
650 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
651 *
652 * @since 1.27
653 * @param array $filePaths
654 * @return array
655 */
656 public static function getRelativePaths( array $filePaths ) {
657 global $IP;
658 return array_map( static function ( $path ) use ( $IP ) {
659 return RelPath::getRelativePath( $path, $IP );
660 }, $filePaths );
661 }
662
663 /**
664 * Expand directories relative to $IP.
665 *
666 * @since 1.27
667 * @param array $filePaths
668 * @return array
669 */
670 public static function expandRelativePaths( array $filePaths ) {
671 global $IP;
672 return array_map( static function ( $path ) use ( $IP ) {
673 return RelPath::joinPath( $IP, $path );
674 }, $filePaths );
675 }
676
677 /**
678 * Get the hash of the message blob.
679 *
680 * @stable to override
681 * @since 1.27
682 * @param Context $context
683 * @return string|null JSON blob or null if module has no messages
684 * @return-taint none -- do not propagate taint from $context->getLanguage()
685 */
686 protected function getMessageBlob( Context $context ) {
687 if ( !$this->getMessages() ) {
688 // Don't bother consulting MessageBlobStore
689 return null;
690 }
691 // Message blobs may only vary language, not by context keys
692 $lang = $context->getLanguage();
693 if ( !isset( $this->msgBlobs[$lang] ) ) {
694 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
695 'module' => $this->getName(),
696 ] );
697 $store = $context->getResourceLoader()->getMessageBlobStore();
698 $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
699 }
700 return $this->msgBlobs[$lang];
701 }
702
703 /**
704 * Set in-object cache for message blobs.
705 *
706 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
707 *
708 * @since 1.27
709 * @param string|null $blob JSON blob or null
710 * @param string $lang Language code
711 */
712 public function setMessageBlob( $blob, $lang ) {
713 $this->msgBlobs[$lang] = $blob;
714 }
715
716 /**
717 * Get headers to send as part of a module web response.
718 *
719 * It is not supported to send headers through this method that are
720 * required to be unique or otherwise sent once in an HTTP response
721 * because clients may make batch requests for multiple modules (as
722 * is the default behaviour for ResourceLoader clients).
723 *
724 * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders().
725 *
726 * @since 1.30
727 * @param Context $context
728 * @return string[] Array of HTTP response headers
729 */
730 final public function getHeaders( Context $context ) {
731 $formattedLinks = [];
732 foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
733 $link = "<{$url}>;rel=preload";
734 foreach ( $attribs as $key => $val ) {
735 $link .= ";{$key}={$val}";
736 }
737 $formattedLinks[] = $link;
738 }
739 if ( $formattedLinks ) {
740 return [ 'Link: ' . implode( ',', $formattedLinks ) ];
741 }
742 return [];
743 }
744
745 /**
746 * Get a list of resources that web browsers may preload.
747 *
748 * Behaviour of rel=preload link is specified at <https://www.w3.org/TR/preload/>.
749 *
750 * Use case for ResourceLoader originally part of T164299.
751 *
752 * @par Example
753 * @code
754 * protected function getPreloadLinks() {
755 * return [
756 * 'https://example.org/script.js' => [ 'as' => 'script' ],
757 * 'https://example.org/image.png' => [ 'as' => 'image' ],
758 * ];
759 * }
760 * @endcode
761 *
762 * @par Example using HiDPI image variants
763 * @code
764 * protected function getPreloadLinks() {
765 * return [
766 * 'https://example.org/logo.png' => [
767 * 'as' => 'image',
768 * 'media' => 'not all and (min-resolution: 2dppx)',
769 * ],
770 * 'https://example.org/[email protected]' => [
771 * 'as' => 'image',
772 * 'media' => '(min-resolution: 2dppx)',
773 * ],
774 * ];
775 * }
776 * @endcode
777 *
778 * @see Module::getHeaders
779 *
780 * @stable to override
781 * @since 1.30
782 * @param Context $context
783 * @return array Keyed by url, values must be an array containing
784 * at least an 'as' key. Optionally a 'media' key as well.
785 *
786 */
787 protected function getPreloadLinks( Context $context ) {
788 return [];
789 }
790
791 /**
792 * Get module-specific LESS variables, if any.
793 *
794 * @stable to override
795 * @since 1.27
796 * @param Context $context
797 * @return array Module-specific LESS variables.
798 */
799 protected function getLessVars( Context $context ) {
800 return [];
801 }
802
803 /**
804 * Get an array of this module's resources. Ready for serving to the web.
805 *
806 * @since 1.26
807 * @param Context $context
808 * @return array
809 */
810 public function getModuleContent( Context $context ) {
811 $contextHash = $context->getHash();
812 // Cache this expensive operation. This calls builds the scripts, styles, and messages
813 // content which typically involves filesystem and/or database access.
814 if ( !array_key_exists( $contextHash, $this->contents ) ) {
815 $this->contents[$contextHash] = $this->buildContent( $context );
816 }
817 return $this->contents[$contextHash];
818 }
819
820 /**
821 * Bundle all resources attached to this module into an array.
822 *
823 * @since 1.26
824 * @param Context $context
825 * @return array
826 */
827 final protected function buildContent( Context $context ) {
828 $statsFactory = MediaWikiServices::getInstance()->getStatsFactory();
829 $statStart = microtime( true );
830
831 // This MUST build both scripts and styles, regardless of whether $context->getOnly()
832 // is 'scripts' or 'styles' because the result is used by getVersionHash which
833 // must be consistent regardless of the 'only' filter on the current request.
834 // Also, when introducing new module content resources (e.g. templates, headers),
835 // these should only be included in the array when they are non-empty so that
836 // existing modules not using them do not get their cache invalidated.
837 $content = [];
838
839 // Scripts
840 if ( $context->getDebug() === $context::DEBUG_LEGACY && !$context->getOnly() && $this->supportsURLLoading() ) {
841 // In legacy debug mode, let supporting modules like FileModule replace the bundled
842 // script closure with an array of alternative script URLs to consecutively load instead.
843 // See self::getScriptURLsForDebug() more details.
844 $scripts = $this->getScriptURLsForDebug( $context );
845 } else {
846 $scripts = $this->getScript( $context );
847 if ( is_string( $scripts ) ) {
848 $scripts = [ 'plainScripts' => [ [ 'content' => $scripts ] ] ];
849 }
850 }
851 $content['scripts'] = $scripts;
852
853 $styles = [];
854 // Don't create empty stylesheets like [ '' => '' ] for modules
855 // that don't *have* any stylesheets (T40024).
856 $stylePairs = $this->getStyles( $context );
857 if ( count( $stylePairs ) ) {
858 // If we are in debug mode without &only= set, we'll want to return an array of URLs
859 // See comment near shouldIncludeScripts() for more details
860 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
861 $styles = [
862 'url' => $this->getStyleURLsForDebug( $context )
863 ];
864 } else {
865 // Minify CSS before embedding in mw.loader.impl call
866 // (unless in debug mode)
867 if ( !$context->getDebug() ) {
868 foreach ( $stylePairs as $media => $style ) {
869 // Can be either a string or an array of strings.
870 if ( is_array( $style ) ) {
871 $stylePairs[$media] = [];
872 foreach ( $style as $cssText ) {
873 if ( is_string( $cssText ) ) {
874 $stylePairs[$media][] =
875 ResourceLoader::filter( 'minify-css', $cssText );
876 }
877 }
878 } elseif ( is_string( $style ) ) {
879 $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
880 }
881 }
882 }
883 // Wrap styles into @media groups as needed and flatten into a numerical array
884 $styles = [
885 'css' => ResourceLoader::makeCombinedStyles( $stylePairs )
886 ];
887 }
888 }
889 $content['styles'] = $styles;
890
891 // Messages
892 $blob = $this->getMessageBlob( $context );
893 if ( $blob ) {
894 $content['messagesBlob'] = $blob;
895 }
896
897 $templates = $this->getTemplates();
898 if ( $templates ) {
899 $content['templates'] = $templates;
900 }
901
902 $headers = $this->getHeaders( $context );
903 if ( $headers ) {
904 $content['headers'] = $headers;
905 }
906
907 $deprecationWarning = $this->getDeprecationWarning();
908 if ( $deprecationWarning !== null ) {
909 $content['deprecationWarning'] = $deprecationWarning;
910 }
911
912 $statTiming = microtime( true ) - $statStart;
913 $statName = strtr( $this->getName(), '.', '_' );
914
915 $statsFactory->getTiming( 'resourceloader_build_seconds' )
916 ->setLabel( 'name', $statName )
917 ->copyToStatsdAt( [
918 'resourceloader_build.all',
919 "resourceloader_build.$statName",
920 ] )
921 ->observe( 1000 * $statTiming );
922
923 return $content;
924 }
925
926 /**
927 * Get a string identifying the current version of this module in a given context.
928 *
929 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
930 * messages) this value must change. This value is used to store module responses in caches,
931 * both server-side (by a CDN, or other HTTP cache), and client-side (in `mw.loader.store`,
932 * and in the browser's own HTTP cache).
933 *
934 * The underlying methods called here for any given module should be quick because this
935 * is called for potentially thousands of module bundles in the same request as part of the
936 * StartUpModule, which is how we invalidate caches and propagate changes to clients.
937 *
938 * @since 1.26
939 * @see self::getDefinitionSummary for how to customize version computation.
940 * @param Context $context
941 * @return string Hash formatted by ResourceLoader::makeHash
942 */
943 final public function getVersionHash( Context $context ) {
944 if ( $context->getDebug() ) {
945 // In debug mode, make uncached startup module extra fast by not computing any hashes.
946 // Server responses from load.php for individual modules already have no-cache so
947 // we don't need them. This also makes breakpoint debugging easier, as each module
948 // gets its own consistent URL. (T235672)
949 return '';
950 }
951
952 // Cache this somewhat expensive operation. Especially because some classes
953 // (e.g. startup module) iterate more than once over all modules to get versions.
954 $contextHash = $context->getHash();
955 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
956 if ( $this->enableModuleContentVersion() ) {
957 // Detect changes directly by hashing the module contents.
958 $str = json_encode( $this->getModuleContent( $context ) );
959 } else {
960 // Infer changes based on definition and other metrics
961 $summary = $this->getDefinitionSummary( $context );
962 if ( !isset( $summary['_class'] ) ) {
963 throw new LogicException( 'getDefinitionSummary must call parent method' );
964 }
965 $str = json_encode( $summary );
966 }
967
968 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
969 }
970 return $this->versionHash[$contextHash];
971 }
972
973 /**
974 * Whether to generate version hash based on module content.
975 *
976 * If a module requires database or file system access to build the module
977 * content, consider disabling this in favour of manually tracking relevant
978 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
979 *
980 * @stable to override
981 * @return bool
982 */
983 public function enableModuleContentVersion() {
984 return false;
985 }
986
987 /**
988 * Get the definition summary for this module.
989 *
990 * This is the method subclasses are recommended to use to track data that
991 * should influence the module's version hash.
992 *
993 * Subclasses must call the parent getDefinitionSummary() and add to the
994 * returned array. It is recommended that each subclass appends its own array,
995 * to prevent clashes or accidental overwrites of array keys from the parent
996 * class. This gives each subclass a clean scope.
997 *
998 * @code
999 * $summary = parent::getDefinitionSummary( $context );
1000 * $summary[] = [
1001 * 'foo' => 123,
1002 * 'bar' => 'quux',
1003 * ];
1004 * return $summary;
1005 * @endcode
1006 *
1007 * Return an array that contains all significant properties that define the
1008 * module. The returned data should be deterministic and only change when
1009 * the generated module response would change. Prefer content hashes over
1010 * modified timestamps because timestamps may change for unrelated reasons
1011 * and are not deterministic (T102578). For example, because timestamps are
1012 * not stored in Git, each branch checkout would cause all files to appear as
1013 * new. Timestamps also tend to not match between servers causing additional
1014 * ever-lasting churning of the version hash.
1015 *
1016 * Be careful not to normalise the data too much in an effort to be deterministic.
1017 * For example, if a module concatenates files together (order is significant),
1018 * then the definition summary could be a list of file names, and a list of
1019 * file hashes. These lists should not be sorted as that would mean the cache
1020 * is not invalidated when the order changes (T39812).
1021 *
1022 * This data structure must exclusively contain primitive "scalar" values,
1023 * as it will be serialised using `json_encode`.
1024 *
1025 * @stable to override
1026 * @since 1.23
1027 * @param Context $context
1028 * @return array|null
1029 */
1030 public function getDefinitionSummary( Context $context ) {
1031 return [
1032 '_class' => static::class,
1033 // Make sure that when filter cache for minification is invalidated,
1034 // we also change the HTTP urls and mw.loader.store keys (T176884).
1035 '_cacheVersion' => ResourceLoader::CACHE_VERSION,
1036 ];
1037 }
1038
1039 /**
1040 * Check whether this module is known to be empty. If a child class
1041 * has an easy and cheap way to determine that this module is
1042 * definitely going to be empty, it should override this method to
1043 * return true in that case. Callers may optimize the request for this
1044 * module away if this function returns true.
1045 *
1046 * @stable to override
1047 * @param Context $context
1048 * @return bool
1049 */
1050 public function isKnownEmpty( Context $context ) {
1051 return false;
1052 }
1053
1054 /**
1055 * Check whether this module should be embedded rather than linked
1056 *
1057 * Modules returning true here will be embedded rather than loaded by
1058 * ClientHtml.
1059 *
1060 * @since 1.30
1061 * @stable to override
1062 * @param Context $context
1063 * @return bool
1064 */
1065 public function shouldEmbedModule( Context $context ) {
1066 return $this->getGroup() === self::GROUP_PRIVATE;
1067 }
1068
1069 /**
1070 * Whether to skip the structure test ResourcesTest::testRespond() for this
1071 * module.
1072 *
1073 * @since 1.42
1074 * @stable to override
1075 * @return bool
1076 */
1077 public function shouldSkipStructureTest() {
1078 return $this->getGroup() === self::GROUP_PRIVATE;
1079 }
1080
1081 /**
1082 * Validate a user-provided JavaScript blob.
1083 *
1084 * @param string $fileName
1085 * @param string $contents JavaScript code
1086 * @return string JavaScript code, either the original content or a replacement
1087 * that uses `mw.log.error()` to communicate a syntax error.
1088 */
1089 protected function validateScriptFile( $fileName, $contents ) {
1090 if ( !$this->getConfig()->get( MainConfigNames::ResourceLoaderValidateJS ) ) {
1091 return $contents;
1092 }
1093 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1094 // Cache potentially slow parsing of JavaScript code during the
1095 // critical path. This happens lazily when responding to requests
1096 // for modules=site, modules=user, and Gadgets.
1097 $error = $cache->getWithSetCallback(
1098 $cache->makeKey(
1099 'resourceloader-userjsparse',
1100 self::USERJSPARSE_CACHE_VERSION,
1101 md5( $contents ),
1102 $fileName
1103 ),
1104 $cache::TTL_WEEK,
1105 static function () use ( $contents, $fileName ) {
1106 try {
1107 Peast::ES2016( $contents )->parse();
1108 } catch ( PeastSyntaxException $e ) {
1109 return $e->getMessage() . " on line " . $e->getPosition()->getLine();
1110 }
1111 // Cache success as null
1112 return null;
1113 }
1114 );
1115
1116 if ( $error ) {
1117 // Send the error to the browser console client-side.
1118 // By returning this as replacement for the actual script,
1119 // we ensure user-provided scripts are safe to include in a batch
1120 // request, without risk of a syntax error in this blob breaking
1121 // the response itself.
1122 return 'mw.log.error(' .
1123 json_encode(
1124 'Parse error: ' . $error
1125 ) .
1126 ');';
1127 }
1128 return $contents;
1129 }
1130
1131 /**
1132 * Compute a non-cryptographic string hash of a file's contents.
1133 * If the file does not exist or cannot be read, returns an empty string.
1134 *
1135 * @since 1.26 Uses MD4 instead of SHA1.
1136 * @param string $filePath
1137 * @return string Hash
1138 */
1139 protected static function safeFileHash( $filePath ) {
1140 return FileContentsHasher::getFileContentsHash( $filePath );
1141 }
1142
1143 /**
1144 * Get vary string.
1145 *
1146 * @internal For internal use only.
1147 * @param Context $context
1148 * @return string
1149 */
1150 public static function getVary( Context $context ) {
1151 return implode( '|', [
1152 $context->getSkin(),
1153 $context->getLanguage(),
1154 ] );
1155 }
1156 }