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