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