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( $options = array(), $localBasePath = null,
222 $remoteBasePath = null
224 global $IP, $wgScriptPath, $wgResourceBasePath;
225 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
226 if ( $remoteBasePath !== null ) {
227 $this->remoteBasePath
= $remoteBasePath;
229 $this->remoteBasePath
= $wgResourceBasePath === null ?
$wgScriptPath : $wgResourceBasePath;
232 if ( isset( $options['remoteExtPath'] ) ) {
233 global $wgExtensionAssetsPath;
234 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
237 if ( isset( $options['remoteSkinPath'] ) ) {
239 $this->remoteBasePath
= $wgStylePath . '/' . $options['remoteSkinPath'];
242 foreach ( $options as $member => $option ) {
244 // Lists of file paths
247 case 'loaderScripts':
249 $this->{$member} = (array)$option;
251 // Collated lists of file paths
252 case 'languageScripts':
255 if ( !is_array( $option ) ) {
256 throw new MWException(
257 "Invalid collated file path list error. " .
258 "'$option' given, array expected."
261 foreach ( $option as $key => $value ) {
262 if ( !is_string( $key ) ) {
263 throw new MWException(
264 "Invalid collated file path list key error. " .
265 "'$key' given, string expected."
268 $this->{$member}[$key] = (array)$value;
276 $option = array_values( array_unique( (array)$option ) );
279 $this->{$member} = $option;
284 case 'localBasePath':
285 case 'remoteBasePath':
287 $this->{$member} = (string)$option;
292 $this->{$member} = (bool)$option;
296 // Make sure the remote base path is a complete valid URL,
297 // but possibly protocol-relative to avoid cache pollution
298 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
, PROTO_RELATIVE
);
302 * Gets all scripts for a given context concatenated together.
304 * @param ResourceLoaderContext $context Context in which to generate script
305 * @return string JavaScript code for $context
307 public function getScript( ResourceLoaderContext
$context ) {
308 $files = $this->getScriptFiles( $context );
309 return $this->readScriptFiles( $files );
313 * @param ResourceLoaderContext $context
316 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
318 foreach ( $this->getScriptFiles( $context ) as $file ) {
319 $urls[] = $this->getRemotePath( $file );
327 public function supportsURLLoading() {
328 return $this->debugRaw
;
334 * @return string|false JavaScript code to be added to startup module
336 public function getLoaderScript() {
337 if ( count( $this->loaderScripts
) === 0 ) {
340 return $this->readScriptFiles( $this->loaderScripts
);
344 * Get all styles for a given context.
346 * @param ResourceLoaderContext $context
347 * @return array CSS code for $context as an associative array mapping media type to CSS text.
349 public function getStyles( ResourceLoaderContext
$context ) {
350 $styles = $this->readStyleFiles(
351 $this->getStyleFiles( $context ),
352 $this->getFlip( $context )
354 // Collect referenced files
355 $this->localFileRefs
= array_unique( $this->localFileRefs
);
356 // If the list has been modified since last time we cached it, update the cache
358 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
359 $dbw = wfGetDB( DB_MASTER
);
360 $dbw->replace( 'module_deps',
361 array( array( 'md_module', 'md_skin' ) ), array(
362 'md_module' => $this->getName(),
363 'md_skin' => $context->getSkin(),
364 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
368 } catch ( Exception
$e ) {
369 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
375 * @param ResourceLoaderContext $context
378 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
379 if ( $this->hasGeneratedStyles
) {
380 // Do the default behaviour of returning a url back to load.php
381 // but with only=styles.
382 return parent
::getStyleURLsForDebug( $context );
384 // Our module consists entirely of real css files,
385 // in debug mode we can load those directly.
387 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
388 $urls[$mediaType] = array();
389 foreach ( $list as $file ) {
390 $urls[$mediaType][] = $this->getRemotePath( $file );
397 * Gets list of message keys used by this module.
399 * @return array List of message keys
401 public function getMessages() {
402 return $this->messages
;
406 * Gets the name of the group this module should be loaded in.
408 * @return string Group name
410 public function getGroup() {
417 public function getPosition() {
418 return $this->position
;
422 * Gets list of names of modules this module depends on.
424 * @return array List of module names
426 public function getDependencies() {
427 return $this->dependencies
;
431 * Get the skip function.
433 * @return string|null
435 public function getSkipFunction() {
436 if ( !$this->skipFunction
) {
440 global $wgResourceLoaderValidateStaticJS;
441 $localPath = $this->getLocalPath( $this->skipFunction
);
442 if ( !file_exists( $localPath ) ) {
443 throw new MWException( __METHOD__
. ": skip function file not found: \"$localPath\"" );
445 $contents = file_get_contents( $localPath );
446 if ( $wgResourceLoaderValidateStaticJS ) {
447 $contents = $this->validateScriptFile( $fileName, $contents );
455 public function isRaw() {
460 * Get the last modified timestamp of this module.
462 * Last modified timestamps are calculated from the highest last modified
463 * timestamp of this module's constituent files as well as the files it
464 * depends on. This function is context-sensitive, only performing
465 * calculations on files relevant to the given language, skin and debug
468 * @param ResourceLoaderContext $context Context in which to calculate
470 * @return int UNIX timestamp
471 * @see ResourceLoaderModule::getFileDependencies
473 public function getModifiedTime( ResourceLoaderContext
$context ) {
474 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
475 return $this->modifiedTime
[$context->getHash()];
477 wfProfileIn( __METHOD__
);
481 // Flatten style files into $files
482 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
483 foreach ( $styles as $styleFiles ) {
484 $files = array_merge( $files, $styleFiles );
487 $skinFiles = self
::collateFilePathListByOption(
488 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
492 foreach ( $skinFiles as $styleFiles ) {
493 $files = array_merge( $files, $styleFiles );
496 // Final merge, this should result in a master list of dependent files
497 $files = array_merge(
500 $context->getDebug() ?
$this->debugScripts
: array(),
501 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
502 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
505 if ( $this->skipFunction
) {
506 $files[] = $this->skipFunction
;
508 $files = array_map( array( $this, 'getLocalPath' ), $files );
509 // File deps need to be treated separately because they're already prefixed
510 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
512 // If a module is nothing but a list of dependencies, we need to avoid
513 // giving max() an empty array
514 if ( count( $files ) === 0 ) {
515 $this->modifiedTime
[$context->getHash()] = 1;
516 wfProfileOut( __METHOD__
);
517 return $this->modifiedTime
[$context->getHash()];
520 wfProfileIn( __METHOD__
. '-filemtime' );
521 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
522 wfProfileOut( __METHOD__
. '-filemtime' );
524 $this->modifiedTime
[$context->getHash()] = max(
526 $this->getMsgBlobMtime( $context->getLanguage() ),
527 $this->getDefinitionMtime( $context )
530 wfProfileOut( __METHOD__
);
531 return $this->modifiedTime
[$context->getHash()];
535 * Get the definition summary for this module.
539 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
541 'class' => get_class( $this ),
562 $summary[$member] = $this->{$member};
567 /* Protected Methods */
570 * @param string $path
573 protected function getLocalPath( $path ) {
574 return "{$this->localBasePath}/$path";
578 * @param string $path
581 protected function getRemotePath( $path ) {
582 return "{$this->remoteBasePath}/$path";
586 * Infer the stylesheet language from a stylesheet file path.
589 * @param string $path
590 * @return string The stylesheet language name
592 public function getStyleSheetLang( $path ) {
593 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
597 * Collates file paths by option (where provided).
599 * @param array $list List of file paths in any combination of index/path
600 * or path/options pairs
601 * @param string $option Option name
602 * @param mixed $default Default value if the option isn't set
603 * @return array List of file paths, collated by $option
605 protected static function collateFilePathListByOption( array $list, $option, $default ) {
606 $collatedFiles = array();
607 foreach ( (array)$list as $key => $value ) {
608 if ( is_int( $key ) ) {
609 // File name as the value
610 if ( !isset( $collatedFiles[$default] ) ) {
611 $collatedFiles[$default] = array();
613 $collatedFiles[$default][] = $value;
614 } elseif ( is_array( $value ) ) {
615 // File name as the key, options array as the value
616 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
617 if ( !isset( $collatedFiles[$optionValue] ) ) {
618 $collatedFiles[$optionValue] = array();
620 $collatedFiles[$optionValue][] = $key;
623 return $collatedFiles;
627 * Get a list of element that match a key, optionally using a fallback key.
629 * @param array $list List of lists to select from
630 * @param string $key Key to look for in $map
631 * @param string $fallback Key to look for in $list if $key doesn't exist
632 * @return array List of elements from $map which matched $key or $fallback,
633 * or an empty list in case of no match
635 protected static function tryForKey( array $list, $key, $fallback = null ) {
636 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
638 } elseif ( is_string( $fallback )
639 && isset( $list[$fallback] )
640 && is_array( $list[$fallback] )
642 return $list[$fallback];
648 * Get a list of file paths for all scripts in this module, in order of proper execution.
650 * @param ResourceLoaderContext $context
651 * @return array List of file paths
653 protected function getScriptFiles( ResourceLoaderContext
$context ) {
654 $files = array_merge(
656 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
657 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
659 if ( $context->getDebug() ) {
660 $files = array_merge( $files, $this->debugScripts
);
663 return array_unique( $files );
667 * Get a list of file paths for all styles in this module, in order of proper inclusion.
669 * @param ResourceLoaderContext $context
670 * @return array List of file paths
672 public function getStyleFiles( ResourceLoaderContext
$context ) {
673 return array_merge_recursive(
674 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
675 self
::collateFilePathListByOption(
676 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
684 * Gets a list of file paths for all skin styles in the module used by
687 * @param string $skinName The name of the skin
688 * @return array A list of file paths collated by media type
690 protected function getSkinStyleFiles( $skinName ) {
691 return self
::collateFilePathListByOption(
692 self
::tryForKey( $this->skinStyles
, $skinName ),
699 * Gets a list of file paths for all skin style files in the module,
700 * for all available skins.
702 * @return array A list of file paths collated by media type
704 protected function getAllSkinStyleFiles() {
705 $styleFiles = array();
706 $internalSkinNames = array_keys( Skin
::getSkinNames() );
707 $internalSkinNames[] = 'default';
709 foreach ( $internalSkinNames as $internalSkinName ) {
710 $styleFiles = array_merge_recursive(
712 $this->getSkinStyleFiles( $internalSkinName )
720 * Returns all style files and all skin style files used by this module.
724 public function getAllStyleFiles() {
725 $collatedStyleFiles = array_merge_recursive(
726 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
727 $this->getAllSkinStyleFiles()
732 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
733 foreach ( $styleFiles as $styleFile ) {
734 $result[] = $this->getLocalPath( $styleFile );
742 * Gets the contents of a list of JavaScript files.
744 * @param array $scripts List of file paths to scripts to read, remap and concetenate
745 * @throws MWException
746 * @return string Concatenated and remapped JavaScript data from $scripts
748 protected function readScriptFiles( array $scripts ) {
749 global $wgResourceLoaderValidateStaticJS;
750 if ( empty( $scripts ) ) {
754 foreach ( array_unique( $scripts ) as $fileName ) {
755 $localPath = $this->getLocalPath( $fileName );
756 if ( !file_exists( $localPath ) ) {
757 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
759 $contents = file_get_contents( $localPath );
760 if ( $wgResourceLoaderValidateStaticJS ) {
761 // Static files don't really need to be checked as often; unlike
762 // on-wiki module they shouldn't change unexpectedly without
763 // admin interference.
764 $contents = $this->validateScriptFile( $fileName, $contents );
766 $js .= $contents . "\n";
772 * Gets the contents of a list of CSS files.
774 * @param array $styles List of media type/list of file paths pairs, to read, remap and
779 * @throws MWException
780 * @return array List of concatenated and remapped CSS data from $styles,
781 * keyed by media type
783 public function readStyleFiles( array $styles, $flip ) {
784 if ( empty( $styles ) ) {
787 foreach ( $styles as $media => $files ) {
788 $uniqueFiles = array_unique( $files );
789 $styleFiles = array();
790 foreach ( $uniqueFiles as $file ) {
791 $styleFiles[] = $this->readStyleFile( $file, $flip );
793 $styles[$media] = implode( "\n", $styleFiles );
799 * Reads a style file.
801 * This method can be used as a callback for array_map()
803 * @param string $path File path of style file to read
806 * @return string CSS data in script file
807 * @throws MWException if the file doesn't exist
809 protected function readStyleFile( $path, $flip ) {
810 $localPath = $this->getLocalPath( $path );
811 if ( !file_exists( $localPath ) ) {
812 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
813 wfDebugLog( 'resourceloader', $msg );
814 throw new MWException( $msg );
817 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
818 $style = $this->compileLESSFile( $localPath );
819 $this->hasGeneratedStyles
= true;
821 $style = file_get_contents( $localPath );
825 $style = CSSJanus
::transform( $style, true, false );
827 $dirname = dirname( $path );
828 if ( $dirname == '.' ) {
829 // If $path doesn't have a directory component, don't prepend a dot
832 $dir = $this->getLocalPath( $dirname );
833 $remoteDir = $this->getRemotePath( $dirname );
834 // Get and register local file references
835 $this->localFileRefs
= array_merge(
836 $this->localFileRefs
,
837 CSSMin
::getLocalFileReferences( $style, $dir )
839 return CSSMin
::remap(
840 $style, $dir, $remoteDir, true
845 * Get whether CSS for this module should be flipped
846 * @param ResourceLoaderContext $context
849 public function getFlip( $context ) {
850 return $context->getDirection() === 'rtl';
854 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
856 * @return array Array of strings
858 public function getTargets() {
859 return $this->targets
;
863 * Generate a cache key for a LESS file.
865 * The cache key varies on the file name and the names and values of global
869 * @param string $fileName File name of root LESS file.
870 * @return string Cache key
872 protected static function getLESSCacheKey( $fileName ) {
873 $vars = json_encode( ResourceLoader
::getLESSVars() );
874 $hash = md5( $fileName . $vars );
875 return wfMemcKey( 'resourceloader', 'less', $hash );
879 * Compile a LESS file into CSS.
881 * If invalid, returns replacement CSS source consisting of the compilation
882 * error message encoded as a comment. To save work, we cache a result object
883 * which comprises the compiled CSS and the names & mtimes of the files
884 * that were processed. lessphp compares the cached & current mtimes and
885 * recompiles as necessary.
888 * @throws Exception If Less encounters a parse error
889 * @throws MWException If Less compilation returns unexpection result
890 * @param string $fileName File path of LESS source
891 * @return string CSS source
893 protected function compileLESSFile( $fileName ) {
894 $key = self
::getLESSCacheKey( $fileName );
895 $cache = wfGetCache( CACHE_ANYTHING
);
897 // The input to lessc. Either an associative array representing the
898 // cached results of a previous compilation, or the string file name if
899 // no cache result exists.
900 $source = $cache->get( $key );
901 if ( !is_array( $source ) ||
!isset( $source['root'] ) ) {
905 $compiler = ResourceLoader
::getLessCompiler();
908 $result = $compiler->cachedCompile( $source );
910 if ( !is_array( $result ) ) {
911 throw new MWException( 'LESS compiler result has type '
912 . gettype( $result ) . '; array expected.' );
915 $this->localFileRefs +
= array_keys( $result['files'] );
916 $cache->set( $key, $result );
917 return $result['compiled'];