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