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;
115 * Array: Cache for mtime
118 * array( [hash] => [mtime], [hash] => [mtime], ... )
121 protected $modifiedTime = array();
123 * Array: Place where readStyleFile() tracks file dependencies
126 * array( [file-path], [file-path], ... )
129 protected $localFileRefs = array();
134 * Constructs a new module from an options array.
136 * @param $options Array: List of options; if not given or empty, an empty module will be
138 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
140 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
143 * Below is a description for the $options array:
144 * @par Construction options:
147 * // Base path to prepend to all local paths in $options. Defaults to $IP
148 * 'localBasePath' => [base path],
149 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
150 * 'remoteBasePath' => [base path],
151 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
152 * 'remoteExtPath' => [base path],
153 * // Scripts to always include
154 * 'scripts' => [file path string or array of file path strings],
155 * // Scripts to include in specific language contexts
156 * 'languageScripts' => array(
157 * [language code] => [file path string or array of file path strings],
159 * // Scripts to include in specific skin contexts
160 * 'skinScripts' => array(
161 * [skin name] => [file path string or array of file path strings],
163 * // Scripts to include in debug contexts
164 * 'debugScripts' => [file path string or array of file path strings],
165 * // Scripts to include in the startup module
166 * 'loaderScripts' => [file path string or array of file path strings],
167 * // Modules which must be loaded before this module
168 * 'dependencies' => [modile name string or array of module name strings],
169 * // Styles to always load
170 * 'styles' => [file path string or array of file path strings],
171 * // Styles to include in specific skin contexts
172 * 'skinStyles' => array(
173 * [skin name] => [file path string or array of file path strings],
175 * // Messages to always load
176 * 'messages' => [array of message key strings],
177 * // Group which this module should be loaded together with
178 * 'group' => [group name string],
179 * // Position on the page to load this module at
180 * 'position' => ['bottom' (default) or 'top']
184 public function __construct( $options = array(), $localBasePath = null,
185 $remoteBasePath = null )
187 global $IP, $wgScriptPath, $wgResourceBasePath;
188 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
189 if ( $remoteBasePath !== null ) {
190 $this->remoteBasePath
= $remoteBasePath;
192 $this->remoteBasePath
= $wgResourceBasePath === null ?
$wgScriptPath : $wgResourceBasePath;
195 if ( isset( $options['remoteExtPath'] ) ) {
196 global $wgExtensionAssetsPath;
197 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
200 foreach ( $options as $member => $option ) {
202 // Lists of file paths
205 case 'loaderScripts':
207 $this->{$member} = (array) $option;
209 // Collated lists of file paths
210 case 'languageScripts':
213 if ( !is_array( $option ) ) {
214 throw new MWException(
215 "Invalid collated file path list error. " .
216 "'$option' given, array expected."
219 foreach ( $option as $key => $value ) {
220 if ( !is_string( $key ) ) {
221 throw new MWException(
222 "Invalid collated file path list key error. " .
223 "'$key' given, string expected."
226 $this->{$member}[$key] = (array) $value;
232 $this->{$member} = (array) $option;
237 case 'localBasePath':
238 case 'remoteBasePath':
239 $this->{$member} = (string) $option;
243 $this->{$member} = (bool) $option;
247 // Make sure the remote base path is a complete valid URL,
248 // but possibly protocol-relative to avoid cache pollution
249 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
, PROTO_RELATIVE
);
253 * Gets all scripts for a given context concatenated together.
255 * @param $context ResourceLoaderContext: Context in which to generate script
256 * @return String: JavaScript code for $context
258 public function getScript( ResourceLoaderContext
$context ) {
259 $files = $this->getScriptFiles( $context );
260 return $this->readScriptFiles( $files );
264 * @param $context ResourceLoaderContext
267 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
269 foreach ( $this->getScriptFiles( $context ) as $file ) {
270 $urls[] = $this->getRemotePath( $file );
278 public function supportsURLLoading() {
279 return $this->debugRaw
;
283 * Gets loader script.
285 * @return String: JavaScript code to be added to startup module
287 public function getLoaderScript() {
288 if ( count( $this->loaderScripts
) == 0 ) {
291 return $this->readScriptFiles( $this->loaderScripts
);
295 * Gets all styles for a given context concatenated together.
297 * @param $context ResourceLoaderContext: Context in which to generate styles
298 * @return String: CSS code for $context
300 public function getStyles( ResourceLoaderContext
$context ) {
301 $styles = $this->readStyleFiles(
302 $this->getStyleFiles( $context ),
303 $this->getFlip( $context )
305 // Collect referenced files
306 $this->localFileRefs
= array_unique( $this->localFileRefs
);
307 // If the list has been modified since last time we cached it, update the cache
308 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) && !wfReadOnly() ) {
309 $dbw = wfGetDB( DB_MASTER
);
310 $dbw->replace( 'module_deps',
311 array( array( 'md_module', 'md_skin' ) ), array(
312 'md_module' => $this->getName(),
313 'md_skin' => $context->getSkin(),
314 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
322 * @param $context ResourceLoaderContext
325 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
327 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
328 $urls[$mediaType] = array();
329 foreach ( $list as $file ) {
330 $urls[$mediaType][] = $this->getRemotePath( $file );
337 * Gets list of message keys used by this module.
339 * @return Array: List of message keys
341 public function getMessages() {
342 return $this->messages
;
346 * Gets the name of the group this module should be loaded in.
348 * @return String: Group name
350 public function getGroup() {
357 public function getPosition() {
358 return $this->position
;
362 * Gets list of names of modules this module depends on.
364 * @return Array: List of module names
366 public function getDependencies() {
367 return $this->dependencies
;
371 * Get the last modified timestamp of this module.
373 * Last modified timestamps are calculated from the highest last modified
374 * timestamp of this module's constituent files as well as the files it
375 * depends on. This function is context-sensitive, only performing
376 * calculations on files relevant to the given language, skin and debug
379 * @param $context ResourceLoaderContext: Context in which to calculate
381 * @return Integer: UNIX timestamp
382 * @see ResourceLoaderModule::getFileDependencies
384 public function getModifiedTime( ResourceLoaderContext
$context ) {
385 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
386 return $this->modifiedTime
[$context->getHash()];
388 wfProfileIn( __METHOD__
);
392 // Flatten style files into $files
393 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
394 foreach ( $styles as $styleFiles ) {
395 $files = array_merge( $files, $styleFiles );
397 $skinFiles = self
::tryForKey(
398 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ),
402 foreach ( $skinFiles as $styleFiles ) {
403 $files = array_merge( $files, $styleFiles );
406 // Final merge, this should result in a master list of dependent files
407 $files = array_merge(
410 $context->getDebug() ?
$this->debugScripts
: array(),
411 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
412 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
415 $files = array_map( array( $this, 'getLocalPath' ), $files );
416 // File deps need to be treated separately because they're already prefixed
417 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
419 // If a module is nothing but a list of dependencies, we need to avoid
420 // giving max() an empty array
421 if ( count( $files ) === 0 ) {
422 wfProfileOut( __METHOD__
);
423 return $this->modifiedTime
[$context->getHash()] = 1;
426 wfProfileIn( __METHOD__
.'-filemtime' );
427 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
428 wfProfileOut( __METHOD__
.'-filemtime' );
429 $this->modifiedTime
[$context->getHash()] = max(
431 $this->getMsgBlobMtime( $context->getLanguage() ) );
433 wfProfileOut( __METHOD__
);
434 return $this->modifiedTime
[$context->getHash()];
437 /* Protected Methods */
440 * @param $path string
443 protected function getLocalPath( $path ) {
444 return "{$this->localBasePath}/$path";
448 * @param $path string
451 protected function getRemotePath( $path ) {
452 return "{$this->remoteBasePath}/$path";
456 * Collates file paths by option (where provided).
458 * @param $list Array: List of file paths in any combination of index/path
459 * or path/options pairs
460 * @param $option String: option name
461 * @param $default Mixed: default value if the option isn't set
462 * @return Array: List of file paths, collated by $option
464 protected static function collateFilePathListByOption( array $list, $option, $default ) {
465 $collatedFiles = array();
466 foreach ( (array) $list as $key => $value ) {
467 if ( is_int( $key ) ) {
468 // File name as the value
469 if ( !isset( $collatedFiles[$default] ) ) {
470 $collatedFiles[$default] = array();
472 $collatedFiles[$default][] = $value;
473 } elseif ( is_array( $value ) ) {
474 // File name as the key, options array as the value
475 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
476 if ( !isset( $collatedFiles[$optionValue] ) ) {
477 $collatedFiles[$optionValue] = array();
479 $collatedFiles[$optionValue][] = $key;
482 return $collatedFiles;
486 * Gets a list of element that match a key, optionally using a fallback key.
488 * @param $list Array: List of lists to select from
489 * @param $key String: Key to look for in $map
490 * @param $fallback String: Key to look for in $list if $key doesn't exist
491 * @return Array: List of elements from $map which matched $key or $fallback,
492 * or an empty list in case of no match
494 protected static function tryForKey( array $list, $key, $fallback = null ) {
495 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
497 } elseif ( is_string( $fallback )
498 && isset( $list[$fallback] )
499 && is_array( $list[$fallback] ) )
501 return $list[$fallback];
507 * Gets a list of file paths for all scripts in this module, in order of propper execution.
509 * @param $context ResourceLoaderContext: Context
510 * @return Array: List of file paths
512 protected function getScriptFiles( ResourceLoaderContext
$context ) {
513 $files = array_merge(
515 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
516 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
518 if ( $context->getDebug() ) {
519 $files = array_merge( $files, $this->debugScripts
);
525 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
527 * @param $context ResourceLoaderContext: Context
528 * @return Array: List of file paths
530 protected function getStyleFiles( ResourceLoaderContext
$context ) {
531 return array_merge_recursive(
532 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
533 self
::collateFilePathListByOption(
534 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ), 'media', 'all'
540 * Gets the contents of a list of JavaScript files.
542 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
543 * @return String: Concatenated and remapped JavaScript data from $scripts
545 protected function readScriptFiles( array $scripts ) {
546 global $wgResourceLoaderValidateStaticJS;
547 if ( empty( $scripts ) ) {
551 foreach ( array_unique( $scripts ) as $fileName ) {
552 $localPath = $this->getLocalPath( $fileName );
553 if ( !file_exists( $localPath ) ) {
554 throw new MWException( __METHOD__
.": script file not found: \"$localPath\"" );
556 $contents = file_get_contents( $localPath );
557 if ( $wgResourceLoaderValidateStaticJS ) {
558 // Static files don't really need to be checked as often; unlike
559 // on-wiki module they shouldn't change unexpectedly without
560 // admin interference.
561 $contents = $this->validateScriptFile( $fileName, $contents );
563 $js .= $contents . "\n";
569 * Gets the contents of a list of CSS files.
571 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
576 * @return Array: List of concatenated and remapped CSS data from $styles,
577 * keyed by media type
579 protected function readStyleFiles( array $styles, $flip ) {
580 if ( empty( $styles ) ) {
583 foreach ( $styles as $media => $files ) {
584 $uniqueFiles = array_unique( $files );
585 $styles[$media] = implode(
588 array( $this, 'readStyleFile' ),
590 array_fill( 0, count( $uniqueFiles ), $flip )
598 * Reads a style file.
600 * This method can be used as a callback for array_map()
602 * @param $path String: File path of style file to read
605 * @return String: CSS data in script file
606 * @throws MWException if the file doesn't exist
608 protected function readStyleFile( $path, $flip ) {
609 $localPath = $this->getLocalPath( $path );
610 if ( !file_exists( $localPath ) ) {
611 throw new MWException( __METHOD__
.": style file not found: \"$localPath\"" );
613 $style = file_get_contents( $localPath );
615 $style = CSSJanus
::transform( $style, true, false );
617 $dirname = dirname( $path );
618 if ( $dirname == '.' ) {
619 // If $path doesn't have a directory component, don't prepend a dot
622 $dir = $this->getLocalPath( $dirname );
623 $remoteDir = $this->getRemotePath( $dirname );
624 // Get and register local file references
625 $this->localFileRefs
= array_merge(
626 $this->localFileRefs
,
627 CSSMin
::getLocalFileReferences( $style, $dir ) );
628 return CSSMin
::remap(
629 $style, $dir, $remoteDir, true
634 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
635 * but returns 1 instead.
636 * @param $filename string File name
637 * @return int UNIX timestamp, or 1 if the file doesn't exist
639 protected static function safeFilemtime( $filename ) {
640 if ( file_exists( $filename ) ) {
641 return filemtime( $filename );
643 // We only ever map this function on an array if we're gonna call max() after,
644 // so return our standard minimum timestamps here. This is 1, not 0, because
645 // wfTimestamp(0) == NOW
651 * Get whether CSS for this module should be flipped
652 * @param $context ResourceLoaderContext
655 public function getFlip( $context ) {
656 return $context->getDirection() === 'rtl';