Merge "Import: Handle uploads with sha1 starting with 0 properly"
[mediawiki.git] / includes / resourceloader / ResourceLoaderModule.php
blob113fc84aff7d60bee601cd4bec24b883e5e9be90
1 <?php
2 /**
3 * Abstraction for ResourceLoader modules.
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.
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.
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 use Psr\Log\LoggerAwareInterface;
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
29 /**
30 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
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';
38 # sitewide core module like a skin file or jQuery component
39 const ORIGIN_CORE_SITEWIDE = 1;
41 # per-user module generated by the software
42 const ORIGIN_CORE_INDIVIDUAL = 2;
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;
48 # per-user module generated from user-editable files, like User:Me/vector.js
49 const ORIGIN_USER_INDIVIDUAL = 4;
51 # an access constant; make sure this is kept as the largest number in this group
52 const ORIGIN_ALL = 10;
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;
60 /* Protected Members */
62 protected $name = null;
63 protected $targets = array( 'desktop' );
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();
74 /**
75 * @var Config
77 protected $config;
79 /**
80 * @var LoggerInterface
82 protected $logger;
84 /* Methods */
86 /**
87 * Get this module's name. This is set when the module is registered
88 * with ResourceLoader::register()
90 * @return string|null Name (string) or null if no name was set
92 public function getName() {
93 return $this->name;
96 /**
97 * Set this module's name. This is called by ResourceLoader::register()
98 * when registering the module. Other code should not call this.
100 * @param string $name Name
102 public function setName( $name ) {
103 $this->name = $name;
107 * Get this module's origin. This is set when the module is registered
108 * with ResourceLoader::register()
110 * @return int ResourceLoaderModule class constant, the subclass default
111 * if not set manually
113 public function getOrigin() {
114 return $this->origin;
118 * Set this module's origin. This is called by ResourceLoader::register()
119 * when registering the module. Other code should not call this.
121 * @param int $origin Origin
123 public function setOrigin( $origin ) {
124 $this->origin = $origin;
128 * @param ResourceLoaderContext $context
129 * @return bool
131 public function getFlip( $context ) {
132 global $wgContLang;
134 return $wgContLang->getDir() !== $context->getDirection();
138 * Get all JS for this module for a given language and skin.
139 * Includes all relevant JS except loader scripts.
141 * @param ResourceLoaderContext $context
142 * @return string JavaScript code
144 public function getScript( ResourceLoaderContext $context ) {
145 // Stub, override expected
146 return '';
150 * Takes named templates by the module and returns an array mapping.
152 * @return array of templates mapping template alias to content
154 public function getTemplates() {
155 // Stub, override expected.
156 return array();
160 * @return Config
161 * @since 1.24
163 public function getConfig() {
164 if ( $this->config === null ) {
165 // Ugh, fall back to default
166 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
169 return $this->config;
173 * @param Config $config
174 * @since 1.24
176 public function setConfig( Config $config ) {
177 $this->config = $config;
181 * @since 1.27
182 * @param LoggerInterface $logger
184 public function setLogger( LoggerInterface $logger ) {
185 $this->logger = $logger;
189 * @since 1.27
190 * @return LoggerInterface
192 protected function getLogger() {
193 if ( !$this->logger ) {
194 $this->logger = new NullLogger();
196 return $this->logger;
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.
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.
210 * @param ResourceLoaderContext $context
211 * @return array Array of URLs
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 );
220 $url = $resourceLoader->createLoaderURL(
221 $this->getSource(),
222 $derivative
225 return array( $url );
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
234 public function supportsURLLoading() {
235 return true;
239 * Get all CSS for this module for a given skin.
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 }' ) );
246 public function getStyles( ResourceLoaderContext $context ) {
247 // Stub, override expected
248 return array();
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()
257 * @param ResourceLoaderContext $context
258 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
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 );
267 $url = $resourceLoader->createLoaderURL(
268 $this->getSource(),
269 $derivative
272 return array( 'all' => array( $url ) );
276 * Get the messages needed for this module.
278 * To get a JSON blob with messages, use MessageBlobStore::get()
280 * @return array List of message keys. Keys may occur more than once
282 public function getMessages() {
283 // Stub, override expected
284 return array();
288 * Get the group this module is in.
290 * @return string Group name
292 public function getGroup() {
293 // Stub, override expected
294 return null;
298 * Get the origin of this module. Should only be overridden for foreign modules.
300 * @return string Origin name, 'local' for local modules
302 public function getSource() {
303 // Stub, override expected
304 return 'local';
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>"
312 * @return string
314 public function getPosition() {
315 return 'bottom';
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.
323 * @return bool
325 public function isRaw() {
326 return false;
330 * Get a list of modules this module depends on.
332 * Dependency information is taken into account when loading a module
333 * on the client side.
335 * Note: It is expected that $context will be made non-optional in the near
336 * future.
338 * @param ResourceLoaderContext $context
339 * @return array List of module names as strings
341 public function getDependencies( ResourceLoaderContext $context = null ) {
342 // Stub, override expected
343 return array();
347 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
349 * @return array Array of strings
351 public function getTargets() {
352 return $this->targets;
356 * Get the skip function.
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.
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.
367 * @return string|null A JavaScript function body returning a boolean value, or null
369 public function getSkipFunction() {
370 return null;
374 * Get the files this module depends on indirectly for a given skin.
376 * These are only image files referenced by the module's stylesheet.
378 * @param ResourceLoaderContext $context
379 * @return array List of files
381 protected function getFileDependencies( ResourceLoaderContext $context ) {
382 $vary = $context->getSkin() . '|' . $context->getLanguage();
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,
393 __METHOD__
396 if ( !is_null( $deps ) ) {
397 $this->fileDeps[$vary] = self::expandRelativePaths(
398 (array)FormatJson::decode( $deps, true )
400 } else {
401 $this->fileDeps[$vary] = array();
404 return $this->fileDeps[$vary];
408 * Set in-object cache for file dependencies.
410 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
411 * To save the data, use saveFileDependencies().
413 * @param string $skin Skin name
414 * @param array $deps Array of file names
416 public function setFileDependencies( ResourceLoaderContext $context, $files ) {
417 $vary = $context->getSkin() . '|' . $context->getLanguage();
418 $this->fileDeps[$vary] = $files;
422 * Set the files this module depends on indirectly for a given skin.
424 * @since 1.27
425 * @param ResourceLoaderContext $context
426 * @param array $localFileRefs List of files
428 protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
429 // Normalise array
430 $localFileRefs = array_values( array_unique( $localFileRefs ) );
431 sort( $localFileRefs );
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 $vary = $context->getSkin() . '|' . $context->getLanguage();
437 $dbw = wfGetDB( DB_MASTER );
438 $dbw->replace( 'module_deps',
439 array( array( 'md_module', 'md_skin' ) ), array(
440 'md_module' => $this->getName(),
441 'md_skin' => $vary,
442 // Use relative paths to avoid ghost entries when $IP changes (T111481)
443 'md_deps' => FormatJson::encode( self::getRelativePaths( $localFileRefs ) ),
447 } catch ( Exception $e ) {
448 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
453 * Make file paths relative to MediaWiki directory.
455 * This is used to make file paths safe for storing in a database without the paths
456 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
458 * @since 1.27
459 * @param array $filePaths
460 * @return array
462 public static function getRelativePaths( Array $filePaths ) {
463 global $IP;
464 return array_map( function ( $path ) use ( $IP ) {
465 return RelPath\getRelativePath( $path, $IP );
466 }, $filePaths );
470 * Expand directories relative to $IP.
472 * @since 1.27
473 * @param array $filePaths
474 * @return array
476 public static function expandRelativePaths( Array $filePaths ) {
477 global $IP;
478 return array_map( function ( $path ) use ( $IP ) {
479 return RelPath\joinPath( $IP, $path );
480 }, $filePaths );
484 * Get the hash of the message blob.
486 * @since 1.27
487 * @param ResourceLoaderContext $context
488 * @return string|null JSON blob or null if module has no messages
490 protected function getMessageBlob( ResourceLoaderContext $context ) {
491 if ( !$this->getMessages() ) {
492 // Don't bother consulting MessageBlobStore
493 return null;
495 // Message blobs may only vary language, not by context keys
496 $lang = $context->getLanguage();
497 if ( !isset( $this->msgBlobs[$lang] ) ) {
498 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', array(
499 'module' => $this->getName(),
500 ) );
501 $store = $context->getResourceLoader()->getMessageBlobStore();
502 $this->msgBlobs[$lang] = $store->getBlob( $this, $lang );
504 return $this->msgBlobs[$lang];
508 * Set in-object cache for message blobs.
510 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
512 * @since 1.27
513 * @param string|null $blob JSON blob or null
514 * @param string $lang Language code
516 public function setMessageBlob( $blob, $lang ) {
517 $this->msgBlobs[$lang] = $blob;
521 * Get module-specific LESS variables, if any.
523 * @since 1.27
524 * @param ResourceLoaderContext $context
525 * @return array Module-specific LESS variables.
527 protected function getLessVars( ResourceLoaderContext $context ) {
528 return array();
532 * Get an array of this module's resources. Ready for serving to the web.
534 * @since 1.26
535 * @param ResourceLoaderContext $context
536 * @return array
538 public function getModuleContent( ResourceLoaderContext $context ) {
539 $contextHash = $context->getHash();
540 // Cache this expensive operation. This calls builds the scripts, styles, and messages
541 // content which typically involves filesystem and/or database access.
542 if ( !array_key_exists( $contextHash, $this->contents ) ) {
543 $this->contents[$contextHash] = $this->buildContent( $context );
545 return $this->contents[$contextHash];
549 * Bundle all resources attached to this module into an array.
551 * @since 1.26
552 * @param ResourceLoaderContext $context
553 * @return array
555 final protected function buildContent( ResourceLoaderContext $context ) {
556 $rl = $context->getResourceLoader();
557 $stats = RequestContext::getMain()->getStats();
558 $statStart = microtime( true );
560 // Only include properties that are relevant to this context (e.g. only=scripts)
561 // and that are non-empty (e.g. don't include "templates" for modules without
562 // templates). This helps prevent invalidating cache for all modules when new
563 // optional properties are introduced.
564 $content = array();
566 // Scripts
567 if ( $context->shouldIncludeScripts() ) {
568 // If we are in debug mode, we'll want to return an array of URLs if possible
569 // However, we can't do this if the module doesn't support it
570 // We also can't do this if there is an only= parameter, because we have to give
571 // the module a way to return a load.php URL without causing an infinite loop
572 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
573 $scripts = $this->getScriptURLsForDebug( $context );
574 } else {
575 $scripts = $this->getScript( $context );
576 // rtrim() because there are usually a few line breaks
577 // after the last ';'. A new line at EOF, a new line
578 // added by ResourceLoaderFileModule::readScriptFiles, etc.
579 if ( is_string( $scripts )
580 && strlen( $scripts )
581 && substr( rtrim( $scripts ), -1 ) !== ';'
583 // Append semicolon to prevent weird bugs caused by files not
584 // terminating their statements right (bug 27054)
585 $scripts .= ";\n";
588 $content['scripts'] = $scripts;
591 // Styles
592 if ( $context->shouldIncludeStyles() ) {
593 $styles = array();
594 // Don't create empty stylesheets like array( '' => '' ) for modules
595 // that don't *have* any stylesheets (bug 38024).
596 $stylePairs = $this->getStyles( $context );
597 if ( count( $stylePairs ) ) {
598 // If we are in debug mode without &only= set, we'll want to return an array of URLs
599 // See comment near shouldIncludeScripts() for more details
600 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
601 $styles = array(
602 'url' => $this->getStyleURLsForDebug( $context )
604 } else {
605 // Minify CSS before embedding in mw.loader.implement call
606 // (unless in debug mode)
607 if ( !$context->getDebug() ) {
608 foreach ( $stylePairs as $media => $style ) {
609 // Can be either a string or an array of strings.
610 if ( is_array( $style ) ) {
611 $stylePairs[$media] = array();
612 foreach ( $style as $cssText ) {
613 if ( is_string( $cssText ) ) {
614 $stylePairs[$media][] =
615 ResourceLoader::filter( 'minify-css', $cssText );
618 } elseif ( is_string( $style ) ) {
619 $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
623 // Wrap styles into @media groups as needed and flatten into a numerical array
624 $styles = array(
625 'css' => $rl->makeCombinedStyles( $stylePairs )
629 $content['styles'] = $styles;
632 // Messages
633 $blob = $this->getMessageBlob( $context );
634 if ( $blob ) {
635 $content['messagesBlob'] = $blob;
638 $templates = $this->getTemplates();
639 if ( $templates ) {
640 $content['templates'] = $templates;
643 $statTiming = microtime( true ) - $statStart;
644 $statName = strtr( $this->getName(), '.', '_' );
645 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
646 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
648 return $content;
652 * Get a string identifying the current version of this module in a given context.
654 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
655 * messages) this value must change. This value is used to store module responses in cache.
656 * (Both client-side and server-side.)
658 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
659 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
661 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
662 * propagate changes to the client and effectively invalidate cache.
664 * For backward-compatibility, the following optional data providers are automatically included:
666 * - getModifiedTime()
667 * - getModifiedHash()
669 * @since 1.26
670 * @param ResourceLoaderContext $context
671 * @return string Hash (should use ResourceLoader::makeHash)
673 public function getVersionHash( ResourceLoaderContext $context ) {
674 // The startup module produces a manifest with versions representing the entire module.
675 // Typically, the request for the startup module itself has only=scripts. That must apply
676 // only to the startup module content, and not to the module version computed here.
677 $context = new DerivativeResourceLoaderContext( $context );
678 $context->setModules( array() );
679 // Version hash must cover all resources, regardless of startup request itself.
680 $context->setOnly( null );
681 // Compute version hash based on content, not debug urls.
682 $context->setDebug( false );
684 // Cache this somewhat expensive operation. Especially because some classes
685 // (e.g. startup module) iterate more than once over all modules to get versions.
686 $contextHash = $context->getHash();
687 if ( !array_key_exists( $contextHash, $this->versionHash ) ) {
689 if ( $this->enableModuleContentVersion() ) {
690 // Detect changes directly
691 $str = json_encode( $this->getModuleContent( $context ) );
692 } else {
693 // Infer changes based on definition and other metrics
694 $summary = $this->getDefinitionSummary( $context );
695 if ( !isset( $summary['_cacheEpoch'] ) ) {
696 throw new LogicException( 'getDefinitionSummary must call parent method' );
698 $str = json_encode( $summary );
700 $mtime = $this->getModifiedTime( $context );
701 if ( $mtime !== null ) {
702 // Support: MediaWiki 1.25 and earlier
703 $str .= strval( $mtime );
706 $mhash = $this->getModifiedHash( $context );
707 if ( $mhash !== null ) {
708 // Support: MediaWiki 1.25 and earlier
709 $str .= strval( $mhash );
713 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
715 return $this->versionHash[$contextHash];
719 * Whether to generate version hash based on module content.
721 * If a module requires database or file system access to build the module
722 * content, consider disabling this in favour of manually tracking relevant
723 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
725 * @return bool
727 public function enableModuleContentVersion() {
728 return false;
732 * Get the definition summary for this module.
734 * This is the method subclasses are recommended to use to track values in their
735 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
737 * Subclasses must call the parent getDefinitionSummary() and build on that.
738 * It is recommended that each subclass appends its own new array. This prevents
739 * clashes or accidental overwrites of existing keys and gives each subclass
740 * its own scope for simple array keys.
742 * @code
743 * $summary = parent::getDefinitionSummary( $context );
744 * $summary[] = array(
745 * 'foo' => 123,
746 * 'bar' => 'quux',
747 * );
748 * return $summary;
749 * @endcode
751 * Return an array containing values from all significant properties of this
752 * module's definition.
754 * Be careful not to normalise too much. Especially preserve the order of things
755 * that carry significance in getScript and getStyles (T39812).
757 * Avoid including things that are insiginificant (e.g. order of message keys is
758 * insignificant and should be sorted to avoid unnecessary cache invalidation).
760 * This data structure must exclusively contain arrays and scalars as values (avoid
761 * object instances) to allow simple serialisation using json_encode.
763 * If modules have a hash or timestamp from another source, that may be incuded as-is.
765 * A number of utility methods are available to help you gather data. These are not
766 * called by default and must be included by the subclass' getDefinitionSummary().
768 * - getMessageBlob()
770 * @since 1.23
771 * @param ResourceLoaderContext $context
772 * @return array|null
774 public function getDefinitionSummary( ResourceLoaderContext $context ) {
775 return array(
776 '_class' => get_class( $this ),
777 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
782 * Get this module's last modification timestamp for a given context.
784 * @deprecated since 1.26 Use getDefinitionSummary() instead
785 * @param ResourceLoaderContext $context Context object
786 * @return int|null UNIX timestamp
788 public function getModifiedTime( ResourceLoaderContext $context ) {
789 return null;
793 * Helper method for providing a version hash to getVersionHash().
795 * @deprecated since 1.26 Use getDefinitionSummary() instead
796 * @param ResourceLoaderContext $context
797 * @return string|null Hash
799 public function getModifiedHash( ResourceLoaderContext $context ) {
800 return null;
804 * Back-compat dummy for old subclass implementations of getModifiedTime().
806 * This method used to use ObjectCache to track when a hash was first seen. That principle
807 * stems from a time that ResourceLoader could only identify module versions by timestamp.
808 * That is no longer the case. Use getDefinitionSummary() directly.
810 * @deprecated since 1.26 Superseded by getVersionHash()
811 * @param ResourceLoaderContext $context
812 * @return int UNIX timestamp
814 public function getHashMtime( ResourceLoaderContext $context ) {
815 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
816 return 1;
818 // Dummy that is > 1
819 return 2;
823 * Back-compat dummy for old subclass implementations of getModifiedTime().
825 * @since 1.23
826 * @deprecated since 1.26 Superseded by getVersionHash()
827 * @param ResourceLoaderContext $context
828 * @return int UNIX timestamp
830 public function getDefinitionMtime( ResourceLoaderContext $context ) {
831 if ( $this->getDefinitionSummary( $context ) === null ) {
832 return 1;
834 // Dummy that is > 1
835 return 2;
839 * Check whether this module is known to be empty. If a child class
840 * has an easy and cheap way to determine that this module is
841 * definitely going to be empty, it should override this method to
842 * return true in that case. Callers may optimize the request for this
843 * module away if this function returns true.
844 * @param ResourceLoaderContext $context
845 * @return bool
847 public function isKnownEmpty( ResourceLoaderContext $context ) {
848 return false;
851 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
852 private static $jsParser;
853 private static $parseCacheVersion = 1;
856 * Validate a given script file; if valid returns the original source.
857 * If invalid, returns replacement JS source that throws an exception.
859 * @param string $fileName
860 * @param string $contents
861 * @return string JS with the original, or a replacement error
863 protected function validateScriptFile( $fileName, $contents ) {
864 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
865 // Try for cache hit
866 $cache = ObjectCache::getMainWANInstance();
867 $key = $cache->makeKey(
868 'resourceloader',
869 'jsparse',
870 self::$parseCacheVersion,
871 md5( $contents )
873 $cacheEntry = $cache->get( $key );
874 if ( is_string( $cacheEntry ) ) {
875 return $cacheEntry;
878 $parser = self::javaScriptParser();
879 try {
880 $parser->parse( $contents, $fileName, 1 );
881 $result = $contents;
882 } catch ( Exception $e ) {
883 // We'll save this to cache to avoid having to validate broken JS over and over...
884 $err = $e->getMessage();
885 $result = "mw.log.error(" .
886 Xml::encodeJsVar( "JavaScript parse error: $err" ) . ");";
889 $cache->set( $key, $result );
890 return $result;
891 } else {
892 return $contents;
897 * @return JSParser
899 protected static function javaScriptParser() {
900 if ( !self::$jsParser ) {
901 self::$jsParser = new JSParser();
903 return self::$jsParser;
907 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
908 * Defaults to 1.
910 * @param string $filePath File path
911 * @return int UNIX timestamp
913 protected static function safeFilemtime( $filePath ) {
914 MediaWiki\suppressWarnings();
915 $mtime = filemtime( $filePath ) ?: 1;
916 MediaWiki\restoreWarnings();
917 return $mtime;
921 * Compute a non-cryptographic string hash of a file's contents.
922 * If the file does not exist or cannot be read, returns an empty string.
924 * @since 1.26 Uses MD4 instead of SHA1.
925 * @param string $filePath File path
926 * @return string Hash
928 protected static function safeFileHash( $filePath ) {
929 return FileContentsHasher::getFileContentsHash( $filePath );