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