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