wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blobf5b3bad5c3e798e90b75a6ec2a05115b0b9a6d7e
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 = 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 CSS files to always include
78 * @par Usage:
79 * @code
80 * array( [file-path], [file-path], ... )
81 * @endcode
83 protected $styles = array();
85 /**
86 * @var array List of paths to CSS files to include when using specific skins
87 * @par Usage:
88 * @code
89 * array( [file-path], [file-path], ... )
90 * @endcode
92 protected $skinStyles = array();
94 /**
95 * @var array List of modules this module depends on
96 * @par Usage:
97 * @code
98 * array( [file-path], [file-path], ... )
99 * @endcode
101 protected $dependencies = array();
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 * array( [message-key], [message-key], ... )
113 * @endcode
115 protected $messages = array();
117 /** @var string Name of group to load this module in */
118 protected $group;
120 /** @var string Position on the page to load this module at */
121 protected $position = 'bottom';
123 /** @var bool Link to raw files in debug mode */
124 protected $debugRaw = true;
126 /** @var bool Whether mw.loader.state() call should be omitted */
127 protected $raw = false;
129 protected $targets = array( 'desktop' );
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 * array( [file-path], [file-path], ... )
142 * @endcode
144 protected $localFileRefs = array();
147 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
148 * Used in tests to detect missing dependencies.
150 protected $missingLocalFileRefs = array();
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
168 * array(
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' => array(
181 * [language code] => [file path string or array of file path strings],
182 * ),
183 * // Scripts to include in specific skin contexts
184 * 'skinScripts' => array(
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' => array(
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' => array(
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 * // Position on the page to load this module at
205 * 'position' => ['bottom' (default) or 'top']
206 * // Function that, if it returns true, makes the loader skip this module.
207 * // The file must contain valid JavaScript for execution in a private function.
208 * // The file must not contain the "function () {" and "}" wrapper though.
209 * 'skipFunction' => [file path]
211 * @endcode
213 public function __construct(
214 $options = array(),
215 $localBasePath = null,
216 $remoteBasePath = null
218 // Flag to decide whether to automagically add the mediawiki.template module
219 $hasTemplates = false;
220 // localBasePath and remoteBasePath both have unbelievably long fallback chains
221 // and need to be handled separately.
222 list( $this->localBasePath, $this->remoteBasePath ) =
223 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
225 // Extract, validate and normalise remaining options
226 foreach ( $options as $member => $option ) {
227 switch ( $member ) {
228 // Lists of file paths
229 case 'scripts':
230 case 'debugScripts':
231 case 'styles':
232 $this->{$member} = (array)$option;
233 break;
234 case 'templates':
235 $hasTemplates = true;
236 $this->{$member} = (array)$option;
237 break;
238 // Collated lists of file paths
239 case 'languageScripts':
240 case 'skinScripts':
241 case 'skinStyles':
242 if ( !is_array( $option ) ) {
243 throw new InvalidArgumentException(
244 "Invalid collated file path list error. " .
245 "'$option' given, array expected."
248 foreach ( $option as $key => $value ) {
249 if ( !is_string( $key ) ) {
250 throw new InvalidArgumentException(
251 "Invalid collated file path list key error. " .
252 "'$key' given, string expected."
255 $this->{$member}[$key] = (array)$value;
257 break;
258 // Lists of strings
259 case 'dependencies':
260 case 'messages':
261 case 'targets':
262 // Normalise
263 $option = array_values( array_unique( (array)$option ) );
264 sort( $option );
266 $this->{$member} = $option;
267 break;
268 // Single strings
269 case 'position':
270 case 'group':
271 case 'skipFunction':
272 $this->{$member} = (string)$option;
273 break;
274 // Single booleans
275 case 'debugRaw':
276 case 'raw':
277 $this->{$member} = (bool)$option;
278 break;
281 if ( $hasTemplates ) {
282 $this->dependencies[] = 'mediawiki.template';
283 // Ensure relevant template compiler module gets loaded
284 foreach ( $this->templates as $alias => $templatePath ) {
285 if ( is_int( $alias ) ) {
286 $alias = $templatePath;
288 $suffix = explode( '.', $alias );
289 $suffix = end( $suffix );
290 $compilerModule = 'mediawiki.template.' . $suffix;
291 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
292 $this->dependencies[] = $compilerModule;
299 * Extract a pair of local and remote base paths from module definition information.
300 * Implementation note: the amount of global state used in this function is staggering.
302 * @param array $options Module definition
303 * @param string $localBasePath Path to use if not provided in module definition. Defaults
304 * to $IP
305 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
306 * to $wgResourceBasePath
307 * @return array Array( localBasePath, remoteBasePath )
309 public static function extractBasePaths(
310 $options = array(),
311 $localBasePath = null,
312 $remoteBasePath = null
314 global $IP, $wgResourceBasePath;
316 // The different ways these checks are done, and their ordering, look very silly,
317 // but were preserved for backwards-compatibility just in case. Tread lightly.
319 if ( $localBasePath === null ) {
320 $localBasePath = $IP;
322 if ( $remoteBasePath === null ) {
323 $remoteBasePath = $wgResourceBasePath;
326 if ( isset( $options['remoteExtPath'] ) ) {
327 global $wgExtensionAssetsPath;
328 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
331 if ( isset( $options['remoteSkinPath'] ) ) {
332 global $wgStylePath;
333 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
336 if ( array_key_exists( 'localBasePath', $options ) ) {
337 $localBasePath = (string)$options['localBasePath'];
340 if ( array_key_exists( 'remoteBasePath', $options ) ) {
341 $remoteBasePath = (string)$options['remoteBasePath'];
344 // Make sure the remote base path is a complete valid URL,
345 // but possibly protocol-relative to avoid cache pollution
346 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
348 return array( $localBasePath, $remoteBasePath );
352 * Gets all scripts for a given context concatenated together.
354 * @param ResourceLoaderContext $context Context in which to generate script
355 * @return string JavaScript code for $context
357 public function getScript( ResourceLoaderContext $context ) {
358 $files = $this->getScriptFiles( $context );
359 return $this->readScriptFiles( $files );
363 * @param ResourceLoaderContext $context
364 * @return array
366 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
367 $urls = array();
368 foreach ( $this->getScriptFiles( $context ) as $file ) {
369 $urls[] = $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 = array();
412 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
413 $urls[$mediaType] = array();
414 foreach ( $list as $file ) {
415 $urls[$mediaType][] = $this->getRemotePath( $file );
418 return $urls;
422 * Gets list of message keys used by this module.
424 * @return array List of message keys
426 public function getMessages() {
427 return $this->messages;
431 * Gets the name of the group this module should be loaded in.
433 * @return string Group name
435 public function getGroup() {
436 return $this->group;
440 * @return string
442 public function getPosition() {
443 return $this->position;
447 * Gets list of names of modules this module depends on.
448 * @param ResourceLoaderContext|null $context
449 * @return array List of module names
451 public function getDependencies( ResourceLoaderContext $context = null ) {
452 return $this->dependencies;
456 * Get the skip function.
457 * @return null|string
458 * @throws MWException
460 public function getSkipFunction() {
461 if ( !$this->skipFunction ) {
462 return null;
465 $localPath = $this->getLocalPath( $this->skipFunction );
466 if ( !file_exists( $localPath ) ) {
467 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
469 $contents = file_get_contents( $localPath );
470 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
471 $contents = $this->validateScriptFile( $localPath, $contents );
473 return $contents;
477 * @return bool
479 public function isRaw() {
480 return $this->raw;
484 * Disable module content versioning.
486 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
487 * involved with building the full module content inside a startup request.
489 * @return bool
491 public function enableModuleContentVersion() {
492 return false;
496 * Helper method to gather file hashes for getDefinitionSummary.
498 * This function is context-sensitive, only computing hashes of files relevant to the
499 * given language, skin, etc.
501 * @see ResourceLoaderModule::getFileDependencies
502 * @param ResourceLoaderContext $context
503 * @return array
505 protected function getFileHashes( ResourceLoaderContext $context ) {
506 $files = array();
508 // Flatten style files into $files
509 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
510 foreach ( $styles as $styleFiles ) {
511 $files = array_merge( $files, $styleFiles );
514 $skinFiles = self::collateFilePathListByOption(
515 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
516 'media',
517 'all'
519 foreach ( $skinFiles as $styleFiles ) {
520 $files = array_merge( $files, $styleFiles );
523 // Final merge, this should result in a master list of dependent files
524 $files = array_merge(
525 $files,
526 $this->scripts,
527 $this->templates,
528 $context->getDebug() ? $this->debugScripts : array(),
529 $this->getLanguageScripts( $context->getLanguage() ),
530 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
532 if ( $this->skipFunction ) {
533 $files[] = $this->skipFunction;
535 $files = array_map( array( $this, 'getLocalPath' ), $files );
536 // File deps need to be treated separately because they're already prefixed
537 $files = array_merge( $files, $this->getFileDependencies( $context ) );
538 // Filter out any duplicates from getFileDependencies() and others.
539 // Most commonly introduced by compileLessFile(), which always includes the
540 // entry point Less file we already know about.
541 $files = array_values( array_unique( $files ) );
543 // Don't include keys or file paths here, only the hashes. Including that would needlessly
544 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
545 // Any significant ordering is already detected by the definition summary.
546 return array_map( array( __CLASS__, 'safeFileHash' ), $files );
550 * Get the definition summary for this module.
552 * @param ResourceLoaderContext $context
553 * @return array
555 public function getDefinitionSummary( ResourceLoaderContext $context ) {
556 $summary = parent::getDefinitionSummary( $context );
558 $options = array();
559 foreach ( array(
560 // The following properties are omitted because they don't affect the module reponse:
561 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
562 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
563 // - remoteBasePath (Per T104950)
564 // - dependencies (provided via startup module)
565 // - targets
566 // - group (provided via startup module)
567 // - position (only used by OutputPage)
568 'scripts',
569 'debugScripts',
570 'styles',
571 'languageScripts',
572 'skinScripts',
573 'skinStyles',
574 'messages',
575 'templates',
576 'skipFunction',
577 'debugRaw',
578 'raw',
579 ) as $member ) {
580 $options[$member] = $this->{$member};
583 $summary[] = array(
584 'options' => $options,
585 'fileHashes' => $this->getFileHashes( $context ),
586 'messageBlob' => $this->getMessageBlob( $context ),
588 return $summary;
592 * @param string|ResourceLoaderFilePath $path
593 * @return string
595 protected function getLocalPath( $path ) {
596 if ( $path instanceof ResourceLoaderFilePath ) {
597 return $path->getLocalPath();
600 return "{$this->localBasePath}/$path";
604 * @param string|ResourceLoaderFilePath $path
605 * @return string
607 protected function getRemotePath( $path ) {
608 if ( $path instanceof ResourceLoaderFilePath ) {
609 return $path->getRemotePath();
612 return "{$this->remoteBasePath}/$path";
616 * Infer the stylesheet language from a stylesheet file path.
618 * @since 1.22
619 * @param string $path
620 * @return string The stylesheet language name
622 public function getStyleSheetLang( $path ) {
623 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
627 * Collates file paths by option (where provided).
629 * @param array $list List of file paths in any combination of index/path
630 * or path/options pairs
631 * @param string $option Option name
632 * @param mixed $default Default value if the option isn't set
633 * @return array List of file paths, collated by $option
635 protected static function collateFilePathListByOption( array $list, $option, $default ) {
636 $collatedFiles = array();
637 foreach ( (array)$list as $key => $value ) {
638 if ( is_int( $key ) ) {
639 // File name as the value
640 if ( !isset( $collatedFiles[$default] ) ) {
641 $collatedFiles[$default] = array();
643 $collatedFiles[$default][] = $value;
644 } elseif ( is_array( $value ) ) {
645 // File name as the key, options array as the value
646 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
647 if ( !isset( $collatedFiles[$optionValue] ) ) {
648 $collatedFiles[$optionValue] = array();
650 $collatedFiles[$optionValue][] = $key;
653 return $collatedFiles;
657 * Get a list of element that match a key, optionally using a fallback key.
659 * @param array $list List of lists to select from
660 * @param string $key Key to look for in $map
661 * @param string $fallback Key to look for in $list if $key doesn't exist
662 * @return array List of elements from $map which matched $key or $fallback,
663 * or an empty list in case of no match
665 protected static function tryForKey( array $list, $key, $fallback = null ) {
666 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
667 return $list[$key];
668 } elseif ( is_string( $fallback )
669 && isset( $list[$fallback] )
670 && is_array( $list[$fallback] )
672 return $list[$fallback];
674 return array();
678 * Get a list of file paths for all scripts in this module, in order of proper execution.
680 * @param ResourceLoaderContext $context
681 * @return array List of file paths
683 protected function getScriptFiles( ResourceLoaderContext $context ) {
684 $files = array_merge(
685 $this->scripts,
686 $this->getLanguageScripts( $context->getLanguage() ),
687 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
689 if ( $context->getDebug() ) {
690 $files = array_merge( $files, $this->debugScripts );
693 return array_unique( $files, SORT_REGULAR );
697 * Get the set of language scripts for the given language,
698 * possibly using a fallback language.
700 * @param string $lang
701 * @return array
703 private function getLanguageScripts( $lang ) {
704 $scripts = self::tryForKey( $this->languageScripts, $lang );
705 if ( $scripts ) {
706 return $scripts;
708 $fallbacks = Language::getFallbacksFor( $lang );
709 foreach ( $fallbacks as $lang ) {
710 $scripts = self::tryForKey( $this->languageScripts, $lang );
711 if ( $scripts ) {
712 return $scripts;
716 return array();
720 * Get a list of file paths for all styles in this module, in order of proper inclusion.
722 * @param ResourceLoaderContext $context
723 * @return array List of file paths
725 public function getStyleFiles( ResourceLoaderContext $context ) {
726 return array_merge_recursive(
727 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
728 self::collateFilePathListByOption(
729 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
730 'media',
731 'all'
737 * Gets a list of file paths for all skin styles in the module used by
738 * the skin.
740 * @param string $skinName The name of the skin
741 * @return array A list of file paths collated by media type
743 protected function getSkinStyleFiles( $skinName ) {
744 return self::collateFilePathListByOption(
745 self::tryForKey( $this->skinStyles, $skinName ),
746 'media',
747 'all'
752 * Gets a list of file paths for all skin style files in the module,
753 * for all available skins.
755 * @return array A list of file paths collated by media type
757 protected function getAllSkinStyleFiles() {
758 $styleFiles = array();
759 $internalSkinNames = array_keys( Skin::getSkinNames() );
760 $internalSkinNames[] = 'default';
762 foreach ( $internalSkinNames as $internalSkinName ) {
763 $styleFiles = array_merge_recursive(
764 $styleFiles,
765 $this->getSkinStyleFiles( $internalSkinName )
769 return $styleFiles;
773 * Returns all style files and all skin style files used by this module.
775 * @return array
777 public function getAllStyleFiles() {
778 $collatedStyleFiles = array_merge_recursive(
779 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
780 $this->getAllSkinStyleFiles()
783 $result = array();
785 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
786 foreach ( $styleFiles as $styleFile ) {
787 $result[] = $this->getLocalPath( $styleFile );
791 return $result;
795 * Gets the contents of a list of JavaScript files.
797 * @param array $scripts List of file paths to scripts to read, remap and concetenate
798 * @throws MWException
799 * @return string Concatenated and remapped JavaScript data from $scripts
801 protected function readScriptFiles( array $scripts ) {
802 if ( empty( $scripts ) ) {
803 return '';
805 $js = '';
806 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
807 $localPath = $this->getLocalPath( $fileName );
808 if ( !file_exists( $localPath ) ) {
809 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
811 $contents = file_get_contents( $localPath );
812 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
813 // Static files don't really need to be checked as often; unlike
814 // on-wiki module they shouldn't change unexpectedly without
815 // admin interference.
816 $contents = $this->validateScriptFile( $fileName, $contents );
818 $js .= $contents . "\n";
820 return $js;
824 * Gets the contents of a list of CSS files.
826 * @param array $styles List of media type/list of file paths pairs, to read, remap and
827 * concetenate
828 * @param bool $flip
829 * @param ResourceLoaderContext $context
831 * @throws MWException
832 * @return array List of concatenated and remapped CSS data from $styles,
833 * keyed by media type
835 * @since 1.27 Calling this method without a ResourceLoaderContext instance
836 * is deprecated.
838 public function readStyleFiles( array $styles, $flip, $context = null ) {
839 if ( $context === null ) {
840 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
841 $context = ResourceLoaderContext::newDummyContext();
844 if ( empty( $styles ) ) {
845 return array();
847 foreach ( $styles as $media => $files ) {
848 $uniqueFiles = array_unique( $files, SORT_REGULAR );
849 $styleFiles = array();
850 foreach ( $uniqueFiles as $file ) {
851 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
853 $styles[$media] = implode( "\n", $styleFiles );
855 return $styles;
859 * Reads a style file.
861 * This method can be used as a callback for array_map()
863 * @param string $path File path of style file to read
864 * @param bool $flip
865 * @param ResourceLoaderContext $context
867 * @return string CSS data in script file
868 * @throws MWException If the file doesn't exist
870 protected function readStyleFile( $path, $flip, $context ) {
871 $localPath = $this->getLocalPath( $path );
872 $remotePath = $this->getRemotePath( $path );
873 if ( !file_exists( $localPath ) ) {
874 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
875 wfDebugLog( 'resourceloader', $msg );
876 throw new MWException( $msg );
879 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
880 $style = $this->compileLessFile( $localPath, $context );
881 $this->hasGeneratedStyles = true;
882 } else {
883 $style = file_get_contents( $localPath );
886 if ( $flip ) {
887 $style = CSSJanus::transform( $style, true, false );
889 $localDir = dirname( $localPath );
890 $remoteDir = dirname( $remotePath );
891 // Get and register local file references
892 $localFileRefs = CSSMin::getAllLocalFileReferences( $style, $localDir );
893 foreach ( $localFileRefs as $file ) {
894 if ( file_exists( $file ) ) {
895 $this->localFileRefs[] = $file;
896 } else {
897 $this->missingLocalFileRefs[] = $file;
900 return MemoizedCallable::call( 'CSSMin::remap',
901 array( $style, $localDir, $remoteDir, true ) );
905 * Get whether CSS for this module should be flipped
906 * @param ResourceLoaderContext $context
907 * @return bool
909 public function getFlip( $context ) {
910 return $context->getDirection() === 'rtl';
914 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
916 * @return array Array of strings
918 public function getTargets() {
919 return $this->targets;
923 * Compile a LESS file into CSS.
925 * Keeps track of all used files and adds them to localFileRefs.
927 * @since 1.22
928 * @since 1.27 Added $context paramter.
929 * @throws Exception If less.php encounters a parse error
930 * @param string $fileName File path of LESS source
931 * @param ResourceLoaderContext $context Context in which to generate script
932 * @return string CSS source
934 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
935 static $cache;
937 if ( !$cache ) {
938 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
941 // Construct a cache key from the LESS file name and a hash digest
942 // of the LESS variables used for compilation.
943 $vars = $this->getLessVars( $context );
944 ksort( $vars );
945 $varsHash = hash( 'md4', serialize( $vars ) );
946 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
947 $cachedCompile = $cache->get( $cacheKey );
949 // If we got a cached value, we have to validate it by getting a
950 // checksum of all the files that were loaded by the parser and
951 // ensuring it matches the cached entry's.
952 if ( isset( $cachedCompile['hash'] ) ) {
953 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
954 if ( $contentHash === $cachedCompile['hash'] ) {
955 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
956 return $cachedCompile['css'];
960 $compiler = ResourceLoader::getLessCompiler( $this->getConfig(), $vars );
961 $css = $compiler->parseFile( $fileName )->getCss();
962 $files = $compiler->AllParsedFiles();
963 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
965 $cache->set( $cacheKey, array(
966 'css' => $css,
967 'files' => $files,
968 'hash' => FileContentsHasher::getFileContentsHash( $files ),
969 ), 60 * 60 * 24 ); // 86400 seconds, or 24 hours.
971 return $css;
975 * Takes named templates by the module and returns an array mapping.
976 * @return array of templates mapping template alias to content
977 * @throws MWException
979 public function getTemplates() {
980 $templates = array();
982 foreach ( $this->templates as $alias => $templatePath ) {
983 // Alias is optional
984 if ( is_int( $alias ) ) {
985 $alias = $templatePath;
987 $localPath = $this->getLocalPath( $templatePath );
988 if ( file_exists( $localPath ) ) {
989 $content = file_get_contents( $localPath );
990 $templates[$alias] = $content;
991 } else {
992 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
993 wfDebugLog( 'resourceloader', $msg );
994 throw new MWException( $msg );
997 return $templates;