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