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