Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blob725bc6a05e0d54bed5263f2a7fa71525efff288d
1 <?php
2 /**
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29 /* Protected Members */
31 /** @var string Local base path, see __construct() */
32 protected $localBasePath = '';
34 /** @var string Remote base path, see __construct() */
35 protected $remoteBasePath = '';
37 /** @var array Saves a list of the templates named by the modules. */
38 protected $templates = [];
40 /**
41 * @var array List of paths to JavaScript files to always include
42 * @par Usage:
43 * @code
44 * [ [file-path], [file-path], ... ]
45 * @endcode
47 protected $scripts = [];
49 /**
50 * @var array List of JavaScript files to include when using a specific language
51 * @par Usage:
52 * @code
53 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
54 * @endcode
56 protected $languageScripts = [];
58 /**
59 * @var array List of JavaScript files to include when using a specific skin
60 * @par Usage:
61 * @code
62 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
63 * @endcode
65 protected $skinScripts = [];
67 /**
68 * @var array List of paths to JavaScript files to include in debug mode
69 * @par Usage:
70 * @code
71 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
72 * @endcode
74 protected $debugScripts = [];
76 /**
77 * @var array List of paths to CSS files to always include
78 * @par Usage:
79 * @code
80 * [ [file-path], [file-path], ... ]
81 * @endcode
83 protected $styles = [];
85 /**
86 * @var array List of paths to CSS files to include when using specific skins
87 * @par Usage:
88 * @code
89 * [ [file-path], [file-path], ... ]
90 * @endcode
92 protected $skinStyles = [];
94 /**
95 * @var array List of modules this module depends on
96 * @par Usage:
97 * @code
98 * [ [file-path], [file-path], ... ]
99 * @endcode
101 protected $dependencies = [];
104 * @var string File name containing the body of the skip function
106 protected $skipFunction = null;
109 * @var array List of message keys used by this module
110 * @par Usage:
111 * @code
112 * [ [message-key], [message-key], ... ]
113 * @endcode
115 protected $messages = [];
117 /** @var string Name of group to load this module in */
118 protected $group;
120 /** @var bool Link to raw files in debug mode */
121 protected $debugRaw = true;
123 /** @var bool Whether mw.loader.state() call should be omitted */
124 protected $raw = false;
126 protected $targets = [ 'desktop' ];
128 /** @var bool Whether CSSJanus flipping should be skipped for this module */
129 protected $noflip = false;
132 * @var bool Whether getStyleURLsForDebug should return raw file paths,
133 * or return load.php urls
135 protected $hasGeneratedStyles = false;
138 * @var array Place where readStyleFile() tracks file dependencies
139 * @par Usage:
140 * @code
141 * [ [file-path], [file-path], ... ]
142 * @endcode
144 protected $localFileRefs = [];
147 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
148 * Used in tests to detect missing dependencies.
150 protected $missingLocalFileRefs = [];
152 /* Methods */
155 * Constructs a new module from an options array.
157 * @param array $options List of options; if not given or empty, an empty module will be
158 * constructed
159 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
160 * to $IP
161 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
162 * to $wgResourceBasePath
164 * Below is a description for the $options array:
165 * @throws InvalidArgumentException
166 * @par Construction options:
167 * @code
169 * // Base path to prepend to all local paths in $options. Defaults to $IP
170 * 'localBasePath' => [base path],
171 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
172 * 'remoteBasePath' => [base path],
173 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
174 * 'remoteExtPath' => [base path],
175 * // Equivalent of remoteBasePath, but relative to $wgStylePath
176 * 'remoteSkinPath' => [base path],
177 * // Scripts to always include
178 * 'scripts' => [file path string or array of file path strings],
179 * // Scripts to include in specific language contexts
180 * 'languageScripts' => [
181 * [language code] => [file path string or array of file path strings],
182 * ],
183 * // Scripts to include in specific skin contexts
184 * 'skinScripts' => [
185 * [skin name] => [file path string or array of file path strings],
186 * ],
187 * // Scripts to include in debug contexts
188 * 'debugScripts' => [file path string or array of file path strings],
189 * // Modules which must be loaded before this module
190 * 'dependencies' => [module name string or array of module name strings],
191 * 'templates' => [
192 * [template alias with file.ext] => [file path to a template file],
193 * ],
194 * // Styles to always load
195 * 'styles' => [file path string or array of file path strings],
196 * // Styles to include in specific skin contexts
197 * 'skinStyles' => [
198 * [skin name] => [file path string or array of file path strings],
199 * ],
200 * // Messages to always load
201 * 'messages' => [array of message key strings],
202 * // Group which this module should be loaded together with
203 * 'group' => [group name string],
204 * // Function that, if it returns true, makes the loader skip this module.
205 * // The file must contain valid JavaScript for execution in a private function.
206 * // The file must not contain the "function () {" and "}" wrapper though.
207 * 'skipFunction' => [file path]
209 * @endcode
211 public function __construct(
212 $options = [],
213 $localBasePath = null,
214 $remoteBasePath = null
216 // Flag to decide whether to automagically add the mediawiki.template module
217 $hasTemplates = false;
218 // localBasePath and remoteBasePath both have unbelievably long fallback chains
219 // and need to be handled separately.
220 list( $this->localBasePath, $this->remoteBasePath ) =
221 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
223 // Extract, validate and normalise remaining options
224 foreach ( $options as $member => $option ) {
225 switch ( $member ) {
226 // Lists of file paths
227 case 'scripts':
228 case 'debugScripts':
229 case 'styles':
230 $this->{$member} = (array)$option;
231 break;
232 case 'templates':
233 $hasTemplates = true;
234 $this->{$member} = (array)$option;
235 break;
236 // Collated lists of file paths
237 case 'languageScripts':
238 case 'skinScripts':
239 case 'skinStyles':
240 if ( !is_array( $option ) ) {
241 throw new InvalidArgumentException(
242 "Invalid collated file path list error. " .
243 "'$option' given, array expected."
246 foreach ( $option as $key => $value ) {
247 if ( !is_string( $key ) ) {
248 throw new InvalidArgumentException(
249 "Invalid collated file path list key error. " .
250 "'$key' given, string expected."
253 $this->{$member}[$key] = (array)$value;
255 break;
256 case 'deprecated':
257 $this->deprecated = $option;
258 break;
259 // Lists of strings
260 case 'dependencies':
261 case 'messages':
262 case 'targets':
263 // Normalise
264 $option = array_values( array_unique( (array)$option ) );
265 sort( $option );
267 $this->{$member} = $option;
268 break;
269 // Single strings
270 case 'group':
271 case 'skipFunction':
272 $this->{$member} = (string)$option;
273 break;
274 // Single booleans
275 case 'debugRaw':
276 case 'raw':
277 case 'noflip':
278 $this->{$member} = (bool)$option;
279 break;
282 if ( $hasTemplates ) {
283 $this->dependencies[] = 'mediawiki.template';
284 // Ensure relevant template compiler module gets loaded
285 foreach ( $this->templates as $alias => $templatePath ) {
286 if ( is_int( $alias ) ) {
287 $alias = $templatePath;
289 $suffix = explode( '.', $alias );
290 $suffix = end( $suffix );
291 $compilerModule = 'mediawiki.template.' . $suffix;
292 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
293 $this->dependencies[] = $compilerModule;
300 * Extract a pair of local and remote base paths from module definition information.
301 * Implementation note: the amount of global state used in this function is staggering.
303 * @param array $options Module definition
304 * @param string $localBasePath Path to use if not provided in module definition. Defaults
305 * to $IP
306 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
307 * to $wgResourceBasePath
308 * @return array Array( localBasePath, remoteBasePath )
310 public static function extractBasePaths(
311 $options = [],
312 $localBasePath = null,
313 $remoteBasePath = null
315 global $IP, $wgResourceBasePath;
317 // The different ways these checks are done, and their ordering, look very silly,
318 // but were preserved for backwards-compatibility just in case. Tread lightly.
320 if ( $localBasePath === null ) {
321 $localBasePath = $IP;
323 if ( $remoteBasePath === null ) {
324 $remoteBasePath = $wgResourceBasePath;
327 if ( isset( $options['remoteExtPath'] ) ) {
328 global $wgExtensionAssetsPath;
329 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
332 if ( isset( $options['remoteSkinPath'] ) ) {
333 global $wgStylePath;
334 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
337 if ( array_key_exists( 'localBasePath', $options ) ) {
338 $localBasePath = (string)$options['localBasePath'];
341 if ( array_key_exists( 'remoteBasePath', $options ) ) {
342 $remoteBasePath = (string)$options['remoteBasePath'];
345 return [ $localBasePath, $remoteBasePath ];
349 * Gets all scripts for a given context concatenated together.
351 * @param ResourceLoaderContext $context Context in which to generate script
352 * @return string JavaScript code for $context
354 public function getScript( ResourceLoaderContext $context ) {
355 $files = $this->getScriptFiles( $context );
356 return $this->getDeprecationInformation() . $this->readScriptFiles( $files );
360 * @param ResourceLoaderContext $context
361 * @return array
363 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
364 $urls = [];
365 foreach ( $this->getScriptFiles( $context ) as $file ) {
366 $urls[] = OutputPage::transformResourcePath(
367 $this->getConfig(),
368 $this->getRemotePath( $file )
371 return $urls;
375 * @return bool
377 public function supportsURLLoading() {
378 return $this->debugRaw;
382 * Get all styles for a given context.
384 * @param ResourceLoaderContext $context
385 * @return array CSS code for $context as an associative array mapping media type to CSS text.
387 public function getStyles( ResourceLoaderContext $context ) {
388 $styles = $this->readStyleFiles(
389 $this->getStyleFiles( $context ),
390 $this->getFlip( $context ),
391 $context
393 // Collect referenced files
394 $this->saveFileDependencies( $context, $this->localFileRefs );
396 return $styles;
400 * @param ResourceLoaderContext $context
401 * @return array
403 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
404 if ( $this->hasGeneratedStyles ) {
405 // Do the default behaviour of returning a url back to load.php
406 // but with only=styles.
407 return parent::getStyleURLsForDebug( $context );
409 // Our module consists entirely of real css files,
410 // in debug mode we can load those directly.
411 $urls = [];
412 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
413 $urls[$mediaType] = [];
414 foreach ( $list as $file ) {
415 $urls[$mediaType][] = OutputPage::transformResourcePath(
416 $this->getConfig(),
417 $this->getRemotePath( $file )
421 return $urls;
425 * Gets list of message keys used by this module.
427 * @return array List of message keys
429 public function getMessages() {
430 return $this->messages;
434 * Gets the name of the group this module should be loaded in.
436 * @return string Group name
438 public function getGroup() {
439 return $this->group;
443 * Gets list of names of modules this module depends on.
444 * @param ResourceLoaderContext|null $context
445 * @return array List of module names
447 public function getDependencies( ResourceLoaderContext $context = null ) {
448 return $this->dependencies;
452 * Get the skip function.
453 * @return null|string
454 * @throws MWException
456 public function getSkipFunction() {
457 if ( !$this->skipFunction ) {
458 return null;
461 $localPath = $this->getLocalPath( $this->skipFunction );
462 if ( !file_exists( $localPath ) ) {
463 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
465 $contents = $this->stripBom( file_get_contents( $localPath ) );
466 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
467 $contents = $this->validateScriptFile( $localPath, $contents );
469 return $contents;
473 * @return bool
475 public function isRaw() {
476 return $this->raw;
480 * Disable module content versioning.
482 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
483 * involved with building the full module content inside a startup request.
485 * @return bool
487 public function enableModuleContentVersion() {
488 return false;
492 * Helper method to gather file hashes for getDefinitionSummary.
494 * This function is context-sensitive, only computing hashes of files relevant to the
495 * given language, skin, etc.
497 * @see ResourceLoaderModule::getFileDependencies
498 * @param ResourceLoaderContext $context
499 * @return array
501 protected function getFileHashes( ResourceLoaderContext $context ) {
502 $files = [];
504 // Flatten style files into $files
505 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
506 foreach ( $styles as $styleFiles ) {
507 $files = array_merge( $files, $styleFiles );
510 $skinFiles = self::collateFilePathListByOption(
511 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
512 'media',
513 'all'
515 foreach ( $skinFiles as $styleFiles ) {
516 $files = array_merge( $files, $styleFiles );
519 // Final merge, this should result in a master list of dependent files
520 $files = array_merge(
521 $files,
522 $this->scripts,
523 $this->templates,
524 $context->getDebug() ? $this->debugScripts : [],
525 $this->getLanguageScripts( $context->getLanguage() ),
526 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
528 if ( $this->skipFunction ) {
529 $files[] = $this->skipFunction;
531 $files = array_map( [ $this, 'getLocalPath' ], $files );
532 // File deps need to be treated separately because they're already prefixed
533 $files = array_merge( $files, $this->getFileDependencies( $context ) );
534 // Filter out any duplicates from getFileDependencies() and others.
535 // Most commonly introduced by compileLessFile(), which always includes the
536 // entry point Less file we already know about.
537 $files = array_values( array_unique( $files ) );
539 // Don't include keys or file paths here, only the hashes. Including that would needlessly
540 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
541 // Any significant ordering is already detected by the definition summary.
542 return array_map( [ __CLASS__, 'safeFileHash' ], $files );
546 * Get the definition summary for this module.
548 * @param ResourceLoaderContext $context
549 * @return array
551 public function getDefinitionSummary( ResourceLoaderContext $context ) {
552 $summary = parent::getDefinitionSummary( $context );
554 $options = [];
555 foreach ( [
556 // The following properties are omitted because they don't affect the module reponse:
557 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
558 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
559 // - remoteBasePath (Per T104950)
560 // - dependencies (provided via startup module)
561 // - targets
562 // - group (provided via startup module)
563 'scripts',
564 'debugScripts',
565 'styles',
566 'languageScripts',
567 'skinScripts',
568 'skinStyles',
569 'messages',
570 'templates',
571 'skipFunction',
572 'debugRaw',
573 'raw',
574 ] as $member ) {
575 $options[$member] = $this->{$member};
578 $summary[] = [
579 'options' => $options,
580 'fileHashes' => $this->getFileHashes( $context ),
581 'messageBlob' => $this->getMessageBlob( $context ),
583 return $summary;
587 * @param string|ResourceLoaderFilePath $path
588 * @return string
590 protected function getLocalPath( $path ) {
591 if ( $path instanceof ResourceLoaderFilePath ) {
592 return $path->getLocalPath();
595 return "{$this->localBasePath}/$path";
599 * @param string|ResourceLoaderFilePath $path
600 * @return string
602 protected function getRemotePath( $path ) {
603 if ( $path instanceof ResourceLoaderFilePath ) {
604 return $path->getRemotePath();
607 return "{$this->remoteBasePath}/$path";
611 * Infer the stylesheet language from a stylesheet file path.
613 * @since 1.22
614 * @param string $path
615 * @return string The stylesheet language name
617 public function getStyleSheetLang( $path ) {
618 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
622 * Collates file paths by option (where provided).
624 * @param array $list List of file paths in any combination of index/path
625 * or path/options pairs
626 * @param string $option Option name
627 * @param mixed $default Default value if the option isn't set
628 * @return array List of file paths, collated by $option
630 protected static function collateFilePathListByOption( array $list, $option, $default ) {
631 $collatedFiles = [];
632 foreach ( (array)$list as $key => $value ) {
633 if ( is_int( $key ) ) {
634 // File name as the value
635 if ( !isset( $collatedFiles[$default] ) ) {
636 $collatedFiles[$default] = [];
638 $collatedFiles[$default][] = $value;
639 } elseif ( is_array( $value ) ) {
640 // File name as the key, options array as the value
641 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
642 if ( !isset( $collatedFiles[$optionValue] ) ) {
643 $collatedFiles[$optionValue] = [];
645 $collatedFiles[$optionValue][] = $key;
648 return $collatedFiles;
652 * Get a list of element that match a key, optionally using a fallback key.
654 * @param array $list List of lists to select from
655 * @param string $key Key to look for in $map
656 * @param string $fallback Key to look for in $list if $key doesn't exist
657 * @return array List of elements from $map which matched $key or $fallback,
658 * or an empty list in case of no match
660 protected static function tryForKey( array $list, $key, $fallback = null ) {
661 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
662 return $list[$key];
663 } elseif ( is_string( $fallback )
664 && isset( $list[$fallback] )
665 && is_array( $list[$fallback] )
667 return $list[$fallback];
669 return [];
673 * Get a list of file paths for all scripts in this module, in order of proper execution.
675 * @param ResourceLoaderContext $context
676 * @return array List of file paths
678 protected function getScriptFiles( ResourceLoaderContext $context ) {
679 $files = array_merge(
680 $this->scripts,
681 $this->getLanguageScripts( $context->getLanguage() ),
682 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
684 if ( $context->getDebug() ) {
685 $files = array_merge( $files, $this->debugScripts );
688 return array_unique( $files, SORT_REGULAR );
692 * Get the set of language scripts for the given language,
693 * possibly using a fallback language.
695 * @param string $lang
696 * @return array
698 private function getLanguageScripts( $lang ) {
699 $scripts = self::tryForKey( $this->languageScripts, $lang );
700 if ( $scripts ) {
701 return $scripts;
703 $fallbacks = Language::getFallbacksFor( $lang );
704 foreach ( $fallbacks as $lang ) {
705 $scripts = self::tryForKey( $this->languageScripts, $lang );
706 if ( $scripts ) {
707 return $scripts;
711 return [];
715 * Get a list of file paths for all styles in this module, in order of proper inclusion.
717 * @param ResourceLoaderContext $context
718 * @return array List of file paths
720 public function getStyleFiles( ResourceLoaderContext $context ) {
721 return array_merge_recursive(
722 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
723 self::collateFilePathListByOption(
724 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
725 'media',
726 'all'
732 * Gets a list of file paths for all skin styles in the module used by
733 * the skin.
735 * @param string $skinName The name of the skin
736 * @return array A list of file paths collated by media type
738 protected function getSkinStyleFiles( $skinName ) {
739 return self::collateFilePathListByOption(
740 self::tryForKey( $this->skinStyles, $skinName ),
741 'media',
742 'all'
747 * Gets a list of file paths for all skin style files in the module,
748 * for all available skins.
750 * @return array A list of file paths collated by media type
752 protected function getAllSkinStyleFiles() {
753 $styleFiles = [];
754 $internalSkinNames = array_keys( Skin::getSkinNames() );
755 $internalSkinNames[] = 'default';
757 foreach ( $internalSkinNames as $internalSkinName ) {
758 $styleFiles = array_merge_recursive(
759 $styleFiles,
760 $this->getSkinStyleFiles( $internalSkinName )
764 return $styleFiles;
768 * Returns all style files and all skin style files used by this module.
770 * @return array
772 public function getAllStyleFiles() {
773 $collatedStyleFiles = array_merge_recursive(
774 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
775 $this->getAllSkinStyleFiles()
778 $result = [];
780 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
781 foreach ( $styleFiles as $styleFile ) {
782 $result[] = $this->getLocalPath( $styleFile );
786 return $result;
790 * Gets the contents of a list of JavaScript files.
792 * @param array $scripts List of file paths to scripts to read, remap and concetenate
793 * @throws MWException
794 * @return string Concatenated and remapped JavaScript data from $scripts
796 protected function readScriptFiles( array $scripts ) {
797 if ( empty( $scripts ) ) {
798 return '';
800 $js = '';
801 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
802 $localPath = $this->getLocalPath( $fileName );
803 if ( !file_exists( $localPath ) ) {
804 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
806 $contents = $this->stripBom( file_get_contents( $localPath ) );
807 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
808 // Static files don't really need to be checked as often; unlike
809 // on-wiki module they shouldn't change unexpectedly without
810 // admin interference.
811 $contents = $this->validateScriptFile( $fileName, $contents );
813 $js .= $contents . "\n";
815 return $js;
819 * Gets the contents of a list of CSS files.
821 * @param array $styles List of media type/list of file paths pairs, to read, remap and
822 * concetenate
823 * @param bool $flip
824 * @param ResourceLoaderContext $context
826 * @throws MWException
827 * @return array List of concatenated and remapped CSS data from $styles,
828 * keyed by media type
830 * @since 1.27 Calling this method without a ResourceLoaderContext instance
831 * is deprecated.
833 public function readStyleFiles( array $styles, $flip, $context = null ) {
834 if ( $context === null ) {
835 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
836 $context = ResourceLoaderContext::newDummyContext();
839 if ( empty( $styles ) ) {
840 return [];
842 foreach ( $styles as $media => $files ) {
843 $uniqueFiles = array_unique( $files, SORT_REGULAR );
844 $styleFiles = [];
845 foreach ( $uniqueFiles as $file ) {
846 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
848 $styles[$media] = implode( "\n", $styleFiles );
850 return $styles;
854 * Reads a style file.
856 * This method can be used as a callback for array_map()
858 * @param string $path File path of style file to read
859 * @param bool $flip
860 * @param ResourceLoaderContext $context
862 * @return string CSS data in script file
863 * @throws MWException If the file doesn't exist
865 protected function readStyleFile( $path, $flip, $context ) {
866 $localPath = $this->getLocalPath( $path );
867 $remotePath = $this->getRemotePath( $path );
868 if ( !file_exists( $localPath ) ) {
869 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
870 wfDebugLog( 'resourceloader', $msg );
871 throw new MWException( $msg );
874 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
875 $style = $this->compileLessFile( $localPath, $context );
876 $this->hasGeneratedStyles = true;
877 } else {
878 $style = $this->stripBom( file_get_contents( $localPath ) );
881 if ( $flip ) {
882 $style = CSSJanus::transform( $style, true, false );
884 $localDir = dirname( $localPath );
885 $remoteDir = dirname( $remotePath );
886 // Get and register local file references
887 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
888 foreach ( $localFileRefs as $file ) {
889 if ( file_exists( $file ) ) {
890 $this->localFileRefs[] = $file;
891 } else {
892 $this->missingLocalFileRefs[] = $file;
895 // Don't cache this call. remap() ensures data URIs embeds are up to date,
896 // and urls contain correct content hashes in their query string. (T128668)
897 return CSSMin::remap( $style, $localDir, $remoteDir, true );
901 * Get whether CSS for this module should be flipped
902 * @param ResourceLoaderContext $context
903 * @return bool
905 public function getFlip( $context ) {
906 return $context->getDirection() === 'rtl' && !$this->noflip;
910 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
912 * @return array Array of strings
914 public function getTargets() {
915 return $this->targets;
919 * Get the module's load type.
921 * @since 1.28
922 * @return string
924 public function getType() {
925 $canBeStylesOnly = !(
926 // All options except 'styles', 'skinStyles' and 'debugRaw'
927 $this->scripts
928 || $this->debugScripts
929 || $this->templates
930 || $this->languageScripts
931 || $this->skinScripts
932 || $this->dependencies
933 || $this->messages
934 || $this->skipFunction
935 || $this->raw
937 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
941 * Compile a LESS file into CSS.
943 * Keeps track of all used files and adds them to localFileRefs.
945 * @since 1.22
946 * @since 1.27 Added $context paramter.
947 * @throws Exception If less.php encounters a parse error
948 * @param string $fileName File path of LESS source
949 * @param ResourceLoaderContext $context Context in which to generate script
950 * @return string CSS source
952 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
953 static $cache;
955 if ( !$cache ) {
956 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
959 // Construct a cache key from the LESS file name and a hash digest
960 // of the LESS variables used for compilation.
961 $vars = $this->getLessVars( $context );
962 ksort( $vars );
963 $varsHash = hash( 'md4', serialize( $vars ) );
964 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
965 $cachedCompile = $cache->get( $cacheKey );
967 // If we got a cached value, we have to validate it by getting a
968 // checksum of all the files that were loaded by the parser and
969 // ensuring it matches the cached entry's.
970 if ( isset( $cachedCompile['hash'] ) ) {
971 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
972 if ( $contentHash === $cachedCompile['hash'] ) {
973 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
974 return $cachedCompile['css'];
978 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
979 $css = $compiler->parseFile( $fileName )->getCss();
980 $files = $compiler->AllParsedFiles();
981 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
983 $cache->set( $cacheKey, [
984 'css' => $css,
985 'files' => $files,
986 'hash' => FileContentsHasher::getFileContentsHash( $files ),
987 ], 60 * 60 * 24 ); // 86400 seconds, or 24 hours.
989 return $css;
993 * Takes named templates by the module and returns an array mapping.
994 * @return array of templates mapping template alias to content
995 * @throws MWException
997 public function getTemplates() {
998 $templates = [];
1000 foreach ( $this->templates as $alias => $templatePath ) {
1001 // Alias is optional
1002 if ( is_int( $alias ) ) {
1003 $alias = $templatePath;
1005 $localPath = $this->getLocalPath( $templatePath );
1006 if ( file_exists( $localPath ) ) {
1007 $content = file_get_contents( $localPath );
1008 $templates[$alias] = $this->stripBom( $content );
1009 } else {
1010 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
1011 wfDebugLog( 'resourceloader', $msg );
1012 throw new MWException( $msg );
1015 return $templates;
1019 * Takes an input string and removes the UTF-8 BOM character if present
1021 * We need to remove these after reading a file, because we concatenate our files and
1022 * the BOM character is not valid in the middle of a string.
1023 * We already assume UTF-8 everywhere, so this should be safe.
1025 * @return string input minus the intial BOM char
1027 protected function stripBom( $input ) {
1028 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1029 return substr( $input, 3 );
1031 return $input;