68ea0c07ab21eb159d76544f588bb4ee976e3a5a
3 * ResourceLoader module based on local JavaScript/CSS files.
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
21 * @author Trevor Parscal
22 * @author Roan Kattouw
26 * ResourceLoader module based on local JavaScript/CSS files.
28 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
30 /** @var string Local base path, see __construct() */
31 protected $localBasePath = '';
33 /** @var string Remote base path, see __construct() */
34 protected $remoteBasePath = '';
36 /** @var array Saves a list of the templates named by the modules. */
37 protected $templates = [];
40 * @var array List of paths to JavaScript files to always include
43 * [ [file-path], [file-path], ... ]
46 protected $scripts = [];
49 * @var array List of JavaScript files to include when using a specific language
52 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
55 protected $languageScripts = [];
58 * @var array List of JavaScript files to include when using a specific skin
61 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
64 protected $skinScripts = [];
67 * @var array List of paths to JavaScript files to include in debug mode
70 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
73 protected $debugScripts = [];
76 * @var array List of paths to CSS files to always include
79 * [ [file-path], [file-path], ... ]
82 protected $styles = [];
85 * @var array List of paths to CSS files to include when using specific skins
88 * [ [file-path], [file-path], ... ]
91 protected $skinStyles = [];
94 * @var array List of modules this module depends on
97 * [ [file-path], [file-path], ... ]
100 protected $dependencies = [];
103 * @var string File name containing the body of the skip function
105 protected $skipFunction = null;
108 * @var array List of message keys used by this module
111 * [ [message-key], [message-key], ... ]
114 protected $messages = [];
116 /** @var string Name of group to load this module in */
119 /** @var bool Link to raw files in debug mode */
120 protected $debugRaw = true;
122 /** @var bool Whether mw.loader.state() call should be omitted */
123 protected $raw = false;
125 protected $targets = [ 'desktop' ];
127 /** @var bool Whether CSSJanus flipping should be skipped for this module */
128 protected $noflip = false;
131 * @var bool Whether getStyleURLsForDebug should return raw file paths,
132 * or return load.php urls
134 protected $hasGeneratedStyles = false;
137 * @var array Place where readStyleFile() tracks file dependencies
140 * [ [file-path], [file-path], ... ]
143 protected $localFileRefs = [];
146 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
147 * Used in tests to detect missing dependencies.
149 protected $missingLocalFileRefs = [];
152 * Constructs a new module from an options array.
154 * @param array $options List of options; if not given or empty, an empty module will be
156 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
158 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
159 * to $wgResourceBasePath
161 * Below is a description for the $options array:
162 * @throws InvalidArgumentException
163 * @par Construction options:
166 * // Base path to prepend to all local paths in $options. Defaults to $IP
167 * 'localBasePath' => [base path],
168 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
169 * 'remoteBasePath' => [base path],
170 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
171 * 'remoteExtPath' => [base path],
172 * // Equivalent of remoteBasePath, but relative to $wgStylePath
173 * 'remoteSkinPath' => [base path],
174 * // Scripts to always include
175 * 'scripts' => [file path string or array of file path strings],
176 * // Scripts to include in specific language contexts
177 * 'languageScripts' => [
178 * [language code] => [file path string or array of file path strings],
180 * // Scripts to include in specific skin contexts
182 * [skin name] => [file path string or array of file path strings],
184 * // Scripts to include in debug contexts
185 * 'debugScripts' => [file path string or array of file path strings],
186 * // Modules which must be loaded before this module
187 * 'dependencies' => [module name string or array of module name strings],
189 * [template alias with file.ext] => [file path to a template file],
191 * // Styles to always load
192 * 'styles' => [file path string or array of file path strings],
193 * // Styles to include in specific skin contexts
195 * [skin name] => [file path string or array of file path strings],
197 * // Messages to always load
198 * 'messages' => [array of message key strings],
199 * // Group which this module should be loaded together with
200 * 'group' => [group name string],
201 * // Function that, if it returns true, makes the loader skip this module.
202 * // The file must contain valid JavaScript for execution in a private function.
203 * // The file must not contain the "function () {" and "}" wrapper though.
204 * 'skipFunction' => [file path]
208 public function __construct(
210 $localBasePath = null,
211 $remoteBasePath = null
213 // Flag to decide whether to automagically add the mediawiki.template module
214 $hasTemplates = false;
215 // localBasePath and remoteBasePath both have unbelievably long fallback chains
216 // and need to be handled separately.
217 list( $this->localBasePath
, $this->remoteBasePath
) =
218 self
::extractBasePaths( $options, $localBasePath, $remoteBasePath );
220 // Extract, validate and normalise remaining options
221 foreach ( $options as $member => $option ) {
223 // Lists of file paths
227 $this->{$member} = (array)$option;
230 $hasTemplates = true;
231 $this->{$member} = (array)$option;
233 // Collated lists of file paths
234 case 'languageScripts':
237 if ( !is_array( $option ) ) {
238 throw new InvalidArgumentException(
239 "Invalid collated file path list error. " .
240 "'$option' given, array expected."
243 foreach ( $option as $key => $value ) {
244 if ( !is_string( $key ) ) {
245 throw new InvalidArgumentException(
246 "Invalid collated file path list key error. " .
247 "'$key' given, string expected."
250 $this->{$member}[$key] = (array)$value;
254 $this->deprecated
= $option;
261 $option = array_values( array_unique( (array)$option ) );
264 $this->{$member} = $option;
269 $this->{$member} = (string)$option;
275 $this->{$member} = (bool)$option;
279 if ( $hasTemplates ) {
280 $this->dependencies
[] = 'mediawiki.template';
281 // Ensure relevant template compiler module gets loaded
282 foreach ( $this->templates
as $alias => $templatePath ) {
283 if ( is_int( $alias ) ) {
284 $alias = $templatePath;
286 $suffix = explode( '.', $alias );
287 $suffix = end( $suffix );
288 $compilerModule = 'mediawiki.template.' . $suffix;
289 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies
) ) {
290 $this->dependencies
[] = $compilerModule;
297 * Extract a pair of local and remote base paths from module definition information.
298 * Implementation note: the amount of global state used in this function is staggering.
300 * @param array $options Module definition
301 * @param string $localBasePath Path to use if not provided in module definition. Defaults
303 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
304 * to $wgResourceBasePath
305 * @return array Array( localBasePath, remoteBasePath )
307 public static function extractBasePaths(
309 $localBasePath = null,
310 $remoteBasePath = null
312 global $IP, $wgResourceBasePath;
314 // The different ways these checks are done, and their ordering, look very silly,
315 // but were preserved for backwards-compatibility just in case. Tread lightly.
317 if ( $localBasePath === null ) {
318 $localBasePath = $IP;
320 if ( $remoteBasePath === null ) {
321 $remoteBasePath = $wgResourceBasePath;
324 if ( isset( $options['remoteExtPath'] ) ) {
325 global $wgExtensionAssetsPath;
326 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
329 if ( isset( $options['remoteSkinPath'] ) ) {
331 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
334 if ( array_key_exists( 'localBasePath', $options ) ) {
335 $localBasePath = (string)$options['localBasePath'];
338 if ( array_key_exists( 'remoteBasePath', $options ) ) {
339 $remoteBasePath = (string)$options['remoteBasePath'];
342 return [ $localBasePath, $remoteBasePath ];
346 * Gets all scripts for a given context concatenated together.
348 * @param ResourceLoaderContext $context Context in which to generate script
349 * @return string JavaScript code for $context
351 public function getScript( ResourceLoaderContext
$context ) {
352 $files = $this->getScriptFiles( $context );
353 return $this->getDeprecationInformation() . $this->readScriptFiles( $files );
357 * @param ResourceLoaderContext $context
360 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
362 foreach ( $this->getScriptFiles( $context ) as $file ) {
363 $urls[] = OutputPage
::transformResourcePath(
365 $this->getRemotePath( $file )
374 public function supportsURLLoading() {
375 return $this->debugRaw
;
379 * Get all styles for a given context.
381 * @param ResourceLoaderContext $context
382 * @return array CSS code for $context as an associative array mapping media type to CSS text.
384 public function getStyles( ResourceLoaderContext
$context ) {
385 $styles = $this->readStyleFiles(
386 $this->getStyleFiles( $context ),
387 $this->getFlip( $context ),
390 // Collect referenced files
391 $this->saveFileDependencies( $context, $this->localFileRefs
);
397 * @param ResourceLoaderContext $context
400 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
401 if ( $this->hasGeneratedStyles
) {
402 // Do the default behaviour of returning a url back to load.php
403 // but with only=styles.
404 return parent
::getStyleURLsForDebug( $context );
406 // Our module consists entirely of real css files,
407 // in debug mode we can load those directly.
409 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
410 $urls[$mediaType] = [];
411 foreach ( $list as $file ) {
412 $urls[$mediaType][] = OutputPage
::transformResourcePath(
414 $this->getRemotePath( $file )
422 * Gets list of message keys used by this module.
424 * @return array List of message keys
426 public function getMessages() {
427 return $this->messages
;
431 * Gets the name of the group this module should be loaded in.
433 * @return string Group name
435 public function getGroup() {
440 * Gets list of names of modules this module depends on.
441 * @param ResourceLoaderContext|null $context
442 * @return array List of module names
444 public function getDependencies( ResourceLoaderContext
$context = null ) {
445 return $this->dependencies
;
449 * Get the skip function.
450 * @return null|string
451 * @throws MWException
453 public function getSkipFunction() {
454 if ( !$this->skipFunction
) {
458 $localPath = $this->getLocalPath( $this->skipFunction
);
459 if ( !file_exists( $localPath ) ) {
460 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
462 $contents = $this->stripBom( file_get_contents( $localPath ) );
463 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
464 $contents = $this->validateScriptFile( $localPath, $contents );
472 public function isRaw() {
477 * Disable module content versioning.
479 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
480 * involved with building the full module content inside a startup request.
484 public function enableModuleContentVersion() {
489 * Helper method for getDefinitionSummary.
491 * @see ResourceLoaderModule::getFileDependencies
492 * @param ResourceLoaderContext $context
495 private function getFileHashes( ResourceLoaderContext
$context ) {
498 // Flatten style files into $files
499 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
500 foreach ( $styles as $styleFiles ) {
501 $files = array_merge( $files, $styleFiles );
504 $skinFiles = self
::collateFilePathListByOption(
505 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
509 foreach ( $skinFiles as $styleFiles ) {
510 $files = array_merge( $files, $styleFiles );
513 // Final merge, this should result in a master list of dependent files
514 $files = array_merge(
518 $context->getDebug() ?
$this->debugScripts
: [],
519 $this->getLanguageScripts( $context->getLanguage() ),
520 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
522 if ( $this->skipFunction
) {
523 $files[] = $this->skipFunction
;
525 $files = array_map( [ $this, 'getLocalPath' ], $files );
526 // File deps need to be treated separately because they're already prefixed
527 $files = array_merge( $files, $this->getFileDependencies( $context ) );
528 // Filter out any duplicates from getFileDependencies() and others.
529 // Most commonly introduced by compileLessFile(), which always includes the
530 // entry point Less file we already know about.
531 $files = array_values( array_unique( $files ) );
533 // Don't include keys or file paths here, only the hashes. Including that would needlessly
534 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
535 // Any significant ordering is already detected by the definition summary.
536 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
540 * Get the definition summary for this module.
542 * @param ResourceLoaderContext $context
545 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
546 $summary = parent
::getDefinitionSummary( $context );
550 // The following properties are omitted because they don't affect the module reponse:
551 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
552 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
553 // - remoteBasePath (Per T104950)
554 // - dependencies (provided via startup module)
556 // - group (provided via startup module)
569 $options[$member] = $this->{$member};
573 'options' => $options,
574 'fileHashes' => $this->getFileHashes( $context ),
575 'messageBlob' => $this->getMessageBlob( $context ),
578 $lessVars = $this->getLessVars( $context );
580 $summary[] = [ 'lessVars' => $lessVars ];
587 * @param string|ResourceLoaderFilePath $path
590 protected function getLocalPath( $path ) {
591 if ( $path instanceof ResourceLoaderFilePath
) {
592 return $path->getLocalPath();
595 return "{$this->localBasePath}/$path";
599 * @param string|ResourceLoaderFilePath $path
602 protected function getRemotePath( $path ) {
603 if ( $path instanceof ResourceLoaderFilePath
) {
604 return $path->getRemotePath();
607 return "{$this->remoteBasePath}/$path";
611 * Infer the stylesheet language from a stylesheet file path.
614 * @param string $path
615 * @return string The stylesheet language name
617 public function getStyleSheetLang( $path ) {
618 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
622 * Collates file paths by option (where provided).
624 * @param array $list List of file paths in any combination of index/path
625 * or path/options pairs
626 * @param string $option Option name
627 * @param mixed $default Default value if the option isn't set
628 * @return array List of file paths, collated by $option
630 protected static function collateFilePathListByOption( array $list, $option, $default ) {
632 foreach ( (array)$list as $key => $value ) {
633 if ( is_int( $key ) ) {
634 // File name as the value
635 if ( !isset( $collatedFiles[$default] ) ) {
636 $collatedFiles[$default] = [];
638 $collatedFiles[$default][] = $value;
639 } elseif ( is_array( $value ) ) {
640 // File name as the key, options array as the value
641 $optionValue = $value[$option] ??
$default;
642 if ( !isset( $collatedFiles[$optionValue] ) ) {
643 $collatedFiles[$optionValue] = [];
645 $collatedFiles[$optionValue][] = $key;
648 return $collatedFiles;
652 * Get a list of element that match a key, optionally using a fallback key.
654 * @param array $list List of lists to select from
655 * @param string $key Key to look for in $map
656 * @param string $fallback Key to look for in $list if $key doesn't exist
657 * @return array List of elements from $map which matched $key or $fallback,
658 * or an empty list in case of no match
660 protected static function tryForKey( array $list, $key, $fallback = null ) {
661 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
663 } elseif ( is_string( $fallback )
664 && isset( $list[$fallback] )
665 && is_array( $list[$fallback] )
667 return $list[$fallback];
673 * Get a list of script file paths for this module, in order of proper execution.
675 * @param ResourceLoaderContext $context
676 * @return array List of file paths
678 private function getScriptFiles( ResourceLoaderContext
$context ) {
679 $files = array_merge(
681 $this->getLanguageScripts( $context->getLanguage() ),
682 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
684 if ( $context->getDebug() ) {
685 $files = array_merge( $files, $this->debugScripts
);
688 return array_unique( $files, SORT_REGULAR
);
692 * Get the set of language scripts for the given language,
693 * possibly using a fallback language.
695 * @param string $lang
698 private function getLanguageScripts( $lang ) {
699 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
703 $fallbacks = Language
::getFallbacksFor( $lang );
704 foreach ( $fallbacks as $lang ) {
705 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
715 * Get a list of file paths for all styles in this module, in order of proper inclusion.
717 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
720 * @param ResourceLoaderContext $context
721 * @return array List of file paths
723 public function getStyleFiles( ResourceLoaderContext
$context ) {
724 return array_merge_recursive(
725 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
726 self
::collateFilePathListByOption(
727 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
735 * Gets a list of file paths for all skin styles in the module used by
738 * @param string $skinName The name of the skin
739 * @return array A list of file paths collated by media type
741 protected function getSkinStyleFiles( $skinName ) {
742 return self
::collateFilePathListByOption(
743 self
::tryForKey( $this->skinStyles
, $skinName ),
750 * Gets a list of file paths for all skin style files in the module,
751 * for all available skins.
753 * @return array A list of file paths collated by media type
755 protected function getAllSkinStyleFiles() {
757 $internalSkinNames = array_keys( Skin
::getSkinNames() );
758 $internalSkinNames[] = 'default';
760 foreach ( $internalSkinNames as $internalSkinName ) {
761 $styleFiles = array_merge_recursive(
763 $this->getSkinStyleFiles( $internalSkinName )
771 * Returns all style files and all skin style files used by this module.
775 public function getAllStyleFiles() {
776 $collatedStyleFiles = array_merge_recursive(
777 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
778 $this->getAllSkinStyleFiles()
783 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
784 foreach ( $styleFiles as $styleFile ) {
785 $result[] = $this->getLocalPath( $styleFile );
793 * Get the contents of a list of JavaScript files. Helper for getScript().
795 * @param array $scripts List of file paths to scripts to read, remap and concetenate
796 * @return string Concatenated and remapped JavaScript data from $scripts
797 * @throws MWException
799 private function readScriptFiles( array $scripts ) {
800 if ( empty( $scripts ) ) {
804 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
805 $localPath = $this->getLocalPath( $fileName );
806 if ( !file_exists( $localPath ) ) {
807 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
809 $contents = $this->stripBom( file_get_contents( $localPath ) );
810 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
811 // Static files don't really need to be checked as often; unlike
812 // on-wiki module they shouldn't change unexpectedly without
813 // admin interference.
814 $contents = $this->validateScriptFile( $fileName, $contents );
816 $js .= $contents . "\n";
822 * Get the contents of a list of CSS files.
824 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
827 * @param array $styles Map of media type to file paths to read, remap, and concatenate
829 * @param ResourceLoaderContext $context
830 * @return array List of concatenated and remapped CSS data from $styles,
831 * keyed by media type
832 * @throws MWException
833 * @since 1.27 Calling this method without a ResourceLoaderContext instance
836 public function readStyleFiles( array $styles, $flip, $context = null ) {
837 if ( $context === null ) {
838 wfDeprecated( __METHOD__
. ' without a ResourceLoader context', '1.27' );
839 $context = ResourceLoaderContext
::newDummyContext();
842 if ( empty( $styles ) ) {
845 foreach ( $styles as $media => $files ) {
846 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
848 foreach ( $uniqueFiles as $file ) {
849 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
851 $styles[$media] = implode( "\n", $styleFiles );
857 * Reads a style file.
859 * This method can be used as a callback for array_map()
861 * @param string $path File path of style file to read
863 * @param ResourceLoaderContext $context
865 * @return string CSS data in script file
866 * @throws MWException If the file doesn't exist
868 protected function readStyleFile( $path, $flip, $context ) {
869 $localPath = $this->getLocalPath( $path );
870 $remotePath = $this->getRemotePath( $path );
871 if ( !file_exists( $localPath ) ) {
872 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
873 wfDebugLog( 'resourceloader', $msg );
874 throw new MWException( $msg );
877 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
878 $style = $this->compileLessFile( $localPath, $context );
879 $this->hasGeneratedStyles
= true;
881 $style = $this->stripBom( file_get_contents( $localPath ) );
885 $style = CSSJanus
::transform( $style, true, false );
887 $localDir = dirname( $localPath );
888 $remoteDir = dirname( $remotePath );
889 // Get and register local file references
890 $localFileRefs = CSSMin
::getLocalFileReferences( $style, $localDir );
891 foreach ( $localFileRefs as $file ) {
892 if ( file_exists( $file ) ) {
893 $this->localFileRefs
[] = $file;
895 $this->missingLocalFileRefs
[] = $file;
898 // Don't cache this call. remap() ensures data URIs embeds are up to date,
899 // and urls contain correct content hashes in their query string. (T128668)
900 return CSSMin
::remap( $style, $localDir, $remoteDir, true );
904 * Get whether CSS for this module should be flipped
905 * @param ResourceLoaderContext $context
908 public function getFlip( $context ) {
909 return $context->getDirection() === 'rtl' && !$this->noflip
;
913 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
915 * @return array Array of strings
917 public function getTargets() {
918 return $this->targets
;
922 * Get the module's load type.
927 public function getType() {
928 $canBeStylesOnly = !(
929 // All options except 'styles', 'skinStyles' and 'debugRaw'
931 ||
$this->debugScripts
933 ||
$this->languageScripts
934 ||
$this->skinScripts
935 ||
$this->dependencies
937 ||
$this->skipFunction
940 return $canBeStylesOnly ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;
944 * Compile a LESS file into CSS.
946 * Keeps track of all used files and adds them to localFileRefs.
949 * @since 1.27 Added $context paramter.
950 * @throws Exception If less.php encounters a parse error
951 * @param string $fileName File path of LESS source
952 * @param ResourceLoaderContext $context Context in which to generate script
953 * @return string CSS source
955 protected function compileLessFile( $fileName, ResourceLoaderContext
$context ) {
959 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
963 $context->getResourceLoader()->getLessVars(),
964 $this->getLessVars( $context )
966 // Construct a cache key from the LESS file name, and a hash digest
967 // of the LESS variables used for compilation.
969 $varsHash = hash( 'md4', serialize( $vars ) );
970 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
971 $cachedCompile = $cache->get( $cacheKey );
973 // If we got a cached value, we have to validate it by getting a
974 // checksum of all the files that were loaded by the parser and
975 // ensuring it matches the cached entry's.
976 if ( isset( $cachedCompile['hash'] ) ) {
977 $contentHash = FileContentsHasher
::getFileContentsHash( $cachedCompile['files'] );
978 if ( $contentHash === $cachedCompile['hash'] ) {
979 $this->localFileRefs
= array_merge( $this->localFileRefs
, $cachedCompile['files'] );
980 return $cachedCompile['css'];
984 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
985 $css = $compiler->parseFile( $fileName )->getCss();
986 $files = $compiler->AllParsedFiles();
987 $this->localFileRefs
= array_merge( $this->localFileRefs
, $files );
989 // Cache for 24 hours (86400 seconds).
990 $cache->set( $cacheKey, [
993 'hash' => FileContentsHasher
::getFileContentsHash( $files ),
1000 * Takes named templates by the module and returns an array mapping.
1001 * @return array Templates mapping template alias to content
1002 * @throws MWException
1004 public function getTemplates() {
1007 foreach ( $this->templates
as $alias => $templatePath ) {
1008 // Alias is optional
1009 if ( is_int( $alias ) ) {
1010 $alias = $templatePath;
1012 $localPath = $this->getLocalPath( $templatePath );
1013 if ( file_exists( $localPath ) ) {
1014 $content = file_get_contents( $localPath );
1015 $templates[$alias] = $this->stripBom( $content );
1017 $msg = __METHOD__
. ": template file not found: \"$localPath\"";
1018 wfDebugLog( 'resourceloader', $msg );
1019 throw new MWException( $msg );
1026 * Takes an input string and removes the UTF-8 BOM character if present
1028 * We need to remove these after reading a file, because we concatenate our files and
1029 * the BOM character is not valid in the middle of a string.
1030 * We already assume UTF-8 everywhere, so this should be safe.
1032 * @param string $input
1033 * @return string Input minus the intial BOM char
1035 protected function stripBom( $input ) {
1036 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1037 return substr( $input, 3 );