3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Trevor Parscal
20 * @author Roan Kattouw
24 * Module based on local JavaScript/CSS files.
26 * The following public methods can query the database:
28 * - getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
29 * - getVersionHash / getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
30 * - getStyles / ResourceLoaderModule::saveFileDependencies.
32 * @ingroup ResourceLoader
35 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
37 /** @var string Local base path, see __construct() */
38 protected $localBasePath = '';
40 /** @var string Remote base path, see __construct() */
41 protected $remoteBasePath = '';
43 /** @var array Saves a list of the templates named by the modules. */
44 protected $templates = [];
47 * @var array List of paths to JavaScript files to always include
50 * [ [file-path], [file-path], ... ]
53 protected $scripts = [];
56 * @var array List of JavaScript files to include when using a specific language
59 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
62 protected $languageScripts = [];
65 * @var array List of JavaScript files to include when using a specific skin
68 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
71 protected $skinScripts = [];
74 * @var array List of paths to JavaScript files to include in debug mode
77 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
80 protected $debugScripts = [];
83 * @var array List of paths to CSS files to always include
86 * [ [file-path], [file-path], ... ]
89 protected $styles = [];
92 * @var array List of paths to CSS files to include when using specific skins
95 * [ [file-path], [file-path], ... ]
98 protected $skinStyles = [];
101 * @var array List of packaged files to make available through require()
104 * [ [file-path], [file-path], ... ]
107 protected $packageFiles = null;
110 * @var array Expanded versions of $packageFiles, lazy-computed by expandPackageFiles();
111 * keyed by context hash
113 private $expandedPackageFiles = [];
116 * @var array List of modules this module depends on
119 * [ [file-path], [file-path], ... ]
122 protected $dependencies = [];
125 * @var string File name containing the body of the skip function
127 protected $skipFunction = null;
130 * @var array List of message keys used by this module
133 * [ [message-key], [message-key], ... ]
136 protected $messages = [];
138 /** @var string Name of group to load this module in */
141 /** @var bool Link to raw files in debug mode */
142 protected $debugRaw = true;
144 protected $targets = [ 'desktop' ];
146 /** @var bool Whether CSSJanus flipping should be skipped for this module */
147 protected $noflip = false;
150 * @var bool Whether getStyleURLsForDebug should return raw file paths,
151 * or return load.php urls
153 protected $hasGeneratedStyles = false;
156 * @var array Place where readStyleFile() tracks file dependencies
159 * [ [file-path], [file-path], ... ]
162 protected $localFileRefs = [];
165 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
166 * Used in tests to detect missing dependencies.
168 protected $missingLocalFileRefs = [];
171 * Constructs a new module from an options array.
173 * @param array $options List of options; if not given or empty, an empty module will be
175 * @param string|null $localBasePath Base path to prepend to all local paths in $options.
177 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
178 * Defaults to $wgResourceBasePath
180 * Below is a description for the $options array:
181 * @throws InvalidArgumentException
182 * @par Construction options:
185 * // Base path to prepend to all local paths in $options. Defaults to $IP
186 * 'localBasePath' => [base path],
187 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
188 * 'remoteBasePath' => [base path],
189 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
190 * 'remoteExtPath' => [base path],
191 * // Equivalent of remoteBasePath, but relative to $wgStylePath
192 * 'remoteSkinPath' => [base path],
193 * // Scripts to always include (cannot be set if 'packageFiles' is also set, see below)
194 * 'scripts' => [file path string or array of file path strings],
195 * // Scripts to include in specific language contexts
196 * 'languageScripts' => [
197 * [language code] => [file path string or array of file path strings],
199 * // Scripts to include in specific skin contexts
201 * [skin name] => [file path string or array of file path strings],
203 * // Scripts to include in debug contexts
204 * 'debugScripts' => [file path string or array of file path strings],
205 * // For package modules: files to be made available for internal require() do not
206 * // need to have 'type' defined; it will be inferred from the file name extension
207 * // if omitted. 'config' can only be used when 'type' is 'data'; the variables are
208 * // resolved with Config::get(). The first entry in 'packageFiles' is always the
209 * // module entry point. If 'packageFiles' is set, 'scripts' cannot also be set.
210 * 'packageFiles' => [
211 * [file path string], // or:
212 * [ 'name' => [file name], 'file' => [file path], 'type' => 'script'|'data' ], // or:
213 * [ 'name' => [name], 'content' => [string], 'type' => 'script'|'data' ], // or:
214 * [ 'name' => [name], 'callback' => [callable], 'type' => 'script'|'data' ],
215 * [ 'name' => [name], 'config' => [ [config var name], ... ], 'type' => 'data' ],
216 * [ 'name' => [name], 'config' => [ [JS name] => [PHP name] ], 'type' => 'data' ],
218 * // Modules which must be loaded before this module
219 * 'dependencies' => [module name string or array of module name strings],
221 * [template alias with file.ext] => [file path to a template file],
223 * // Styles to always load
224 * 'styles' => [file path string or array of file path strings],
225 * // Styles to include in specific skin contexts
227 * [skin name] => [file path string or array of file path strings],
229 * // Messages to always load
230 * 'messages' => [array of message key strings],
231 * // Group which this module should be loaded together with
232 * 'group' => [group name string],
233 * // Function that, if it returns true, makes the loader skip this module.
234 * // The file must contain valid JavaScript for execution in a private function.
235 * // The file must not contain the "function () {" and "}" wrapper though.
236 * 'skipFunction' => [file path]
240 public function __construct(
242 $localBasePath = null,
243 $remoteBasePath = null
245 // Flag to decide whether to automagically add the mediawiki.template module
246 $hasTemplates = false;
247 // localBasePath and remoteBasePath both have unbelievably long fallback chains
248 // and need to be handled separately.
249 list( $this->localBasePath
, $this->remoteBasePath
) =
250 self
::extractBasePaths( $options, $localBasePath, $remoteBasePath );
252 // Extract, validate and normalise remaining options
253 foreach ( $options as $member => $option ) {
255 // Lists of file paths
260 $this->{$member} = is_array( $option ) ?
$option : [ $option ];
263 $hasTemplates = true;
264 $this->{$member} = is_array( $option ) ?
$option : [ $option ];
266 // Collated lists of file paths
267 case 'languageScripts':
270 if ( !is_array( $option ) ) {
271 throw new InvalidArgumentException(
272 "Invalid collated file path list error. " .
273 "'$option' given, array expected."
276 foreach ( $option as $key => $value ) {
277 if ( !is_string( $key ) ) {
278 throw new InvalidArgumentException(
279 "Invalid collated file path list key error. " .
280 "'$key' given, string expected."
283 $this->{$member}[$key] = is_array( $value ) ?
$value : [ $value ];
287 $this->deprecated
= $option;
294 $option = array_values( array_unique( (array)$option ) );
297 $this->{$member} = $option;
302 $this->{$member} = (string)$option;
307 $this->{$member} = (bool)$option;
311 if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
312 throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
314 if ( $hasTemplates ) {
315 $this->dependencies
[] = 'mediawiki.template';
316 // Ensure relevant template compiler module gets loaded
317 foreach ( $this->templates
as $alias => $templatePath ) {
318 if ( is_int( $alias ) ) {
319 $alias = $this->getPath( $templatePath );
321 $suffix = explode( '.', $alias );
322 $suffix = end( $suffix );
323 $compilerModule = 'mediawiki.template.' . $suffix;
324 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies
) ) {
325 $this->dependencies
[] = $compilerModule;
332 * Extract a pair of local and remote base paths from module definition information.
333 * Implementation note: the amount of global state used in this function is staggering.
335 * @param array $options Module definition
336 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
338 * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
339 * to $wgResourceBasePath
340 * @return array [ localBasePath, remoteBasePath ]
342 public static function extractBasePaths(
344 $localBasePath = null,
345 $remoteBasePath = null
347 global $IP, $wgResourceBasePath;
349 // The different ways these checks are done, and their ordering, look very silly,
350 // but were preserved for backwards-compatibility just in case. Tread lightly.
352 if ( $localBasePath === null ) {
353 $localBasePath = $IP;
355 if ( $remoteBasePath === null ) {
356 $remoteBasePath = $wgResourceBasePath;
359 if ( isset( $options['remoteExtPath'] ) ) {
360 global $wgExtensionAssetsPath;
361 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
364 if ( isset( $options['remoteSkinPath'] ) ) {
366 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
369 if ( array_key_exists( 'localBasePath', $options ) ) {
370 $localBasePath = (string)$options['localBasePath'];
373 if ( array_key_exists( 'remoteBasePath', $options ) ) {
374 $remoteBasePath = (string)$options['remoteBasePath'];
377 return [ $localBasePath, $remoteBasePath ];
381 * Gets all scripts for a given context concatenated together.
383 * @param ResourceLoaderContext $context Context in which to generate script
384 * @return string|array JavaScript code for $context, or package files data structure
386 public function getScript( ResourceLoaderContext
$context ) {
387 $deprecationScript = $this->getDeprecationInformation();
388 if ( $this->packageFiles
!== null ) {
389 $packageFiles = $this->getPackageFiles( $context );
390 if ( $deprecationScript ) {
391 $mainFile =& $packageFiles['files'][$packageFiles['main']];
392 $mainFile['content'] = $deprecationScript . $mainFile['content'];
394 return $packageFiles;
397 $files = $this->getScriptFiles( $context );
398 return $deprecationScript . $this->readScriptFiles( $files );
402 * @param ResourceLoaderContext $context
405 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
407 foreach ( $this->getScriptFiles( $context ) as $file ) {
408 $urls[] = OutputPage
::transformResourcePath(
410 $this->getRemotePath( $file )
419 public function supportsURLLoading() {
420 // If package files are involved, don't support URL loading, because that breaks
421 // scoped require() functions
422 return $this->debugRaw
&& !$this->packageFiles
;
426 * Get all styles for a given context.
428 * @param ResourceLoaderContext $context
429 * @return array CSS code for $context as an associative array mapping media type to CSS text.
431 public function getStyles( ResourceLoaderContext
$context ) {
432 $styles = $this->readStyleFiles(
433 $this->getStyleFiles( $context ),
434 $this->getFlip( $context ),
437 // Collect referenced files
438 $this->saveFileDependencies( $context, $this->localFileRefs
);
444 * @param ResourceLoaderContext $context
447 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
448 if ( $this->hasGeneratedStyles
) {
449 // Do the default behaviour of returning a url back to load.php
450 // but with only=styles.
451 return parent
::getStyleURLsForDebug( $context );
453 // Our module consists entirely of real css files,
454 // in debug mode we can load those directly.
456 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
457 $urls[$mediaType] = [];
458 foreach ( $list as $file ) {
459 $urls[$mediaType][] = OutputPage
::transformResourcePath(
461 $this->getRemotePath( $file )
469 * Gets list of message keys used by this module.
471 * @return array List of message keys
473 public function getMessages() {
474 return $this->messages
;
478 * Gets the name of the group this module should be loaded in.
480 * @return string Group name
482 public function getGroup() {
487 * Gets list of names of modules this module depends on.
488 * @param ResourceLoaderContext|null $context
489 * @return array List of module names
491 public function getDependencies( ResourceLoaderContext
$context = null ) {
492 return $this->dependencies
;
496 * Get the skip function.
497 * @return null|string
498 * @throws MWException
500 public function getSkipFunction() {
501 if ( !$this->skipFunction
) {
505 $localPath = $this->getLocalPath( $this->skipFunction
);
506 if ( !file_exists( $localPath ) ) {
507 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
509 $contents = $this->stripBom( file_get_contents( $localPath ) );
514 * Disable module content versioning.
516 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
517 * involved with building the full module content inside a startup request.
521 public function enableModuleContentVersion() {
526 * Helper method for getDefinitionSummary.
528 * @see ResourceLoaderModule::getFileDependencies
529 * @param ResourceLoaderContext $context
532 private function getFileHashes( ResourceLoaderContext
$context ) {
535 // Flatten style files into $files
536 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
537 foreach ( $styles as $styleFiles ) {
538 $files = array_merge( $files, $styleFiles );
541 $skinFiles = self
::collateFilePathListByOption(
542 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
546 foreach ( $skinFiles as $styleFiles ) {
547 $files = array_merge( $files, $styleFiles );
550 // Extract file names for package files
551 $expandedPackageFiles = $this->expandPackageFiles( $context );
552 $packageFiles = $expandedPackageFiles ?
553 array_filter( array_map( function ( $fileInfo ) {
554 return $fileInfo['filePath'] ??
null;
555 }, $expandedPackageFiles['files'] ) ) :
558 // Final merge, this should result in a master list of dependent files
559 $files = array_merge(
564 $context->getDebug() ?
$this->debugScripts
: [],
565 $this->getLanguageScripts( $context->getLanguage() ),
566 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
568 if ( $this->skipFunction
) {
569 $files[] = $this->skipFunction
;
571 $files = array_map( [ $this, 'getLocalPath' ], $files );
572 // File deps need to be treated separately because they're already prefixed
573 $files = array_merge( $files, $this->getFileDependencies( $context ) );
574 // Filter out any duplicates from getFileDependencies() and others.
575 // Most commonly introduced by compileLessFile(), which always includes the
576 // entry point Less file we already know about.
577 $files = array_values( array_unique( $files ) );
579 // Don't include keys or file paths here, only the hashes. Including that would needlessly
580 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
581 // Any significant ordering is already detected by the definition summary.
582 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
586 * Get the definition summary for this module.
588 * @param ResourceLoaderContext $context
591 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
592 $summary = parent
::getDefinitionSummary( $context );
596 // The following properties are omitted because they don't affect the module reponse:
597 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
598 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
599 // - remoteBasePath (Per T104950)
600 // - dependencies (provided via startup module)
602 // - group (provided via startup module)
614 $options[$member] = $this->{$member};
617 $packageFiles = $this->expandPackageFiles( $context );
618 if ( $packageFiles ) {
619 // Extract the minimum needed:
620 // - The 'main' pointer (included as-is).
621 // - The 'files' array, simplied to only which files exist (the keys of
622 // this array), and something that represents their non-file content.
623 // For packaged files that reflect files directly from disk, the
624 // 'getFileHashes' method tracks this already.
625 // It is important that the keys of the 'files' array are preserved,
626 // as they affect the module output.
627 $packageFiles['files'] = array_map( function ( $fileInfo ) {
628 return $fileInfo['definitionSummary'] ??
( $fileInfo['content'] ??
null );
629 }, $packageFiles['files'] );
633 'options' => $options,
634 'packageFiles' => $packageFiles,
635 'fileHashes' => $this->getFileHashes( $context ),
636 'messageBlob' => $this->getMessageBlob( $context ),
639 $lessVars = $this->getLessVars( $context );
641 $summary[] = [ 'lessVars' => $lessVars ];
648 * @param string|ResourceLoaderFilePath $path
651 protected function getPath( $path ) {
652 if ( $path instanceof ResourceLoaderFilePath
) {
653 return $path->getPath();
660 * @param string|ResourceLoaderFilePath $path
663 protected function getLocalPath( $path ) {
664 if ( $path instanceof ResourceLoaderFilePath
) {
665 return $path->getLocalPath();
668 return "{$this->localBasePath}/$path";
672 * @param string|ResourceLoaderFilePath $path
675 protected function getRemotePath( $path ) {
676 if ( $path instanceof ResourceLoaderFilePath
) {
677 return $path->getRemotePath();
680 return "{$this->remoteBasePath}/$path";
684 * Infer the stylesheet language from a stylesheet file path.
687 * @param string $path
688 * @return string The stylesheet language name
690 public function getStyleSheetLang( $path ) {
691 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
695 * Infer the file type from a package file path.
696 * @param string $path
697 * @return string 'script' or 'data'
699 public static function getPackageFileType( $path ) {
700 if ( preg_match( '/\.json$/i', $path ) ) {
707 * Collates file paths by option (where provided).
709 * @param array $list List of file paths in any combination of index/path
710 * or path/options pairs
711 * @param string $option Option name
712 * @param mixed $default Default value if the option isn't set
713 * @return array List of file paths, collated by $option
715 protected static function collateFilePathListByOption( array $list, $option, $default ) {
717 foreach ( (array)$list as $key => $value ) {
718 if ( is_int( $key ) ) {
719 // File name as the value
720 if ( !isset( $collatedFiles[$default] ) ) {
721 $collatedFiles[$default] = [];
723 $collatedFiles[$default][] = $value;
724 } elseif ( is_array( $value ) ) {
725 // File name as the key, options array as the value
726 $optionValue = $value[$option] ??
$default;
727 if ( !isset( $collatedFiles[$optionValue] ) ) {
728 $collatedFiles[$optionValue] = [];
730 $collatedFiles[$optionValue][] = $key;
733 return $collatedFiles;
737 * Get a list of element that match a key, optionally using a fallback key.
739 * @param array $list List of lists to select from
740 * @param string $key Key to look for in $map
741 * @param string|null $fallback Key to look for in $list if $key doesn't exist
742 * @return array List of elements from $map which matched $key or $fallback,
743 * or an empty list in case of no match
745 protected static function tryForKey( array $list, $key, $fallback = null ) {
746 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
748 } elseif ( is_string( $fallback )
749 && isset( $list[$fallback] )
750 && is_array( $list[$fallback] )
752 return $list[$fallback];
758 * Get a list of script file paths for this module, in order of proper execution.
760 * @param ResourceLoaderContext $context
761 * @return array List of file paths
763 private function getScriptFiles( ResourceLoaderContext
$context ) {
764 $files = array_merge(
766 $this->getLanguageScripts( $context->getLanguage() ),
767 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
769 if ( $context->getDebug() ) {
770 $files = array_merge( $files, $this->debugScripts
);
773 return array_unique( $files, SORT_REGULAR
);
777 * Get the set of language scripts for the given language,
778 * possibly using a fallback language.
780 * @param string $lang
783 private function getLanguageScripts( $lang ) {
784 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
788 $fallbacks = Language
::getFallbacksFor( $lang );
789 foreach ( $fallbacks as $lang ) {
790 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
800 * Get a list of file paths for all styles in this module, in order of proper inclusion.
802 * @internal Exposed only for use by WebInstallerOutput.
803 * @param ResourceLoaderContext $context
804 * @return array List of file paths
806 public function getStyleFiles( ResourceLoaderContext
$context ) {
807 return array_merge_recursive(
808 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
809 self
::collateFilePathListByOption(
810 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
818 * Gets a list of file paths for all skin styles in the module used by
821 * @param string $skinName The name of the skin
822 * @return array A list of file paths collated by media type
824 protected function getSkinStyleFiles( $skinName ) {
825 return self
::collateFilePathListByOption(
826 self
::tryForKey( $this->skinStyles
, $skinName ),
833 * Gets a list of file paths for all skin style files in the module,
834 * for all available skins.
836 * @return array A list of file paths collated by media type
838 protected function getAllSkinStyleFiles() {
840 $internalSkinNames = array_keys( Skin
::getSkinNames() );
841 $internalSkinNames[] = 'default';
843 foreach ( $internalSkinNames as $internalSkinName ) {
844 $styleFiles = array_merge_recursive(
846 $this->getSkinStyleFiles( $internalSkinName )
854 * Returns all style files and all skin style files used by this module.
858 public function getAllStyleFiles() {
859 $collatedStyleFiles = array_merge_recursive(
860 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
861 $this->getAllSkinStyleFiles()
866 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
867 foreach ( $styleFiles as $styleFile ) {
868 $result[] = $this->getLocalPath( $styleFile );
876 * Get the contents of a list of JavaScript files. Helper for getScript().
878 * @param array $scripts List of file paths to scripts to read, remap and concetenate
879 * @return string Concatenated JavaScript data from $scripts
880 * @throws MWException
882 private function readScriptFiles( array $scripts ) {
883 if ( empty( $scripts ) ) {
887 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
888 $localPath = $this->getLocalPath( $fileName );
889 if ( !file_exists( $localPath ) ) {
890 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
892 $contents = $this->stripBom( file_get_contents( $localPath ) );
893 $js .= $contents . "\n";
899 * Get the contents of a list of CSS files.
901 * @internal This is considered a private method. Exposed for internal use by WebInstallerOutput.
902 * @param array $styles Map of media type to file paths to read, remap, and concatenate
904 * @param ResourceLoaderContext $context
905 * @return array List of concatenated and remapped CSS data from $styles,
906 * keyed by media type
907 * @throws MWException
909 public function readStyleFiles( array $styles, $flip, $context ) {
913 foreach ( $styles as $media => $files ) {
914 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
916 foreach ( $uniqueFiles as $file ) {
917 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
919 $styles[$media] = implode( "\n", $styleFiles );
925 * Reads a style file.
927 * This method can be used as a callback for array_map()
929 * @param string $path File path of style file to read
931 * @param ResourceLoaderContext $context
933 * @return string CSS data in script file
934 * @throws MWException If the file doesn't exist
936 protected function readStyleFile( $path, $flip, $context ) {
937 $localPath = $this->getLocalPath( $path );
938 $remotePath = $this->getRemotePath( $path );
939 if ( !file_exists( $localPath ) ) {
940 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
941 wfDebugLog( 'resourceloader', $msg );
942 throw new MWException( $msg );
945 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
946 $style = $this->compileLessFile( $localPath, $context );
947 $this->hasGeneratedStyles
= true;
949 $style = $this->stripBom( file_get_contents( $localPath ) );
953 $style = CSSJanus
::transform( $style, true, false );
955 $localDir = dirname( $localPath );
956 $remoteDir = dirname( $remotePath );
957 // Get and register local file references
958 $localFileRefs = CSSMin
::getLocalFileReferences( $style, $localDir );
959 foreach ( $localFileRefs as $file ) {
960 if ( file_exists( $file ) ) {
961 $this->localFileRefs
[] = $file;
963 $this->missingLocalFileRefs
[] = $file;
966 // Don't cache this call. remap() ensures data URIs embeds are up to date,
967 // and urls contain correct content hashes in their query string. (T128668)
968 return CSSMin
::remap( $style, $localDir, $remoteDir, true );
972 * Get whether CSS for this module should be flipped
973 * @param ResourceLoaderContext $context
976 public function getFlip( $context ) {
977 return $context->getDirection() === 'rtl' && !$this->noflip
;
981 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
983 * @return array Array of strings
985 public function getTargets() {
986 return $this->targets
;
990 * Get the module's load type.
995 public function getType() {
996 $canBeStylesOnly = !(
997 // All options except 'styles', 'skinStyles' and 'debugRaw'
999 ||
$this->debugScripts
1001 ||
$this->languageScripts
1002 ||
$this->skinScripts
1003 ||
$this->dependencies
1005 ||
$this->skipFunction
1006 ||
$this->packageFiles
1008 return $canBeStylesOnly ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;
1012 * Compile a LESS file into CSS.
1014 * Keeps track of all used files and adds them to localFileRefs.
1017 * @since 1.27 Added $context parameter.
1018 * @throws Exception If less.php encounters a parse error
1019 * @param string $fileName File path of LESS source
1020 * @param ResourceLoaderContext $context Context in which to generate script
1021 * @return string CSS source
1023 protected function compileLessFile( $fileName, ResourceLoaderContext
$context ) {
1027 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
1030 $vars = $this->getLessVars( $context );
1031 // Construct a cache key from the LESS file name, and a hash digest
1032 // of the LESS variables used for compilation.
1034 $varsHash = hash( 'md4', serialize( $vars ) );
1035 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
1036 $cachedCompile = $cache->get( $cacheKey );
1038 // If we got a cached value, we have to validate it by getting a
1039 // checksum of all the files that were loaded by the parser and
1040 // ensuring it matches the cached entry's.
1041 if ( isset( $cachedCompile['hash'] ) ) {
1042 $contentHash = FileContentsHasher
::getFileContentsHash( $cachedCompile['files'] );
1043 if ( $contentHash === $cachedCompile['hash'] ) {
1044 $this->localFileRefs
= array_merge( $this->localFileRefs
, $cachedCompile['files'] );
1045 return $cachedCompile['css'];
1049 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
1050 $css = $compiler->parseFile( $fileName )->getCss();
1051 $files = $compiler->AllParsedFiles();
1052 $this->localFileRefs
= array_merge( $this->localFileRefs
, $files );
1054 // Cache for 24 hours (86400 seconds).
1055 $cache->set( $cacheKey, [
1058 'hash' => FileContentsHasher
::getFileContentsHash( $files ),
1065 * Takes named templates by the module and returns an array mapping.
1066 * @return array Templates mapping template alias to content
1067 * @throws MWException
1069 public function getTemplates() {
1072 foreach ( $this->templates
as $alias => $templatePath ) {
1073 // Alias is optional
1074 if ( is_int( $alias ) ) {
1075 $alias = $this->getPath( $templatePath );
1077 $localPath = $this->getLocalPath( $templatePath );
1078 if ( file_exists( $localPath ) ) {
1079 $content = file_get_contents( $localPath );
1080 $templates[$alias] = $this->stripBom( $content );
1082 $msg = __METHOD__
. ": template file not found: \"$localPath\"";
1083 wfDebugLog( 'resourceloader', $msg );
1084 throw new MWException( $msg );
1091 * Internal helper for use by getPackageFiles(), getFileHashes() and getDefinitionSummary().
1093 * This expands the 'packageFiles' definition into something that's (almost) the right format
1094 * for getPackageFiles() to return. It expands shorthands, resolves config vars, and handles
1095 * summarising any non-file data for getVersionHash(). For file-based data, getFileHashes()
1096 * handles it instead, which also ends up in getDefinitionSummary().
1098 * What it does not do is reading the actual contents of any specified files, nor invoking
1099 * the computation callbacks. Those things are done by getPackageFiles() instead to improve
1100 * backend performance by only doing this work when the module response is needed, and not
1101 * when merely computing the version hash for StartupModule, or when checking
1102 * If-None-Match headers for a HTTP 304 response.
1104 * @param ResourceLoaderContext $context
1105 * @return array|null
1106 * @throws MWException If the 'packageFiles' definition is invalid.
1108 private function expandPackageFiles( ResourceLoaderContext
$context ) {
1109 $hash = $context->getHash();
1110 if ( isset( $this->expandedPackageFiles
[$hash] ) ) {
1111 return $this->expandedPackageFiles
[$hash];
1113 if ( $this->packageFiles
=== null ) {
1116 $expandedFiles = [];
1119 foreach ( $this->packageFiles
as $alias => $fileInfo ) {
1120 if ( is_string( $fileInfo ) ) {
1121 $fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
1122 } elseif ( !isset( $fileInfo['name'] ) ) {
1123 $msg = __METHOD__
. ": invalid package file definition for module " .
1124 "\"{$this->getName()}\": 'name' key is required when value is not a string";
1125 wfDebugLog( 'resourceloader', $msg );
1126 throw new MWException( $msg );
1129 // Infer type from alias if needed
1130 $type = $fileInfo['type'] ?? self
::getPackageFileType( $fileInfo['name'] );
1131 $expanded = [ 'type' => $type ];
1132 if ( !empty( $fileInfo['main'] ) ) {
1133 $mainFile = $fileInfo['name'];
1134 if ( $type !== 'script' ) {
1135 $msg = __METHOD__
. ": invalid package file definition for module " .
1136 "\"{$this->getName()}\": main file \"$mainFile\" must be of type \"script\", not \"$type\"";
1137 wfDebugLog( 'resourceloader', $msg );
1138 throw new MWException( $msg );
1142 // Perform expansions (except 'file' and 'callback'), creating one of these keys:
1143 // - 'content': literal value.
1144 // - 'filePath': content to be read from a file.
1145 // - 'callback': content computed by a callable.
1146 if ( isset( $fileInfo['content'] ) ) {
1147 $expanded['content'] = $fileInfo['content'];
1148 } elseif ( isset( $fileInfo['file'] ) ) {
1149 $expanded['filePath'] = $fileInfo['file'];
1150 } elseif ( isset( $fileInfo['callback'] ) ) {
1151 if ( !is_callable( $fileInfo['callback'] ) ) {
1152 $msg = __METHOD__
. ": invalid callback for package file \"{$fileInfo['name']}\"" .
1153 " in module \"{$this->getName()}\"";
1154 wfDebugLog( 'resourceloader', $msg );
1155 throw new MWException( $msg );
1157 if ( isset( $fileInfo['versionCallback'] ) ) {
1158 if ( !is_callable( $fileInfo['versionCallback'] ) ) {
1159 throw new MWException( __METHOD__
. ": invalid versionCallback for file" .
1160 " \"{$fileInfo['name']}\" in module \"{$this->getName()}\"" );
1162 $expanded['definitionSummary'] =
1163 ( $fileInfo['versionCallback'] )( $context, $this->getConfig() );
1164 // Don't invoke 'callback' here as it may be expensive (T223260).
1165 $expanded['callback'] = $fileInfo['callback'];
1167 $expanded['content'] = ( $fileInfo['callback'] )( $context, $this->getConfig() );
1169 } elseif ( isset( $fileInfo['config'] ) ) {
1170 if ( $type !== 'data' ) {
1171 $msg = __METHOD__
. ": invalid use of \"config\" for package file \"{$fileInfo['name']}\" " .
1172 "in module \"{$this->getName()}\": type must be \"data\" but is \"$type\"";
1173 wfDebugLog( 'resourceloader', $msg );
1174 throw new MWException( $msg );
1176 $expandedConfig = [];
1177 foreach ( $fileInfo['config'] as $key => $var ) {
1178 $expandedConfig[ is_numeric( $key ) ?
$var : $key ] = $this->getConfig()->get( $var );
1180 $expanded['content'] = $expandedConfig;
1181 } elseif ( !empty( $fileInfo['main'] ) ) {
1182 // [ 'name' => 'foo.js', 'main' => true ] is shorthand
1183 $expanded['filePath'] = $fileInfo['name'];
1185 $msg = __METHOD__
. ": invalid package file definition for \"{$fileInfo['name']}\" " .
1186 "in module \"{$this->getName()}\": one of \"file\", \"content\", \"callback\" or \"config\" " .
1188 wfDebugLog( 'resourceloader', $msg );
1189 throw new MWException( $msg );
1192 $expandedFiles[$fileInfo['name']] = $expanded;
1195 if ( $expandedFiles && $mainFile === null ) {
1196 // The first package file that is a script is the main file
1197 foreach ( $expandedFiles as $path => &$file ) {
1198 if ( $file['type'] === 'script' ) {
1206 'main' => $mainFile,
1207 'files' => $expandedFiles
1210 $this->expandedPackageFiles
[$hash] = $result;
1215 * Resolves the package files defintion and generates the content of each package file.
1216 * @param ResourceLoaderContext $context
1217 * @return array Package files data structure, see ResourceLoaderModule::getScript()
1219 public function getPackageFiles( ResourceLoaderContext
$context ) {
1220 if ( $this->packageFiles
=== null ) {
1223 $expandedPackageFiles = $this->expandPackageFiles( $context );
1225 // Expand file contents
1226 foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
1227 // Turn any 'filePath' or 'callback' key into actual 'content',
1228 // and remove the key after that.
1229 if ( isset( $fileInfo['filePath'] ) ) {
1230 $localPath = $this->getLocalPath( $fileInfo['filePath'] );
1231 if ( !file_exists( $localPath ) ) {
1232 $msg = __METHOD__
. ": package file not found: \"$localPath\"" .
1233 " in module \"{$this->getName()}\"";
1234 wfDebugLog( 'resourceloader', $msg );
1235 throw new MWException( $msg );
1237 $content = $this->stripBom( file_get_contents( $localPath ) );
1238 if ( $fileInfo['type'] === 'data' ) {
1239 $content = json_decode( $content );
1241 $fileInfo['content'] = $content;
1242 unset( $fileInfo['filePath'] );
1243 } elseif ( isset( $fileInfo['callback'] ) ) {
1244 $fileInfo['content'] = ( $fileInfo['callback'] )( $context, $this->getConfig() );
1245 unset( $fileInfo['callback'] );
1248 // Not needed for client response, exists for getDefinitionSummary().
1249 unset( $fileInfo['definitionSummary'] );
1252 return $expandedPackageFiles;
1256 * Takes an input string and removes the UTF-8 BOM character if present
1258 * We need to remove these after reading a file, because we concatenate our files and
1259 * the BOM character is not valid in the middle of a string.
1260 * We already assume UTF-8 everywhere, so this should be safe.
1262 * @param string $input
1263 * @return string Input minus the intial BOM char
1265 protected function stripBom( $input ) {
1266 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1267 return substr( $input, 3 );