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 /** @var string Local base path, see __construct() */
33 protected $localBasePath = '';
34 /** @var string Remote base path, see __construct() */
35 protected $remoteBasePath = '';
37 * @var array List of paths to JavaScript files to always include
40 * array( [file-path], [file-path], ... )
43 protected $scripts = array();
45 * @var 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 * @var 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 * @var 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 * @var array List of paths to JavaScript files to include in the startup module
72 * array( [file-path], [file-path], ... )
75 protected $loaderScripts = array();
77 * @var array List of paths to CSS files to always include
80 * array( [file-path], [file-path], ... )
83 protected $styles = array();
85 * @var array List of paths to CSS files to include when using specific skins
88 * array( [file-path], [file-path], ... )
91 protected $skinStyles = array();
93 * @var array List of modules this module depends on
96 * array( [file-path], [file-path], ... )
99 protected $dependencies = array();
101 * @var array List of message keys used by this module
104 * array( [message-key], [message-key], ... )
107 protected $messages = array();
108 /** @var string Name of group to load this module in */
110 /** @var string Position on the page to load this module at */
111 protected $position = 'bottom';
112 /** @var bool Link to raw files in debug mode */
113 protected $debugRaw = true;
114 /** @var bool Whether mw.loader.state() call should be omitted */
115 protected $raw = false;
116 protected $targets = array( 'desktop' );
119 * @var bool Whether getStyleURLsForDebug should return raw file paths,
120 * or return load.php urls
122 protected $hasGeneratedStyles = false;
125 * @var array Cache for mtime
128 * array( [hash] => [mtime], [hash] => [mtime], ... )
131 protected $modifiedTime = array();
133 * @var 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 );
433 $skinFiles = self
::collateFilePathListByOption(
434 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
438 foreach ( $skinFiles as $styleFiles ) {
439 $files = array_merge( $files, $styleFiles );
442 // Final merge, this should result in a master list of dependent files
443 $files = array_merge(
446 $context->getDebug() ?
$this->debugScripts
: array(),
447 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
448 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
451 $files = array_map( array( $this, 'getLocalPath' ), $files );
452 // File deps need to be treated separately because they're already prefixed
453 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
455 // If a module is nothing but a list of dependencies, we need to avoid
456 // giving max() an empty array
457 if ( count( $files ) === 0 ) {
458 $this->modifiedTime
[$context->getHash()] = 1;
459 wfProfileOut( __METHOD__
);
460 return $this->modifiedTime
[$context->getHash()];
463 wfProfileIn( __METHOD__
. '-filemtime' );
464 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
465 wfProfileOut( __METHOD__
. '-filemtime' );
467 $this->modifiedTime
[$context->getHash()] = max(
469 $this->getMsgBlobMtime( $context->getLanguage() ),
470 $this->getDefinitionMtime( $context )
473 wfProfileOut( __METHOD__
);
474 return $this->modifiedTime
[$context->getHash()];
478 * Get the definition summary for this module.
482 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
484 'class' => get_class( $this ),
504 $summary[$member] = $this->{$member};
509 /* Protected Methods */
512 * @param string $path
515 protected function getLocalPath( $path ) {
516 return "{$this->localBasePath}/$path";
520 * @param string $path
523 protected function getRemotePath( $path ) {
524 return "{$this->remoteBasePath}/$path";
528 * Infer the stylesheet language from a stylesheet file path.
531 * @param string $path
532 * @return string The stylesheet language name
534 public function getStyleSheetLang( $path ) {
535 return preg_match( '/\.less$/i', $path ) ?
'less' : 'css';
539 * Collates file paths by option (where provided).
541 * @param array $list List of file paths in any combination of index/path
542 * or path/options pairs
543 * @param string $option Option name
544 * @param mixed $default Default value if the option isn't set
545 * @return array List of file paths, collated by $option
547 protected static function collateFilePathListByOption( array $list, $option, $default ) {
548 $collatedFiles = array();
549 foreach ( (array)$list as $key => $value ) {
550 if ( is_int( $key ) ) {
551 // File name as the value
552 if ( !isset( $collatedFiles[$default] ) ) {
553 $collatedFiles[$default] = array();
555 $collatedFiles[$default][] = $value;
556 } elseif ( is_array( $value ) ) {
557 // File name as the key, options array as the value
558 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
559 if ( !isset( $collatedFiles[$optionValue] ) ) {
560 $collatedFiles[$optionValue] = array();
562 $collatedFiles[$optionValue][] = $key;
565 return $collatedFiles;
569 * Gets a list of element that match a key, optionally using a fallback key.
571 * @param array $list List of lists to select from
572 * @param string $key Key to look for in $map
573 * @param string $fallback Key to look for in $list if $key doesn't exist
574 * @return array List of elements from $map which matched $key or $fallback,
575 * or an empty list in case of no match
577 protected static function tryForKey( array $list, $key, $fallback = null ) {
578 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
580 } elseif ( is_string( $fallback )
581 && isset( $list[$fallback] )
582 && is_array( $list[$fallback] )
584 return $list[$fallback];
590 * Gets a list of file paths for all scripts in this module, in order of propper execution.
592 * @param ResourceLoaderContext $context
593 * @return array List of file paths
595 protected function getScriptFiles( ResourceLoaderContext
$context ) {
596 $files = array_merge(
598 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
599 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
601 if ( $context->getDebug() ) {
602 $files = array_merge( $files, $this->debugScripts
);
605 return array_unique( $files );
609 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
611 * @param ResourceLoaderContext $context
612 * @return array List of file paths
614 protected function getStyleFiles( ResourceLoaderContext
$context ) {
615 return array_merge_recursive(
616 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
617 self
::collateFilePathListByOption(
618 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ),
626 * Returns all style files used by this module
629 public function getAllStyleFiles() {
631 foreach ( (array)$this->styles
as $key => $value ) {
632 if ( is_array( $value ) ) {
637 $files[] = $this->getLocalPath( $path );
643 * Gets the contents of a list of JavaScript files.
645 * @param array $scripts List of file paths to scripts to read, remap and concetenate
646 * @throws MWException
647 * @return string Concatenated and remapped JavaScript data from $scripts
649 protected function readScriptFiles( array $scripts ) {
650 global $wgResourceLoaderValidateStaticJS;
651 if ( empty( $scripts ) ) {
655 foreach ( array_unique( $scripts ) as $fileName ) {
656 $localPath = $this->getLocalPath( $fileName );
657 if ( !file_exists( $localPath ) ) {
658 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
660 $contents = file_get_contents( $localPath );
661 if ( $wgResourceLoaderValidateStaticJS ) {
662 // Static files don't really need to be checked as often; unlike
663 // on-wiki module they shouldn't change unexpectedly without
664 // admin interference.
665 $contents = $this->validateScriptFile( $fileName, $contents );
667 $js .= $contents . "\n";
673 * Gets the contents of a list of CSS files.
675 * @param array $styles List of media type/list of file paths pairs, to read, remap and
680 * @throws MWException
681 * @return array List of concatenated and remapped CSS data from $styles,
682 * keyed by media type
684 protected function readStyleFiles( array $styles, $flip ) {
685 if ( empty( $styles ) ) {
688 foreach ( $styles as $media => $files ) {
689 $uniqueFiles = array_unique( $files );
690 $styleFiles = array();
691 foreach ( $uniqueFiles as $file ) {
692 $styleFiles[] = $this->readStyleFile( $file, $flip );
694 $styles[$media] = implode( "\n", $styleFiles );
700 * Reads a style file.
702 * This method can be used as a callback for array_map()
704 * @param string $path File path of style file to read
707 * @return string CSS data in script file
708 * @throws MWException if the file doesn't exist
710 protected function readStyleFile( $path, $flip ) {
711 $localPath = $this->getLocalPath( $path );
712 if ( !file_exists( $localPath ) ) {
713 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
714 wfDebugLog( 'resourceloader', $msg );
715 throw new MWException( $msg );
718 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
719 $style = $this->compileLESSFile( $localPath );
720 $this->hasGeneratedStyles
= true;
722 $style = file_get_contents( $localPath );
726 $style = CSSJanus
::transform( $style, true, false );
728 $dirname = dirname( $path );
729 if ( $dirname == '.' ) {
730 // If $path doesn't have a directory component, don't prepend a dot
733 $dir = $this->getLocalPath( $dirname );
734 $remoteDir = $this->getRemotePath( $dirname );
735 // Get and register local file references
736 $this->localFileRefs
= array_merge(
737 $this->localFileRefs
,
738 CSSMin
::getLocalFileReferences( $style, $dir )
740 return CSSMin
::remap(
741 $style, $dir, $remoteDir, true
746 * Get whether CSS for this module should be flipped
747 * @param ResourceLoaderContext $context
750 public function getFlip( $context ) {
751 return $context->getDirection() === 'rtl';
755 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
757 * @return array Array of strings
759 public function getTargets() {
760 return $this->targets
;
764 * Generate a cache key for a LESS file.
766 * The cache key varies on the file name and the names and values of global
770 * @param string $fileName File name of root LESS file.
771 * @return string Cache key
773 protected static function getLESSCacheKey( $fileName ) {
774 $vars = json_encode( ResourceLoader
::getLESSVars() );
775 $hash = md5( $fileName . $vars );
776 return wfMemcKey( 'resourceloader', 'less', $hash );
780 * Compile a LESS file into CSS.
782 * If invalid, returns replacement CSS source consisting of the compilation
783 * error message encoded as a comment. To save work, we cache a result object
784 * which comprises the compiled CSS and the names & mtimes of the files
785 * that were processed. lessphp compares the cached & current mtimes and
786 * recompiles as necessary.
789 * @throws Exception If Less encounters a parse error
790 * @throws MWException If Less compilation returns unexpection result
791 * @param string $fileName File path of LESS source
792 * @return string CSS source
794 protected function compileLESSFile( $fileName ) {
795 $key = self
::getLESSCacheKey( $fileName );
796 $cache = wfGetCache( CACHE_ANYTHING
);
798 // The input to lessc. Either an associative array representing the
799 // cached results of a previous compilation, or the string file name if
800 // no cache result exists.
801 $source = $cache->get( $key );
802 if ( !is_array( $source ) ||
!isset( $source['root'] ) ) {
806 $compiler = ResourceLoader
::getLessCompiler();
809 $result = $compiler->cachedCompile( $source );
811 if ( !is_array( $result ) ) {
812 throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' );
815 $this->localFileRefs +
= array_keys( $result['files'] );
816 $cache->set( $key, $result );
817 return $result['compiled'];