Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / resourceloader / ResourceLoaderModule.php
blob121a6c9928dbfb10ad8d56bdb8b65d789c08ae5f
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 = [ 'desktop' ];
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 = [];
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 * @param ResourceLoaderContext $context
119 * @return bool
121 public function getFlip( $context ) {
122 global $wgContLang;
124 return $wgContLang->getDir() !== $context->getDirection();
128 * Get all JS for this module for a given language and skin.
129 * Includes all relevant JS except loader scripts.
131 * @param ResourceLoaderContext $context
132 * @return string JavaScript code
134 public function getScript( ResourceLoaderContext $context ) {
135 // Stub, override expected
136 return '';
140 * Takes named templates by the module and returns an array mapping.
142 * @return array of templates mapping template alias to content
144 public function getTemplates() {
145 // Stub, override expected.
146 return [];
150 * @return Config
151 * @since 1.24
153 public function getConfig() {
154 if ( $this->config === null ) {
155 // Ugh, fall back to default
156 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
159 return $this->config;
163 * @param Config $config
164 * @since 1.24
166 public function setConfig( Config $config ) {
167 $this->config = $config;
171 * @since 1.27
172 * @param LoggerInterface $logger
173 * @return null
175 public function setLogger( LoggerInterface $logger ) {
176 $this->logger = $logger;
180 * @since 1.27
181 * @return LoggerInterface
183 protected function getLogger() {
184 if ( !$this->logger ) {
185 $this->logger = new NullLogger();
187 return $this->logger;
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.
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.
201 * @param ResourceLoaderContext $context
202 * @return array Array of URLs
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 );
211 $url = $resourceLoader->createLoaderURL(
212 $this->getSource(),
213 $derivative
216 return [ $url ];
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
225 public function supportsURLLoading() {
226 return true;
230 * Get all CSS for this module for a given skin.
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 }' ) );
237 public function getStyles( ResourceLoaderContext $context ) {
238 // Stub, override expected
239 return [];
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()
248 * @param ResourceLoaderContext $context
249 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
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 );
258 $url = $resourceLoader->createLoaderURL(
259 $this->getSource(),
260 $derivative
263 return [ 'all' => [ $url ] ];
267 * Get the messages needed for this module.
269 * To get a JSON blob with messages, use MessageBlobStore::get()
271 * @return array List of message keys. Keys may occur more than once
273 public function getMessages() {
274 // Stub, override expected
275 return [];
279 * Get the group this module is in.
281 * @return string Group name
283 public function getGroup() {
284 // Stub, override expected
285 return null;
289 * Get the origin of this module. Should only be overridden for foreign modules.
291 * @return string Origin name, 'local' for local modules
293 public function getSource() {
294 // Stub, override expected
295 return 'local';
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>"
303 * @return string
305 public function getPosition() {
306 return 'bottom';
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.
314 * @return bool
316 public function isRaw() {
317 return false;
321 * Get a list of modules this module depends on.
323 * Dependency information is taken into account when loading a module
324 * on the client side.
326 * Note: It is expected that $context will be made non-optional in the near
327 * future.
329 * @param ResourceLoaderContext $context
330 * @return array List of module names as strings
332 public function getDependencies( ResourceLoaderContext $context = null ) {
333 // Stub, override expected
334 return [];
338 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
340 * @return array Array of strings
342 public function getTargets() {
343 return $this->targets;
347 * Get the skip function.
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.
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.
358 * @return string|null A JavaScript function body returning a boolean value, or null
360 public function getSkipFunction() {
361 return null;
365 * Get the files this module depends on indirectly for a given skin.
367 * These are only image files referenced by the module's stylesheet.
369 * @param ResourceLoaderContext $context
370 * @return array List of files
372 protected function getFileDependencies( ResourceLoaderContext $context ) {
373 $vary = $context->getSkin() . '|' . $context->getLanguage();
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',
381 'md_module' => $this->getName(),
382 'md_skin' => $vary,
384 __METHOD__
387 if ( !is_null( $deps ) ) {
388 $this->fileDeps[$vary] = self::expandRelativePaths(
389 (array)FormatJson::decode( $deps, true )
391 } else {
392 $this->fileDeps[$vary] = [];
395 return $this->fileDeps[$vary];
399 * Set in-object cache for file dependencies.
401 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
402 * To save the data, use saveFileDependencies().
404 * @param ResourceLoaderContext $context
405 * @param string[] $files Array of file names
407 public function setFileDependencies( ResourceLoaderContext $context, $files ) {
408 $vary = $context->getSkin() . '|' . $context->getLanguage();
409 $this->fileDeps[$vary] = $files;
413 * Set the files this module depends on indirectly for a given skin.
415 * @since 1.27
416 * @param ResourceLoaderContext $context
417 * @param array $localFileRefs List of files
419 protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) {
420 // Normalise array
421 $localFileRefs = array_values( array_unique( $localFileRefs ) );
422 sort( $localFileRefs );
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
434 $vary = $context->getSkin() . '|' . $context->getLanguage();
435 $dbw = wfGetDB( DB_MASTER );
436 $dbw->replace( 'module_deps',
437 [ [ 'md_module', 'md_skin' ] ],
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 ) ),
446 $dbw->onTransactionIdle( function () use ( &$scopeLock ) {
447 ScopedCallback::consume( $scopeLock ); // release after commit
448 } );
450 } catch ( Exception $e ) {
451 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
456 * Make file paths relative to MediaWiki directory.
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).
461 * @since 1.27
462 * @param array $filePaths
463 * @return array
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 );
473 * Expand directories relative to $IP.
475 * @since 1.27
476 * @param array $filePaths
477 * @return array
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 );
487 * Get the hash of the message blob.
489 * @since 1.27
490 * @param ResourceLoaderContext $context
491 * @return string|null JSON blob or null if module has no messages
493 protected function getMessageBlob( ResourceLoaderContext $context ) {
494 if ( !$this->getMessages() ) {
495 // Don't bother consulting MessageBlobStore
496 return null;
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 );
507 return $this->msgBlobs[$lang];
511 * Set in-object cache for message blobs.
513 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
515 * @since 1.27
516 * @param string|null $blob JSON blob or null
517 * @param string $lang Language code
519 public function setMessageBlob( $blob, $lang ) {
520 $this->msgBlobs[$lang] = $blob;
524 * Get module-specific LESS variables, if any.
526 * @since 1.27
527 * @param ResourceLoaderContext $context
528 * @return array Module-specific LESS variables.
530 protected function getLessVars( ResourceLoaderContext $context ) {
531 return [];
535 * Get an array of this module's resources. Ready for serving to the web.
537 * @since 1.26
538 * @param ResourceLoaderContext $context
539 * @return array
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 );
548 return $this->contents[$contextHash];
552 * Bundle all resources attached to this module into an array.
554 * @since 1.26
555 * @param ResourceLoaderContext $context
556 * @return array
558 final protected function buildContent( ResourceLoaderContext $context ) {
559 $rl = $context->getResourceLoader();
560 $stats = RequestContext::getMain()->getStats();
561 $statStart = microtime( true );
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 = [];
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 ) !== ';'
586 // Append semicolon to prevent weird bugs caused by files not
587 // terminating their statements right (bug 27054)
588 $scripts .= ";\n";
591 $content['scripts'] = $scripts;
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 )
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 );
621 } elseif ( is_string( $style ) ) {
622 $stylePairs[$media] = ResourceLoader::filter( 'minify-css', $style );
626 // Wrap styles into @media groups as needed and flatten into a numerical array
627 $styles = [
628 'css' => $rl->makeCombinedStyles( $stylePairs )
632 $content['styles'] = $styles;
635 // Messages
636 $blob = $this->getMessageBlob( $context );
637 if ( $blob ) {
638 $content['messagesBlob'] = $blob;
641 $templates = $this->getTemplates();
642 if ( $templates ) {
643 $content['templates'] = $templates;
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 );
651 return $content;
655 * Get a string identifying the current version of this module in a given context.
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.)
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.
664 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
665 * propagate changes to the client and effectively invalidate cache.
667 * For backward-compatibility, the following optional data providers are automatically included:
669 * - getModifiedTime()
670 * - getModifiedHash()
672 * @since 1.26
673 * @param ResourceLoaderContext $context
674 * @return string Hash (should use ResourceLoader::makeHash)
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 );
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 ) ) {
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' );
701 $str = json_encode( $summary );
703 $mtime = $this->getModifiedTime( $context );
704 if ( $mtime !== null ) {
705 // Support: MediaWiki 1.25 and earlier
706 $str .= strval( $mtime );
709 $mhash = $this->getModifiedHash( $context );
710 if ( $mhash !== null ) {
711 // Support: MediaWiki 1.25 and earlier
712 $str .= strval( $mhash );
716 $this->versionHash[$contextHash] = ResourceLoader::makeHash( $str );
718 return $this->versionHash[$contextHash];
722 * Whether to generate version hash based on module content.
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.
728 * @return bool
730 public function enableModuleContentVersion() {
731 return false;
735 * Get the definition summary for this module.
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.
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.
745 * @code
746 * $summary = parent::getDefinitionSummary( $context );
747 * $summary[] = array(
748 * 'foo' => 123,
749 * 'bar' => 'quux',
750 * );
751 * return $summary;
752 * @endcode
754 * Return an array containing values from all significant properties of this
755 * module's definition.
757 * Be careful not to normalise too much. Especially preserve the order of things
758 * that carry significance in getScript and getStyles (T39812).
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).
763 * This data structure must exclusively contain arrays and scalars as values (avoid
764 * object instances) to allow simple serialisation using json_encode.
766 * If modules have a hash or timestamp from another source, that may be incuded as-is.
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().
771 * - getMessageBlob()
773 * @since 1.23
774 * @param ResourceLoaderContext $context
775 * @return array|null
777 public function getDefinitionSummary( ResourceLoaderContext $context ) {
778 return [
779 '_class' => get_class( $this ),
780 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
785 * Get this module's last modification timestamp for a given context.
787 * @deprecated since 1.26 Use getDefinitionSummary() instead
788 * @param ResourceLoaderContext $context Context object
789 * @return int|null UNIX timestamp
791 public function getModifiedTime( ResourceLoaderContext $context ) {
792 return null;
796 * Helper method for providing a version hash to getVersionHash().
798 * @deprecated since 1.26 Use getDefinitionSummary() instead
799 * @param ResourceLoaderContext $context
800 * @return string|null Hash
802 public function getModifiedHash( ResourceLoaderContext $context ) {
803 return null;
807 * Back-compat dummy for old subclass implementations of getModifiedTime().
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.
813 * @deprecated since 1.26 Superseded by getVersionHash()
814 * @param ResourceLoaderContext $context
815 * @return int UNIX timestamp
817 public function getHashMtime( ResourceLoaderContext $context ) {
818 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
819 return 1;
821 // Dummy that is > 1
822 return 2;
826 * Back-compat dummy for old subclass implementations of getModifiedTime().
828 * @since 1.23
829 * @deprecated since 1.26 Superseded by getVersionHash()
830 * @param ResourceLoaderContext $context
831 * @return int UNIX timestamp
833 public function getDefinitionMtime( ResourceLoaderContext $context ) {
834 if ( $this->getDefinitionSummary( $context ) === null ) {
835 return 1;
837 // Dummy that is > 1
838 return 2;
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
850 public function isKnownEmpty( ResourceLoaderContext $context ) {
851 return false;
854 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
855 private static $jsParser;
856 private static $parseCacheVersion = 1;
859 * Validate a given script file; if valid returns the original source.
860 * If invalid, returns replacement JS source that throws an exception.
862 * @param string $fileName
863 * @param string $contents
864 * @return string JS with the original, or a replacement error
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 )
876 $cacheEntry = $cache->get( $key );
877 if ( is_string( $cacheEntry ) ) {
878 return $cacheEntry;
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" ) . ");";
892 $cache->set( $key, $result );
893 return $result;
894 } else {
895 return $contents;
900 * @return JSParser
902 protected static function javaScriptParser() {
903 if ( !self::$jsParser ) {
904 self::$jsParser = new JSParser();
906 return self::$jsParser;
910 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
911 * Defaults to 1.
913 * @param string $filePath File path
914 * @return int UNIX timestamp
916 protected static function safeFilemtime( $filePath ) {
917 MediaWiki\suppressWarnings();
918 $mtime = filemtime( $filePath ) ?: 1;
919 MediaWiki\restoreWarnings();
920 return $mtime;
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.
927 * @since 1.26 Uses MD4 instead of SHA1.
928 * @param string $filePath File path
929 * @return string Hash
931 protected static function safeFileHash( $filePath ) {
932 return FileContentsHasher::getFileContentsHash( $filePath );