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
21 * @author Trevor Parscal
22 * @author Roan Kattouw
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 = '';
38 * @var array List of paths to JavaScript files to always include
41 * array( [file-path], [file-path], ... )
44 protected $scripts = array();
47 * @var array List of JavaScript files to include when using a specific language
50 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
53 protected $languageScripts = array();
56 * @var array List of JavaScript files to include when using a specific skin
59 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
62 protected $skinScripts = array();
65 * @var array List of paths to JavaScript files to include in debug mode
68 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
71 protected $debugScripts = array();
74 * @var array List of paths to JavaScript files to include in the startup module
77 * array( [file-path], [file-path], ... )
80 protected $loaderScripts = array();
83 * @var array List of paths to CSS files to always include
86 * array( [file-path], [file-path], ... )
89 protected $styles = array();
92 * @var array List of paths to CSS files to include when using specific skins
95 * array( [file-path], [file-path], ... )
98 protected $skinStyles = array();
101 * @var array List of modules this module depends on
104 * array( [file-path], [file-path], ... )
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
118 * array( [message-key], [message-key], ... )
121 protected $messages = array();
123 /** @var string Name of group to load this module in */
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
147 * array( [hash] => [mtime], [hash] => [mtime], ... )
150 protected $modifiedTime = array();
153 * @var array Place where readStyleFile() tracks file dependencies
156 * array( [file-path], [file-path], ... )
159 protected $localFileRefs = array();
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
168 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
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:
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],
192 * // Scripts to include in specific skin contexts
193 * 'skinScripts' => array(
194 * [skin name] => [file path string or array of file path strings],
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],
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]
221 public function __construct(
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 ) {
234 // Lists of file paths
237 case 'loaderScripts':
239 $this->{$member} = (array)$option;
241 // Collated lists of file paths
242 case 'languageScripts':
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;
266 $option = array_values( array_unique( (array)$option ) );
269 $this->{$member} = $option;
275 $this->{$member} = (string)$option;
280 $this->{$member} = (bool)$option;
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
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(
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'] ) ) {
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
354 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
356 foreach ( $this->getScriptFiles( $context ) as $file ) {
357 $urls[] = $this->getRemotePath( $file );
365 public function supportsURLLoading() {
366 return $this->debugRaw
;
372 * @return string|bool JavaScript code to be added to startup module
374 public function getLoaderScript() {
375 if ( count( $this->loaderScripts
) === 0 ) {
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 ),
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
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" );
414 * @param ResourceLoaderContext $context
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.
426 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
427 $urls[$mediaType] = array();
428 foreach ( $list as $file ) {
429 $urls[$mediaType][] = $this->getRemotePath( $file );
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() {
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
) {
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 );
493 public function isRaw() {
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
506 * @param ResourceLoaderContext $context Context in which to calculate
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__
);
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' ),
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(
538 $context->getDebug() ?
$this->debugScripts
: array(),
539 $this->getLanguageScripts( $context->getLanguage() ),
540 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
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(
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
578 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
580 'class' => get_class( $this ),
601 $summary[$member] = $this->{$member};
606 /* Protected Methods */
609 * @param string|ResourceLoaderFilePath $path
612 protected function getLocalPath( $path ) {
613 if ( $path instanceof ResourceLoaderFilePath
) {
614 return $path->getLocalPath();
617 return "{$this->localBasePath}/$path";
621 * @param string|ResourceLoaderFilePath $path
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.
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] ) ) {
685 } elseif ( is_string( $fallback )
686 && isset( $list[$fallback] )
687 && is_array( $list[$fallback] )
689 return $list[$fallback];
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(
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
720 private function getLanguageScripts( $lang ) {
721 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
725 $fallbacks = Language
::getFallbacksFor( $lang );
726 foreach ( $fallbacks as $lang ) {
727 $scripts = self
::tryForKey( $this->languageScripts
, $lang );
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' ),
754 * Gets a list of file paths for all skin styles in the module used by
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 ),
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(
782 $this->getSkinStyleFiles( $internalSkinName )
790 * Returns all style files and all skin style files used by this module.
794 public function getAllStyleFiles() {
795 $collatedStyleFiles = array_merge_recursive(
796 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
797 $this->getAllSkinStyleFiles()
802 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
803 foreach ( $styleFiles as $styleFile ) {
804 $result[] = $this->getLocalPath( $styleFile );
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 ) ) {
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";
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
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 ) ) {
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 );
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
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;
893 $style = file_get_contents( $localPath );
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
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.
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 ) {
942 $compiler = $this->getLessCompiler();
944 $result = $compiler->compileFile( $fileName );
945 $this->localFileRefs +
= array_keys( $compiler->allParsedFiles() );
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
959 protected function getLessCompiler( ResourceLoaderContext
$context = null ) {
960 return ResourceLoader
::getLessCompiler( $this->getConfig() );