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 protected $targets = [ 'desktop' ];
145 /** @var bool Whether CSSJanus flipping should be skipped for this module */
146 protected $noflip = false;
149 * @var bool Whether getStyleURLsForDebug should return raw file paths,
150 * or return load.php urls
152 protected $hasGeneratedStyles = false;
155 * @var array Place where readStyleFile() tracks file dependencies
158 * [ [file-path], [file-path], ... ]
161 protected $localFileRefs = [];
164 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
165 * Used in tests to detect missing dependencies.
167 protected $missingLocalFileRefs = [];
170 * Constructs a new module from an options array.
172 * @param array $options List of options; if not given or empty, an empty module will be
174 * @param string|null $localBasePath Base path to prepend to all local paths in $options.
176 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
177 * Defaults to $wgResourceBasePath
179 * Below is a description for the $options array:
180 * @throws InvalidArgumentException
181 * @par Construction options:
184 * // Base path to prepend to all local paths in $options. Defaults to $IP
185 * 'localBasePath' => [base path],
186 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
187 * 'remoteBasePath' => [base path],
188 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
189 * 'remoteExtPath' => [base path],
190 * // Equivalent of remoteBasePath, but relative to $wgStylePath
191 * 'remoteSkinPath' => [base path],
192 * // Scripts to always include (cannot be set if 'packageFiles' is also set, see below)
193 * 'scripts' => [file path string or array of file path strings],
194 * // Scripts to include in specific language contexts
195 * 'languageScripts' => [
196 * [language code] => [file path string or array of file path strings],
198 * // Scripts to include in specific skin contexts
200 * [skin name] => [file path string or array of file path strings],
202 * // Scripts to include in debug contexts
203 * 'debugScripts' => [file path string or array of file path strings],
204 * // For package modules: files to be made available for internal require() do not
205 * // need to have 'type' defined; it will be inferred from the file name extension
206 * // if omitted. 'config' can only be used when 'type' is 'data'; the variables are
207 * // resolved with Config::get(). The first entry in 'packageFiles' is always the
208 * // module entry point. If 'packageFiles' is set, 'scripts' cannot also be set.
209 * 'packageFiles' => [
210 * [file path string], // or:
211 * [ 'name' => [file name], 'file' => [file path], 'type' => 'script'|'data' ], // or:
212 * [ 'name' => [name], 'content' => [string], 'type' => 'script'|'data' ], // or:
213 * [ 'name' => [name], 'callback' => [callable], 'type' => 'script'|'data' ],
214 * [ 'name' => [name], 'config' => [ [config var name], ... ], 'type' => 'data' ],
215 * [ 'name' => [name], 'config' => [ [JS name] => [PHP name] ], 'type' => 'data' ],
217 * // Modules which must be loaded before this module
218 * 'dependencies' => [module name string or array of module name strings],
220 * [template alias with file.ext] => [file path to a template file],
222 * // Styles to always load
223 * 'styles' => [file path string or array of file path strings],
224 * // Styles to include in specific skin contexts
226 * [skin name] => [file path string or array of file path strings],
228 * // Messages to always load
229 * 'messages' => [array of message key strings],
230 * // Group which this module should be loaded together with
231 * 'group' => [group name string],
232 * // Function that, if it returns true, makes the loader skip this module.
233 * // The file must contain valid JavaScript for execution in a private function.
234 * // The file must not contain the "function () {" and "}" wrapper though.
235 * 'skipFunction' => [file path]
239 public function __construct(
241 $localBasePath = null,
242 $remoteBasePath = null
244 // Flag to decide whether to automagically add the mediawiki.template module
245 $hasTemplates = false;
246 // localBasePath and remoteBasePath both have unbelievably long fallback chains
247 // and need to be handled separately.
248 list( $this->localBasePath
, $this->remoteBasePath
) =
249 self
::extractBasePaths( $options, $localBasePath, $remoteBasePath );
251 // Extract, validate and normalise remaining options
252 foreach ( $options as $member => $option ) {
254 // Lists of file paths
259 $this->{$member} = is_array( $option ) ?
$option : [ $option ];
262 $hasTemplates = true;
263 $this->{$member} = is_array( $option ) ?
$option : [ $option ];
265 // Collated lists of file paths
266 case 'languageScripts':
269 if ( !is_array( $option ) ) {
270 throw new InvalidArgumentException(
271 "Invalid collated file path list error. " .
272 "'$option' given, array expected."
275 foreach ( $option as $key => $value ) {
276 if ( !is_string( $key ) ) {
277 throw new InvalidArgumentException(
278 "Invalid collated file path list key error. " .
279 "'$key' given, string expected."
282 $this->{$member}[$key] = is_array( $value ) ?
$value : [ $value ];
286 $this->deprecated
= $option;
293 $option = array_values( array_unique( (array)$option ) );
296 $this->{$member} = $option;
301 $this->{$member} = (string)$option;
306 $this->{$member} = (bool)$option;
310 if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
311 throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
313 if ( $hasTemplates ) {
314 $this->dependencies
[] = 'mediawiki.template';
315 // Ensure relevant template compiler module gets loaded
316 foreach ( $this->templates
as $alias => $templatePath ) {
317 if ( is_int( $alias ) ) {
318 $alias = $this->getPath( $templatePath );
320 $suffix = explode( '.', $alias );
321 $suffix = end( $suffix );
322 $compilerModule = 'mediawiki.template.' . $suffix;
323 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies
) ) {
324 $this->dependencies
[] = $compilerModule;
331 * Extract a pair of local and remote base paths from module definition information.
332 * Implementation note: the amount of global state used in this function is staggering.
334 * @param array $options Module definition
335 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
337 * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
338 * to $wgResourceBasePath
339 * @return array [ localBasePath, remoteBasePath ]
341 public static function extractBasePaths(
343 $localBasePath = null,
344 $remoteBasePath = null
346 global $IP, $wgResourceBasePath;
348 // The different ways these checks are done, and their ordering, look very silly,
349 // but were preserved for backwards-compatibility just in case. Tread lightly.
351 if ( $localBasePath === null ) {
352 $localBasePath = $IP;
354 if ( $remoteBasePath === null ) {
355 $remoteBasePath = $wgResourceBasePath;
358 if ( isset( $options['remoteExtPath'] ) ) {
359 global $wgExtensionAssetsPath;
360 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
363 if ( isset( $options['remoteSkinPath'] ) ) {
365 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
368 if ( array_key_exists( 'localBasePath', $options ) ) {
369 $localBasePath = (string)$options['localBasePath'];
372 if ( array_key_exists( 'remoteBasePath', $options ) ) {
373 $remoteBasePath = (string)$options['remoteBasePath'];
376 return [ $localBasePath, $remoteBasePath ];
380 * Gets all scripts for a given context concatenated together.
382 * @param ResourceLoaderContext $context Context in which to generate script
383 * @return string|array JavaScript code for $context, or package files data structure
385 public function getScript( ResourceLoaderContext
$context ) {
386 $deprecationScript = $this->getDeprecationInformation();
387 if ( $this->packageFiles
!== null ) {
388 $packageFiles = $this->getPackageFiles( $context );
389 if ( $deprecationScript ) {
390 $mainFile =& $packageFiles['files'][$packageFiles['main']];
391 $mainFile['content'] = $deprecationScript . $mainFile['content'];
393 return $packageFiles;
396 $files = $this->getScriptFiles( $context );
397 return $deprecationScript . $this->readScriptFiles( $files );
401 * @param ResourceLoaderContext $context
404 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
406 foreach ( $this->getScriptFiles( $context ) as $file ) {
407 $urls[] = OutputPage
::transformResourcePath(
409 $this->getRemotePath( $file )
418 public function supportsURLLoading() {
419 // If package files are involved, don't support URL loading, because that breaks
420 // scoped require() functions
421 return $this->debugRaw
&& !$this->packageFiles
;
425 * Get all styles for a given context.
427 * @param ResourceLoaderContext $context
428 * @return array CSS code for $context as an associative array mapping media type to CSS text.
430 public function getStyles( ResourceLoaderContext
$context ) {
431 $styles = $this->readStyleFiles(
432 $this->getStyleFiles( $context ),
433 $this->getFlip( $context ),
436 // Collect referenced files
437 $this->saveFileDependencies( $context, $this->localFileRefs
);
443 * @param ResourceLoaderContext $context
446 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
447 if ( $this->hasGeneratedStyles
) {
448 // Do the default behaviour of returning a url back to load.php
449 // but with only=styles.
450 return parent
::getStyleURLsForDebug( $context );
452 // Our module consists entirely of real css files,
453 // in debug mode we can load those directly.
455 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
456 $urls[$mediaType] = [];
457 foreach ( $list as $file ) {
458 $urls[$mediaType][] = OutputPage
::transformResourcePath(
460 $this->getRemotePath( $file )
468 * Gets list of message keys used by this module.
470 * @return array List of message keys
472 public function getMessages() {
473 return $this->messages
;
477 * Gets the name of the group this module should be loaded in.
479 * @return string Group name
481 public function getGroup() {
486 * Gets list of names of modules this module depends on.
487 * @param ResourceLoaderContext|null $context
488 * @return array List of module names
490 public function getDependencies( ResourceLoaderContext
$context = null ) {
491 return $this->dependencies
;
495 * Get the skip function.
496 * @return null|string
497 * @throws MWException
499 public function getSkipFunction() {
500 if ( !$this->skipFunction
) {
504 $localPath = $this->getLocalPath( $this->skipFunction
);
505 if ( !file_exists( $localPath ) ) {
506 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
508 $contents = $this->stripBom( file_get_contents( $localPath ) );
513 * Disable module content versioning.
515 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
516 * involved with building the full module content inside a startup request.
520 public function enableModuleContentVersion() {
525 * Helper method for getDefinitionSummary.
527 * @see ResourceLoaderModule::getFileDependencies
528 * @param ResourceLoaderContext $context
531 private function getFileHashes( ResourceLoaderContext
$context ) {
534 // Flatten style files into $files
535 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
536 foreach ( $styles as $styleFiles ) {
537 $files = array_merge( $files, $styleFiles );
540 $skinFiles = self
::collateFilePathListByOption(
541 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
545 foreach ( $skinFiles as $styleFiles ) {
546 $files = array_merge( $files, $styleFiles );
549 // Extract file names for package files
550 $expandedPackageFiles = $this->expandPackageFiles( $context );
551 $packageFiles = $expandedPackageFiles ?
552 array_filter( array_map( function ( $fileInfo ) {
553 return $fileInfo['filePath'] ??
null;
554 }, $expandedPackageFiles['files'] ) ) :
557 // Final merge, this should result in a master list of dependent files
558 $files = array_merge(
563 $context->getDebug() ?
$this->debugScripts
: [],
564 $this->getLanguageScripts( $context->getLanguage() ),
565 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
567 if ( $this->skipFunction
) {
568 $files[] = $this->skipFunction
;
570 $files = array_map( [ $this, 'getLocalPath' ], $files );
571 // File deps need to be treated separately because they're already prefixed
572 $files = array_merge( $files, $this->getFileDependencies( $context ) );
573 // Filter out any duplicates from getFileDependencies() and others.
574 // Most commonly introduced by compileLessFile(), which always includes the
575 // entry point Less file we already know about.
576 $files = array_values( array_unique( $files ) );
578 // Don't include keys or file paths here, only the hashes. Including that would needlessly
579 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
580 // Any significant ordering is already detected by the definition summary.
581 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
585 * Get the definition summary for this module.
587 * @param ResourceLoaderContext $context
590 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
591 $summary = parent
::getDefinitionSummary( $context );
595 // The following properties are omitted because they don't affect the module reponse:
596 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
597 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
598 // - remoteBasePath (Per T104950)
599 // - dependencies (provided via startup module)
601 // - group (provided via startup module)
613 $options[$member] = $this->{$member};
616 $packageFiles = $this->expandPackageFiles( $context );
617 if ( $packageFiles ) {
618 // Extract the minimum needed:
619 // - The 'main' pointer (included as-is).
620 // - The 'files' array, simplied to only which files exist (the keys of
621 // this array), and something that represents their non-file content.
622 // For packaged files that reflect files directly from disk, the
623 // 'getFileHashes' method tracks this already.
624 // It is important that the keys of the 'files' array are preserved,
625 // as they affect the module output.
626 $packageFiles['files'] = array_map( function ( $fileInfo ) {
627 return $fileInfo['definitionSummary'] ??
( $fileInfo['content'] ??
null );
628 }, $packageFiles['files'] );
632 'options' => $options,
633 'packageFiles' => $packageFiles,
634 'fileHashes' => $this->getFileHashes( $context ),
635 'messageBlob' => $this->getMessageBlob( $context ),
638 $lessVars = $this->getLessVars( $context );
640 $summary[] = [ 'lessVars' => $lessVars ];
647 * @param string|ResourceLoaderFilePath $path
650 protected function getPath( $path ) {
651 if ( $path instanceof ResourceLoaderFilePath
) {
652 return $path->getPath();
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
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 paramter.
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'] = ( $fileInfo['versionCallback'] )( $context );
1163 // Don't invoke 'callback' here as it may be expensive (T223260).
1164 $expanded['callback'] = $fileInfo['callback'];
1166 $expanded['content'] = ( $fileInfo['callback'] )( $context );
1168 } elseif ( isset( $fileInfo['config'] ) ) {
1169 if ( $type !== 'data' ) {
1170 $msg = __METHOD__
. ": invalid use of \"config\" for package file \"{$fileInfo['name']}\" " .
1171 "in module \"{$this->getName()}\": type must be \"data\" but is \"$type\"";
1172 wfDebugLog( 'resourceloader', $msg );
1173 throw new MWException( $msg );
1175 $expandedConfig = [];
1176 foreach ( $fileInfo['config'] as $key => $var ) {
1177 $expandedConfig[ is_numeric( $key ) ?
$var : $key ] = $this->getConfig()->get( $var );
1179 $expanded['content'] = $expandedConfig;
1180 } elseif ( !empty( $fileInfo['main'] ) ) {
1181 // [ 'name' => 'foo.js', 'main' => true ] is shorthand
1182 $expanded['filePath'] = $fileInfo['name'];
1184 $msg = __METHOD__
. ": invalid package file definition for \"{$fileInfo['name']}\" " .
1185 "in module \"{$this->getName()}\": one of \"file\", \"content\", \"callback\" or \"config\" " .
1187 wfDebugLog( 'resourceloader', $msg );
1188 throw new MWException( $msg );
1191 $expandedFiles[$fileInfo['name']] = $expanded;
1194 if ( $expandedFiles && $mainFile === null ) {
1195 // The first package file that is a script is the main file
1196 foreach ( $expandedFiles as $path => &$file ) {
1197 if ( $file['type'] === 'script' ) {
1205 'main' => $mainFile,
1206 'files' => $expandedFiles
1209 $this->expandedPackageFiles
[$hash] = $result;
1214 * Resolves the package files defintion and generates the content of each package file.
1215 * @param ResourceLoaderContext $context
1216 * @return array Package files data structure, see ResourceLoaderModule::getScript()
1218 public function getPackageFiles( ResourceLoaderContext
$context ) {
1219 if ( $this->packageFiles
=== null ) {
1222 $expandedPackageFiles = $this->expandPackageFiles( $context );
1224 // Expand file contents
1225 foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
1226 // Turn any 'filePath' or 'callback' key into actual 'content',
1227 // and remove the key after that.
1228 if ( isset( $fileInfo['filePath'] ) ) {
1229 $localPath = $this->getLocalPath( $fileInfo['filePath'] );
1230 if ( !file_exists( $localPath ) ) {
1231 $msg = __METHOD__
. ": package file not found: \"$localPath\"" .
1232 " in module \"{$this->getName()}\"";
1233 wfDebugLog( 'resourceloader', $msg );
1234 throw new MWException( $msg );
1236 $content = $this->stripBom( file_get_contents( $localPath ) );
1237 if ( $fileInfo['type'] === 'data' ) {
1238 $content = json_decode( $content );
1240 $fileInfo['content'] = $content;
1241 unset( $fileInfo['filePath'] );
1242 } elseif ( isset( $fileInfo['callback'] ) ) {
1243 $fileInfo['content'] = ( $fileInfo['callback'] )( $context );
1244 unset( $fileInfo['callback'] );
1247 // Not needed for client response, exists for getDefinitionSummary().
1248 unset( $fileInfo['definitionSummary'] );
1251 return $expandedPackageFiles;
1255 * Takes an input string and removes the UTF-8 BOM character if present
1257 * We need to remove these after reading a file, because we concatenate our files and
1258 * the BOM character is not valid in the middle of a string.
1259 * We already assume UTF-8 everywhere, so this should be safe.
1261 * @param string $input
1262 * @return string Input minus the intial BOM char
1264 protected function stripBom( $input ) {
1265 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1266 return substr( $input, 3 );