Remove unused variable in ProfilerMwprof
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blob7bbc9bbe6afbd00832780656833c6182383f1160
1 <?php
2 /**
3 * Resource loader 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 /**
38 * @var array List of paths to JavaScript files to always include
39 * @par Usage:
40 * @code
41 * array( [file-path], [file-path], ... )
42 * @endcode
44 protected $scripts = array();
46 /**
47 * @var array List of JavaScript files to include when using a specific language
48 * @par Usage:
49 * @code
50 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
51 * @endcode
53 protected $languageScripts = array();
55 /**
56 * @var array List of JavaScript files to include when using a specific skin
57 * @par Usage:
58 * @code
59 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
60 * @endcode
62 protected $skinScripts = array();
64 /**
65 * @var array List of paths to JavaScript files to include in debug mode
66 * @par Usage:
67 * @code
68 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
69 * @endcode
71 protected $debugScripts = array();
73 /**
74 * @var array List of paths to JavaScript files to include in the startup module
75 * @par Usage:
76 * @code
77 * array( [file-path], [file-path], ... )
78 * @endcode
80 protected $loaderScripts = array();
82 /**
83 * @var array List of paths to CSS files to always include
84 * @par Usage:
85 * @code
86 * array( [file-path], [file-path], ... )
87 * @endcode
89 protected $styles = array();
91 /**
92 * @var array List of paths to CSS files to include when using specific skins
93 * @par Usage:
94 * @code
95 * array( [file-path], [file-path], ... )
96 * @endcode
98 protected $skinStyles = array();
101 * @var array List of modules this module depends on
102 * @par Usage:
103 * @code
104 * array( [file-path], [file-path], ... )
105 * @endcode
107 protected $dependencies = array();
110 * @var string File name containing the body of the skip function
112 protected $skipFunction = null;
115 * @var array List of message keys used by this module
116 * @par Usage:
117 * @code
118 * array( [message-key], [message-key], ... )
119 * @endcode
121 protected $messages = array();
123 /** @var string Name of group to load this module in */
124 protected $group;
126 /** @var string Position on the page to load this module at */
127 protected $position = 'bottom';
129 /** @var bool Link to raw files in debug mode */
130 protected $debugRaw = true;
132 /** @var bool Whether mw.loader.state() call should be omitted */
133 protected $raw = false;
135 protected $targets = array( 'desktop' );
138 * @var bool Whether getStyleURLsForDebug should return raw file paths,
139 * or return load.php urls
141 protected $hasGeneratedStyles = false;
144 * @var array Cache for mtime
145 * @par Usage:
146 * @code
147 * array( [hash] => [mtime], [hash] => [mtime], ... )
148 * @endcode
150 protected $modifiedTime = array();
153 * @var array Place where readStyleFile() tracks file dependencies
154 * @par Usage:
155 * @code
156 * array( [file-path], [file-path], ... )
157 * @endcode
159 protected $localFileRefs = array();
161 /* Methods */
164 * Constructs a new module from an options array.
166 * @param array $options List of options; if not given or empty, an empty module will be
167 * constructed
168 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
169 * to $IP
170 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
171 * to $wgResourceBasePath
173 * Below is a description for the $options array:
174 * @throws MWException
175 * @par Construction options:
176 * @code
177 * array(
178 * // Base path to prepend to all local paths in $options. Defaults to $IP
179 * 'localBasePath' => [base path],
180 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
181 * 'remoteBasePath' => [base path],
182 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
183 * 'remoteExtPath' => [base path],
184 * // Equivalent of remoteBasePath, but relative to $wgStylePath
185 * 'remoteSkinPath' => [base path],
186 * // Scripts to always include
187 * 'scripts' => [file path string or array of file path strings],
188 * // Scripts to include in specific language contexts
189 * 'languageScripts' => array(
190 * [language code] => [file path string or array of file path strings],
191 * ),
192 * // Scripts to include in specific skin contexts
193 * 'skinScripts' => array(
194 * [skin name] => [file path string or array of file path strings],
195 * ),
196 * // Scripts to include in debug contexts
197 * 'debugScripts' => [file path string or array of file path strings],
198 * // Scripts to include in the startup module
199 * 'loaderScripts' => [file path string or array of file path strings],
200 * // Modules which must be loaded before this module
201 * 'dependencies' => [module name string or array of module name strings],
202 * // Styles to always load
203 * 'styles' => [file path string or array of file path strings],
204 * // Styles to include in specific skin contexts
205 * 'skinStyles' => array(
206 * [skin name] => [file path string or array of file path strings],
207 * ),
208 * // Messages to always load
209 * 'messages' => [array of message key strings],
210 * // Group which this module should be loaded together with
211 * 'group' => [group name string],
212 * // Position on the page to load this module at
213 * 'position' => ['bottom' (default) or 'top']
214 * // Function that, if it returns true, makes the loader skip this module.
215 * // The file must contain valid JavaScript for execution in a private function.
216 * // The file must not contain the "function () {" and "}" wrapper though.
217 * 'skipFunction' => [file path]
219 * @endcode
221 public function __construct(
222 $options = array(),
223 $localBasePath = null,
224 $remoteBasePath = null
226 // localBasePath and remoteBasePath both have unbelievably long fallback chains
227 // and need to be handled separately.
228 list( $this->localBasePath, $this->remoteBasePath ) =
229 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
231 // Extract, validate and normalise remaining options
232 foreach ( $options as $member => $option ) {
233 switch ( $member ) {
234 // Lists of file paths
235 case 'scripts':
236 case 'debugScripts':
237 case 'loaderScripts':
238 case 'styles':
239 $this->{$member} = (array)$option;
240 break;
241 // Collated lists of file paths
242 case 'languageScripts':
243 case 'skinScripts':
244 case 'skinStyles':
245 if ( !is_array( $option ) ) {
246 throw new MWException(
247 "Invalid collated file path list error. " .
248 "'$option' given, array expected."
251 foreach ( $option as $key => $value ) {
252 if ( !is_string( $key ) ) {
253 throw new MWException(
254 "Invalid collated file path list key error. " .
255 "'$key' given, string expected."
258 $this->{$member}[$key] = (array)$value;
260 break;
261 // Lists of strings
262 case 'dependencies':
263 case 'messages':
264 case 'targets':
265 // Normalise
266 $option = array_values( array_unique( (array)$option ) );
267 sort( $option );
269 $this->{$member} = $option;
270 break;
271 // Single strings
272 case 'group':
273 case 'position':
274 case 'skipFunction':
275 $this->{$member} = (string)$option;
276 break;
277 // Single booleans
278 case 'debugRaw':
279 case 'raw':
280 $this->{$member} = (bool)$option;
281 break;
287 * Extract a pair of local and remote base paths from module definition information.
288 * Implementation note: the amount of global state used in this function is staggering.
290 * @param array $options Module definition
291 * @param string $localBasePath Path to use if not provided in module definition. Defaults
292 * to $IP
293 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
294 * to $wgResourceBasePath
295 * @return array Array( localBasePath, remoteBasePath )
297 public static function extractBasePaths(
298 $options = array(),
299 $localBasePath = null,
300 $remoteBasePath = null
302 global $IP, $wgResourceBasePath;
304 // The different ways these checks are done, and their ordering, look very silly,
305 // but were preserved for backwards-compatibility just in case. Tread lightly.
307 if ( $localBasePath === null ) {
308 $localBasePath = $IP;
310 if ( $remoteBasePath === null ) {
311 $remoteBasePath = $wgResourceBasePath;
314 if ( isset( $options['remoteExtPath'] ) ) {
315 global $wgExtensionAssetsPath;
316 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
319 if ( isset( $options['remoteSkinPath'] ) ) {
320 global $wgStylePath;
321 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
324 if ( array_key_exists( 'localBasePath', $options ) ) {
325 $localBasePath = (string)$options['localBasePath'];
328 if ( array_key_exists( 'remoteBasePath', $options ) ) {
329 $remoteBasePath = (string)$options['remoteBasePath'];
332 // Make sure the remote base path is a complete valid URL,
333 // but possibly protocol-relative to avoid cache pollution
334 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
336 return array( $localBasePath, $remoteBasePath );
340 * Gets all scripts for a given context concatenated together.
342 * @param ResourceLoaderContext $context Context in which to generate script
343 * @return string JavaScript code for $context
345 public function getScript( ResourceLoaderContext $context ) {
346 $files = $this->getScriptFiles( $context );
347 return $this->readScriptFiles( $files );
351 * @param ResourceLoaderContext $context
352 * @return array
354 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
355 $urls = array();
356 foreach ( $this->getScriptFiles( $context ) as $file ) {
357 $urls[] = $this->getRemotePath( $file );
359 return $urls;
363 * @return bool
365 public function supportsURLLoading() {
366 return $this->debugRaw;
370 * Get loader script.
372 * @return string|bool JavaScript code to be added to startup module
374 public function getLoaderScript() {
375 if ( count( $this->loaderScripts ) === 0 ) {
376 return false;
378 return $this->readScriptFiles( $this->loaderScripts );
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->localFileRefs = array_unique( $this->localFileRefs );
395 // If the list has been modified since last time we cached it, update the cache
396 try {
397 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
398 $dbw = wfGetDB( DB_MASTER );
399 $dbw->replace( 'module_deps',
400 array( array( 'md_module', 'md_skin' ) ), array(
401 'md_module' => $this->getName(),
402 'md_skin' => $context->getSkin(),
403 'md_deps' => FormatJson::encode( $this->localFileRefs ),
407 } catch ( Exception $e ) {
408 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
410 return $styles;
414 * @param ResourceLoaderContext $context
415 * @return array
417 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
418 if ( $this->hasGeneratedStyles ) {
419 // Do the default behaviour of returning a url back to load.php
420 // but with only=styles.
421 return parent::getStyleURLsForDebug( $context );
423 // Our module consists entirely of real css files,
424 // in debug mode we can load those directly.
425 $urls = array();
426 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
427 $urls[$mediaType] = array();
428 foreach ( $list as $file ) {
429 $urls[$mediaType][] = $this->getRemotePath( $file );
432 return $urls;
436 * Gets list of message keys used by this module.
438 * @return array List of message keys
440 public function getMessages() {
441 return $this->messages;
445 * Gets the name of the group this module should be loaded in.
447 * @return string Group name
449 public function getGroup() {
450 return $this->group;
454 * @return string
456 public function getPosition() {
457 return $this->position;
461 * Gets list of names of modules this module depends on.
463 * @return array List of module names
465 public function getDependencies() {
466 return $this->dependencies;
470 * Get the skip function.
472 * @return string|null
474 public function getSkipFunction() {
475 if ( !$this->skipFunction ) {
476 return null;
479 $localPath = $this->getLocalPath( $this->skipFunction );
480 if ( !file_exists( $localPath ) ) {
481 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
483 $contents = file_get_contents( $localPath );
484 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
485 $contents = $this->validateScriptFile( $localPath, $contents );
487 return $contents;
491 * @return bool
493 public function isRaw() {
494 return $this->raw;
498 * Get the last modified timestamp of this module.
500 * Last modified timestamps are calculated from the highest last modified
501 * timestamp of this module's constituent files as well as the files it
502 * depends on. This function is context-sensitive, only performing
503 * calculations on files relevant to the given language, skin and debug
504 * mode.
506 * @param ResourceLoaderContext $context Context in which to calculate
507 * the modified time
508 * @return int UNIX timestamp
509 * @see ResourceLoaderModule::getFileDependencies
511 public function getModifiedTime( ResourceLoaderContext $context ) {
512 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
513 return $this->modifiedTime[$context->getHash()];
515 wfProfileIn( __METHOD__ );
517 $files = array();
519 // Flatten style files into $files
520 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
521 foreach ( $styles as $styleFiles ) {
522 $files = array_merge( $files, $styleFiles );
525 $skinFiles = self::collateFilePathListByOption(
526 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
527 'media',
528 'all'
530 foreach ( $skinFiles as $styleFiles ) {
531 $files = array_merge( $files, $styleFiles );
534 // Final merge, this should result in a master list of dependent files
535 $files = array_merge(
536 $files,
537 $this->scripts,
538 $context->getDebug() ? $this->debugScripts : array(),
539 $this->getLanguageScripts( $context->getLanguage() ),
540 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
541 $this->loaderScripts
543 if ( $this->skipFunction ) {
544 $files[] = $this->skipFunction;
546 $files = array_map( array( $this, 'getLocalPath' ), $files );
547 // File deps need to be treated separately because they're already prefixed
548 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
550 // If a module is nothing but a list of dependencies, we need to avoid
551 // giving max() an empty array
552 if ( count( $files ) === 0 ) {
553 $this->modifiedTime[$context->getHash()] = 1;
554 wfProfileOut( __METHOD__ );
555 return $this->modifiedTime[$context->getHash()];
558 wfProfileIn( __METHOD__ . '-filemtime' );
559 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
560 wfProfileOut( __METHOD__ . '-filemtime' );
562 $this->modifiedTime[$context->getHash()] = max(
563 $filesMtime,
564 $this->getMsgBlobMtime( $context->getLanguage() ),
565 $this->getDefinitionMtime( $context )
568 wfProfileOut( __METHOD__ );
569 return $this->modifiedTime[$context->getHash()];
573 * Get the definition summary for this module.
575 * @param ResourceLoaderContext $context
576 * @return array
578 public function getDefinitionSummary( ResourceLoaderContext $context ) {
579 $summary = array(
580 'class' => get_class( $this ),
582 foreach ( array(
583 'scripts',
584 'debugScripts',
585 'loaderScripts',
586 'styles',
587 'languageScripts',
588 'skinScripts',
589 'skinStyles',
590 'dependencies',
591 'messages',
592 'targets',
593 'group',
594 'position',
595 'skipFunction',
596 'localBasePath',
597 'remoteBasePath',
598 'debugRaw',
599 'raw',
600 ) as $member ) {
601 $summary[$member] = $this->{$member};
603 return $summary;
606 /* Protected Methods */
609 * @param string|ResourceLoaderFilePath $path
610 * @return string
612 protected function getLocalPath( $path ) {
613 if ( $path instanceof ResourceLoaderFilePath ) {
614 return $path->getLocalPath();
617 return "{$this->localBasePath}/$path";
621 * @param string|ResourceLoaderFilePath $path
622 * @return string
624 protected function getRemotePath( $path ) {
625 if ( $path instanceof ResourceLoaderFilePath ) {
626 return $path->getRemotePath();
629 return "{$this->remoteBasePath}/$path";
633 * Infer the stylesheet language from a stylesheet file path.
635 * @since 1.22
636 * @param string $path
637 * @return string The stylesheet language name
639 public function getStyleSheetLang( $path ) {
640 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
644 * Collates file paths by option (where provided).
646 * @param array $list List of file paths in any combination of index/path
647 * or path/options pairs
648 * @param string $option Option name
649 * @param mixed $default Default value if the option isn't set
650 * @return array List of file paths, collated by $option
652 protected static function collateFilePathListByOption( array $list, $option, $default ) {
653 $collatedFiles = array();
654 foreach ( (array)$list as $key => $value ) {
655 if ( is_int( $key ) ) {
656 // File name as the value
657 if ( !isset( $collatedFiles[$default] ) ) {
658 $collatedFiles[$default] = array();
660 $collatedFiles[$default][] = $value;
661 } elseif ( is_array( $value ) ) {
662 // File name as the key, options array as the value
663 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
664 if ( !isset( $collatedFiles[$optionValue] ) ) {
665 $collatedFiles[$optionValue] = array();
667 $collatedFiles[$optionValue][] = $key;
670 return $collatedFiles;
674 * Get a list of element that match a key, optionally using a fallback key.
676 * @param array $list List of lists to select from
677 * @param string $key Key to look for in $map
678 * @param string $fallback Key to look for in $list if $key doesn't exist
679 * @return array List of elements from $map which matched $key or $fallback,
680 * or an empty list in case of no match
682 protected static function tryForKey( array $list, $key, $fallback = null ) {
683 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
684 return $list[$key];
685 } elseif ( is_string( $fallback )
686 && isset( $list[$fallback] )
687 && is_array( $list[$fallback] )
689 return $list[$fallback];
691 return array();
695 * Get a list of file paths for all scripts in this module, in order of proper execution.
697 * @param ResourceLoaderContext $context
698 * @return array List of file paths
700 protected function getScriptFiles( ResourceLoaderContext $context ) {
701 $files = array_merge(
702 $this->scripts,
703 $this->getLanguageScripts( $context->getLanguage() ),
704 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
706 if ( $context->getDebug() ) {
707 $files = array_merge( $files, $this->debugScripts );
710 return array_unique( $files, SORT_REGULAR );
714 * Get the set of language scripts for the given language,
715 * possibly using a fallback language.
717 * @param string $lang
718 * @return array
720 private function getLanguageScripts( $lang ) {
721 $scripts = self::tryForKey( $this->languageScripts, $lang );
722 if ( $scripts ) {
723 return $scripts;
725 $fallbacks = Language::getFallbacksFor( $lang );
726 foreach ( $fallbacks as $lang ) {
727 $scripts = self::tryForKey( $this->languageScripts, $lang );
728 if ( $scripts ) {
729 return $scripts;
733 return array();
737 * Get a list of file paths for all styles in this module, in order of proper inclusion.
739 * @param ResourceLoaderContext $context
740 * @return array List of file paths
742 public function getStyleFiles( ResourceLoaderContext $context ) {
743 return array_merge_recursive(
744 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
745 self::collateFilePathListByOption(
746 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
747 'media',
748 'all'
754 * Gets a list of file paths for all skin styles in the module used by
755 * the skin.
757 * @param string $skinName The name of the skin
758 * @return array A list of file paths collated by media type
760 protected function getSkinStyleFiles( $skinName ) {
761 return self::collateFilePathListByOption(
762 self::tryForKey( $this->skinStyles, $skinName ),
763 'media',
764 'all'
769 * Gets a list of file paths for all skin style files in the module,
770 * for all available skins.
772 * @return array A list of file paths collated by media type
774 protected function getAllSkinStyleFiles() {
775 $styleFiles = array();
776 $internalSkinNames = array_keys( Skin::getSkinNames() );
777 $internalSkinNames[] = 'default';
779 foreach ( $internalSkinNames as $internalSkinName ) {
780 $styleFiles = array_merge_recursive(
781 $styleFiles,
782 $this->getSkinStyleFiles( $internalSkinName )
786 return $styleFiles;
790 * Returns all style files and all skin style files used by this module.
792 * @return array
794 public function getAllStyleFiles() {
795 $collatedStyleFiles = array_merge_recursive(
796 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
797 $this->getAllSkinStyleFiles()
800 $result = array();
802 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
803 foreach ( $styleFiles as $styleFile ) {
804 $result[] = $this->getLocalPath( $styleFile );
808 return $result;
812 * Gets the contents of a list of JavaScript files.
814 * @param array $scripts List of file paths to scripts to read, remap and concetenate
815 * @throws MWException
816 * @return string Concatenated and remapped JavaScript data from $scripts
818 protected function readScriptFiles( array $scripts ) {
819 if ( empty( $scripts ) ) {
820 return '';
822 $js = '';
823 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
824 $localPath = $this->getLocalPath( $fileName );
825 if ( !file_exists( $localPath ) ) {
826 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
828 $contents = file_get_contents( $localPath );
829 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
830 // Static files don't really need to be checked as often; unlike
831 // on-wiki module they shouldn't change unexpectedly without
832 // admin interference.
833 $contents = $this->validateScriptFile( $fileName, $contents );
835 $js .= $contents . "\n";
837 return $js;
841 * Gets the contents of a list of CSS files.
843 * @param array $styles List of media type/list of file paths pairs, to read, remap and
844 * concetenate
845 * @param bool $flip
846 * @param ResourceLoaderContext $context (optional)
848 * @throws MWException
849 * @return array List of concatenated and remapped CSS data from $styles,
850 * keyed by media type
852 public function readStyleFiles( array $styles, $flip, $context = null ) {
853 if ( empty( $styles ) ) {
854 return array();
856 foreach ( $styles as $media => $files ) {
857 $uniqueFiles = array_unique( $files, SORT_REGULAR );
858 $styleFiles = array();
859 foreach ( $uniqueFiles as $file ) {
860 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
862 $styles[$media] = implode( "\n", $styleFiles );
864 return $styles;
868 * Reads a style file.
870 * This method can be used as a callback for array_map()
872 * @param string $path File path of style file to read
873 * @param bool $flip
874 * @param ResourceLoaderContext $context (optional)
876 * @return string CSS data in script file
877 * @throws MWException If the file doesn't exist
879 protected function readStyleFile( $path, $flip, $context = null ) {
880 $localPath = $this->getLocalPath( $path );
881 $remotePath = $this->getRemotePath( $path );
882 if ( !file_exists( $localPath ) ) {
883 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
884 wfDebugLog( 'resourceloader', $msg );
885 throw new MWException( $msg );
888 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
889 $compiler = $this->getLessCompiler( $context );
890 $style = $this->compileLessFile( $localPath, $compiler );
891 $this->hasGeneratedStyles = true;
892 } else {
893 $style = file_get_contents( $localPath );
896 if ( $flip ) {
897 $style = CSSJanus::transform( $style, true, false );
899 $localDir = dirname( $localPath );
900 $remoteDir = dirname( $remotePath );
901 // Get and register local file references
902 $this->localFileRefs = array_merge(
903 $this->localFileRefs,
904 CSSMin::getLocalFileReferences( $style, $localDir )
906 return CSSMin::remap(
907 $style, $localDir, $remoteDir, true
912 * Get whether CSS for this module should be flipped
913 * @param ResourceLoaderContext $context
914 * @return bool
916 public function getFlip( $context ) {
917 return $context->getDirection() === 'rtl';
921 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
923 * @return array Array of strings
925 public function getTargets() {
926 return $this->targets;
930 * Compile a LESS file into CSS.
932 * Keeps track of all used files and adds them to localFileRefs.
934 * @since 1.22
935 * @throws Exception If lessc encounters a parse error
936 * @param string $fileName File path of LESS source
937 * @param lessc $compiler Compiler to use, if not default
938 * @return string CSS source
940 protected function compileLessFile( $fileName, $compiler = null ) {
941 if ( !$compiler ) {
942 $compiler = $this->getLessCompiler();
944 $result = $compiler->compileFile( $fileName );
945 $this->localFileRefs += array_keys( $compiler->allParsedFiles() );
946 return $result;
950 * Get a LESS compiler instance for this module in given context.
952 * Just calls ResourceLoader::getLessCompiler() by default to get a global compiler.
954 * @param ResourceLoaderContext $context
955 * @throws MWException
956 * @since 1.24
957 * @return lessc
959 protected function getLessCompiler( ResourceLoaderContext $context = null ) {
960 return ResourceLoader::getLessCompiler( $this->getConfig() );