Merge "Import.php: Use Config instead of globals"
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blobbcef149db4c1cd5ec8d5478ae8162aa251478b18
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 /** @var array Saves a list of the templates named by the modules. */
38 protected $templates = array();
40 /**
41 * @var array List of paths to JavaScript files to always include
42 * @par Usage:
43 * @code
44 * array( [file-path], [file-path], ... )
45 * @endcode
47 protected $scripts = array();
49 /**
50 * @var array List of JavaScript files to include when using a specific language
51 * @par Usage:
52 * @code
53 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
54 * @endcode
56 protected $languageScripts = array();
58 /**
59 * @var array List of JavaScript files to include when using a specific skin
60 * @par Usage:
61 * @code
62 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
63 * @endcode
65 protected $skinScripts = array();
67 /**
68 * @var array List of paths to JavaScript files to include in debug mode
69 * @par Usage:
70 * @code
71 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
72 * @endcode
74 protected $debugScripts = array();
76 /**
77 * @var array List of paths to JavaScript files to include in the startup module
78 * @par Usage:
79 * @code
80 * array( [file-path], [file-path], ... )
81 * @endcode
83 protected $loaderScripts = array();
85 /**
86 * @var array List of paths to CSS files to always include
87 * @par Usage:
88 * @code
89 * array( [file-path], [file-path], ... )
90 * @endcode
92 protected $styles = array();
94 /**
95 * @var array List of paths to CSS files to include when using specific skins
96 * @par Usage:
97 * @code
98 * array( [file-path], [file-path], ... )
99 * @endcode
101 protected $skinStyles = array();
104 * @var array List of modules this module depends on
105 * @par Usage:
106 * @code
107 * array( [file-path], [file-path], ... )
108 * @endcode
110 protected $dependencies = array();
113 * @var string File name containing the body of the skip function
115 protected $skipFunction = null;
118 * @var array List of message keys used by this module
119 * @par Usage:
120 * @code
121 * array( [message-key], [message-key], ... )
122 * @endcode
124 protected $messages = array();
126 /** @var string Name of group to load this module in */
127 protected $group;
129 /** @var string Position on the page to load this module at */
130 protected $position = 'bottom';
132 /** @var bool Link to raw files in debug mode */
133 protected $debugRaw = true;
135 /** @var bool Whether mw.loader.state() call should be omitted */
136 protected $raw = false;
138 protected $targets = array( 'desktop' );
141 * @var bool Whether getStyleURLsForDebug should return raw file paths,
142 * or return load.php urls
144 protected $hasGeneratedStyles = false;
147 * @var array Cache for mtime
148 * @par Usage:
149 * @code
150 * array( [hash] => [mtime], [hash] => [mtime], ... )
151 * @endcode
153 protected $modifiedTime = array();
156 * @var array Place where readStyleFile() tracks file dependencies
157 * @par Usage:
158 * @code
159 * array( [file-path], [file-path], ... )
160 * @endcode
162 protected $localFileRefs = array();
164 /* Methods */
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
170 * constructed
171 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
172 * to $IP
173 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
174 * to $wgResourceBasePath
176 * Below is a description for the $options array:
177 * @throws MWException
178 * @par Construction options:
179 * @code
180 * array(
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
190 * 'scripts' => [file path string or array of file path strings],
191 * // Scripts to include in specific language contexts
192 * 'languageScripts' => array(
193 * [language code] => [file path string or array of file path strings],
194 * ),
195 * // Scripts to include in specific skin contexts
196 * 'skinScripts' => array(
197 * [skin name] => [file path string or array of file path strings],
198 * ),
199 * // Scripts to include in debug contexts
200 * 'debugScripts' => [file path string or array of file path strings],
201 * // Scripts to include in the startup module
202 * 'loaderScripts' => [file path string or array of file path strings],
203 * // Modules which must be loaded before this module
204 * 'dependencies' => [module name string or array of module name strings],
205 * 'templates' => array(
206 * [template alias with file.ext] => [file path to a template file],
207 * ),
208 * // Styles to always load
209 * 'styles' => [file path string or array of file path strings],
210 * // Styles to include in specific skin contexts
211 * 'skinStyles' => array(
212 * [skin name] => [file path string or array of file path strings],
213 * ),
214 * // Messages to always load
215 * 'messages' => [array of message key strings],
216 * // Group which this module should be loaded together with
217 * 'group' => [group name string],
218 * // Position on the page to load this module at
219 * 'position' => ['bottom' (default) or 'top']
220 * // Function that, if it returns true, makes the loader skip this module.
221 * // The file must contain valid JavaScript for execution in a private function.
222 * // The file must not contain the "function () {" and "}" wrapper though.
223 * 'skipFunction' => [file path]
225 * @endcode
227 public function __construct(
228 $options = array(),
229 $localBasePath = null,
230 $remoteBasePath = null
232 // Flag to decide whether to automagically add the mediawiki.template module
233 $hasTemplates = false;
234 // localBasePath and remoteBasePath both have unbelievably long fallback chains
235 // and need to be handled separately.
236 list( $this->localBasePath, $this->remoteBasePath ) =
237 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
239 // Extract, validate and normalise remaining options
240 foreach ( $options as $member => $option ) {
241 switch ( $member ) {
242 // Lists of file paths
243 case 'scripts':
244 case 'debugScripts':
245 case 'loaderScripts':
246 case 'styles':
247 $this->{$member} = (array)$option;
248 break;
249 case 'templates':
250 $hasTemplates = true;
251 $this->{$member} = (array)$option;
252 break;
253 // Collated lists of file paths
254 case 'languageScripts':
255 case 'skinScripts':
256 case 'skinStyles':
257 if ( !is_array( $option ) ) {
258 throw new MWException(
259 "Invalid collated file path list error. " .
260 "'$option' given, array expected."
263 foreach ( $option as $key => $value ) {
264 if ( !is_string( $key ) ) {
265 throw new MWException(
266 "Invalid collated file path list key error. " .
267 "'$key' given, string expected."
270 $this->{$member}[$key] = (array)$value;
272 break;
273 // Lists of strings
274 case 'dependencies':
275 case 'messages':
276 case 'targets':
277 // Normalise
278 $option = array_values( array_unique( (array)$option ) );
279 sort( $option );
281 $this->{$member} = $option;
282 break;
283 // Single strings
284 case 'group':
285 case 'position':
286 case 'skipFunction':
287 $this->{$member} = (string)$option;
288 break;
289 // Single booleans
290 case 'debugRaw':
291 case 'raw':
292 $this->{$member} = (bool)$option;
293 break;
296 if ( $hasTemplates ) {
297 $this->dependencies[] = 'mediawiki.template';
302 * Extract a pair of local and remote base paths from module definition information.
303 * Implementation note: the amount of global state used in this function is staggering.
305 * @param array $options Module definition
306 * @param string $localBasePath Path to use if not provided in module definition. Defaults
307 * to $IP
308 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
309 * to $wgResourceBasePath
310 * @return array Array( localBasePath, remoteBasePath )
312 public static function extractBasePaths(
313 $options = array(),
314 $localBasePath = null,
315 $remoteBasePath = null
317 global $IP, $wgResourceBasePath;
319 // The different ways these checks are done, and their ordering, look very silly,
320 // but were preserved for backwards-compatibility just in case. Tread lightly.
322 if ( $localBasePath === null ) {
323 $localBasePath = $IP;
325 if ( $remoteBasePath === null ) {
326 $remoteBasePath = $wgResourceBasePath;
329 if ( isset( $options['remoteExtPath'] ) ) {
330 global $wgExtensionAssetsPath;
331 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
334 if ( isset( $options['remoteSkinPath'] ) ) {
335 global $wgStylePath;
336 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
339 if ( array_key_exists( 'localBasePath', $options ) ) {
340 $localBasePath = (string)$options['localBasePath'];
343 if ( array_key_exists( 'remoteBasePath', $options ) ) {
344 $remoteBasePath = (string)$options['remoteBasePath'];
347 // Make sure the remote base path is a complete valid URL,
348 // but possibly protocol-relative to avoid cache pollution
349 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
351 return array( $localBasePath, $remoteBasePath );
355 * Gets all scripts for a given context concatenated together.
357 * @param ResourceLoaderContext $context Context in which to generate script
358 * @return string JavaScript code for $context
360 public function getScript( ResourceLoaderContext $context ) {
361 $files = $this->getScriptFiles( $context );
362 return $this->readScriptFiles( $files );
366 * @param ResourceLoaderContext $context
367 * @return array
369 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
370 $urls = array();
371 foreach ( $this->getScriptFiles( $context ) as $file ) {
372 $urls[] = $this->getRemotePath( $file );
374 return $urls;
378 * @return bool
380 public function supportsURLLoading() {
381 return $this->debugRaw;
385 * Get loader script.
387 * @return string|bool JavaScript code to be added to startup module
389 public function getLoaderScript() {
390 if ( count( $this->loaderScripts ) === 0 ) {
391 return false;
393 return $this->readScriptFiles( $this->loaderScripts );
397 * Get all styles for a given context.
399 * @param ResourceLoaderContext $context
400 * @return array CSS code for $context as an associative array mapping media type to CSS text.
402 public function getStyles( ResourceLoaderContext $context ) {
403 $styles = $this->readStyleFiles(
404 $this->getStyleFiles( $context ),
405 $this->getFlip( $context ),
406 $context
408 // Collect referenced files
409 $this->localFileRefs = array_unique( $this->localFileRefs );
410 // If the list has been modified since last time we cached it, update the cache
411 try {
412 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
413 $dbw = wfGetDB( DB_MASTER );
414 $dbw->replace( 'module_deps',
415 array( array( 'md_module', 'md_skin' ) ), array(
416 'md_module' => $this->getName(),
417 'md_skin' => $context->getSkin(),
418 'md_deps' => FormatJson::encode( $this->localFileRefs ),
422 } catch ( Exception $e ) {
423 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
425 return $styles;
429 * @param ResourceLoaderContext $context
430 * @return array
432 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
433 if ( $this->hasGeneratedStyles ) {
434 // Do the default behaviour of returning a url back to load.php
435 // but with only=styles.
436 return parent::getStyleURLsForDebug( $context );
438 // Our module consists entirely of real css files,
439 // in debug mode we can load those directly.
440 $urls = array();
441 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
442 $urls[$mediaType] = array();
443 foreach ( $list as $file ) {
444 $urls[$mediaType][] = $this->getRemotePath( $file );
447 return $urls;
451 * Gets list of message keys used by this module.
453 * @return array List of message keys
455 public function getMessages() {
456 return $this->messages;
460 * Gets the name of the group this module should be loaded in.
462 * @return string Group name
464 public function getGroup() {
465 return $this->group;
469 * @return string
471 public function getPosition() {
472 return $this->position;
476 * Gets list of names of modules this module depends on.
478 * @return array List of module names
480 public function getDependencies() {
481 return $this->dependencies;
485 * Get the skip function.
487 * @return string|null
489 public function getSkipFunction() {
490 if ( !$this->skipFunction ) {
491 return null;
494 $localPath = $this->getLocalPath( $this->skipFunction );
495 if ( !file_exists( $localPath ) ) {
496 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
498 $contents = file_get_contents( $localPath );
499 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
500 $contents = $this->validateScriptFile( $localPath, $contents );
502 return $contents;
506 * @return bool
508 public function isRaw() {
509 return $this->raw;
513 * Get the last modified timestamp of this module.
515 * Last modified timestamps are calculated from the highest last modified
516 * timestamp of this module's constituent files as well as the files it
517 * depends on. This function is context-sensitive, only performing
518 * calculations on files relevant to the given language, skin and debug
519 * mode.
521 * @param ResourceLoaderContext $context Context in which to calculate
522 * the modified time
523 * @return int UNIX timestamp
524 * @see ResourceLoaderModule::getFileDependencies
526 public function getModifiedTime( ResourceLoaderContext $context ) {
527 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
528 return $this->modifiedTime[$context->getHash()];
530 wfProfileIn( __METHOD__ );
532 $files = array();
534 // Flatten style files into $files
535 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
536 foreach ( $styles as $styleFiles ) {
537 $files = array_merge( $files, $styleFiles );
540 $skinFiles = self::collateFilePathListByOption(
541 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
542 'media',
543 'all'
545 foreach ( $skinFiles as $styleFiles ) {
546 $files = array_merge( $files, $styleFiles );
549 // Final merge, this should result in a master list of dependent files
550 $files = array_merge(
551 $files,
552 $this->scripts,
553 $this->templates,
554 $context->getDebug() ? $this->debugScripts : array(),
555 $this->getLanguageScripts( $context->getLanguage() ),
556 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
557 $this->loaderScripts
559 if ( $this->skipFunction ) {
560 $files[] = $this->skipFunction;
562 $files = array_map( array( $this, 'getLocalPath' ), $files );
563 // File deps need to be treated separately because they're already prefixed
564 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
566 // If a module is nothing but a list of dependencies, we need to avoid
567 // giving max() an empty array
568 if ( count( $files ) === 0 ) {
569 $this->modifiedTime[$context->getHash()] = 1;
570 wfProfileOut( __METHOD__ );
571 return $this->modifiedTime[$context->getHash()];
574 wfProfileIn( __METHOD__ . '-filemtime' );
575 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
576 wfProfileOut( __METHOD__ . '-filemtime' );
578 $this->modifiedTime[$context->getHash()] = max(
579 $filesMtime,
580 $this->getMsgBlobMtime( $context->getLanguage() ),
581 $this->getDefinitionMtime( $context )
584 wfProfileOut( __METHOD__ );
585 return $this->modifiedTime[$context->getHash()];
589 * Get the definition summary for this module.
591 * @param ResourceLoaderContext $context
592 * @return array
594 public function getDefinitionSummary( ResourceLoaderContext $context ) {
595 $summary = array(
596 'class' => get_class( $this ),
598 foreach ( array(
599 'scripts',
600 'debugScripts',
601 'loaderScripts',
602 'styles',
603 'languageScripts',
604 'skinScripts',
605 'skinStyles',
606 'dependencies',
607 'messages',
608 'targets',
609 'templates',
610 'group',
611 'position',
612 'skipFunction',
613 'localBasePath',
614 'remoteBasePath',
615 'debugRaw',
616 'raw',
617 ) as $member ) {
618 $summary[$member] = $this->{$member};
620 return $summary;
623 /* Protected Methods */
626 * @param string|ResourceLoaderFilePath $path
627 * @return string
629 protected function getLocalPath( $path ) {
630 if ( $path instanceof ResourceLoaderFilePath ) {
631 return $path->getLocalPath();
634 return "{$this->localBasePath}/$path";
638 * @param string|ResourceLoaderFilePath $path
639 * @return string
641 protected function getRemotePath( $path ) {
642 if ( $path instanceof ResourceLoaderFilePath ) {
643 return $path->getRemotePath();
646 return "{$this->remoteBasePath}/$path";
650 * Infer the stylesheet language from a stylesheet file path.
652 * @since 1.22
653 * @param string $path
654 * @return string The stylesheet language name
656 public function getStyleSheetLang( $path ) {
657 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
661 * Collates file paths by option (where provided).
663 * @param array $list List of file paths in any combination of index/path
664 * or path/options pairs
665 * @param string $option Option name
666 * @param mixed $default Default value if the option isn't set
667 * @return array List of file paths, collated by $option
669 protected static function collateFilePathListByOption( array $list, $option, $default ) {
670 $collatedFiles = array();
671 foreach ( (array)$list as $key => $value ) {
672 if ( is_int( $key ) ) {
673 // File name as the value
674 if ( !isset( $collatedFiles[$default] ) ) {
675 $collatedFiles[$default] = array();
677 $collatedFiles[$default][] = $value;
678 } elseif ( is_array( $value ) ) {
679 // File name as the key, options array as the value
680 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
681 if ( !isset( $collatedFiles[$optionValue] ) ) {
682 $collatedFiles[$optionValue] = array();
684 $collatedFiles[$optionValue][] = $key;
687 return $collatedFiles;
691 * Get a list of element that match a key, optionally using a fallback key.
693 * @param array $list List of lists to select from
694 * @param string $key Key to look for in $map
695 * @param string $fallback Key to look for in $list if $key doesn't exist
696 * @return array List of elements from $map which matched $key or $fallback,
697 * or an empty list in case of no match
699 protected static function tryForKey( array $list, $key, $fallback = null ) {
700 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
701 return $list[$key];
702 } elseif ( is_string( $fallback )
703 && isset( $list[$fallback] )
704 && is_array( $list[$fallback] )
706 return $list[$fallback];
708 return array();
712 * Get a list of file paths for all scripts in this module, in order of proper execution.
714 * @param ResourceLoaderContext $context
715 * @return array List of file paths
717 protected function getScriptFiles( ResourceLoaderContext $context ) {
718 $files = array_merge(
719 $this->scripts,
720 $this->getLanguageScripts( $context->getLanguage() ),
721 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
723 if ( $context->getDebug() ) {
724 $files = array_merge( $files, $this->debugScripts );
727 return array_unique( $files, SORT_REGULAR );
731 * Get the set of language scripts for the given language,
732 * possibly using a fallback language.
734 * @param string $lang
735 * @return array
737 private function getLanguageScripts( $lang ) {
738 $scripts = self::tryForKey( $this->languageScripts, $lang );
739 if ( $scripts ) {
740 return $scripts;
742 $fallbacks = Language::getFallbacksFor( $lang );
743 foreach ( $fallbacks as $lang ) {
744 $scripts = self::tryForKey( $this->languageScripts, $lang );
745 if ( $scripts ) {
746 return $scripts;
750 return array();
754 * Get a list of file paths for all styles in this module, in order of proper inclusion.
756 * @param ResourceLoaderContext $context
757 * @return array List of file paths
759 public function getStyleFiles( ResourceLoaderContext $context ) {
760 return array_merge_recursive(
761 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
762 self::collateFilePathListByOption(
763 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
764 'media',
765 'all'
771 * Gets a list of file paths for all skin styles in the module used by
772 * the skin.
774 * @param string $skinName The name of the skin
775 * @return array A list of file paths collated by media type
777 protected function getSkinStyleFiles( $skinName ) {
778 return self::collateFilePathListByOption(
779 self::tryForKey( $this->skinStyles, $skinName ),
780 'media',
781 'all'
786 * Gets a list of file paths for all skin style files in the module,
787 * for all available skins.
789 * @return array A list of file paths collated by media type
791 protected function getAllSkinStyleFiles() {
792 $styleFiles = array();
793 $internalSkinNames = array_keys( Skin::getSkinNames() );
794 $internalSkinNames[] = 'default';
796 foreach ( $internalSkinNames as $internalSkinName ) {
797 $styleFiles = array_merge_recursive(
798 $styleFiles,
799 $this->getSkinStyleFiles( $internalSkinName )
803 return $styleFiles;
807 * Returns all style files and all skin style files used by this module.
809 * @return array
811 public function getAllStyleFiles() {
812 $collatedStyleFiles = array_merge_recursive(
813 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
814 $this->getAllSkinStyleFiles()
817 $result = array();
819 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
820 foreach ( $styleFiles as $styleFile ) {
821 $result[] = $this->getLocalPath( $styleFile );
825 return $result;
829 * Gets the contents of a list of JavaScript files.
831 * @param array $scripts List of file paths to scripts to read, remap and concetenate
832 * @throws MWException
833 * @return string Concatenated and remapped JavaScript data from $scripts
835 protected function readScriptFiles( array $scripts ) {
836 if ( empty( $scripts ) ) {
837 return '';
839 $js = '';
840 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
841 $localPath = $this->getLocalPath( $fileName );
842 if ( !file_exists( $localPath ) ) {
843 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
845 $contents = file_get_contents( $localPath );
846 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
847 // Static files don't really need to be checked as often; unlike
848 // on-wiki module they shouldn't change unexpectedly without
849 // admin interference.
850 $contents = $this->validateScriptFile( $fileName, $contents );
852 $js .= $contents . "\n";
854 return $js;
858 * Gets the contents of a list of CSS files.
860 * @param array $styles List of media type/list of file paths pairs, to read, remap and
861 * concetenate
862 * @param bool $flip
863 * @param ResourceLoaderContext $context (optional)
865 * @throws MWException
866 * @return array List of concatenated and remapped CSS data from $styles,
867 * keyed by media type
869 public function readStyleFiles( array $styles, $flip, $context = null ) {
870 if ( empty( $styles ) ) {
871 return array();
873 foreach ( $styles as $media => $files ) {
874 $uniqueFiles = array_unique( $files, SORT_REGULAR );
875 $styleFiles = array();
876 foreach ( $uniqueFiles as $file ) {
877 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
879 $styles[$media] = implode( "\n", $styleFiles );
881 return $styles;
885 * Reads a style file.
887 * This method can be used as a callback for array_map()
889 * @param string $path File path of style file to read
890 * @param bool $flip
891 * @param ResourceLoaderContext $context (optional)
893 * @return string CSS data in script file
894 * @throws MWException If the file doesn't exist
896 protected function readStyleFile( $path, $flip, $context = null ) {
897 $localPath = $this->getLocalPath( $path );
898 $remotePath = $this->getRemotePath( $path );
899 if ( !file_exists( $localPath ) ) {
900 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
901 wfDebugLog( 'resourceloader', $msg );
902 throw new MWException( $msg );
905 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
906 $compiler = $this->getLessCompiler( $context );
907 $style = $this->compileLessFile( $localPath, $compiler );
908 $this->hasGeneratedStyles = true;
909 } else {
910 $style = file_get_contents( $localPath );
913 if ( $flip ) {
914 $style = CSSJanus::transform( $style, true, false );
916 $localDir = dirname( $localPath );
917 $remoteDir = dirname( $remotePath );
918 // Get and register local file references
919 $this->localFileRefs = array_merge(
920 $this->localFileRefs,
921 CSSMin::getLocalFileReferences( $style, $localDir )
923 return CSSMin::remap(
924 $style, $localDir, $remoteDir, true
929 * Get whether CSS for this module should be flipped
930 * @param ResourceLoaderContext $context
931 * @return bool
933 public function getFlip( $context ) {
934 return $context->getDirection() === 'rtl';
938 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
940 * @return array Array of strings
942 public function getTargets() {
943 return $this->targets;
947 * Compile a LESS file into CSS.
949 * Keeps track of all used files and adds them to localFileRefs.
951 * @since 1.22
952 * @throws Exception If lessc encounters a parse error
953 * @param string $fileName File path of LESS source
954 * @param lessc $compiler Compiler to use, if not default
955 * @return string CSS source
957 protected function compileLessFile( $fileName, $compiler = null ) {
958 if ( !$compiler ) {
959 $compiler = $this->getLessCompiler();
961 $result = $compiler->compileFile( $fileName );
962 $this->localFileRefs += array_keys( $compiler->allParsedFiles() );
963 return $result;
967 * Get a LESS compiler instance for this module in given context.
969 * Just calls ResourceLoader::getLessCompiler() by default to get a global compiler.
971 * @param ResourceLoaderContext $context
972 * @throws MWException
973 * @since 1.24
974 * @return lessc
976 protected function getLessCompiler( ResourceLoaderContext $context = null ) {
977 return ResourceLoader::getLessCompiler( $this->getConfig() );
981 * Takes named templates by the module and returns an array mapping.
983 * @return array of templates mapping template alias to content
985 public function getTemplates() {
986 $templates = array();
988 foreach ( $this->templates as $alias => $templatePath ) {
989 // Alias is optional
990 if ( is_int( $alias ) ) {
991 $alias = $templatePath;
993 $localPath = $this->getLocalPath( $templatePath );
994 if ( file_exists( $localPath ) ) {
995 $content = file_get_contents( $localPath );
996 $templates[$alias] = $content;
997 } else {
998 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
999 wfDebugLog( 'resourceloader', $msg );
1000 throw new MWException( $msg );
1003 return $templates;