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 * The following public methods can query the database:
30 * - getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
31 * - getVersionHash / getDefinitionSummary / … / ResourceLoaderModule::getFileDependencies.
32 * - getStyles / ResourceLoaderModule::saveFileDependencies.
34 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
36 /** @var string Local base path, see __construct() */
37 protected $localBasePath = '';
39 /** @var string Remote base path, see __construct() */
40 protected $remoteBasePath = '';
42 /** @var array Saves a list of the templates named by the modules. */
43 protected $templates = [];
46 * @var array List of paths to JavaScript files to always include
49 * [ [file-path], [file-path], ... ]
52 protected $scripts = [];
55 * @var array List of JavaScript files to include when using a specific language
58 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
61 protected $languageScripts = [];
64 * @var array List of JavaScript files to include when using a specific skin
67 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
70 protected $skinScripts = [];
73 * @var array List of paths to JavaScript files to include in debug mode
76 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
79 protected $debugScripts = [];
82 * @var array List of paths to CSS files to always include
85 * [ [file-path], [file-path], ... ]
88 protected $styles = [];
91 * @var array List of paths to CSS files to include when using specific skins
94 * [ [file-path], [file-path], ... ]
97 protected $skinStyles = [];
100 * @var array List of packaged files to make available through require()
103 * [ [file-path], [file-path], ... ]
106 protected $packageFiles = null;
109 * @var array Expanded versions of $packageFiles, lazy-computed by expandPackageFiles();
110 * keyed by context hash
112 private $expandedPackageFiles = [];
115 * @var array List of modules this module depends on
118 * [ [file-path], [file-path], ... ]
121 protected $dependencies = [];
124 * @var string File name containing the body of the skip function
126 protected $skipFunction = null;
129 * @var array List of message keys used by this module
132 * [ [message-key], [message-key], ... ]
135 protected $messages = [];
137 /** @var string Name of group to load this module in */
140 /** @var bool Link to raw files in debug mode */
141 protected $debugRaw = true;
143 /** @var bool Whether mw.loader.state() call should be omitted */
144 protected $raw = false;
146 protected $targets = [ 'desktop' ];
148 /** @var bool Whether CSSJanus flipping should be skipped for this module */
149 protected $noflip = false;
152 * @var bool Whether getStyleURLsForDebug should return raw file paths,
153 * or return load.php urls
155 protected $hasGeneratedStyles = false;
158 * @var array Place where readStyleFile() tracks file dependencies
161 * [ [file-path], [file-path], ... ]
164 protected $localFileRefs = [];
167 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
168 * Used in tests to detect missing dependencies.
170 protected $missingLocalFileRefs = [];
173 * Constructs a new module from an options array.
175 * @param array $options List of options; if not given or empty, an empty module will be
177 * @param string|null $localBasePath Base path to prepend to all local paths in $options.
179 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
180 * Defaults to $wgResourceBasePath
182 * Below is a description for the $options array:
183 * @throws InvalidArgumentException
184 * @par Construction options:
187 * // Base path to prepend to all local paths in $options. Defaults to $IP
188 * 'localBasePath' => [base path],
189 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
190 * 'remoteBasePath' => [base path],
191 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
192 * 'remoteExtPath' => [base path],
193 * // Equivalent of remoteBasePath, but relative to $wgStylePath
194 * 'remoteSkinPath' => [base path],
195 * // Scripts to always include (cannot be set if 'packageFiles' is also set, see below)
196 * 'scripts' => [file path string or array of file path strings],
197 * // Scripts to include in specific language contexts
198 * 'languageScripts' => [
199 * [language code] => [file path string or array of file path strings],
201 * // Scripts to include in specific skin contexts
203 * [skin name] => [file path string or array of file path strings],
205 * // Scripts to include in debug contexts
206 * 'debugScripts' => [file path string or array of file path strings],
207 * // For package modules: files to be made available for internal require() do not
208 * // need to have 'type' defined; it will be inferred from the file name extension
209 * // if omitted. 'config' can only be used when 'type' is 'data'; the variables are
210 * // resolved with Config::get(). The first entry in 'packageFiles' is always the
211 * // module entry point. If 'packageFiles' is set, 'scripts' cannot also be set.
212 * 'packageFiles' => [
213 * [file path string], // or:
214 * [ 'name' => [file name], 'file' => [file path], 'type' => 'script'|'data' ], // or:
215 * [ 'name' => [name], 'content' => [string], 'type' => 'script'|'data' ], // or:
216 * [ 'name' => [name], 'callback' => [callable], 'type' => 'script'|'data' ],
217 * [ 'name' => [name], 'config' => [ [config var name], ... ], 'type' => 'data' ],
218 * [ 'name' => [name], 'config' => [ [JS name] => [PHP name] ], 'type' => 'data' ],
220 * // Modules which must be loaded before this module
221 * 'dependencies' => [module name string or array of module name strings],
223 * [template alias with file.ext] => [file path to a template file],
225 * // Styles to always load
226 * 'styles' => [file path string or array of file path strings],
227 * // Styles to include in specific skin contexts
229 * [skin name] => [file path string or array of file path strings],
231 * // Messages to always load
232 * 'messages' => [array of message key strings],
233 * // Group which this module should be loaded together with
234 * 'group' => [group name string],
235 * // Function that, if it returns true, makes the loader skip this module.
236 * // The file must contain valid JavaScript for execution in a private function.
237 * // The file must not contain the "function () {" and "}" wrapper though.
238 * 'skipFunction' => [file path]
242 public function __construct(
244 $localBasePath = null,
245 $remoteBasePath = null
247 // Flag to decide whether to automagically add the mediawiki.template module
248 $hasTemplates = false;
249 // localBasePath and remoteBasePath both have unbelievably long fallback chains
250 // and need to be handled separately.
251 list( $this->localBasePath
, $this->remoteBasePath
) =
252 self
::extractBasePaths( $options, $localBasePath, $remoteBasePath );
254 // Extract, validate and normalise remaining options
255 foreach ( $options as $member => $option ) {
257 // Lists of file paths
262 $this->{$member} = (array)$option;
265 $hasTemplates = true;
266 $this->{$member} = (array)$option;
268 // Collated lists of file paths
269 case 'languageScripts':
272 if ( !is_array( $option ) ) {
273 throw new InvalidArgumentException(
274 "Invalid collated file path list error. " .
275 "'$option' given, array expected."
278 foreach ( $option as $key => $value ) {
279 if ( !is_string( $key ) ) {
280 throw new InvalidArgumentException(
281 "Invalid collated file path list key error. " .
282 "'$key' given, string expected."
285 $this->{$member}[$key] = (array)$value;
289 $this->deprecated
= $option;
296 $option = array_values( array_unique( (array)$option ) );
299 $this->{$member} = $option;
304 $this->{$member} = (string)$option;
310 $this->{$member} = (bool)$option;
314 if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
315 throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
317 if ( $hasTemplates ) {
318 $this->dependencies
[] = 'mediawiki.template';
319 // Ensure relevant template compiler module gets loaded
320 foreach ( $this->templates
as $alias => $templatePath ) {
321 if ( is_int( $alias ) ) {
322 $alias = $templatePath;
324 $suffix = explode( '.', $alias );
325 $suffix = end( $suffix );
326 $compilerModule = 'mediawiki.template.' . $suffix;
327 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies
) ) {
328 $this->dependencies
[] = $compilerModule;
335 * Extract a pair of local and remote base paths from module definition information.
336 * Implementation note: the amount of global state used in this function is staggering.
338 * @param array $options Module definition
339 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
341 * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
342 * to $wgResourceBasePath
343 * @return array [ localBasePath, remoteBasePath ]
345 public static function extractBasePaths(
347 $localBasePath = null,
348 $remoteBasePath = null
350 global $IP, $wgResourceBasePath;
352 // The different ways these checks are done, and their ordering, look very silly,
353 // but were preserved for backwards-compatibility just in case. Tread lightly.
355 if ( $localBasePath === null ) {
356 $localBasePath = $IP;
358 if ( $remoteBasePath === null ) {
359 $remoteBasePath = $wgResourceBasePath;
362 if ( isset( $options['remoteExtPath'] ) ) {
363 global $wgExtensionAssetsPath;
364 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
367 if ( isset( $options['remoteSkinPath'] ) ) {
369 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
372 if ( array_key_exists( 'localBasePath', $options ) ) {
373 $localBasePath = (string)$options['localBasePath'];
376 if ( array_key_exists( 'remoteBasePath', $options ) ) {
377 $remoteBasePath = (string)$options['remoteBasePath'];
380 return [ $localBasePath, $remoteBasePath ];
384 * Gets all scripts for a given context concatenated together.
386 * @param ResourceLoaderContext $context Context in which to generate script
387 * @return string|array JavaScript code for $context, or package files data structure
389 public function getScript( ResourceLoaderContext
$context ) {
390 $deprecationScript = $this->getDeprecationInformation();
391 if ( $this->packageFiles
!== null ) {
392 $packageFiles = $this->getPackageFiles( $context );
393 if ( $deprecationScript ) {
394 $mainFile =& $packageFiles['files'][$packageFiles['main']];
395 $mainFile['content'] = $deprecationScript . $mainFile['content'];
397 return $packageFiles;
400 $files = $this->getScriptFiles( $context );
401 return $deprecationScript . $this->readScriptFiles( $files );
405 * @param ResourceLoaderContext $context
408 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
410 foreach ( $this->getScriptFiles( $context ) as $file ) {
411 $urls[] = OutputPage
::transformResourcePath(
413 $this->getRemotePath( $file )
422 public function supportsURLLoading() {
423 // If package files are involved, don't support URL loading, because that breaks
424 // scoped require() functions
425 return $this->debugRaw
&& !$this->packageFiles
;
429 * Get all styles for a given context.
431 * @param ResourceLoaderContext $context
432 * @return array CSS code for $context as an associative array mapping media type to CSS text.
434 public function getStyles( ResourceLoaderContext
$context ) {
435 $styles = $this->readStyleFiles(
436 $this->getStyleFiles( $context ),
437 $this->getFlip( $context ),
440 // Collect referenced files
441 $this->saveFileDependencies( $context, $this->localFileRefs
);
447 * @param ResourceLoaderContext $context
450 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
451 if ( $this->hasGeneratedStyles
) {
452 // Do the default behaviour of returning a url back to load.php
453 // but with only=styles.
454 return parent
::getStyleURLsForDebug( $context );
456 // Our module consists entirely of real css files,
457 // in debug mode we can load those directly.
459 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
460 $urls[$mediaType] = [];
461 foreach ( $list as $file ) {
462 $urls[$mediaType][] = OutputPage
::transformResourcePath(
464 $this->getRemotePath( $file )
472 * Gets list of message keys used by this module.
474 * @return array List of message keys
476 public function getMessages() {
477 return $this->messages
;
481 * Gets the name of the group this module should be loaded in.
483 * @return string Group name
485 public function getGroup() {
490 * Gets list of names of modules this module depends on.
491 * @param ResourceLoaderContext|null $context
492 * @return array List of module names
494 public function getDependencies( ResourceLoaderContext
$context = null ) {
495 return $this->dependencies
;
499 * Get the skip function.
500 * @return null|string
501 * @throws MWException
503 public function getSkipFunction() {
504 if ( !$this->skipFunction
) {
508 $localPath = $this->getLocalPath( $this->skipFunction
);
509 if ( !file_exists( $localPath ) ) {
510 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
512 $contents = $this->stripBom( file_get_contents( $localPath ) );
519 public function isRaw() {
524 * Disable module content versioning.
526 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
527 * involved with building the full module content inside a startup request.
531 public function enableModuleContentVersion() {
536 * Helper method for getDefinitionSummary.
538 * @see ResourceLoaderModule::getFileDependencies
539 * @param ResourceLoaderContext $context
542 private function getFileHashes( ResourceLoaderContext
$context ) {
545 // Flatten style files into $files
546 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
547 foreach ( $styles as $styleFiles ) {
548 $files = array_merge( $files, $styleFiles );
551 $skinFiles = self
::collateFilePathListByOption(
552 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
556 foreach ( $skinFiles as $styleFiles ) {
557 $files = array_merge( $files, $styleFiles );
560 // Extract file names for package files
561 $expandedPackageFiles = $this->expandPackageFiles( $context );
562 $packageFiles = $expandedPackageFiles ?
563 array_filter( array_map( function ( $fileInfo ) {
564 return $fileInfo['filePath'] ??
null;
565 }, $expandedPackageFiles['files'] ) ) :
568 // Final merge, this should result in a master list of dependent files
569 $files = array_merge(
574 $context->getDebug() ?
$this->debugScripts
: [],
575 $this->getLanguageScripts( $context->getLanguage() ),
576 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
578 if ( $this->skipFunction
) {
579 $files[] = $this->skipFunction
;
581 $files = array_map( [ $this, 'getLocalPath' ], $files );
582 // File deps need to be treated separately because they're already prefixed
583 $files = array_merge( $files, $this->getFileDependencies( $context ) );
584 // Filter out any duplicates from getFileDependencies() and others.
585 // Most commonly introduced by compileLessFile(), which always includes the
586 // entry point Less file we already know about.
587 $files = array_values( array_unique( $files ) );
589 // Don't include keys or file paths here, only the hashes. Including that would needlessly
590 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
591 // Any significant ordering is already detected by the definition summary.
592 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
596 * Get the definition summary for this module.
598 * @param ResourceLoaderContext $context
601 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
602 $summary = parent
::getDefinitionSummary( $context );
606 // The following properties are omitted because they don't affect the module reponse:
607 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
608 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
609 // - remoteBasePath (Per T104950)
610 // - dependencies (provided via startup module)
612 // - group (provided via startup module)
625 $options[$member] = $this->{$member};
628 $packageFiles = $this->expandPackageFiles( $context );
629 if ( $packageFiles ) {
630 // Extract the minimum needed:
631 // - The 'main' pointer (included as-is).
632 // - The 'files' array, simplied to only which files exist (the keys of
633 // this array), and something that represents their non-file content.
634 // For packaged files that reflect files directly from disk, the
635 // 'getFileHashes' method tracks this already.
636 // It is important that the keys of the 'files' array are preserved,
637 // as they affect the module output.
638 $packageFiles['files'] = array_map( function ( $fileInfo ) {
639 return $fileInfo['definitionSummary'] ??
( $fileInfo['content'] ??
null );
640 }, $packageFiles['files'] );
644 'options' => $options,
645 'packageFiles' => $packageFiles,
646 'fileHashes' => $this->getFileHashes( $context ),
647 'messageBlob' => $this->getMessageBlob( $context ),
650 $lessVars = $this->getLessVars( $context );
652 $summary[] = [ 'lessVars' => $lessVars ];
659 * @param string|ResourceLoaderFilePath $path
662 protected function getLocalPath( $path ) {
663 if ( $path instanceof ResourceLoaderFilePath
) {
664 return $path->getLocalPath();
667 return "{$this->localBasePath}/$path";
671 * @param string|ResourceLoaderFilePath $path
674 protected function getRemotePath( $path ) {
675 if ( $path instanceof ResourceLoaderFilePath
) {
676 return $path->getRemotePath();
679 return "{$this->remoteBasePath}/$path";
683 * Infer the stylesheet language from a stylesheet file path.
686 * @param string $path
687 * @return string The stylesheet language name
689 public function getStyleSheetLang( $path ) {
690 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
694 * Infer the file type from a package file path.
695 * @param string $path
696 * @return string 'script' or 'data'
698 public static function getPackageFileType( $path ) {
699 if ( preg_match( '/\.json$/i', $path ) ) {
706 * Collates file paths by option (where provided).
708 * @param array $list List of file paths in any combination of index/path
709 * or path/options pairs
710 * @param string $option Option name
711 * @param mixed $default Default value if the option isn't set
712 * @return array List of file paths, collated by $option
714 protected static function collateFilePathListByOption( array $list, $option, $default ) {
716 foreach ( (array)$list as $key => $value ) {
717 if ( is_int( $key ) ) {
718 // File name as the value
719 if ( !isset( $collatedFiles[$default] ) ) {
720 $collatedFiles[$default] = [];
722 $collatedFiles[$default][] = $value;
723 } elseif ( is_array( $value ) ) {
724 // File name as the key, options array as the value
725 $optionValue = $value[$option] ??
$default;
726 if ( !isset( $collatedFiles[$optionValue] ) ) {
727 $collatedFiles[$optionValue] = [];
729 $collatedFiles[$optionValue][] = $key;
732 return $collatedFiles;
736 * Get a list of element that match a key, optionally using a fallback key.
738 * @param array $list List of lists to select from
739 * @param string $key Key to look for in $map
740 * @param string|null $fallback Key to look for in $list if $key doesn't exist
741 * @return array List of elements from $map which matched $key or $fallback,
742 * or an empty list in case of no match
744 protected static function tryForKey( array $list, $key, $fallback = null ) {
745 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
747 } elseif ( is_string( $fallback )
748 && isset( $list[$fallback] )
749 && is_array( $list[$fallback] )
751 return $list[$fallback];
757 * Get a list of script file paths for this module, in order of proper execution.
759 * @param ResourceLoaderContext $context
760 * @return array List of file paths
762 private function getScriptFiles( ResourceLoaderContext
$context ) {
763 $files = array_merge(
765 $this->getLanguageScripts( $context->getLanguage() ),
766 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
768 if ( $context->getDebug() ) {
769 $files = array_merge( $files, $this->debugScripts
);
772 return array_unique( $files, SORT_REGULAR
);
776 * Get the set of language scripts for the given language,
777 * possibly using a fallback language.
779 * @param string $lang
782 private function getLanguageScripts( $lang ) {
783 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
787 $fallbacks = Language
::getFallbacksFor( $lang );
788 foreach ( $fallbacks as $lang ) {
789 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
799 * Get a list of file paths for all styles in this module, in order of proper inclusion.
801 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
804 * @param ResourceLoaderContext $context
805 * @return array List of file paths
807 public function getStyleFiles( ResourceLoaderContext
$context ) {
808 return array_merge_recursive(
809 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
810 self
::collateFilePathListByOption(
811 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
819 * Gets a list of file paths for all skin styles in the module used by
822 * @param string $skinName The name of the skin
823 * @return array A list of file paths collated by media type
825 protected function getSkinStyleFiles( $skinName ) {
826 return self
::collateFilePathListByOption(
827 self
::tryForKey( $this->skinStyles
, $skinName ),
834 * Gets a list of file paths for all skin style files in the module,
835 * for all available skins.
837 * @return array A list of file paths collated by media type
839 protected function getAllSkinStyleFiles() {
841 $internalSkinNames = array_keys( Skin
::getSkinNames() );
842 $internalSkinNames[] = 'default';
844 foreach ( $internalSkinNames as $internalSkinName ) {
845 $styleFiles = array_merge_recursive(
847 $this->getSkinStyleFiles( $internalSkinName )
855 * Returns all style files and all skin style files used by this module.
859 public function getAllStyleFiles() {
860 $collatedStyleFiles = array_merge_recursive(
861 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
862 $this->getAllSkinStyleFiles()
867 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
868 foreach ( $styleFiles as $styleFile ) {
869 $result[] = $this->getLocalPath( $styleFile );
877 * Get the contents of a list of JavaScript files. Helper for getScript().
879 * @param array $scripts List of file paths to scripts to read, remap and concetenate
880 * @return string Concatenated JavaScript data from $scripts
881 * @throws MWException
883 private function readScriptFiles( array $scripts ) {
884 if ( empty( $scripts ) ) {
888 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
889 $localPath = $this->getLocalPath( $fileName );
890 if ( !file_exists( $localPath ) ) {
891 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
893 $contents = $this->stripBom( file_get_contents( $localPath ) );
894 $js .= $contents . "\n";
900 * Get the contents of a list of CSS files.
902 * @internal This is considered a private method. Exposed for internal use by WebInstallerOutput.
903 * @param array $styles Map of media type to file paths to read, remap, and concatenate
905 * @param ResourceLoaderContext $context
906 * @return array List of concatenated and remapped CSS data from $styles,
907 * keyed by media type
908 * @throws MWException
910 public function readStyleFiles( array $styles, $flip, $context ) {
914 foreach ( $styles as $media => $files ) {
915 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
917 foreach ( $uniqueFiles as $file ) {
918 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
920 $styles[$media] = implode( "\n", $styleFiles );
926 * Reads a style file.
928 * This method can be used as a callback for array_map()
930 * @param string $path File path of style file to read
932 * @param ResourceLoaderContext $context
934 * @return string CSS data in script file
935 * @throws MWException If the file doesn't exist
937 protected function readStyleFile( $path, $flip, $context ) {
938 $localPath = $this->getLocalPath( $path );
939 $remotePath = $this->getRemotePath( $path );
940 if ( !file_exists( $localPath ) ) {
941 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
942 wfDebugLog( 'resourceloader', $msg );
943 throw new MWException( $msg );
946 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
947 $style = $this->compileLessFile( $localPath, $context );
948 $this->hasGeneratedStyles
= true;
950 $style = $this->stripBom( file_get_contents( $localPath ) );
954 $style = CSSJanus
::transform( $style, true, false );
956 $localDir = dirname( $localPath );
957 $remoteDir = dirname( $remotePath );
958 // Get and register local file references
959 $localFileRefs = CSSMin
::getLocalFileReferences( $style, $localDir );
960 foreach ( $localFileRefs as $file ) {
961 if ( file_exists( $file ) ) {
962 $this->localFileRefs
[] = $file;
964 $this->missingLocalFileRefs
[] = $file;
967 // Don't cache this call. remap() ensures data URIs embeds are up to date,
968 // and urls contain correct content hashes in their query string. (T128668)
969 return CSSMin
::remap( $style, $localDir, $remoteDir, true );
973 * Get whether CSS for this module should be flipped
974 * @param ResourceLoaderContext $context
977 public function getFlip( $context ) {
978 return $context->getDirection() === 'rtl' && !$this->noflip
;
982 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
984 * @return array Array of strings
986 public function getTargets() {
987 return $this->targets
;
991 * Get the module's load type.
996 public function getType() {
997 $canBeStylesOnly = !(
998 // All options except 'styles', 'skinStyles' and 'debugRaw'
1000 ||
$this->debugScripts
1002 ||
$this->languageScripts
1003 ||
$this->skinScripts
1004 ||
$this->dependencies
1006 ||
$this->skipFunction
1009 return $canBeStylesOnly ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;
1013 * Compile a LESS file into CSS.
1015 * Keeps track of all used files and adds them to localFileRefs.
1018 * @since 1.27 Added $context paramter.
1019 * @throws Exception If less.php encounters a parse error
1020 * @param string $fileName File path of LESS source
1021 * @param ResourceLoaderContext $context Context in which to generate script
1022 * @return string CSS source
1024 protected function compileLessFile( $fileName, ResourceLoaderContext
$context ) {
1028 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
1031 $vars = $this->getLessVars( $context );
1032 // Construct a cache key from the LESS file name, and a hash digest
1033 // of the LESS variables used for compilation.
1035 $varsHash = hash( 'md4', serialize( $vars ) );
1036 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
1037 $cachedCompile = $cache->get( $cacheKey );
1039 // If we got a cached value, we have to validate it by getting a
1040 // checksum of all the files that were loaded by the parser and
1041 // ensuring it matches the cached entry's.
1042 if ( isset( $cachedCompile['hash'] ) ) {
1043 $contentHash = FileContentsHasher
::getFileContentsHash( $cachedCompile['files'] );
1044 if ( $contentHash === $cachedCompile['hash'] ) {
1045 $this->localFileRefs
= array_merge( $this->localFileRefs
, $cachedCompile['files'] );
1046 return $cachedCompile['css'];
1050 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
1051 $css = $compiler->parseFile( $fileName )->getCss();
1052 $files = $compiler->AllParsedFiles();
1053 $this->localFileRefs
= array_merge( $this->localFileRefs
, $files );
1055 // Cache for 24 hours (86400 seconds).
1056 $cache->set( $cacheKey, [
1059 'hash' => FileContentsHasher
::getFileContentsHash( $files ),
1066 * Takes named templates by the module and returns an array mapping.
1067 * @return array Templates mapping template alias to content
1068 * @throws MWException
1070 public function getTemplates() {
1073 foreach ( $this->templates
as $alias => $templatePath ) {
1074 // Alias is optional
1075 if ( is_int( $alias ) ) {
1076 $alias = $templatePath;
1078 $localPath = $this->getLocalPath( $templatePath );
1079 if ( file_exists( $localPath ) ) {
1080 $content = file_get_contents( $localPath );
1081 $templates[$alias] = $this->stripBom( $content );
1083 $msg = __METHOD__
. ": template file not found: \"$localPath\"";
1084 wfDebugLog( 'resourceloader', $msg );
1085 throw new MWException( $msg );
1092 * Internal helper for use by getPackageFiles(), getFileHashes() and getDefinitionSummary().
1094 * This expands the 'packageFiles' definition into something that's (almost) the right format
1095 * for getPackageFiles() to return. It expands shorthands, resolves config vars, and handles
1096 * summarising any non-file data for getVersionHash(). For file-based data, getFileHashes()
1097 * handles it instead, which also ends up in getDefinitionSummary().
1099 * What it does not do is reading the actual contents of any specified files, nor invoking
1100 * the computation callbacks. Those things are done by getPackageFiles() instead to improve
1101 * backend performance by only doing this work when the module response is needed, and not
1102 * when merely computing the version hash for StartupModule, or when checking
1103 * If-None-Match headers for a HTTP 304 response.
1105 * @param ResourceLoaderContext $context
1106 * @return array|null
1107 * @throws MWException If the 'packageFiles' definition is invalid.
1109 private function expandPackageFiles( ResourceLoaderContext
$context ) {
1110 $hash = $context->getHash();
1111 if ( isset( $this->expandedPackageFiles
[$hash] ) ) {
1112 return $this->expandedPackageFiles
[$hash];
1114 if ( $this->packageFiles
=== null ) {
1117 $expandedFiles = [];
1120 foreach ( $this->packageFiles
as $alias => $fileInfo ) {
1121 if ( is_string( $fileInfo ) ) {
1122 $fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
1123 } elseif ( !isset( $fileInfo['name'] ) ) {
1124 $msg = __METHOD__
. ": invalid package file definition for module " .
1125 "\"{$this->getName()}\": 'name' key is required when value is not a string";
1126 wfDebugLog( 'resourceloader', $msg );
1127 throw new MWException( $msg );
1130 // Infer type from alias if needed
1131 $type = $fileInfo['type'] ?? self
::getPackageFileType( $fileInfo['name'] );
1132 $expanded = [ 'type' => $type ];
1133 if ( !empty( $fileInfo['main'] ) ) {
1134 $mainFile = $fileInfo['name'];
1135 if ( $type !== 'script' ) {
1136 $msg = __METHOD__
. ": invalid package file definition for module " .
1137 "\"{$this->getName()}\": main file \"$mainFile\" must be of type \"script\", not \"$type\"";
1138 wfDebugLog( 'resourceloader', $msg );
1139 throw new MWException( $msg );
1143 // Perform expansions (except 'file' and 'callback'), creating one of these keys:
1144 // - 'content': literal value.
1145 // - 'filePath': content to be read from a file.
1146 // - 'callback': content computed by a callable.
1147 if ( isset( $fileInfo['content'] ) ) {
1148 $expanded['content'] = $fileInfo['content'];
1149 } elseif ( isset( $fileInfo['file'] ) ) {
1150 $expanded['filePath'] = $fileInfo['file'];
1151 } elseif ( isset( $fileInfo['callback'] ) ) {
1152 if ( !is_callable( $fileInfo['callback'] ) ) {
1153 $msg = __METHOD__
. ": invalid callback for package file \"{$fileInfo['name']}\"" .
1154 " in module \"{$this->getName()}\"";
1155 wfDebugLog( 'resourceloader', $msg );
1156 throw new MWException( $msg );
1158 if ( isset( $fileInfo['versionCallback'] ) ) {
1159 if ( !is_callable( $fileInfo['versionCallback'] ) ) {
1160 throw new MWException( __METHOD__
. ": invalid versionCallback for file" .
1161 " \"{$fileInfo['name']}\" in module \"{$this->getName()}\"" );
1163 $expanded['definitionSummary'] = ( $fileInfo['versionCallback'] )( $context );
1164 // Don't invoke 'callback' here as it may be expensive (T223260).
1165 $expanded['callback'] = $fileInfo['callback'];
1167 $expanded['content'] = ( $fileInfo['callback'] )( $context );
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 );
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 );