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 * Array: Cache for mtime
122 * array( [hash] => [mtime], [hash] => [mtime], ... )
125 protected $modifiedTime = array();
127 * Array: Place where readStyleFile() tracks file dependencies
130 * array( [file-path], [file-path], ... )
133 protected $localFileRefs = array();
138 * Constructs a new module from an options array.
140 * @param array $options List of options; if not given or empty, an empty module will be
142 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
144 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
147 * Below is a description for the $options array:
148 * @throws MWException
149 * @par Construction options:
152 * // Base path to prepend to all local paths in $options. Defaults to $IP
153 * 'localBasePath' => [base path],
154 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
155 * 'remoteBasePath' => [base path],
156 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
157 * 'remoteExtPath' => [base path],
158 * // Scripts to always include
159 * 'scripts' => [file path string or array of file path strings],
160 * // Scripts to include in specific language contexts
161 * 'languageScripts' => array(
162 * [language code] => [file path string or array of file path strings],
164 * // Scripts to include in specific skin contexts
165 * 'skinScripts' => array(
166 * [skin name] => [file path string or array of file path strings],
168 * // Scripts to include in debug contexts
169 * 'debugScripts' => [file path string or array of file path strings],
170 * // Scripts to include in the startup module
171 * 'loaderScripts' => [file path string or array of file path strings],
172 * // Modules which must be loaded before this module
173 * 'dependencies' => [module name string or array of module name strings],
174 * // Styles to always load
175 * 'styles' => [file path string or array of file path strings],
176 * // Styles to include in specific skin contexts
177 * 'skinStyles' => array(
178 * [skin name] => [file path string or array of file path strings],
180 * // Messages to always load
181 * 'messages' => [array of message key strings],
182 * // Group which this module should be loaded together with
183 * 'group' => [group name string],
184 * // Position on the page to load this module at
185 * 'position' => ['bottom' (default) or 'top']
189 public function __construct( $options = array(), $localBasePath = null,
190 $remoteBasePath = null
192 global $IP, $wgScriptPath, $wgResourceBasePath;
193 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
194 if ( $remoteBasePath !== null ) {
195 $this->remoteBasePath
= $remoteBasePath;
197 $this->remoteBasePath
= $wgResourceBasePath === null ?
$wgScriptPath : $wgResourceBasePath;
200 if ( isset( $options['remoteExtPath'] ) ) {
201 global $wgExtensionAssetsPath;
202 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
205 foreach ( $options as $member => $option ) {
207 // Lists of file paths
210 case 'loaderScripts':
212 $this->{$member} = (array)$option;
214 // Collated lists of file paths
215 case 'languageScripts':
218 if ( !is_array( $option ) ) {
219 throw new MWException(
220 "Invalid collated file path list error. " .
221 "'$option' given, array expected."
224 foreach ( $option as $key => $value ) {
225 if ( !is_string( $key ) ) {
226 throw new MWException(
227 "Invalid collated file path list key error. " .
228 "'$key' given, string expected."
231 $this->{$member}[$key] = (array)$value;
238 $this->{$member} = (array)$option;
243 case 'localBasePath':
244 case 'remoteBasePath':
245 $this->{$member} = (string)$option;
250 $this->{$member} = (bool)$option;
254 // Make sure the remote base path is a complete valid URL,
255 // but possibly protocol-relative to avoid cache pollution
256 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
, PROTO_RELATIVE
);
260 * Gets all scripts for a given context concatenated together.
262 * @param $context ResourceLoaderContext: Context in which to generate script
263 * @return String: JavaScript code for $context
265 public function getScript( ResourceLoaderContext
$context ) {
266 $files = $this->getScriptFiles( $context );
267 return $this->readScriptFiles( $files );
271 * @param $context ResourceLoaderContext
274 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
276 foreach ( $this->getScriptFiles( $context ) as $file ) {
277 $urls[] = $this->getRemotePath( $file );
285 public function supportsURLLoading() {
286 return $this->debugRaw
;
290 * Gets loader script.
292 * @return String: JavaScript code to be added to startup module
294 public function getLoaderScript() {
295 if ( count( $this->loaderScripts
) == 0 ) {
298 return $this->readScriptFiles( $this->loaderScripts
);
302 * Gets all styles for a given context concatenated together.
304 * @param $context ResourceLoaderContext: Context in which to generate styles
305 * @return String: CSS code for $context
307 public function getStyles( ResourceLoaderContext
$context ) {
308 $styles = $this->readStyleFiles(
309 $this->getStyleFiles( $context ),
310 $this->getFlip( $context )
312 // Collect referenced files
313 $this->localFileRefs
= array_unique( $this->localFileRefs
);
314 // If the list has been modified since last time we cached it, update the cache
316 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
317 $dbw = wfGetDB( DB_MASTER
);
318 $dbw->replace( 'module_deps',
319 array( array( 'md_module', 'md_skin' ) ), array(
320 'md_module' => $this->getName(),
321 'md_skin' => $context->getSkin(),
322 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
326 } catch ( Exception
$e ) {
327 wfDebug( __METHOD__
. " failed to update DB: $e\n" );
333 * @param $context ResourceLoaderContext
336 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
338 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
339 $urls[$mediaType] = array();
340 foreach ( $list as $file ) {
341 $urls[$mediaType][] = $this->getRemotePath( $file );
348 * Gets list of message keys used by this module.
350 * @return Array: List of message keys
352 public function getMessages() {
353 return $this->messages
;
357 * Gets the name of the group this module should be loaded in.
359 * @return String: Group name
361 public function getGroup() {
368 public function getPosition() {
369 return $this->position
;
373 * Gets list of names of modules this module depends on.
375 * @return Array: List of module names
377 public function getDependencies() {
378 return $this->dependencies
;
384 public function isRaw() {
389 * Get the last modified timestamp of this module.
391 * Last modified timestamps are calculated from the highest last modified
392 * timestamp of this module's constituent files as well as the files it
393 * depends on. This function is context-sensitive, only performing
394 * calculations on files relevant to the given language, skin and debug
397 * @param $context ResourceLoaderContext: Context in which to calculate
399 * @return Integer: UNIX timestamp
400 * @see ResourceLoaderModule::getFileDependencies
402 public function getModifiedTime( ResourceLoaderContext
$context ) {
403 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
404 return $this->modifiedTime
[$context->getHash()];
406 wfProfileIn( __METHOD__
);
410 // Flatten style files into $files
411 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
412 foreach ( $styles as $styleFiles ) {
413 $files = array_merge( $files, $styleFiles );
415 $skinFiles = self
::tryForKey(
416 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ),
420 foreach ( $skinFiles as $styleFiles ) {
421 $files = array_merge( $files, $styleFiles );
424 // Final merge, this should result in a master list of dependent files
425 $files = array_merge(
428 $context->getDebug() ?
$this->debugScripts
: array(),
429 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
430 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
433 $files = array_map( array( $this, 'getLocalPath' ), $files );
434 // File deps need to be treated separately because they're already prefixed
435 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
437 // If a module is nothing but a list of dependencies, we need to avoid
438 // giving max() an empty array
439 if ( count( $files ) === 0 ) {
440 wfProfileOut( __METHOD__
);
441 return $this->modifiedTime
[$context->getHash()] = 1;
444 wfProfileIn( __METHOD__
. '-filemtime' );
445 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
446 wfProfileOut( __METHOD__
. '-filemtime' );
447 $this->modifiedTime
[$context->getHash()] = max(
449 $this->getMsgBlobMtime( $context->getLanguage() ) );
451 wfProfileOut( __METHOD__
);
452 return $this->modifiedTime
[$context->getHash()];
455 /* Protected Methods */
458 * @param $path string
461 protected function getLocalPath( $path ) {
462 return "{$this->localBasePath}/$path";
466 * @param $path string
469 protected function getRemotePath( $path ) {
470 return "{$this->remoteBasePath}/$path";
474 * Collates file paths by option (where provided).
476 * @param array $list List of file paths in any combination of index/path
477 * or path/options pairs
478 * @param string $option option name
479 * @param $default Mixed: default value if the option isn't set
480 * @return Array: List of file paths, collated by $option
482 protected static function collateFilePathListByOption( array $list, $option, $default ) {
483 $collatedFiles = array();
484 foreach ( (array)$list as $key => $value ) {
485 if ( is_int( $key ) ) {
486 // File name as the value
487 if ( !isset( $collatedFiles[$default] ) ) {
488 $collatedFiles[$default] = array();
490 $collatedFiles[$default][] = $value;
491 } elseif ( is_array( $value ) ) {
492 // File name as the key, options array as the value
493 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
494 if ( !isset( $collatedFiles[$optionValue] ) ) {
495 $collatedFiles[$optionValue] = array();
497 $collatedFiles[$optionValue][] = $key;
500 return $collatedFiles;
504 * Gets a list of element that match a key, optionally using a fallback key.
506 * @param array $list List of lists to select from
507 * @param string $key Key to look for in $map
508 * @param string $fallback Key to look for in $list if $key doesn't exist
509 * @return Array: List of elements from $map which matched $key or $fallback,
510 * or an empty list in case of no match
512 protected static function tryForKey( array $list, $key, $fallback = null ) {
513 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
515 } elseif ( is_string( $fallback )
516 && isset( $list[$fallback] )
517 && is_array( $list[$fallback] ) )
519 return $list[$fallback];
525 * Gets a list of file paths for all scripts in this module, in order of propper execution.
527 * @param $context ResourceLoaderContext: Context
528 * @return Array: List of file paths
530 protected function getScriptFiles( ResourceLoaderContext
$context ) {
531 $files = array_merge(
533 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
534 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
536 if ( $context->getDebug() ) {
537 $files = array_merge( $files, $this->debugScripts
);
540 return array_unique( $files );
544 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
546 * @param $context ResourceLoaderContext: Context
547 * @return Array: List of file paths
549 protected function getStyleFiles( ResourceLoaderContext
$context ) {
550 return array_merge_recursive(
551 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
552 self
::collateFilePathListByOption(
553 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ), 'media', 'all'
559 * Gets the contents of a list of JavaScript files.
561 * @param array $scripts List of file paths to scripts to read, remap and concetenate
562 * @throws MWException
563 * @return String: Concatenated and remapped JavaScript data from $scripts
565 protected function readScriptFiles( array $scripts ) {
566 global $wgResourceLoaderValidateStaticJS;
567 if ( empty( $scripts ) ) {
571 foreach ( array_unique( $scripts ) as $fileName ) {
572 $localPath = $this->getLocalPath( $fileName );
573 if ( !file_exists( $localPath ) ) {
574 throw new MWException( __METHOD__
. ": script file not found: \"$localPath\"" );
576 $contents = file_get_contents( $localPath );
577 if ( $wgResourceLoaderValidateStaticJS ) {
578 // Static files don't really need to be checked as often; unlike
579 // on-wiki module they shouldn't change unexpectedly without
580 // admin interference.
581 $contents = $this->validateScriptFile( $fileName, $contents );
583 $js .= $contents . "\n";
589 * Gets the contents of a list of CSS files.
591 * @param array $styles List of media type/list of file paths pairs, to read, remap and
596 * @return Array: List of concatenated and remapped CSS data from $styles,
597 * keyed by media type
599 protected function readStyleFiles( array $styles, $flip ) {
600 if ( empty( $styles ) ) {
603 foreach ( $styles as $media => $files ) {
604 $uniqueFiles = array_unique( $files );
605 $styles[$media] = implode(
608 array( $this, 'readStyleFile' ),
610 array_fill( 0, count( $uniqueFiles ), $flip )
618 * Reads a style file.
620 * This method can be used as a callback for array_map()
622 * @param string $path File path of style file to read
625 * @return String: CSS data in script file
626 * @throws MWException if the file doesn't exist
628 protected function readStyleFile( $path, $flip ) {
629 $localPath = $this->getLocalPath( $path );
630 if ( !file_exists( $localPath ) ) {
631 $msg = __METHOD__
. ": style file not found: \"$localPath\"";
632 wfDebugLog( 'resourceloader', $msg );
633 throw new MWException( $msg );
635 $style = file_get_contents( $localPath );
637 $style = CSSJanus
::transform( $style, true, false );
639 $dirname = dirname( $path );
640 if ( $dirname == '.' ) {
641 // If $path doesn't have a directory component, don't prepend a dot
644 $dir = $this->getLocalPath( $dirname );
645 $remoteDir = $this->getRemotePath( $dirname );
646 // Get and register local file references
647 $this->localFileRefs
= array_merge(
648 $this->localFileRefs
,
649 CSSMin
::getLocalFileReferences( $style, $dir )
651 return CSSMin
::remap(
652 $style, $dir, $remoteDir, true
657 * Get whether CSS for this module should be flipped
658 * @param $context ResourceLoaderContext
661 public function getFlip( $context ) {
662 return $context->getDirection() === 'rtl';
666 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
668 * @return array of strings
670 public function getTargets() {
671 return $this->targets
;