resourceloader: Add type hints for type ResourceLoaderContext
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderModule.php
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 use MediaWiki\MediaWikiServices;
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use Wikimedia\AtEase\AtEase;
28 use Wikimedia\RelPath;
29 use Wikimedia\ScopedCallback;
30
31 /**
32 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
33 *
34 * @ingroup ResourceLoader
35 * @since 1.17
36 */
37 abstract class ResourceLoaderModule implements LoggerAwareInterface {
38 /** @var Config */
39 protected $config;
40 /** @var LoggerInterface */
41 protected $logger;
42
43 /**
44 * Script and style modules form a hierarchy of trustworthiness, with core modules
45 * like skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
46 * limit the types of scripts and styles we allow to load on, say, sensitive special
47 * pages like Special:UserLogin and Special:Preferences
48 * @var int
49 */
50 protected $origin = self::ORIGIN_CORE_SITEWIDE;
51
52 /** @var string|null Module name */
53 protected $name = null;
54 /** @var string[] What client platforms the module targets (e.g. desktop, mobile) */
55 protected $targets = [ 'desktop' ];
56
57 /** @var array Map of (variant => indirect file dependencies) */
58 protected $fileDeps = [];
59 /** @var array Map of (language => in-object cache for message blob) */
60 protected $msgBlobs = [];
61 /** @var array Map of (context hash => cached module version hash) */
62 protected $versionHash = [];
63 /** @var array Map of (context hash => cached module content) */
64 protected $contents = [];
65
66 /** @var string|bool Deprecation string or true if deprecated; false otherwise */
67 protected $deprecated = false;
68
69 /** @var string Scripts only */
70 const TYPE_SCRIPTS = 'scripts';
71 /** @var string Styles only */
72 const TYPE_STYLES = 'styles';
73 /** @var string Scripts and styles */
74 const TYPE_COMBINED = 'combined';
75
76 /** @var string Module only has styles (loaded via <style> or <link rel=stylesheet>) */
77 const LOAD_STYLES = 'styles';
78 /** @var string Module may have other resources (loaded via mw.loader from a script) */
79 const LOAD_GENERAL = 'general';
80
81 /** @var int Sitewide core module like a skin file or jQuery component */
82 const ORIGIN_CORE_SITEWIDE = 1;
83 /** @var int Per-user module generated by the software */
84 const ORIGIN_CORE_INDIVIDUAL = 2;
85 /**
86 * Sitewide module generated from user-editable files, like MediaWiki:Common.js,
87 * or modules accessible to multiple users, such as those generated by the Gadgets extension.
88 * @var int
89 */
90 const ORIGIN_USER_SITEWIDE = 3;
91 /** @var int Per-user module generated from user-editable files, like User:Me/vector.js */
92 const ORIGIN_USER_INDIVIDUAL = 4;
93 /** @var int An access constant; make sure this is kept as the largest number in this group */
94 const ORIGIN_ALL = 10;
95
96 /**
97 * Get this module's name. This is set when the module is registered
98 * with ResourceLoader::register()
99 *
100 * @return string|null Name (string) or null if no name was set
101 */
102 public function getName() {
103 return $this->name;
104 }
105
106 /**
107 * Set this module's name. This is called by ResourceLoader::register()
108 * when registering the module. Other code should not call this.
109 *
110 * @param string $name
111 */
112 public function setName( $name ) {
113 $this->name = $name;
114 }
115
116 /**
117 * Get this module's origin. This is set when the module is registered
118 * with ResourceLoader::register()
119 *
120 * @return int ResourceLoaderModule class constant, the subclass default
121 * if not set manually
122 */
123 public function getOrigin() {
124 return $this->origin;
125 }
126
127 /**
128 * @param ResourceLoaderContext $context
129 * @return bool
130 */
131 public function getFlip( ResourceLoaderContext $context ) {
132 return MediaWikiServices::getInstance()->getContentLanguage()->getDir() !==
133 $context->getDirection();
134 }
135
136 /**
137 * Get JS representing deprecation information for the current module if available
138 *
139 * @return string JavaScript code
140 */
141 public function getDeprecationInformation() {
142 $deprecationInfo = $this->deprecated;
143 if ( $deprecationInfo ) {
144 $name = $this->getName();
145 $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
146 if ( is_string( $deprecationInfo ) ) {
147 $warning .= "\n" . $deprecationInfo;
148 }
149 return 'mw.log.warn(' . ResourceLoader::encodeJsonForScript( $warning ) . ');';
150 } else {
151 return '';
152 }
153 }
154
155 /**
156 * Get all JS for this module for a given language and skin.
157 * Includes all relevant JS except loader scripts.
158 *
159 * For "plain" script modules, this should return a string with JS code. For multi-file modules
160 * where require() is used to load one file from another file, this should return an array
161 * structured as follows:
162 * [
163 * 'files' => [
164 * 'file1.js' => [ 'type' => 'script', 'content' => 'JS code' ],
165 * 'file2.js' => [ 'type' => 'script', 'content' => 'JS code' ],
166 * 'data.json' => [ 'type' => 'data', 'content' => array ]
167 * ],
168 * 'main' => 'file1.js'
169 * ]
170 *
171 * @param ResourceLoaderContext $context
172 * @return string|array JavaScript code (string), or multi-file structure described above (array)
173 */
174 public function getScript( ResourceLoaderContext $context ) {
175 // Stub, override expected
176 return '';
177 }
178
179 /**
180 * Takes named templates by the module and returns an array mapping.
181 *
182 * @return string[] Array of templates mapping template alias to content
183 */
184 public function getTemplates() {
185 // Stub, override expected.
186 return [];
187 }
188
189 /**
190 * @return Config
191 * @since 1.24
192 */
193 public function getConfig() {
194 if ( $this->config === null ) {
195 // Ugh, fall back to default
196 $this->config = MediaWikiServices::getInstance()->getMainConfig();
197 }
198
199 return $this->config;
200 }
201
202 /**
203 * @param Config $config
204 * @since 1.24
205 */
206 public function setConfig( Config $config ) {
207 $this->config = $config;
208 }
209
210 /**
211 * @since 1.27
212 * @param LoggerInterface $logger
213 */
214 public function setLogger( LoggerInterface $logger ) {
215 $this->logger = $logger;
216 }
217
218 /**
219 * @since 1.27
220 * @return LoggerInterface
221 */
222 protected function getLogger() {
223 if ( !$this->logger ) {
224 $this->logger = new NullLogger();
225 }
226 return $this->logger;
227 }
228
229 /**
230 * Get the URL or URLs to load for this module's JS in debug mode.
231 * The default behavior is to return a load.php?only=scripts URL for
232 * the module, but file-based modules will want to override this to
233 * load the files directly.
234 *
235 * This function is called only when 1) we're in debug mode, 2) there
236 * is no only= parameter and 3) supportsURLLoading() returns true.
237 * #2 is important to prevent an infinite loop, therefore this function
238 * MUST return either an only= URL or a non-load.php URL.
239 *
240 * @param ResourceLoaderContext $context
241 * @return array Array of URLs
242 */
243 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
244 $resourceLoader = $context->getResourceLoader();
245 $derivative = new DerivativeResourceLoaderContext( $context );
246 $derivative->setModules( [ $this->getName() ] );
247 $derivative->setOnly( 'scripts' );
248 $derivative->setDebug( true );
249
250 $url = $resourceLoader->createLoaderURL(
251 $this->getSource(),
252 $derivative
253 );
254
255 return [ $url ];
256 }
257
258 /**
259 * Whether this module supports URL loading. If this function returns false,
260 * getScript() will be used even in cases (debug mode, no only param) where
261 * getScriptURLsForDebug() would normally be used instead.
262 * @return bool
263 */
264 public function supportsURLLoading() {
265 return true;
266 }
267
268 /**
269 * Get all CSS for this module for a given skin.
270 *
271 * @param ResourceLoaderContext $context
272 * @return array List of CSS strings or array of CSS strings keyed by media type.
273 * like [ 'screen' => '.foo { width: 0 }' ];
274 * or [ 'screen' => [ '.foo { width: 0 }' ] ];
275 */
276 public function getStyles( ResourceLoaderContext $context ) {
277 // Stub, override expected
278 return [];
279 }
280
281 /**
282 * Get the URL or URLs to load for this module's CSS in debug mode.
283 * The default behavior is to return a load.php?only=styles URL for
284 * the module, but file-based modules will want to override this to
285 * load the files directly. See also getScriptURLsForDebug()
286 *
287 * @param ResourceLoaderContext $context
288 * @return array [ mediaType => [ URL1, URL2, ... ], ... ]
289 */
290 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
291 $resourceLoader = $context->getResourceLoader();
292 $derivative = new DerivativeResourceLoaderContext( $context );
293 $derivative->setModules( [ $this->getName() ] );
294 $derivative->setOnly( 'styles' );
295 $derivative->setDebug( true );
296
297 $url = $resourceLoader->createLoaderURL(
298 $this->getSource(),
299 $derivative
300 );
301
302 return [ 'all' => [ $url ] ];
303 }
304
305 /**
306 * Get the messages needed for this module.
307 *
308 * To get a JSON blob with messages, use MessageBlobStore::get()
309 *
310 * @return array List of message keys. Keys may occur more than once
311 */
312 public function getMessages() {
313 // Stub, override expected
314 return [];
315 }
316
317 /**
318 * Get the group this module is in.
319 *
320 * @return string Group name
321 */
322 public function getGroup() {
323 // Stub, override expected
324 return null;
325 }
326
327 /**
328 * Get the source of this module. Should only be overridden for foreign modules.
329 *
330 * @return string Source name, 'local' for local modules
331 */
332 public function getSource() {
333 // Stub, override expected
334 return 'local';
335 }
336
337 /**
338 * Get a list of modules this module depends on.
339 *
340 * Dependency information is taken into account when loading a module
341 * on the client side.
342 *
343 * Note: It is expected that $context will be made non-optional in the near
344 * future.
345 *
346 * @param ResourceLoaderContext|null $context
347 * @return array List of module names as strings
348 */
349 public function getDependencies( ResourceLoaderContext $context = null ) {
350 // Stub, override expected
351 return [];
352 }
353
354 /**
355 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
356 *
357 * @return array Array of strings
358 */
359 public function getTargets() {
360 return $this->targets;
361 }
362
363 /**
364 * Get the module's load type.
365 *
366 * @since 1.28
367 * @return string ResourceLoaderModule LOAD_* constant
368 */
369 public function getType() {
370 return self::LOAD_GENERAL;
371 }
372
373 /**
374 * Get the skip function.
375 *
376 * Modules that provide fallback functionality can provide a "skip function". This
377 * function, if provided, will be passed along to the module registry on the client.
378 * When this module is loaded (either directly or as a dependency of another module),
379 * then this function is executed first. If the function returns true, the module will
380 * instantly be considered "ready" without requesting the associated module resources.
381 *
382 * The value returned here must be valid javascript for execution in a private function.
383 * It must not contain the "function () {" and "}" wrapper though.
384 *
385 * @return string|null A JavaScript function body returning a boolean value, or null
386 */
387 public function getSkipFunction() {
388 return null;
389 }
390
391 /**
392 * Get the files this module depends on indirectly for a given skin.
393 *
394 * These are only image files referenced by the module's stylesheet.
395 *
396 * @param ResourceLoaderContext $context
397 * @return array List of files
398 */
399 protected function getFileDependencies( ResourceLoaderContext $context ) {
400 $vary = self::getVary( $context );
401
402 // Try in-object cache first
403 if ( !isset( $this->fileDeps[$vary] ) ) {
404 $dbr = wfGetDB( DB_REPLICA );
405 $deps = $dbr->selectField( 'module_deps',
406 'md_deps',
407 [
408 'md_module' => $this->getName(),
409 'md_skin' => $vary,
410 ],
411 __METHOD__
412 );
413
414 if ( !is_null( $deps ) ) {
415 $this->fileDeps[$vary] = self::expandRelativePaths(
416 (array)json_decode( $deps, true )
417 );
418 } else {
419 $this->fileDeps[$vary] = [];
420 }
421 }
422 return $this->fileDeps[$vary];
423 }
424
425 /**
426 * Set in-object cache for file dependencies.
427 *
428 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
429 * To save the data, use saveFileDependencies().
430 *
431 * @param ResourceLoaderContext $context
432 * @param string[] $files Array of file names
433 */
434 public function setFileDependencies( ResourceLoaderContext $context, $files ) {
435 $vary = self::getVary( $context );
436 $this->fileDeps[$vary] = $files;
437 }
438
439 /**
440 * Set the files this module depends on indirectly for a given skin.
441 *
442 * @since 1.27
443 * @param ResourceLoaderContext $context
444 * @param array $localFileRefs List of files
445 */
446 protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
447 try {
448 // Related bugs and performance considerations:
449 // 1. Don't needlessly change the database value with the same list in a
450 // different order or with duplicates.
451 // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
452 // 3. Don't needlessly replace the database with the same value
453 // just because $IP changed (e.g. when upgrading a wiki).
454 // 4. Don't create an endless replace loop on every request for this
455 // module when '../' is used anywhere. Even though both are expanded
456 // (one expanded by getFileDependencies from the DB, the other is
457 // still raw as originally read by RL), the latter has not
458 // been normalized yet.
459
460 // Normalise
461 $localFileRefs = array_values( array_unique( $localFileRefs ) );
462 sort( $localFileRefs );
463 $localPaths = self::getRelativePaths( $localFileRefs );
464 $storedPaths = self::getRelativePaths( $this->getFileDependencies( $context ) );
465
466 if ( $localPaths === $storedPaths ) {
467 // Unchanged. Avoid needless database query (especially master conn!).
468 return;
469 }
470
471 // The file deps list has changed, we want to update it.
472 $vary = self::getVary( $context );
473 $cache = ObjectCache::getLocalClusterInstance();
474 $key = $cache->makeKey( __METHOD__, $this->getName(), $vary );
475 $scopeLock = $cache->getScopedLock( $key, 0 );
476 if ( !$scopeLock ) {
477 // Another request appears to be doing this update already.
478 // Avoid write slams (T124649).
479 return;
480 }
481
482 // No needless escaping as this isn't HTML output.
483 // Only stored in the database and parsed in PHP.
484 $deps = json_encode( $localPaths, JSON_UNESCAPED_SLASHES );
485 $dbw = wfGetDB( DB_MASTER );
486 $dbw->upsert( 'module_deps',
487 [
488 'md_module' => $this->getName(),
489 'md_skin' => $vary,
490 'md_deps' => $deps,
491 ],
492 [ [ 'md_module', 'md_skin' ] ],
493 [
494 'md_deps' => $deps,
495 ],
496 __METHOD__
497 );
498
499 if ( $dbw->trxLevel() ) {
500 $dbw->onTransactionResolution(
501 function () use ( &$scopeLock ) {
502 ScopedCallback::consume( $scopeLock ); // release after commit
503 },
504 __METHOD__
505 );
506 }
507 } catch ( Exception $e ) {
508 // Probably a DB failure. Either the read query from getFileDependencies(),
509 // or the write query above.
510 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
511 }
512 }
513
514 /**
515 * Make file paths relative to MediaWiki directory.
516 *
517 * This is used to make file paths safe for storing in a database without the paths
518 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
519 *
520 * @since 1.27
521 * @param array $filePaths
522 * @return array
523 */
524 public static function getRelativePaths( array $filePaths ) {
525 global $IP;
526 return array_map( function ( $path ) use ( $IP ) {
527 return RelPath::getRelativePath( $path, $IP );
528 }, $filePaths );
529 }
530
531 /**
532 * Expand directories relative to $IP.
533 *
534 * @since 1.27
535 * @param array $filePaths
536 * @return array
537 */
538 public static function expandRelativePaths( array $filePaths ) {
539 global $IP;
540 return array_map( function ( $path ) use ( $IP ) {
541 return RelPath::joinPath( $IP, $path );
542 }, $filePaths );
543 }
544
545 /**
546 * Get the hash of the message blob.
547 *
548 * @since 1.27
549 * @param ResourceLoaderContext $context
550 * @return string|null JSON blob or null if module has no messages
551 */
552 protected function getMessageBlob( ResourceLoaderContext $context ) {
553 if ( !$this->getMessages() ) {
554 // Don't bother consulting MessageBlobStore
555 return null;
556 }
557 // Message blobs may only vary language, not by context keys
558 $lang = $context->getLanguage();
559 if ( !isset( $this->msgBlobs[$lang] ) ) {
560 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
561 'module' => $this->getName(),
562 ] );
563 $store = $context->getResourceLoader()->getMessageBlobStore();
564 $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
565 }
566 return $this->msgBlobs[$lang];
567 }
568
569 /**
570 * Set in-object cache for message blobs.
571 *
572 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
573 *
574 * @since 1.27
575 * @param string|null $blob JSON blob or null
576 * @param string $lang Language code
577 */
578 public function setMessageBlob( $blob, $lang ) {
579 $this->msgBlobs[$lang] = $blob;
580 }
581
582 /**
583 * Get headers to send as part of a module web response.
584 *
585 * It is not supported to send headers through this method that are
586 * required to be unique or otherwise sent once in an HTTP response
587 * because clients may make batch requests for multiple modules (as
588 * is the default behaviour for ResourceLoader clients).
589 *
590 * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders().
591 *
592 * @since 1.30
593 * @param ResourceLoaderContext $context
594 * @return string[] Array of HTTP response headers
595 */
596 final public function getHeaders( ResourceLoaderContext $context ) {
597 $headers = [];
598
599 $formattedLinks = [];
600 foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
601 $link = "<{$url}>;rel=preload";
602 foreach ( $attribs as $key => $val ) {
603 $link .= ";{$key}={$val}";
604 }
605 $formattedLinks[] = $link;
606 }
607 if ( $formattedLinks ) {
608 $headers[] = 'Link: ' . implode( ',', $formattedLinks );
609 }
610
611 return $headers;
612 }
613
614 /**
615 * Get a list of resources that web browsers may preload.
616 *
617 * Behaviour of rel=preload link is specified at <https://www.w3.org/TR/preload/>.
618 *
619 * Use case for ResourceLoader originally part of T164299.
620 *
621 * @par Example
622 * @code
623 * protected function getPreloadLinks() {
624 * return [
625 * 'https://example.org/script.js' => [ 'as' => 'script' ],
626 * 'https://example.org/image.png' => [ 'as' => 'image' ],
627 * ];
628 * }
629 * @endcode
630 *
631 * @par Example using HiDPI image variants
632 * @code
633 * protected function getPreloadLinks() {
634 * return [
635 * 'https://example.org/logo.png' => [
636 * 'as' => 'image',
637 * 'media' => 'not all and (min-resolution: 2dppx)',
638 * ],
639 * 'https://example.org/logo@2x.png' => [
640 * 'as' => 'image',
641 * 'media' => '(min-resolution: 2dppx)',
642 * ],
643 * ];
644 * }
645 * @endcode
646 *
647 * @see ResourceLoaderModule::getHeaders
648 * @since 1.30
649 * @param ResourceLoaderContext $context
650 * @return array Keyed by url, values must be an array containing
651 * at least an 'as' key. Optionally a 'media' key as well.
652 */
653 protected function getPreloadLinks( ResourceLoaderContext $context ) {
654 return [];
655 }
656
657 /**
658 * Get module-specific LESS variables, if any.
659 *
660 * @since 1.27
661 * @param ResourceLoaderContext $context
662 * @return array Module-specific LESS variables.
663 */
664 protected function getLessVars( ResourceLoaderContext $context ) {
665 return [];
666 }
667
668 /**
669 * Get an array of this module's resources. Ready for serving to the web.
670 *
671 * @since 1.26
672 * @param ResourceLoaderContext $context
673 * @return array
674 */
675 public function getModuleContent( ResourceLoaderContext $context ) {
676 $contextHash = $context->getHash();
677 // Cache this expensive operation. This calls builds the scripts, styles, and messages
678 // content which typically involves filesystem and/or database access.
679 if ( !array_key_exists( $contextHash, $this->contents ) ) {
680 $this->contents[$contextHash] = $this->buildContent( $context );
681 }
682 return $this->contents[$contextHash];
683 }
684
685 /**
686 * Bundle all resources attached to this module into an array.
687 *
688 * @since 1.26
689 * @param ResourceLoaderContext $context
690 * @return array
691 */
692 final protected function buildContent( ResourceLoaderContext $context ) {
693 $rl = $context->getResourceLoader();
694 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
695 $statStart = microtime( true );
696
697 // This MUST build both scripts and styles, regardless of whether $context->getOnly()
698 // is 'scripts' or 'styles' because the result is used by getVersionHash which
699 // must be consistent regardless of the 'only' filter on the current request.
700 // Also, when introducing new module content resources (e.g. templates, headers),
701 // these should only be included in the array when they are non-empty so that
702 // existing modules not using them do not get their cache invalidated.
703 $content = [];
704
705 // Scripts
706 // If we are in debug mode, we'll want to return an array of URLs if possible
707 // However, we can't do this if the module doesn't support it.
708 // We also can't do this if there is an only= parameter, because we have to give
709 // the module a way to return a load.php URL without causing an infinite loop
710 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
711 $scripts = $this->getScriptURLsForDebug( $context );
712 } else {
713 $scripts = $this->getScript( $context );
714 // Make the script safe to concatenate by making sure there is at least one
715 // trailing new line at the end of the content. Previously, this looked for
716 // a semi-colon instead, but that breaks concatenation if the semicolon
717 // is inside a comment like "// foo();". Instead, simply use a
718 // line break as separator which matches JavaScript native logic for implicitly
719 // ending statements even if a semi-colon is missing.
720 // Bugs: T29054, T162719.
721 if ( is_string( $scripts )
722 && strlen( $scripts )
723 && substr( $scripts, -1 ) !== "\n"
724 ) {
725 $scripts .= "\n";
726 }
727 }
728 $content['scripts'] = $scripts;
729
730 $styles = [];
731 // Don't create empty stylesheets like [ '' => '' ] for modules
732 // that don't *have* any stylesheets (T40024).
733 $stylePairs = $this->getStyles( $context );
734 if ( count( $stylePairs ) ) {
735 // If we are in debug mode without &only= set, we'll want to return an array of URLs
736 // See comment near shouldIncludeScripts() for more details
737 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
738 $styles = [
739 'url' => $this->getStyleURLsForDebug( $context )
740 ];
741 } else {
742 // Minify CSS before embedding in mw.loader.implement call
743 // (unless in debug mode)
744 if ( !$context->getDebug() ) {
745 foreach ( $stylePairs as $media => $style ) {
746 // Can be either a string or an array of strings.
747 if ( is_array( $style ) ) {
748 $stylePairs[$media] = [];
749 foreach ( $style as $cssText ) {
750 if ( is_string( $cssText ) ) {
751 $stylePairs[$media][] =
752 ResourceLoader::filter( 'minify-css', $cssText );
753 }
754 }
755 } elseif ( is_string( $style ) ) {
756 $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
757 }
758 }
759 }
760 // Wrap styles into @media groups as needed and flatten into a numerical array
761 $styles = [
762 'css' => $rl->makeCombinedStyles( $stylePairs )
763 ];
764 }
765 }
766 $content['styles'] = $styles;
767
768 // Messages
769 $blob = $this->getMessageBlob( $context );
770 if ( $blob ) {
771 $content['messagesBlob'] = $blob;
772 }
773
774 $templates = $this->getTemplates();
775 if ( $templates ) {
776 $content['templates'] = $templates;
777 }
778
779 $headers = $this->getHeaders( $context );
780 if ( $headers ) {
781 $content['headers'] = $headers;
782 }
783
784 $statTiming = microtime( true ) - $statStart;
785 $statName = strtr( $this->getName(), '.', '_' );
786 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
787 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
788
789 return $content;
790 }
791
792 /**
793 * Get a string identifying the current version of this module in a given context.
794 *
795 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
796 * messages) this value must change. This value is used to store module responses in cache.
797 * (Both client-side and server-side.)
798 *
799 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
800 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
801 *
802 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
803 * propagate changes to the client and effectively invalidate cache.
804 *
805 * @since 1.26
806 * @param ResourceLoaderContext $context
807 * @return string Hash (should use ResourceLoader::makeHash)
808 */
809 public function getVersionHash( ResourceLoaderContext $context ) {
810 // Cache this somewhat expensive operation. Especially because some classes
811 // (e.g. startup module) iterate more than once over all modules to get versions.
812 $contextHash = $context->getHash();
813 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
814 if ( $this->enableModuleContentVersion() ) {
815 // Detect changes directly by hashing the module contents.
816 $str = json_encode( $this->getModuleContent( $context ) );
817 } else {
818 // Infer changes based on definition and other metrics
819 $summary = $this->getDefinitionSummary( $context );
820 if ( !isset( $summary['_class'] ) ) {
821 throw new LogicException( 'getDefinitionSummary must call parent method' );
822 }
823 $str = json_encode( $summary );
824 }
825
826 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
827 }
828 return $this->versionHash[$contextHash];
829 }
830
831 /**
832 * Whether to generate version hash based on module content.
833 *
834 * If a module requires database or file system access to build the module
835 * content, consider disabling this in favour of manually tracking relevant
836 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
837 *
838 * @return bool
839 */
840 public function enableModuleContentVersion() {
841 return false;
842 }
843
844 /**
845 * Get the definition summary for this module.
846 *
847 * This is the method subclasses are recommended to use to track values in their
848 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
849 *
850 * Subclasses must call the parent getDefinitionSummary() and build on that.
851 * It is recommended that each subclass appends its own new array. This prevents
852 * clashes or accidental overwrites of existing keys and gives each subclass
853 * its own scope for simple array keys.
854 *
855 * @code
856 * $summary = parent::getDefinitionSummary( $context );
857 * $summary[] = [
858 * 'foo' => 123,
859 * 'bar' => 'quux',
860 * ];
861 * return $summary;
862 * @endcode
863 *
864 * Return an array containing values from all significant properties of this
865 * module's definition.
866 *
867 * Be careful not to normalise too much. Especially preserve the order of things
868 * that carry significance in getScript and getStyles (T39812).
869 *
870 * Avoid including things that are insiginificant (e.g. order of message keys is
871 * insignificant and should be sorted to avoid unnecessary cache invalidation).
872 *
873 * This data structure must exclusively contain arrays and scalars as values (avoid
874 * object instances) to allow simple serialisation using json_encode.
875 *
876 * If modules have a hash or timestamp from another source, that may be incuded as-is.
877 *
878 * A number of utility methods are available to help you gather data. These are not
879 * called by default and must be included by the subclass' getDefinitionSummary().
880 *
881 * - getMessageBlob()
882 *
883 * @since 1.23
884 * @param ResourceLoaderContext $context
885 * @return array|null
886 */
887 public function getDefinitionSummary( ResourceLoaderContext $context ) {
888 return [
889 '_class' => static::class,
890 // Make sure that when filter cache for minification is invalidated,
891 // we also change the HTTP urls and mw.loader.store keys (T176884).
892 '_cacheVersion' => ResourceLoader::CACHE_VERSION,
893 ];
894 }
895
896 /**
897 * Check whether this module is known to be empty. If a child class
898 * has an easy and cheap way to determine that this module is
899 * definitely going to be empty, it should override this method to
900 * return true in that case. Callers may optimize the request for this
901 * module away if this function returns true.
902 * @param ResourceLoaderContext $context
903 * @return bool
904 */
905 public function isKnownEmpty( ResourceLoaderContext $context ) {
906 return false;
907 }
908
909 /**
910 * Check whether this module should be embeded rather than linked
911 *
912 * Modules returning true here will be embedded rather than loaded by
913 * ResourceLoaderClientHtml.
914 *
915 * @since 1.30
916 * @param ResourceLoaderContext $context
917 * @return bool
918 */
919 public function shouldEmbedModule( ResourceLoaderContext $context ) {
920 return $this->getGroup() === 'private';
921 }
922
923 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
924 private static $jsParser;
925 private static $parseCacheVersion = 1;
926
927 /**
928 * Validate a given script file; if valid returns the original source.
929 * If invalid, returns replacement JS source that throws an exception.
930 *
931 * @param string $fileName
932 * @param string $contents
933 * @return string JS with the original, or a replacement error
934 */
935 protected function validateScriptFile( $fileName, $contents ) {
936 if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
937 return $contents;
938 }
939 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
940 return $cache->getWithSetCallback(
941 $cache->makeGlobalKey(
942 'resourceloader-jsparse',
943 self::$parseCacheVersion,
944 md5( $contents ),
945 $fileName
946 ),
947 $cache::TTL_WEEK,
948 function () use ( $contents, $fileName ) {
949 $parser = self::javaScriptParser();
950 $err = null;
951 try {
952 AtEase::suppressWarnings();
953 $parser->parse( $contents, $fileName, 1 );
954 } catch ( Exception $e ) {
955 $err = $e;
956 } finally {
957 AtEase::restoreWarnings();
958 }
959 if ( $err ) {
960 // Send the error to the browser console client-side.
961 // By returning this as replacement for the actual script,
962 // we ensure modules are safe to load in a batch request,
963 // without causing other unrelated modules to break.
964 return 'mw.log.error(' .
965 Xml::encodeJsVar( 'JavaScript parse error: ' . $err->getMessage() ) .
966 ');';
967 }
968 return $contents;
969 }
970 );
971 }
972
973 /**
974 * @return JSParser
975 */
976 protected static function javaScriptParser() {
977 if ( !self::$jsParser ) {
978 self::$jsParser = new JSParser();
979 }
980 return self::$jsParser;
981 }
982
983 /**
984 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
985 * Defaults to 1.
986 *
987 * @param string $filePath File path
988 * @return int UNIX timestamp
989 */
990 protected static function safeFilemtime( $filePath ) {
991 AtEase::suppressWarnings();
992 $mtime = filemtime( $filePath ) ?: 1;
993 AtEase::restoreWarnings();
994 return $mtime;
995 }
996
997 /**
998 * Compute a non-cryptographic string hash of a file's contents.
999 * If the file does not exist or cannot be read, returns an empty string.
1000 *
1001 * @since 1.26 Uses MD4 instead of SHA1.
1002 * @param string $filePath File path
1003 * @return string Hash
1004 */
1005 protected static function safeFileHash( $filePath ) {
1006 return FileContentsHasher::getFileContentsHash( $filePath );
1007 }
1008
1009 /**
1010 * Get vary string.
1011 *
1012 * @internal For internal use only.
1013 * @param ResourceLoaderContext $context
1014 * @return string Vary string
1015 */
1016 public static function getVary( ResourceLoaderContext $context ) {
1017 return implode( '|', [
1018 $context->getSkin(),
1019 $context->getLanguage(),
1020 ] );
1021 }
1022 }