3 * ResourceLoader module based on local JavaScript/CSS files.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Trevor Parscal
22 * @author Roan Kattouw
26 * ResourceLoader module based on local JavaScript/CSS files.
28 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
30 /** @var string Local base path, see __construct() */
31 protected $localBasePath = '';
33 /** @var string Remote base path, see __construct() */
34 protected $remoteBasePath = '';
36 /** @var array Saves a list of the templates named by the modules. */
37 protected $templates = [];
40 * @var array List of paths to JavaScript files to always include
43 * [ [file-path], [file-path], ... ]
46 protected $scripts = [];
49 * @var array List of JavaScript files to include when using a specific language
52 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
55 protected $languageScripts = [];
58 * @var array List of JavaScript files to include when using a specific skin
61 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
64 protected $skinScripts = [];
67 * @var array List of paths to JavaScript files to include in debug mode
70 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
73 protected $debugScripts = [];
76 * @var array List of paths to CSS files to always include
79 * [ [file-path], [file-path], ... ]
82 protected $styles = [];
85 * @var array List of paths to CSS files to include when using specific skins
88 * [ [file-path], [file-path], ... ]
91 protected $skinStyles = [];
94 * @var array List of packaged files to make available through require()
97 * [ [file-path], [file-path], ... ]
100 protected $packageFiles = null;
103 * @var array Expanded versions of $packageFiles, lazy-computed by expandPackageFiles();
104 * keyed by context hash
106 private $expandedPackageFiles = [];
109 * @var array List of modules this module depends on
112 * [ [file-path], [file-path], ... ]
115 protected $dependencies = [];
118 * @var string File name containing the body of the skip function
120 protected $skipFunction = null;
123 * @var array List of message keys used by this module
126 * [ [message-key], [message-key], ... ]
129 protected $messages = [];
131 /** @var string Name of group to load this module in */
134 /** @var bool Link to raw files in debug mode */
135 protected $debugRaw = true;
137 /** @var bool Whether mw.loader.state() call should be omitted */
138 protected $raw = false;
140 protected $targets = [ 'desktop' ];
142 /** @var bool Whether CSSJanus flipping should be skipped for this module */
143 protected $noflip = false;
146 * @var bool Whether getStyleURLsForDebug should return raw file paths,
147 * or return load.php urls
149 protected $hasGeneratedStyles = false;
152 * @var array Place where readStyleFile() tracks file dependencies
155 * [ [file-path], [file-path], ... ]
158 protected $localFileRefs = [];
161 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
162 * Used in tests to detect missing dependencies.
164 protected $missingLocalFileRefs = [];
167 * Constructs a new module from an options array.
169 * @param array $options List of options; if not given or empty, an empty module will be
171 * @param string|null $localBasePath Base path to prepend to all local paths in $options.
173 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
174 * Defaults to $wgResourceBasePath
176 * Below is a description for the $options array:
177 * @throws InvalidArgumentException
178 * @par Construction options:
181 * // Base path to prepend to all local paths in $options. Defaults to $IP
182 * 'localBasePath' => [base path],
183 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
184 * 'remoteBasePath' => [base path],
185 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
186 * 'remoteExtPath' => [base path],
187 * // Equivalent of remoteBasePath, but relative to $wgStylePath
188 * 'remoteSkinPath' => [base path],
189 * // Scripts to always include (cannot be set if 'packageFiles' is also set, see below)
190 * 'scripts' => [file path string or array of file path strings],
191 * // Scripts to include in specific language contexts
192 * 'languageScripts' => [
193 * [language code] => [file path string or array of file path strings],
195 * // Scripts to include in specific skin contexts
197 * [skin name] => [file path string or array of file path strings],
199 * // Scripts to include in debug contexts
200 * 'debugScripts' => [file path string or array of file path strings],
201 * // For package modules: files to make available for internal require() use
202 * // 'type' is optional, and will be inferred from the file name extension if omitted
203 * // 'config' can only be used when 'type' is 'data'; vars are resolved with Config::get()
204 * // If 'packageFiles' is set, 'scripts' cannot also be set
205 * 'packageFiles' => [
206 * [file path string], // or:
207 * [ 'name' => [file name], 'file' => [file path], 'type' => 'script'|'data' ], // or:
208 * [ 'name' => [name], 'content' => [string], 'type' => 'script'|'data' ], // or:
209 * [ 'name' => [name], 'callback' => [callable], 'type' => 'script'|'data' ],
210 * [ 'name' => [name], 'config' => [ [config var name], ... ], 'type' => 'data' ],
211 * [ 'name' => [name], 'config' => [ [JS name] => [PHP name] ], 'type' => 'data' ],
213 * // Modules which must be loaded before this module
214 * 'dependencies' => [module name string or array of module name strings],
216 * [template alias with file.ext] => [file path to a template file],
218 * // Styles to always load
219 * 'styles' => [file path string or array of file path strings],
220 * // Styles to include in specific skin contexts
222 * [skin name] => [file path string or array of file path strings],
224 * // Messages to always load
225 * 'messages' => [array of message key strings],
226 * // Group which this module should be loaded together with
227 * 'group' => [group name string],
228 * // Function that, if it returns true, makes the loader skip this module.
229 * // The file must contain valid JavaScript for execution in a private function.
230 * // The file must not contain the "function () {" and "}" wrapper though.
231 * 'skipFunction' => [file path]
235 public function __construct(
237 $localBasePath = null,
238 $remoteBasePath = null
240 // Flag to decide whether to automagically add the mediawiki.template module
241 $hasTemplates = false;
242 // localBasePath and remoteBasePath both have unbelievably long fallback chains
243 // and need to be handled separately.
244 list( $this->localBasePath
, $this->remoteBasePath
) =
245 self
::extractBasePaths( $options, $localBasePath, $remoteBasePath );
247 // Extract, validate and normalise remaining options
248 foreach ( $options as $member => $option ) {
250 // Lists of file paths
255 $this->{$member} = (array)$option;
258 $hasTemplates = true;
259 $this->{$member} = (array)$option;
261 // Collated lists of file paths
262 case 'languageScripts':
265 if ( !is_array( $option ) ) {
266 throw new InvalidArgumentException(
267 "Invalid collated file path list error. " .
268 "'$option' given, array expected."
271 foreach ( $option as $key => $value ) {
272 if ( !is_string( $key ) ) {
273 throw new InvalidArgumentException(
274 "Invalid collated file path list key error. " .
275 "'$key' given, string expected."
278 $this->{$member}[$key] = (array)$value;
282 $this->deprecated
= $option;
289 $option = array_values( array_unique( (array)$option ) );
292 $this->{$member} = $option;
297 $this->{$member} = (string)$option;
303 $this->{$member} = (bool)$option;
307 if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
308 throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
310 if ( $hasTemplates ) {
311 $this->dependencies
[] = 'mediawiki.template';
312 // Ensure relevant template compiler module gets loaded
313 foreach ( $this->templates
as $alias => $templatePath ) {
314 if ( is_int( $alias ) ) {
315 $alias = $templatePath;
317 $suffix = explode( '.', $alias );
318 $suffix = end( $suffix );
319 $compilerModule = 'mediawiki.template.' . $suffix;
320 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies
) ) {
321 $this->dependencies
[] = $compilerModule;
328 * Extract a pair of local and remote base paths from module definition information.
329 * Implementation note: the amount of global state used in this function is staggering.
331 * @param array $options Module definition
332 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
334 * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
335 * to $wgResourceBasePath
336 * @return array Array( localBasePath, remoteBasePath )
338 public static function extractBasePaths(
340 $localBasePath = null,
341 $remoteBasePath = null
343 global $IP, $wgResourceBasePath;
345 // The different ways these checks are done, and their ordering, look very silly,
346 // but were preserved for backwards-compatibility just in case. Tread lightly.
348 if ( $localBasePath === null ) {
349 $localBasePath = $IP;
351 if ( $remoteBasePath === null ) {
352 $remoteBasePath = $wgResourceBasePath;
355 if ( isset( $options['remoteExtPath'] ) ) {
356 global $wgExtensionAssetsPath;
357 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
360 if ( isset( $options['remoteSkinPath'] ) ) {
362 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
365 if ( array_key_exists( 'localBasePath', $options ) ) {
366 $localBasePath = (string)$options['localBasePath'];
369 if ( array_key_exists( 'remoteBasePath', $options ) ) {
370 $remoteBasePath = (string)$options['remoteBasePath'];
373 return [ $localBasePath, $remoteBasePath ];
377 * Gets all scripts for a given context concatenated together.
379 * @param ResourceLoaderContext $context Context in which to generate script
380 * @return string|array JavaScript code for $context, or package files data structure
382 public function getScript( ResourceLoaderContext
$context ) {
383 $deprecationScript = $this->getDeprecationInformation();
384 if ( $this->packageFiles
!== null ) {
385 $packageFiles = $this->getPackageFiles( $context );
386 if ( $deprecationScript ) {
387 $mainFile =& $packageFiles['files'][ $packageFiles['main'] ];
388 $mainFile['content'] = $deprecationScript . $mainFile['content'];
390 return $packageFiles;
393 $files = $this->getScriptFiles( $context );
394 return $deprecationScript . $this->readScriptFiles( $files );
398 * @param ResourceLoaderContext $context
401 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
403 foreach ( $this->getScriptFiles( $context ) as $file ) {
404 $urls[] = OutputPage
::transformResourcePath(
406 $this->getRemotePath( $file )
415 public function supportsURLLoading() {
416 // If package files are involved, don't support URL loading, because that breaks
417 // scoped require() functions
418 return $this->debugRaw
&& !$this->packageFiles
;
422 * Get all styles for a given context.
424 * @param ResourceLoaderContext $context
425 * @return array CSS code for $context as an associative array mapping media type to CSS text.
427 public function getStyles( ResourceLoaderContext
$context ) {
428 $styles = $this->readStyleFiles(
429 $this->getStyleFiles( $context ),
430 $this->getFlip( $context ),
433 // Collect referenced files
434 $this->saveFileDependencies( $context, $this->localFileRefs
);
440 * @param ResourceLoaderContext $context
443 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
444 if ( $this->hasGeneratedStyles
) {
445 // Do the default behaviour of returning a url back to load.php
446 // but with only=styles.
447 return parent
::getStyleURLsForDebug( $context );
449 // Our module consists entirely of real css files,
450 // in debug mode we can load those directly.
452 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
453 $urls[$mediaType] = [];
454 foreach ( $list as $file ) {
455 $urls[$mediaType][] = OutputPage
::transformResourcePath(
457 $this->getRemotePath( $file )
465 * Gets list of message keys used by this module.
467 * @return array List of message keys
469 public function getMessages() {
470 return $this->messages
;
474 * Gets the name of the group this module should be loaded in.
476 * @return string Group name
478 public function getGroup() {
483 * Gets list of names of modules this module depends on.
484 * @param ResourceLoaderContext|null $context
485 * @return array List of module names
487 public function getDependencies( ResourceLoaderContext
$context = null ) {
488 return $this->dependencies
;
492 * Get the skip function.
493 * @return null|string
494 * @throws MWException
496 public function getSkipFunction() {
497 if ( !$this->skipFunction
) {
501 $localPath = $this->getLocalPath( $this->skipFunction
);
502 if ( !file_exists( $localPath ) ) {
503 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
505 $contents = $this->stripBom( file_get_contents( $localPath ) );
512 public function isRaw() {
517 * Disable module content versioning.
519 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
520 * involved with building the full module content inside a startup request.
524 public function enableModuleContentVersion() {
529 * Helper method for getDefinitionSummary.
531 * @see ResourceLoaderModule::getFileDependencies
532 * @param ResourceLoaderContext $context
535 private function getFileHashes( ResourceLoaderContext
$context ) {
538 // Flatten style files into $files
539 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
540 foreach ( $styles as $styleFiles ) {
541 $files = array_merge( $files, $styleFiles );
544 $skinFiles = self
::collateFilePathListByOption(
545 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
549 foreach ( $skinFiles as $styleFiles ) {
550 $files = array_merge( $files, $styleFiles );
553 // Extract file names for package files
554 $expandedPackageFiles = $this->expandPackageFiles( $context );
555 $packageFiles = $expandedPackageFiles ?
556 array_filter( array_map( function ( $fileInfo ) {
557 return $fileInfo['filePath'] ??
null;
558 }, $expandedPackageFiles['files'] ) ) :
561 // Final merge, this should result in a master list of dependent files
562 $files = array_merge(
567 $context->getDebug() ?
$this->debugScripts
: [],
568 $this->getLanguageScripts( $context->getLanguage() ),
569 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
571 if ( $this->skipFunction
) {
572 $files[] = $this->skipFunction
;
574 $files = array_map( [ $this, 'getLocalPath' ], $files );
575 // File deps need to be treated separately because they're already prefixed
576 $files = array_merge( $files, $this->getFileDependencies( $context ) );
577 // Filter out any duplicates from getFileDependencies() and others.
578 // Most commonly introduced by compileLessFile(), which always includes the
579 // entry point Less file we already know about.
580 $files = array_values( array_unique( $files ) );
582 // Don't include keys or file paths here, only the hashes. Including that would needlessly
583 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
584 // Any significant ordering is already detected by the definition summary.
585 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
589 * Get the definition summary for this module.
591 * @param ResourceLoaderContext $context
594 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
595 $summary = parent
::getDefinitionSummary( $context );
599 // The following properties are omitted because they don't affect the module reponse:
600 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
601 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
602 // - remoteBasePath (Per T104950)
603 // - dependencies (provided via startup module)
605 // - group (provided via startup module)
618 $options[$member] = $this->{$member};
622 'options' => $options,
623 'packageFiles' => $this->expandPackageFiles( $context ),
624 'fileHashes' => $this->getFileHashes( $context ),
625 'messageBlob' => $this->getMessageBlob( $context ),
628 $lessVars = $this->getLessVars( $context );
630 $summary[] = [ 'lessVars' => $lessVars ];
637 * @param string|ResourceLoaderFilePath $path
640 protected function getLocalPath( $path ) {
641 if ( $path instanceof ResourceLoaderFilePath
) {
642 return $path->getLocalPath();
645 return "{$this->localBasePath}/$path";
649 * @param string|ResourceLoaderFilePath $path
652 protected function getRemotePath( $path ) {
653 if ( $path instanceof ResourceLoaderFilePath
) {
654 return $path->getRemotePath();
657 return "{$this->remoteBasePath}/$path";
661 * Infer the stylesheet language from a stylesheet file path.
664 * @param string $path
665 * @return string The stylesheet language name
667 public function getStyleSheetLang( $path ) {
668 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
672 * Infer the file type from a package file path.
673 * @param string $path
674 * @return string 'script' or 'data'
676 public static function getPackageFileType( $path ) {
677 if ( preg_match( '/\.json$/i', $path ) ) {
684 * Collates file paths by option (where provided).
686 * @param array $list List of file paths in any combination of index/path
687 * or path/options pairs
688 * @param string $option Option name
689 * @param mixed $default Default value if the option isn't set
690 * @return array List of file paths, collated by $option
692 protected static function collateFilePathListByOption( array $list, $option, $default ) {
694 foreach ( (array)$list as $key => $value ) {
695 if ( is_int( $key ) ) {
696 // File name as the value
697 if ( !isset( $collatedFiles[$default] ) ) {
698 $collatedFiles[$default] = [];
700 $collatedFiles[$default][] = $value;
701 } elseif ( is_array( $value ) ) {
702 // File name as the key, options array as the value
703 $optionValue = $value[$option] ??
$default;
704 if ( !isset( $collatedFiles[$optionValue] ) ) {
705 $collatedFiles[$optionValue] = [];
707 $collatedFiles[$optionValue][] = $key;
710 return $collatedFiles;
714 * Get a list of element that match a key, optionally using a fallback key.
716 * @param array $list List of lists to select from
717 * @param string $key Key to look for in $map
718 * @param string|null $fallback Key to look for in $list if $key doesn't exist
719 * @return array List of elements from $map which matched $key or $fallback,
720 * or an empty list in case of no match
722 protected static function tryForKey( array $list, $key, $fallback = null ) {
723 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
725 } elseif ( is_string( $fallback )
726 && isset( $list[$fallback] )
727 && is_array( $list[$fallback] )
729 return $list[$fallback];
735 * Get a list of script file paths for this module, in order of proper execution.
737 * @param ResourceLoaderContext $context
738 * @return array List of file paths
740 private function getScriptFiles( ResourceLoaderContext
$context ) {
741 $files = array_merge(
743 $this->getLanguageScripts( $context->getLanguage() ),
744 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
746 if ( $context->getDebug() ) {
747 $files = array_merge( $files, $this->debugScripts
);
750 return array_unique( $files, SORT_REGULAR
);
754 * Get the set of language scripts for the given language,
755 * possibly using a fallback language.
757 * @param string $lang
760 private function getLanguageScripts( $lang ) {
761 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
765 $fallbacks = Language
::getFallbacksFor( $lang );
766 foreach ( $fallbacks as $lang ) {
767 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
777 * Get a list of file paths for all styles in this module, in order of proper inclusion.
779 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
782 * @param ResourceLoaderContext $context
783 * @return array List of file paths
785 public function getStyleFiles( ResourceLoaderContext
$context ) {
786 return array_merge_recursive(
787 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
788 self
::collateFilePathListByOption(
789 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
797 * Gets a list of file paths for all skin styles in the module used by
800 * @param string $skinName The name of the skin
801 * @return array A list of file paths collated by media type
803 protected function getSkinStyleFiles( $skinName ) {
804 return self
::collateFilePathListByOption(
805 self
::tryForKey( $this->skinStyles
, $skinName ),
812 * Gets a list of file paths for all skin style files in the module,
813 * for all available skins.
815 * @return array A list of file paths collated by media type
817 protected function getAllSkinStyleFiles() {
819 $internalSkinNames = array_keys( Skin
::getSkinNames() );
820 $internalSkinNames[] = 'default';
822 foreach ( $internalSkinNames as $internalSkinName ) {
823 $styleFiles = array_merge_recursive(
825 $this->getSkinStyleFiles( $internalSkinName )
833 * Returns all style files and all skin style files used by this module.
837 public function getAllStyleFiles() {
838 $collatedStyleFiles = array_merge_recursive(
839 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
840 $this->getAllSkinStyleFiles()
845 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
846 foreach ( $styleFiles as $styleFile ) {
847 $result[] = $this->getLocalPath( $styleFile );
855 * Get the contents of a list of JavaScript files. Helper for getScript().
857 * @param array $scripts List of file paths to scripts to read, remap and concetenate
858 * @return string Concatenated JavaScript data from $scripts
859 * @throws MWException
861 private function readScriptFiles( array $scripts ) {
862 if ( empty( $scripts ) ) {
866 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
867 $localPath = $this->getLocalPath( $fileName );
868 if ( !file_exists( $localPath ) ) {
869 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
871 $contents = $this->stripBom( file_get_contents( $localPath ) );
872 $js .= $contents . "\n";
878 * Get the contents of a list of CSS files.
880 * @internal This is considered a private method. Exposed for internal use by WebInstallerOutput.
881 * @param array $styles Map of media type to file paths to read, remap, and concatenate
883 * @param ResourceLoaderContext $context
884 * @return array List of concatenated and remapped CSS data from $styles,
885 * keyed by media type
886 * @throws MWException
888 public function readStyleFiles( array $styles, $flip, $context ) {
892 foreach ( $styles as $media => $files ) {
893 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
895 foreach ( $uniqueFiles as $file ) {
896 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
898 $styles[$media] = implode( "\n", $styleFiles );
904 * Reads a style file.
906 * This method can be used as a callback for array_map()
908 * @param string $path File path of style file to read
910 * @param ResourceLoaderContext $context
912 * @return string CSS data in script file
913 * @throws MWException If the file doesn't exist
915 protected function readStyleFile( $path, $flip, $context ) {
916 $localPath = $this->getLocalPath( $path );
917 $remotePath = $this->getRemotePath( $path );
918 if ( !file_exists( $localPath ) ) {
919 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
920 wfDebugLog( 'resourceloader', $msg );
921 throw new MWException( $msg );
924 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
925 $style = $this->compileLessFile( $localPath, $context );
926 $this->hasGeneratedStyles
= true;
928 $style = $this->stripBom( file_get_contents( $localPath ) );
932 $style = CSSJanus
::transform( $style, true, false );
934 $localDir = dirname( $localPath );
935 $remoteDir = dirname( $remotePath );
936 // Get and register local file references
937 $localFileRefs = CSSMin
::getLocalFileReferences( $style, $localDir );
938 foreach ( $localFileRefs as $file ) {
939 if ( file_exists( $file ) ) {
940 $this->localFileRefs
[] = $file;
942 $this->missingLocalFileRefs
[] = $file;
945 // Don't cache this call. remap() ensures data URIs embeds are up to date,
946 // and urls contain correct content hashes in their query string. (T128668)
947 return CSSMin
::remap( $style, $localDir, $remoteDir, true );
951 * Get whether CSS for this module should be flipped
952 * @param ResourceLoaderContext $context
955 public function getFlip( $context ) {
956 return $context->getDirection() === 'rtl' && !$this->noflip
;
960 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
962 * @return array Array of strings
964 public function getTargets() {
965 return $this->targets
;
969 * Get the module's load type.
974 public function getType() {
975 $canBeStylesOnly = !(
976 // All options except 'styles', 'skinStyles' and 'debugRaw'
978 ||
$this->debugScripts
980 ||
$this->languageScripts
981 ||
$this->skinScripts
982 ||
$this->dependencies
984 ||
$this->skipFunction
987 return $canBeStylesOnly ? self
::LOAD_STYLES
: self
::LOAD_GENERAL
;
991 * Compile a LESS file into CSS.
993 * Keeps track of all used files and adds them to localFileRefs.
996 * @since 1.27 Added $context paramter.
997 * @throws Exception If less.php encounters a parse error
998 * @param string $fileName File path of LESS source
999 * @param ResourceLoaderContext $context Context in which to generate script
1000 * @return string CSS source
1002 protected function compileLessFile( $fileName, ResourceLoaderContext
$context ) {
1006 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
1009 $vars = $this->getLessVars( $context );
1010 // Construct a cache key from the LESS file name, and a hash digest
1011 // of the LESS variables used for compilation.
1013 $varsHash = hash( 'md4', serialize( $vars ) );
1014 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
1015 $cachedCompile = $cache->get( $cacheKey );
1017 // If we got a cached value, we have to validate it by getting a
1018 // checksum of all the files that were loaded by the parser and
1019 // ensuring it matches the cached entry's.
1020 if ( isset( $cachedCompile['hash'] ) ) {
1021 $contentHash = FileContentsHasher
::getFileContentsHash( $cachedCompile['files'] );
1022 if ( $contentHash === $cachedCompile['hash'] ) {
1023 $this->localFileRefs
= array_merge( $this->localFileRefs
, $cachedCompile['files'] );
1024 return $cachedCompile['css'];
1028 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
1029 $css = $compiler->parseFile( $fileName )->getCss();
1030 $files = $compiler->AllParsedFiles();
1031 $this->localFileRefs
= array_merge( $this->localFileRefs
, $files );
1033 // Cache for 24 hours (86400 seconds).
1034 $cache->set( $cacheKey, [
1037 'hash' => FileContentsHasher
::getFileContentsHash( $files ),
1044 * Takes named templates by the module and returns an array mapping.
1045 * @return array Templates mapping template alias to content
1046 * @throws MWException
1048 public function getTemplates() {
1051 foreach ( $this->templates
as $alias => $templatePath ) {
1052 // Alias is optional
1053 if ( is_int( $alias ) ) {
1054 $alias = $templatePath;
1056 $localPath = $this->getLocalPath( $templatePath );
1057 if ( file_exists( $localPath ) ) {
1058 $content = file_get_contents( $localPath );
1059 $templates[$alias] = $this->stripBom( $content );
1061 $msg = __METHOD__
. ": template file not found: \"$localPath\"";
1062 wfDebugLog( 'resourceloader', $msg );
1063 throw new MWException( $msg );
1070 * Expand the packageFiles definition into something that's (almost) the right format for
1071 * getPackageFiles() to return. This expands shorthands, resolves config vars and callbacks,
1072 * but does not expand file paths or read the actual contents of files. Those things are done
1073 * by getPackageFiles().
1075 * This is split up in this way so that getFileHashes() can get a list of file names, and
1076 * getDefinitionSummary() can get config vars and callback results in their expanded form.
1078 * @param ResourceLoaderContext $context
1079 * @return array|null
1081 private function expandPackageFiles( ResourceLoaderContext
$context ) {
1082 $hash = $context->getHash();
1083 if ( isset( $this->expandedPackageFiles
[$hash] ) ) {
1084 return $this->expandedPackageFiles
[$hash];
1086 if ( $this->packageFiles
=== null ) {
1089 $expandedFiles = [];
1092 foreach ( $this->packageFiles
as $alias => $fileInfo ) {
1093 if ( is_string( $fileInfo ) ) {
1094 $fileInfo = [ 'name' => $fileInfo, 'file' => $fileInfo ];
1095 } elseif ( !isset( $fileInfo['name'] ) ) {
1096 $msg = __METHOD__
. ": invalid package file definition for module " .
1097 "\"{$this->getName()}\": 'name' key is required when value is not a string";
1098 wfDebugLog( 'resourceloader', $msg );
1099 throw new MWException( $msg );
1102 // Infer type from alias if needed
1103 $type = $fileInfo['type'] ?? self
::getPackageFileType( $fileInfo['name'] );
1104 $expanded = [ 'type' => $type ];
1105 if ( !empty( $fileInfo['main'] ) ) {
1106 $mainFile = $fileInfo['name'];
1107 if ( $type !== 'script' ) {
1108 $msg = __METHOD__
. ": invalid package file definition for module " .
1109 "\"{$this->getName()}\": main file \"$mainFile\" must be of type \"script\", not \"$type\"";
1110 wfDebugLog( 'resourceloader', $msg );
1111 throw new MWException( $msg );
1115 if ( isset( $fileInfo['content'] ) ) {
1116 $expanded['content'] = $fileInfo['content'];
1117 } elseif ( isset( $fileInfo['file'] ) ) {
1118 $expanded['filePath'] = $fileInfo['file'];
1119 } elseif ( isset( $fileInfo['callback'] ) ) {
1120 if ( is_callable( $fileInfo['callback'] ) ) {
1121 $expanded['content'] = $fileInfo['callback']( $context );
1123 $msg = __METHOD__
. ": invalid callback for package file \"{$fileInfo['name']}\"" .
1124 " in module \"{$this->getName()}\"";
1125 wfDebugLog( 'resourceloader', $msg );
1126 throw new MWException( $msg );
1128 } elseif ( isset( $fileInfo['config'] ) ) {
1129 if ( $type !== 'data' ) {
1130 $msg = __METHOD__
. ": invalid use of \"config\" for package file \"{$fileInfo['name']}\" " .
1131 "in module \"{$this->getName()}\": type must be \"data\" but is \"$type\"";
1132 wfDebugLog( 'resourceloader', $msg );
1133 throw new MWException( $msg );
1135 $expandedConfig = [];
1136 foreach ( $fileInfo['config'] as $key => $var ) {
1137 $expandedConfig[ is_numeric( $key ) ?
$var : $key ] = $this->getConfig()->get( $var );
1139 $expanded['content'] = $expandedConfig;
1140 } elseif ( !empty( $fileInfo['main'] ) ) {
1141 // [ 'name' => 'foo.js', 'main' => true ] is shorthand
1142 $expanded['filePath'] = $fileInfo['name'];
1144 $msg = __METHOD__
. ": invalid package file definition for \"{$fileInfo['name']}\" " .
1145 "in module \"{$this->getName()}\": one of \"file\", \"content\", \"callback\" or \"config\" " .
1147 wfDebugLog( 'resourceloader', $msg );
1148 throw new MWException( $msg );
1151 $expandedFiles[$fileInfo['name']] = $expanded;
1154 if ( $expandedFiles && $mainFile === null ) {
1155 // The first package file that is a script is the main file
1156 foreach ( $expandedFiles as $path => &$file ) {
1157 if ( $file['type'] === 'script' ) {
1165 'main' => $mainFile,
1166 'files' => $expandedFiles
1169 $this->expandedPackageFiles
[$hash] = $result;
1174 * Resolves the package files defintion and generates the content of each package file.
1175 * @param ResourceLoaderContext $context
1176 * @return array Package files data structure, see ResourceLoaderModule::getScript()
1178 public function getPackageFiles( ResourceLoaderContext
$context ) {
1179 if ( $this->packageFiles
=== null ) {
1182 $expandedPackageFiles = $this->expandPackageFiles( $context );
1184 // Expand file contents
1185 foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
1186 if ( isset( $fileInfo['filePath'] ) ) {
1187 $localPath = $this->getLocalPath( $fileInfo['filePath'] );
1188 if ( !file_exists( $localPath ) ) {
1189 $msg = __METHOD__
. ": package file not found: \"$localPath\"" .
1190 " in module \"{$this->getName()}\"";
1191 wfDebugLog( 'resourceloader', $msg );
1192 throw new MWException( $msg );
1194 $content = $this->stripBom( file_get_contents( $localPath ) );
1195 if ( $fileInfo['type'] === 'data' ) {
1196 $content = json_decode( $content );
1198 $fileInfo['content'] = $content;
1199 unset( $fileInfo['filePath'] );
1203 return $expandedPackageFiles;
1207 * Takes an input string and removes the UTF-8 BOM character if present
1209 * We need to remove these after reading a file, because we concatenate our files and
1210 * the BOM character is not valid in the middle of a string.
1211 * We already assume UTF-8 everywhere, so this should be safe.
1213 * @param string $input
1214 * @return string Input minus the intial BOM char
1216 protected function stripBom( $input ) {
1217 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1218 return substr( $input, 3 );