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
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 $wgScriptPath
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
295 * @return array Array( localBasePath, remoteBasePath )
297 public static function extractBasePaths(
299 $localBasePath = null,
300 $remoteBasePath = null
302 global $IP, $wgScriptPath, $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 $localBasePath = $localBasePath === null ?
$IP : $localBasePath;
308 if ( $remoteBasePath !== null ) {
309 $remoteBasePath = $remoteBasePath;
311 $remoteBasePath = $wgResourceBasePath === null ?
$wgScriptPath : $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 )
392 // Collect referenced files
393 $this->localFileRefs
= array_unique( $this->localFileRefs
);
394 // If the list has been modified since last time we cached it, update the cache
396 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
397 $dbw = wfGetDB( DB_MASTER
);
398 $dbw->replace( 'module_deps',
399 array( array( 'md_module', 'md_skin' ) ), array(
400 'md_module' => $this->getName(),
401 'md_skin' => $context->getSkin(),
402 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
406 } catch ( Exception
$e ) {
407 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
413 * @param ResourceLoaderContext $context
416 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
417 if ( $this->hasGeneratedStyles
) {
418 // Do the default behaviour of returning a url back to load.php
419 // but with only=styles.
420 return parent
::getStyleURLsForDebug( $context );
422 // Our module consists entirely of real css files,
423 // in debug mode we can load those directly.
425 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
426 $urls[$mediaType] = array();
427 foreach ( $list as $file ) {
428 $urls[$mediaType][] = $this->getRemotePath( $file );
435 * Gets list of message keys used by this module.
437 * @return array List of message keys
439 public function getMessages() {
440 return $this->messages
;
444 * Gets the name of the group this module should be loaded in.
446 * @return string Group name
448 public function getGroup() {
455 public function getPosition() {
456 return $this->position
;
460 * Gets list of names of modules this module depends on.
462 * @return array List of module names
464 public function getDependencies() {
465 return $this->dependencies
;
469 * Get the skip function.
471 * @return string|null
473 public function getSkipFunction() {
474 if ( !$this->skipFunction
) {
478 global $wgResourceLoaderValidateStaticJS;
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 ( $wgResourceLoaderValidateStaticJS ) {
485 $contents = $this->validateScriptFile( $fileName, $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 self
::tryForKey( $this->languageScripts
, $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.
577 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
579 'class' => get_class( $this ),
600 $summary[$member] = $this->{$member};
605 /* Protected Methods */
608 * @param string|ResourceLoaderFilePath $path
611 protected function getLocalPath( $path ) {
612 if ( $path instanceof ResourceLoaderFilePath
) {
613 return $path->getLocalPath();
616 return "{$this->localBasePath}/$path";
620 * @param string|ResourceLoaderFilePath $path
623 protected function getRemotePath( $path ) {
624 if ( $path instanceof ResourceLoaderFilePath
) {
625 return $path->getRemotePath();
628 return "{$this->remoteBasePath}/$path";
632 * Infer the stylesheet language from a stylesheet file path.
635 * @param string $path
636 * @return string The stylesheet language name
638 public function getStyleSheetLang( $path ) {
639 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
643 * Collates file paths by option (where provided).
645 * @param array $list List of file paths in any combination of index/path
646 * or path/options pairs
647 * @param string $option Option name
648 * @param mixed $default Default value if the option isn't set
649 * @return array List of file paths, collated by $option
651 protected static function collateFilePathListByOption( array $list, $option, $default ) {
652 $collatedFiles = array();
653 foreach ( (array)$list as $key => $value ) {
654 if ( is_int( $key ) ) {
655 // File name as the value
656 if ( !isset( $collatedFiles[$default] ) ) {
657 $collatedFiles[$default] = array();
659 $collatedFiles[$default][] = $value;
660 } elseif ( is_array( $value ) ) {
661 // File name as the key, options array as the value
662 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
663 if ( !isset( $collatedFiles[$optionValue] ) ) {
664 $collatedFiles[$optionValue] = array();
666 $collatedFiles[$optionValue][] = $key;
669 return $collatedFiles;
673 * Get a list of element that match a key, optionally using a fallback key.
675 * @param array $list List of lists to select from
676 * @param string $key Key to look for in $map
677 * @param string $fallback Key to look for in $list if $key doesn't exist
678 * @return array List of elements from $map which matched $key or $fallback,
679 * or an empty list in case of no match
681 protected static function tryForKey( array $list, $key, $fallback = null ) {
682 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
684 } elseif ( is_string( $fallback )
685 && isset( $list[$fallback] )
686 && is_array( $list[$fallback] )
688 return $list[$fallback];
694 * Get a list of file paths for all scripts in this module, in order of proper execution.
696 * @param ResourceLoaderContext $context
697 * @return array List of file paths
699 protected function getScriptFiles( ResourceLoaderContext
$context ) {
700 $files = array_merge(
702 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
703 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
705 if ( $context->getDebug() ) {
706 $files = array_merge( $files, $this->debugScripts
);
709 return array_unique( $files, SORT_REGULAR
);
713 * Get a list of file paths for all styles in this module, in order of proper inclusion.
715 * @param ResourceLoaderContext $context
716 * @return array List of file paths
718 public function getStyleFiles( ResourceLoaderContext
$context ) {
719 return array_merge_recursive(
720 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
721 self
::collateFilePathListByOption(
722 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
730 * Gets a list of file paths for all skin styles in the module used by
733 * @param string $skinName The name of the skin
734 * @return array A list of file paths collated by media type
736 protected function getSkinStyleFiles( $skinName ) {
737 return self
::collateFilePathListByOption(
738 self
::tryForKey( $this->skinStyles
, $skinName ),
745 * Gets a list of file paths for all skin style files in the module,
746 * for all available skins.
748 * @return array A list of file paths collated by media type
750 protected function getAllSkinStyleFiles() {
751 $styleFiles = array();
752 $internalSkinNames = array_keys( Skin
::getSkinNames() );
753 $internalSkinNames[] = 'default';
755 foreach ( $internalSkinNames as $internalSkinName ) {
756 $styleFiles = array_merge_recursive(
758 $this->getSkinStyleFiles( $internalSkinName )
766 * Returns all style files and all skin style files used by this module.
770 public function getAllStyleFiles() {
771 $collatedStyleFiles = array_merge_recursive(
772 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
773 $this->getAllSkinStyleFiles()
778 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
779 foreach ( $styleFiles as $styleFile ) {
780 $result[] = $this->getLocalPath( $styleFile );
788 * Gets the contents of a list of JavaScript files.
790 * @param array $scripts List of file paths to scripts to read, remap and concetenate
791 * @throws MWException
792 * @return string Concatenated and remapped JavaScript data from $scripts
794 protected function readScriptFiles( array $scripts ) {
795 global $wgResourceLoaderValidateStaticJS;
796 if ( empty( $scripts ) ) {
800 foreach ( array_unique( $scripts, SORT_REGULAR
) as $fileName ) {
801 $localPath = $this->getLocalPath( $fileName );
802 if ( !file_exists( $localPath ) ) {
803 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
805 $contents = file_get_contents( $localPath );
806 if ( $wgResourceLoaderValidateStaticJS ) {
807 // Static files don't really need to be checked as often; unlike
808 // on-wiki module they shouldn't change unexpectedly without
809 // admin interference.
810 $contents = $this->validateScriptFile( $fileName, $contents );
812 $js .= $contents . "\n";
818 * Gets the contents of a list of CSS files.
820 * @param array $styles List of media type/list of file paths pairs, to read, remap and
825 * @throws MWException
826 * @return array List of concatenated and remapped CSS data from $styles,
827 * keyed by media type
829 public function readStyleFiles( array $styles, $flip ) {
830 if ( empty( $styles ) ) {
833 foreach ( $styles as $media => $files ) {
834 $uniqueFiles = array_unique( $files, SORT_REGULAR
);
835 $styleFiles = array();
836 foreach ( $uniqueFiles as $file ) {
837 $styleFiles[] = $this->readStyleFile( $file, $flip );
839 $styles[$media] = implode( "\n", $styleFiles );
845 * Reads a style file.
847 * This method can be used as a callback for array_map()
849 * @param string $path File path of style file to read
852 * @return string CSS data in script file
853 * @throws MWException If the file doesn't exist
855 protected function readStyleFile( $path, $flip ) {
856 $localPath = $this->getLocalPath( $path );
857 $remotePath = $this->getRemotePath( $path );
858 if ( !file_exists( $localPath ) ) {
859 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
860 wfDebugLog( 'resourceloader', $msg );
861 throw new MWException( $msg );
864 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
865 $style = $this->compileLESSFile( $localPath );
866 $this->hasGeneratedStyles
= true;
868 $style = file_get_contents( $localPath );
872 $style = CSSJanus
::transform( $style, true, false );
874 $localDir = dirname( $localPath );
875 $remoteDir = dirname( $remotePath );
876 // Get and register local file references
877 $this->localFileRefs
= array_merge(
878 $this->localFileRefs
,
879 CSSMin
::getLocalFileReferences( $style, $localDir )
881 return CSSMin
::remap(
882 $style, $localDir, $remoteDir, true
887 * Get whether CSS for this module should be flipped
888 * @param ResourceLoaderContext $context
891 public function getFlip( $context ) {
892 return $context->getDirection() === 'rtl';
896 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
898 * @return array Array of strings
900 public function getTargets() {
901 return $this->targets
;
905 * Generate a cache key for a LESS file.
907 * The cache key varies on the file name and the names and values of global
911 * @param string $fileName File name of root LESS file.
912 * @return string Cache key
914 protected static function getLESSCacheKey( $fileName ) {
915 $vars = json_encode( ResourceLoader
::getLESSVars() );
916 $hash = md5( $fileName . $vars );
917 return wfMemcKey( 'resourceloader', 'less', $hash );
921 * Compile a LESS file into CSS.
923 * If invalid, returns replacement CSS source consisting of the compilation
924 * error message encoded as a comment. To save work, we cache a result object
925 * which comprises the compiled CSS and the names & mtimes of the files
926 * that were processed. lessphp compares the cached & current mtimes and
927 * recompiles as necessary.
930 * @throws Exception If Less encounters a parse error
931 * @throws MWException If Less compilation returns unexpection result
932 * @param string $fileName File path of LESS source
933 * @return string CSS source
935 protected function compileLESSFile( $fileName ) {
936 $key = self
::getLESSCacheKey( $fileName );
937 $cache = wfGetCache( CACHE_ANYTHING
);
939 // The input to lessc. Either an associative array representing the
940 // cached results of a previous compilation, or the string file name if
941 // no cache result exists.
942 $source = $cache->get( $key );
943 if ( !is_array( $source ) ||
!isset( $source['root'] ) ) {
947 $compiler = ResourceLoader
::getLessCompiler();
950 $result = $compiler->cachedCompile( $source );
952 if ( !is_array( $result ) ) {
953 throw new MWException( 'LESS compiler result has type '
954 . gettype( $result ) . '; array expected.' );
957 $this->localFileRefs +
= array_keys( $result['files'] );
958 $cache->set( $key, $result );
959 return $result['compiled'];