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