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
{
30 /* Protected Members */
32 /** String: Local base path, see __construct() */
33 protected $localBasePath = '';
34 /** String: Remote base path, see __construct() */
35 protected $remoteBasePath = '';
37 * Array: List of paths to JavaScript files to always include
40 * array( [file-path], [file-path], ... )
43 protected $scripts = array();
45 * Array: List of JavaScript files to include when using a specific language
48 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
51 protected $languageScripts = array();
53 * Array: List of JavaScript files to include when using a specific skin
56 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
59 protected $skinScripts = array();
61 * Array: List of paths to JavaScript files to include in debug mode
64 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
67 protected $debugScripts = array();
69 * Array: List of paths to JavaScript files to include in the startup module
72 * array( [file-path], [file-path], ... )
75 protected $loaderScripts = array();
77 * Array: List of paths to CSS files to always include
80 * array( [file-path], [file-path], ... )
83 protected $styles = array();
85 * Array: List of paths to CSS files to include when using specific skins
88 * array( [file-path], [file-path], ... )
91 protected $skinStyles = array();
93 * Array: List of modules this module depends on
96 * array( [file-path], [file-path], ... )
99 protected $dependencies = array();
101 * Array: List of message keys used by this module
104 * array( [message-key], [message-key], ... )
107 protected $messages = array();
108 /** String: Name of group to load this module in */
110 /** String: Position on the page to load this module at */
111 protected $position = 'bottom';
112 /** Boolean: Link to raw files in debug mode */
113 protected $debugRaw = true;
114 /** Boolean: Whether mw.loader.state() call should be omitted */
115 protected $raw = false;
116 protected $targets = array( 'desktop' );
119 * Boolean: Whether getStyleURLsForDebug should return raw file paths,
120 * or return load.php urls
122 protected $hasGeneratedStyles = false;
125 * Array: Cache for mtime
128 * array( [hash] => [mtime], [hash] => [mtime], ... )
131 protected $modifiedTime = array();
133 * Array: Place where readStyleFile() tracks file dependencies
136 * array( [file-path], [file-path], ... )
139 protected $localFileRefs = array();
144 * Constructs a new module from an options array.
146 * @param array $options List of options; if not given or empty, an empty module will be
148 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
150 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
153 * Below is a description for the $options array:
154 * @throws MWException
155 * @par Construction options:
158 * // Base path to prepend to all local paths in $options. Defaults to $IP
159 * 'localBasePath' => [base path],
160 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
161 * 'remoteBasePath' => [base path],
162 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
163 * 'remoteExtPath' => [base path],
164 * // Scripts to always include
165 * 'scripts' => [file path string or array of file path strings],
166 * // Scripts to include in specific language contexts
167 * 'languageScripts' => array(
168 * [language code] => [file path string or array of file path strings],
170 * // Scripts to include in specific skin contexts
171 * 'skinScripts' => array(
172 * [skin name] => [file path string or array of file path strings],
174 * // Scripts to include in debug contexts
175 * 'debugScripts' => [file path string or array of file path strings],
176 * // Scripts to include in the startup module
177 * 'loaderScripts' => [file path string or array of file path strings],
178 * // Modules which must be loaded before this module
179 * 'dependencies' => [module name string or array of module name strings],
180 * // Styles to always load
181 * 'styles' => [file path string or array of file path strings],
182 * // Styles to include in specific skin contexts
183 * 'skinStyles' => array(
184 * [skin name] => [file path string or array of file path strings],
186 * // Messages to always load
187 * 'messages' => [array of message key strings],
188 * // Group which this module should be loaded together with
189 * 'group' => [group name string],
190 * // Position on the page to load this module at
191 * 'position' => ['bottom' (default) or 'top']
195 public function __construct( $options = array(), $localBasePath = null,
196 $remoteBasePath = null
198 global $IP, $wgScriptPath, $wgResourceBasePath;
199 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
200 if ( $remoteBasePath !== null ) {
201 $this->remoteBasePath
= $remoteBasePath;
203 $this->remoteBasePath
= $wgResourceBasePath === null ?
$wgScriptPath : $wgResourceBasePath;
206 if ( isset( $options['remoteExtPath'] ) ) {
207 global $wgExtensionAssetsPath;
208 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
211 foreach ( $options as $member => $option ) {
213 // Lists of file paths
216 case 'loaderScripts':
218 $this->{$member} = (array)$option;
220 // Collated lists of file paths
221 case 'languageScripts':
224 if ( !is_array( $option ) ) {
225 throw new MWException(
226 "Invalid collated file path list error. " .
227 "'$option' given, array expected."
230 foreach ( $option as $key => $value ) {
231 if ( !is_string( $key ) ) {
232 throw new MWException(
233 "Invalid collated file path list key error. " .
234 "'$key' given, string expected."
237 $this->{$member}[$key] = (array)$value;
245 $option = array_values( array_unique( (array)$option ) );
248 $this->{$member} = $option;
253 case 'localBasePath':
254 case 'remoteBasePath':
255 $this->{$member} = (string)$option;
260 $this->{$member} = (bool)$option;
264 // Make sure the remote base path is a complete valid URL,
265 // but possibly protocol-relative to avoid cache pollution
266 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
, PROTO_RELATIVE
);
270 * Gets all scripts for a given context concatenated together.
272 * @param ResourceLoaderContext $context Context in which to generate script
273 * @return string: JavaScript code for $context
275 public function getScript( ResourceLoaderContext
$context ) {
276 $files = $this->getScriptFiles( $context );
277 return $this->readScriptFiles( $files );
281 * @param ResourceLoaderContext $context
284 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
286 foreach ( $this->getScriptFiles( $context ) as $file ) {
287 $urls[] = $this->getRemotePath( $file );
295 public function supportsURLLoading() {
296 return $this->debugRaw
;
300 * Gets loader script.
302 * @return string: JavaScript code to be added to startup module
304 public function getLoaderScript() {
305 if ( count( $this->loaderScripts
) == 0 ) {
308 return $this->readScriptFiles( $this->loaderScripts
);
312 * Gets all styles for a given context concatenated together.
314 * @param ResourceLoaderContext $context Context in which to generate styles
315 * @return string: CSS code for $context
317 public function getStyles( ResourceLoaderContext
$context ) {
318 $styles = $this->readStyleFiles(
319 $this->getStyleFiles( $context ),
320 $this->getFlip( $context )
322 // Collect referenced files
323 $this->localFileRefs
= array_unique( $this->localFileRefs
);
324 // If the list has been modified since last time we cached it, update the cache
326 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
327 $dbw = wfGetDB( DB_MASTER
);
328 $dbw->replace( 'module_deps',
329 array( array( 'md_module', 'md_skin' ) ), array(
330 'md_module' => $this->getName(),
331 'md_skin' => $context->getSkin(),
332 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
336 } catch ( Exception
$e ) {
337 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
343 * @param ResourceLoaderContext $context
346 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
347 if ( $this->hasGeneratedStyles
) {
348 // Do the default behaviour of returning a url back to load.php
349 // but with only=styles.
350 return parent
::getStyleURLsForDebug( $context );
352 // Our module consists entirely of real css files,
353 // in debug mode we can load those directly.
355 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
356 $urls[$mediaType] = array();
357 foreach ( $list as $file ) {
358 $urls[$mediaType][] = $this->getRemotePath( $file );
365 * Gets list of message keys used by this module.
367 * @return array: List of message keys
369 public function getMessages() {
370 return $this->messages
;
374 * Gets the name of the group this module should be loaded in.
376 * @return string: Group name
378 public function getGroup() {
385 public function getPosition() {
386 return $this->position
;
390 * Gets list of names of modules this module depends on.
392 * @return array: List of module names
394 public function getDependencies() {
395 return $this->dependencies
;
401 public function isRaw() {
406 * Get the last modified timestamp of this module.
408 * Last modified timestamps are calculated from the highest last modified
409 * timestamp of this module's constituent files as well as the files it
410 * depends on. This function is context-sensitive, only performing
411 * calculations on files relevant to the given language, skin and debug
414 * @param ResourceLoaderContext $context Context in which to calculate
416 * @return int: UNIX timestamp
417 * @see ResourceLoaderModule::getFileDependencies
419 public function getModifiedTime( ResourceLoaderContext
$context ) {
420 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
421 return $this->modifiedTime
[$context->getHash()];
423 wfProfileIn( __METHOD__
);
427 // Flatten style files into $files
428 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
429 foreach ( $styles as $styleFiles ) {
430 $files = array_merge( $files, $styleFiles );
432 $skinFiles = self
::tryForKey(
433 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ),
437 foreach ( $skinFiles as $styleFiles ) {
438 $files = array_merge( $files, $styleFiles );
441 // Final merge, this should result in a master list of dependent files
442 $files = array_merge(
445 $context->getDebug() ?
$this->debugScripts
: array(),
446 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
447 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
450 $files = array_map( array( $this, 'getLocalPath' ), $files );
451 // File deps need to be treated separately because they're already prefixed
452 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
454 // If a module is nothing but a list of dependencies, we need to avoid
455 // giving max() an empty array
456 if ( count( $files ) === 0 ) {
457 wfProfileOut( __METHOD__
);
458 return $this->modifiedTime
[$context->getHash()] = 1;
461 wfProfileIn( __METHOD__
. '-filemtime' );
462 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
463 wfProfileOut( __METHOD__
. '-filemtime' );
465 $this->modifiedTime
[$context->getHash()] = max(
467 $this->getMsgBlobMtime( $context->getLanguage() ),
468 $this->getDefinitionMtime( $context )
471 wfProfileOut( __METHOD__
);
472 return $this->modifiedTime
[$context->getHash()];
476 * Get the definition summary for this module.
480 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
482 'class' => get_class( $this ),
502 $summary[$member] = $this->{$member};
507 /* Protected Methods */
510 * @param string $path
513 protected function getLocalPath( $path ) {
514 return "{$this->localBasePath}/$path";
518 * @param string $path
521 protected function getRemotePath( $path ) {
522 return "{$this->remoteBasePath}/$path";
526 * Infer the stylesheet language from a stylesheet file path.
529 * @param string $path
530 * @return string: the stylesheet language name
532 public function getStyleSheetLang( $path ) {
533 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
537 * Collates file paths by option (where provided).
539 * @param array $list List of file paths in any combination of index/path
540 * or path/options pairs
541 * @param string $option option name
542 * @param mixed $default default value if the option isn't set
543 * @return array: List of file paths, collated by $option
545 protected static function collateFilePathListByOption( array $list, $option, $default ) {
546 $collatedFiles = array();
547 foreach ( (array)$list as $key => $value ) {
548 if ( is_int( $key ) ) {
549 // File name as the value
550 if ( !isset( $collatedFiles[$default] ) ) {
551 $collatedFiles[$default] = array();
553 $collatedFiles[$default][] = $value;
554 } elseif ( is_array( $value ) ) {
555 // File name as the key, options array as the value
556 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
557 if ( !isset( $collatedFiles[$optionValue] ) ) {
558 $collatedFiles[$optionValue] = array();
560 $collatedFiles[$optionValue][] = $key;
563 return $collatedFiles;
567 * Gets a list of element that match a key, optionally using a fallback key.
569 * @param array $list List of lists to select from
570 * @param string $key Key to look for in $map
571 * @param string $fallback Key to look for in $list if $key doesn't exist
572 * @return array: List of elements from $map which matched $key or $fallback,
573 * or an empty list in case of no match
575 protected static function tryForKey( array $list, $key, $fallback = null ) {
576 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
578 } elseif ( is_string( $fallback )
579 && isset( $list[$fallback] )
580 && is_array( $list[$fallback] )
582 return $list[$fallback];
588 * Gets a list of file paths for all scripts in this module, in order of propper execution.
590 * @param ResourceLoaderContext $context
591 * @return array: List of file paths
593 protected function getScriptFiles( ResourceLoaderContext
$context ) {
594 $files = array_merge(
596 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
597 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
599 if ( $context->getDebug() ) {
600 $files = array_merge( $files, $this->debugScripts
);
603 return array_unique( $files );
607 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
609 * @param ResourceLoaderContext $context
610 * @return array: List of file paths
612 protected function getStyleFiles( ResourceLoaderContext
$context ) {
613 return array_merge_recursive(
614 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
615 self
::collateFilePathListByOption(
616 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ), 'media', 'all'
622 * Returns all style files used by this module
625 public function getAllStyleFiles() {
627 foreach ( (array)$this->styles
as $key => $value ) {
628 if ( is_array( $value ) ) {
633 $files[] = $this->getLocalPath( $path );
639 * Gets the contents of a list of JavaScript files.
641 * @param array $scripts List of file paths to scripts to read, remap and concetenate
642 * @throws MWException
643 * @return string: Concatenated and remapped JavaScript data from $scripts
645 protected function readScriptFiles( array $scripts ) {
646 global $wgResourceLoaderValidateStaticJS;
647 if ( empty( $scripts ) ) {
651 foreach ( array_unique( $scripts ) as $fileName ) {
652 $localPath = $this->getLocalPath( $fileName );
653 if ( !file_exists( $localPath ) ) {
654 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
656 $contents = file_get_contents( $localPath );
657 if ( $wgResourceLoaderValidateStaticJS ) {
658 // Static files don't really need to be checked as often; unlike
659 // on-wiki module they shouldn't change unexpectedly without
660 // admin interference.
661 $contents = $this->validateScriptFile( $fileName, $contents );
663 $js .= $contents . "\n";
669 * Gets the contents of a list of CSS files.
671 * @param array $styles List of media type/list of file paths pairs, to read, remap and
676 * @return array: List of concatenated and remapped CSS data from $styles,
677 * keyed by media type
679 protected function readStyleFiles( array $styles, $flip ) {
680 if ( empty( $styles ) ) {
683 foreach ( $styles as $media => $files ) {
684 $uniqueFiles = array_unique( $files );
685 $styles[$media] = implode(
688 array( $this, 'readStyleFile' ),
690 array_fill( 0, count( $uniqueFiles ), $flip )
698 * Reads a style file.
700 * This method can be used as a callback for array_map()
702 * @param string $path File path of style file to read
705 * @return string: CSS data in script file
706 * @throws MWException if the file doesn't exist
708 protected function readStyleFile( $path, $flip ) {
709 $localPath = $this->getLocalPath( $path );
710 if ( !file_exists( $localPath ) ) {
711 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
712 wfDebugLog( 'resourceloader', $msg );
713 throw new MWException( $msg );
716 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
717 $style = $this->compileLESSFile( $localPath );
718 $this->hasGeneratedStyles
= true;
720 $style = file_get_contents( $localPath );
724 $style = CSSJanus
::transform( $style, true, false );
726 $dirname = dirname( $path );
727 if ( $dirname == '.' ) {
728 // If $path doesn't have a directory component, don't prepend a dot
731 $dir = $this->getLocalPath( $dirname );
732 $remoteDir = $this->getRemotePath( $dirname );
733 // Get and register local file references
734 $this->localFileRefs
= array_merge(
735 $this->localFileRefs
,
736 CSSMin
::getLocalFileReferences( $style, $dir )
738 return CSSMin
::remap(
739 $style, $dir, $remoteDir, true
744 * Get whether CSS for this module should be flipped
745 * @param ResourceLoaderContext $context
748 public function getFlip( $context ) {
749 return $context->getDirection() === 'rtl';
753 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
755 * @return array of strings
757 public function getTargets() {
758 return $this->targets
;
762 * Generate a cache key for a LESS file.
764 * The cache key varies on the file name and the names and values of global
768 * @param string $fileName File name of root LESS file.
769 * @return string: Cache key
771 protected static function getLESSCacheKey( $fileName ) {
772 $vars = json_encode( ResourceLoader
::getLESSVars() );
773 $hash = md5( $fileName . $vars );
774 return wfMemcKey( 'resourceloader', 'less', $hash );
778 * Compile a LESS file into CSS.
780 * If invalid, returns replacement CSS source consisting of the compilation
781 * error message encoded as a comment. To save work, we cache a result object
782 * which comprises the compiled CSS and the names & mtimes of the files
783 * that were processed. lessphp compares the cached & current mtimes and
784 * recompiles as necessary.
787 * @throws Exception If Less encounters a parse error
788 * @throws MWException If Less compilation returns unexpection result
789 * @param string $fileName File path of LESS source
790 * @return string: CSS source
792 protected function compileLESSFile( $fileName ) {
793 $key = self
::getLESSCacheKey( $fileName );
794 $cache = wfGetCache( CACHE_ANYTHING
);
796 // The input to lessc. Either an associative array representing the
797 // cached results of a previous compilation, or the string file name if
798 // no cache result exists.
799 $source = $cache->get( $key );
800 if ( !is_array( $source ) ||
!isset( $source['root'] ) ) {
804 $compiler = ResourceLoader
::getLessCompiler();
807 $result = $compiler->cachedCompile( $source );
809 if ( !is_array( $result ) ) {
810 throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' );
813 $this->localFileRefs +
= array_keys( $result['files'] );
814 $cache->set( $key, $result );
815 return $result['compiled'];