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|null $localBasePath Base path to prepend to all local paths in $options.
158 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
159 * Defaults 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|null $localBasePath Path to use if not provided in module definition. Defaults
303 * @param string|null $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 ) );
469 public function isRaw() {
474 * Disable module content versioning.
476 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
477 * involved with building the full module content inside a startup request.
481 public function enableModuleContentVersion() {
486 * Helper method for getDefinitionSummary.
488 * @see ResourceLoaderModule::getFileDependencies
489 * @param ResourceLoaderContext $context
492 private function getFileHashes( ResourceLoaderContext
$context ) {
495 // Flatten style files into $files
496 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
497 foreach ( $styles as $styleFiles ) {
498 $files = array_merge( $files, $styleFiles );
501 $skinFiles = self
::collateFilePathListByOption(
502 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
506 foreach ( $skinFiles as $styleFiles ) {
507 $files = array_merge( $files, $styleFiles );
510 // Final merge, this should result in a master list of dependent files
511 $files = array_merge(
515 $context->getDebug() ?
$this->debugScripts
: [],
516 $this->getLanguageScripts( $context->getLanguage() ),
517 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
519 if ( $this->skipFunction
) {
520 $files[] = $this->skipFunction
;
522 $files = array_map( [ $this, 'getLocalPath' ], $files );
523 // File deps need to be treated separately because they're already prefixed
524 $files = array_merge( $files, $this->getFileDependencies( $context ) );
525 // Filter out any duplicates from getFileDependencies() and others.
526 // Most commonly introduced by compileLessFile(), which always includes the
527 // entry point Less file we already know about.
528 $files = array_values( array_unique( $files ) );
530 // Don't include keys or file paths here, only the hashes. Including that would needlessly
531 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
532 // Any significant ordering is already detected by the definition summary.
533 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
537 * Get the definition summary for this module.
539 * @param ResourceLoaderContext $context
542 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
543 $summary = parent
::getDefinitionSummary( $context );
547 // The following properties are omitted because they don't affect the module reponse:
548 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
549 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
550 // - remoteBasePath (Per T104950)
551 // - dependencies (provided via startup module)
553 // - group (provided via startup module)
566 $options[$member] = $this->{$member};
570 'options' => $options,
571 'fileHashes' => $this->getFileHashes( $context ),
572 'messageBlob' => $this->getMessageBlob( $context ),
575 $lessVars = $this->getLessVars( $context );
577 $summary[] = [ 'lessVars' => $lessVars ];
584 * @param string|ResourceLoaderFilePath $path
587 protected function getLocalPath( $path ) {
588 if ( $path instanceof ResourceLoaderFilePath
) {
589 return $path->getLocalPath();
592 return "{$this->localBasePath}/$path";
596 * @param string|ResourceLoaderFilePath $path
599 protected function getRemotePath( $path ) {
600 if ( $path instanceof ResourceLoaderFilePath
) {
601 return $path->getRemotePath();
604 return "{$this->remoteBasePath}/$path";
608 * Infer the stylesheet language from a stylesheet file path.
611 * @param string $path
612 * @return string The stylesheet language name
614 public function getStyleSheetLang( $path ) {
615 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
619 * Collates file paths by option (where provided).
621 * @param array $list List of file paths in any combination of index/path
622 * or path/options pairs
623 * @param string $option Option name
624 * @param mixed $default Default value if the option isn't set
625 * @return array List of file paths, collated by $option
627 protected static function collateFilePathListByOption( array $list, $option, $default ) {
629 foreach ( (array)$list as $key => $value ) {
630 if ( is_int( $key ) ) {
631 // File name as the value
632 if ( !isset( $collatedFiles[$default] ) ) {
633 $collatedFiles[$default] = [];
635 $collatedFiles[$default][] = $value;
636 } elseif ( is_array( $value ) ) {
637 // File name as the key, options array as the value
638 $optionValue = $value[$option] ??
$default;
639 if ( !isset( $collatedFiles[$optionValue] ) ) {
640 $collatedFiles[$optionValue] = [];
642 $collatedFiles[$optionValue][] = $key;
645 return $collatedFiles;
649 * Get a list of element that match a key, optionally using a fallback key.
651 * @param array $list List of lists to select from
652 * @param string $key Key to look for in $map
653 * @param string|null $fallback Key to look for in $list if $key doesn't exist
654 * @return array List of elements from $map which matched $key or $fallback,
655 * or an empty list in case of no match
657 protected static function tryForKey( array $list, $key, $fallback = null ) {
658 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
660 } elseif ( is_string( $fallback )
661 && isset( $list[$fallback] )
662 && is_array( $list[$fallback] )
664 return $list[$fallback];
670 * Get a list of script file paths for this module, in order of proper execution.
672 * @param ResourceLoaderContext $context
673 * @return array List of file paths
675 private function getScriptFiles( ResourceLoaderContext
$context ) {
676 $files = array_merge(
678 $this->getLanguageScripts( $context->getLanguage() ),
679 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
681 if ( $context->getDebug() ) {
682 $files = array_merge( $files, $this->debugScripts
);
685 return array_unique( $files, SORT_REGULAR
);
689 * Get the set of language scripts for the given language,
690 * possibly using a fallback language.
692 * @param string $lang
695 private function getLanguageScripts( $lang ) {
696 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
700 $fallbacks = Language
::getFallbacksFor( $lang );
701 foreach ( $fallbacks as $lang ) {
702 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
712 * Get a list of file paths for all styles in this module, in order of proper inclusion.
714 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
717 * @param ResourceLoaderContext $context
718 * @return array List of file paths
720 public function getStyleFiles( ResourceLoaderContext
$context ) {
721 return array_merge_recursive(
722 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
723 self
::collateFilePathListByOption(
724 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
732 * Gets a list of file paths for all skin styles in the module used by
735 * @param string $skinName The name of the skin
736 * @return array A list of file paths collated by media type
738 protected function getSkinStyleFiles( $skinName ) {
739 return self
::collateFilePathListByOption(
740 self
::tryForKey( $this->skinStyles
, $skinName ),
747 * Gets a list of file paths for all skin style files in the module,
748 * for all available skins.
750 * @return array A list of file paths collated by media type
752 protected function getAllSkinStyleFiles() {
754 $internalSkinNames = array_keys( Skin
::getSkinNames() );
755 $internalSkinNames[] = 'default';
757 foreach ( $internalSkinNames as $internalSkinName ) {
758 $styleFiles = array_merge_recursive(
760 $this->getSkinStyleFiles( $internalSkinName )
768 * Returns all style files and all skin style files used by this module.
772 public function getAllStyleFiles() {
773 $collatedStyleFiles = array_merge_recursive(
774 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
775 $this->getAllSkinStyleFiles()
780 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
781 foreach ( $styleFiles as $styleFile ) {
782 $result[] = $this->getLocalPath( $styleFile );
790 * Get the contents of a list of JavaScript files. Helper for getScript().
792 * @param array $scripts List of file paths to scripts to read, remap and concetenate
793 * @return string Concatenated and remapped JavaScript data from $scripts
794 * @throws MWException
796 private function readScriptFiles( array $scripts ) {
797 if ( empty( $scripts ) ) {
801 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
802 $localPath = $this->getLocalPath( $fileName );
803 if ( !file_exists( $localPath ) ) {
804 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
806 $contents = $this->stripBom( file_get_contents( $localPath ) );
807 $js .= $contents . "\n";
813 * Get the contents of a list of CSS files.
815 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
818 * @param array $styles Map of media type to file paths to read, remap, and concatenate
820 * @param ResourceLoaderContext|null $context
821 * @return array List of concatenated and remapped CSS data from $styles,
822 * keyed by media type
823 * @throws MWException
824 * @since 1.27 Calling this method without a ResourceLoaderContext instance
827 public function readStyleFiles( array $styles, $flip, $context = null ) {
828 if ( $context === null ) {
829 wfDeprecated( __METHOD__
. ' without a ResourceLoader context', '1.27' );
830 $context = ResourceLoaderContext
::newDummyContext();
833 if ( empty( $styles ) ) {
836 foreach ( $styles as $media => $files ) {
837 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
839 foreach ( $uniqueFiles as $file ) {
840 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
842 $styles[$media] = implode( "\n", $styleFiles );
848 * Reads a style file.
850 * This method can be used as a callback for array_map()
852 * @param string $path File path of style file to read
854 * @param ResourceLoaderContext $context
856 * @return string CSS data in script file
857 * @throws MWException If the file doesn't exist
859 protected function readStyleFile( $path, $flip, $context ) {
860 $localPath = $this->getLocalPath( $path );
861 $remotePath = $this->getRemotePath( $path );
862 if ( !file_exists( $localPath ) ) {
863 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
864 wfDebugLog( 'resourceloader', $msg );
865 throw new MWException( $msg );
868 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
869 $style = $this->compileLessFile( $localPath, $context );
870 $this->hasGeneratedStyles
= true;
872 $style = $this->stripBom( file_get_contents( $localPath ) );
876 $style = CSSJanus
::transform( $style, true, false );
878 $localDir = dirname( $localPath );
879 $remoteDir = dirname( $remotePath );
880 // Get and register local file references
881 $localFileRefs = CSSMin
::getLocalFileReferences( $style, $localDir );
882 foreach ( $localFileRefs as $file ) {
883 if ( file_exists( $file ) ) {
884 $this->localFileRefs
[] = $file;
886 $this->missingLocalFileRefs
[] = $file;
889 // Don't cache this call. remap() ensures data URIs embeds are up to date,
890 // and urls contain correct content hashes in their query string. (T128668)
891 return CSSMin
::remap( $style, $localDir, $remoteDir, true );
895 * Get whether CSS for this module should be flipped
896 * @param ResourceLoaderContext $context
899 public function getFlip( $context ) {
900 return $context->getDirection() === 'rtl' && !$this->noflip
;
904 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
906 * @return array Array of strings
908 public function getTargets() {
909 return $this->targets
;
913 * Get the module's load type.
918 public function getType() {
919 $canBeStylesOnly = !(
920 // All options except 'styles', 'skinStyles' and 'debugRaw'
922 ||
$this->debugScripts
924 ||
$this->languageScripts
925 ||
$this->skinScripts
926 ||
$this->dependencies
928 ||
$this->skipFunction
931 return $canBeStylesOnly ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;
935 * Compile a LESS file into CSS.
937 * Keeps track of all used files and adds them to localFileRefs.
940 * @since 1.27 Added $context paramter.
941 * @throws Exception If less.php encounters a parse error
942 * @param string $fileName File path of LESS source
943 * @param ResourceLoaderContext $context Context in which to generate script
944 * @return string CSS source
946 protected function compileLessFile( $fileName, ResourceLoaderContext
$context ) {
950 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
953 $vars = $this->getLessVars( $context );
954 // Construct a cache key from the LESS file name, and a hash digest
955 // of the LESS variables used for compilation.
957 $varsHash = hash( 'md4', serialize( $vars ) );
958 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
959 $cachedCompile = $cache->get( $cacheKey );
961 // If we got a cached value, we have to validate it by getting a
962 // checksum of all the files that were loaded by the parser and
963 // ensuring it matches the cached entry's.
964 if ( isset( $cachedCompile['hash'] ) ) {
965 $contentHash = FileContentsHasher
::getFileContentsHash( $cachedCompile['files'] );
966 if ( $contentHash === $cachedCompile['hash'] ) {
967 $this->localFileRefs
= array_merge( $this->localFileRefs
, $cachedCompile['files'] );
968 return $cachedCompile['css'];
972 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
973 $css = $compiler->parseFile( $fileName )->getCss();
974 $files = $compiler->AllParsedFiles();
975 $this->localFileRefs
= array_merge( $this->localFileRefs
, $files );
977 // Cache for 24 hours (86400 seconds).
978 $cache->set( $cacheKey, [
981 'hash' => FileContentsHasher
::getFileContentsHash( $files ),
988 * Takes named templates by the module and returns an array mapping.
989 * @return array Templates mapping template alias to content
990 * @throws MWException
992 public function getTemplates() {
995 foreach ( $this->templates
as $alias => $templatePath ) {
997 if ( is_int( $alias ) ) {
998 $alias = $templatePath;
1000 $localPath = $this->getLocalPath( $templatePath );
1001 if ( file_exists( $localPath ) ) {
1002 $content = file_get_contents( $localPath );
1003 $templates[$alias] = $this->stripBom( $content );
1005 $msg = __METHOD__
. ": template file not found: \"$localPath\"";
1006 wfDebugLog( 'resourceloader', $msg );
1007 throw new MWException( $msg );
1014 * Takes an input string and removes the UTF-8 BOM character if present
1016 * We need to remove these after reading a file, because we concatenate our files and
1017 * the BOM character is not valid in the middle of a string.
1018 * We already assume UTF-8 everywhere, so this should be safe.
1020 * @param string $input
1021 * @return string Input minus the intial BOM char
1023 protected function stripBom( $input ) {
1024 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1025 return substr( $input, 3 );