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;
117 * Array: Cache for mtime
120 * array( [hash] => [mtime], [hash] => [mtime], ... )
123 protected $modifiedTime = array();
125 * Array: Place where readStyleFile() tracks file dependencies
128 * array( [file-path], [file-path], ... )
131 protected $localFileRefs = array();
136 * Constructs a new module from an options array.
138 * @param $options Array: List of options; if not given or empty, an empty module will be
140 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
142 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
145 * Below is a description for the $options array:
146 * @throws MWException
147 * @par Construction options:
150 * // Base path to prepend to all local paths in $options. Defaults to $IP
151 * 'localBasePath' => [base path],
152 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
153 * 'remoteBasePath' => [base path],
154 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
155 * 'remoteExtPath' => [base path],
156 * // Scripts to always include
157 * 'scripts' => [file path string or array of file path strings],
158 * // Scripts to include in specific language contexts
159 * 'languageScripts' => array(
160 * [language code] => [file path string or array of file path strings],
162 * // Scripts to include in specific skin contexts
163 * 'skinScripts' => array(
164 * [skin name] => [file path string or array of file path strings],
166 * // Scripts to include in debug contexts
167 * 'debugScripts' => [file path string or array of file path strings],
168 * // Scripts to include in the startup module
169 * 'loaderScripts' => [file path string or array of file path strings],
170 * // Modules which must be loaded before this module
171 * 'dependencies' => [modile name string or array of module name strings],
172 * // Styles to always load
173 * 'styles' => [file path string or array of file path strings],
174 * // Styles to include in specific skin contexts
175 * 'skinStyles' => array(
176 * [skin name] => [file path string or array of file path strings],
178 * // Messages to always load
179 * 'messages' => [array of message key strings],
180 * // Group which this module should be loaded together with
181 * 'group' => [group name string],
182 * // Position on the page to load this module at
183 * 'position' => ['bottom' (default) or 'top']
187 public function __construct( $options = array(), $localBasePath = null,
188 $remoteBasePath = null )
190 global $IP, $wgScriptPath, $wgResourceBasePath;
191 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
192 if ( $remoteBasePath !== null ) {
193 $this->remoteBasePath
= $remoteBasePath;
195 $this->remoteBasePath
= $wgResourceBasePath === null ?
$wgScriptPath : $wgResourceBasePath;
198 if ( isset( $options['remoteExtPath'] ) ) {
199 global $wgExtensionAssetsPath;
200 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
203 foreach ( $options as $member => $option ) {
205 // Lists of file paths
208 case 'loaderScripts':
210 $this->{$member} = (array) $option;
212 // Collated lists of file paths
213 case 'languageScripts':
216 if ( !is_array( $option ) ) {
217 throw new MWException(
218 "Invalid collated file path list error. " .
219 "'$option' given, array expected."
222 foreach ( $option as $key => $value ) {
223 if ( !is_string( $key ) ) {
224 throw new MWException(
225 "Invalid collated file path list key error. " .
226 "'$key' given, string expected."
229 $this->{$member}[$key] = (array) $value;
235 $this->{$member} = (array) $option;
240 case 'localBasePath':
241 case 'remoteBasePath':
242 $this->{$member} = (string) $option;
247 $this->{$member} = (bool) $option;
251 // Make sure the remote base path is a complete valid URL,
252 // but possibly protocol-relative to avoid cache pollution
253 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
, PROTO_RELATIVE
);
257 * Gets all scripts for a given context concatenated together.
259 * @param $context ResourceLoaderContext: Context in which to generate script
260 * @return String: JavaScript code for $context
262 public function getScript( ResourceLoaderContext
$context ) {
263 $files = $this->getScriptFiles( $context );
264 return $this->readScriptFiles( $files );
268 * @param $context ResourceLoaderContext
271 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
273 foreach ( $this->getScriptFiles( $context ) as $file ) {
274 $urls[] = $this->getRemotePath( $file );
282 public function supportsURLLoading() {
283 return $this->debugRaw
;
287 * Gets loader script.
289 * @return String: JavaScript code to be added to startup module
291 public function getLoaderScript() {
292 if ( count( $this->loaderScripts
) == 0 ) {
295 return $this->readScriptFiles( $this->loaderScripts
);
299 * Gets all styles for a given context concatenated together.
301 * @param $context ResourceLoaderContext: Context in which to generate styles
302 * @return String: CSS code for $context
304 public function getStyles( ResourceLoaderContext
$context ) {
305 $styles = $this->readStyleFiles(
306 $this->getStyleFiles( $context ),
307 $this->getFlip( $context )
309 // Collect referenced files
310 $this->localFileRefs
= array_unique( $this->localFileRefs
);
311 // If the list has been modified since last time we cached it, update the cache
312 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) && !wfReadOnly() ) {
313 $dbw = wfGetDB( DB_MASTER
);
314 $dbw->replace( 'module_deps',
315 array( array( 'md_module', 'md_skin' ) ), array(
316 'md_module' => $this->getName(),
317 'md_skin' => $context->getSkin(),
318 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
326 * @param $context ResourceLoaderContext
329 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
331 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
332 $urls[$mediaType] = array();
333 foreach ( $list as $file ) {
334 $urls[$mediaType][] = $this->getRemotePath( $file );
341 * Gets list of message keys used by this module.
343 * @return Array: List of message keys
345 public function getMessages() {
346 return $this->messages
;
350 * Gets the name of the group this module should be loaded in.
352 * @return String: Group name
354 public function getGroup() {
361 public function getPosition() {
362 return $this->position
;
366 * Gets list of names of modules this module depends on.
368 * @return Array: List of module names
370 public function getDependencies() {
371 return $this->dependencies
;
377 public function isRaw() {
382 * Get the last modified timestamp of this module.
384 * Last modified timestamps are calculated from the highest last modified
385 * timestamp of this module's constituent files as well as the files it
386 * depends on. This function is context-sensitive, only performing
387 * calculations on files relevant to the given language, skin and debug
390 * @param $context ResourceLoaderContext: Context in which to calculate
392 * @return Integer: UNIX timestamp
393 * @see ResourceLoaderModule::getFileDependencies
395 public function getModifiedTime( ResourceLoaderContext
$context ) {
396 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
397 return $this->modifiedTime
[$context->getHash()];
399 wfProfileIn( __METHOD__
);
403 // Flatten style files into $files
404 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
405 foreach ( $styles as $styleFiles ) {
406 $files = array_merge( $files, $styleFiles );
408 $skinFiles = self
::tryForKey(
409 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ),
413 foreach ( $skinFiles as $styleFiles ) {
414 $files = array_merge( $files, $styleFiles );
417 // Final merge, this should result in a master list of dependent files
418 $files = array_merge(
421 $context->getDebug() ?
$this->debugScripts
: array(),
422 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
423 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
426 $files = array_map( array( $this, 'getLocalPath' ), $files );
427 // File deps need to be treated separately because they're already prefixed
428 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
430 // If a module is nothing but a list of dependencies, we need to avoid
431 // giving max() an empty array
432 if ( count( $files ) === 0 ) {
433 wfProfileOut( __METHOD__
);
434 return $this->modifiedTime
[$context->getHash()] = 1;
437 wfProfileIn( __METHOD__
.'-filemtime' );
438 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
439 wfProfileOut( __METHOD__
.'-filemtime' );
440 $this->modifiedTime
[$context->getHash()] = max(
442 $this->getMsgBlobMtime( $context->getLanguage() ) );
444 wfProfileOut( __METHOD__
);
445 return $this->modifiedTime
[$context->getHash()];
448 /* Protected Methods */
451 * @param $path string
454 protected function getLocalPath( $path ) {
455 return "{$this->localBasePath}/$path";
459 * @param $path string
462 protected function getRemotePath( $path ) {
463 return "{$this->remoteBasePath}/$path";
467 * Collates file paths by option (where provided).
469 * @param $list Array: List of file paths in any combination of index/path
470 * or path/options pairs
471 * @param $option String: option name
472 * @param $default Mixed: default value if the option isn't set
473 * @return Array: List of file paths, collated by $option
475 protected static function collateFilePathListByOption( array $list, $option, $default ) {
476 $collatedFiles = array();
477 foreach ( (array) $list as $key => $value ) {
478 if ( is_int( $key ) ) {
479 // File name as the value
480 if ( !isset( $collatedFiles[$default] ) ) {
481 $collatedFiles[$default] = array();
483 $collatedFiles[$default][] = $value;
484 } elseif ( is_array( $value ) ) {
485 // File name as the key, options array as the value
486 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
487 if ( !isset( $collatedFiles[$optionValue] ) ) {
488 $collatedFiles[$optionValue] = array();
490 $collatedFiles[$optionValue][] = $key;
493 return $collatedFiles;
497 * Gets a list of element that match a key, optionally using a fallback key.
499 * @param $list Array: List of lists to select from
500 * @param $key String: Key to look for in $map
501 * @param $fallback String: Key to look for in $list if $key doesn't exist
502 * @return Array: List of elements from $map which matched $key or $fallback,
503 * or an empty list in case of no match
505 protected static function tryForKey( array $list, $key, $fallback = null ) {
506 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
508 } elseif ( is_string( $fallback )
509 && isset( $list[$fallback] )
510 && is_array( $list[$fallback] ) )
512 return $list[$fallback];
518 * Gets a list of file paths for all scripts in this module, in order of propper execution.
520 * @param $context ResourceLoaderContext: Context
521 * @return Array: List of file paths
523 protected function getScriptFiles( ResourceLoaderContext
$context ) {
524 $files = array_merge(
526 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
527 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
529 if ( $context->getDebug() ) {
530 $files = array_merge( $files, $this->debugScripts
);
536 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
538 * @param $context ResourceLoaderContext: Context
539 * @return Array: List of file paths
541 protected function getStyleFiles( ResourceLoaderContext
$context ) {
542 return array_merge_recursive(
543 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
544 self
::collateFilePathListByOption(
545 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ), 'media', 'all'
551 * Gets the contents of a list of JavaScript files.
553 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
554 * @throws MWException
555 * @return String: Concatenated and remapped JavaScript data from $scripts
557 protected function readScriptFiles( array $scripts ) {
558 global $wgResourceLoaderValidateStaticJS;
559 if ( empty( $scripts ) ) {
563 foreach ( array_unique( $scripts ) as $fileName ) {
564 $localPath = $this->getLocalPath( $fileName );
565 if ( !file_exists( $localPath ) ) {
566 throw new MWException( __METHOD__
.": script file not found: \"$localPath\"" );
568 $contents = file_get_contents( $localPath );
569 if ( $wgResourceLoaderValidateStaticJS ) {
570 // Static files don't really need to be checked as often; unlike
571 // on-wiki module they shouldn't change unexpectedly without
572 // admin interference.
573 $contents = $this->validateScriptFile( $fileName, $contents );
575 $js .= $contents . "\n";
581 * Gets the contents of a list of CSS files.
583 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
588 * @return Array: List of concatenated and remapped CSS data from $styles,
589 * keyed by media type
591 protected function readStyleFiles( array $styles, $flip ) {
592 if ( empty( $styles ) ) {
595 foreach ( $styles as $media => $files ) {
596 $uniqueFiles = array_unique( $files );
597 $styles[$media] = implode(
600 array( $this, 'readStyleFile' ),
602 array_fill( 0, count( $uniqueFiles ), $flip )
610 * Reads a style file.
612 * This method can be used as a callback for array_map()
614 * @param $path String: File path of style file to read
617 * @return String: CSS data in script file
618 * @throws MWException if the file doesn't exist
620 protected function readStyleFile( $path, $flip ) {
621 $localPath = $this->getLocalPath( $path );
622 if ( !file_exists( $localPath ) ) {
623 $msg = __METHOD__
.": style file not found: \"$localPath\"";
624 wfDebugLog( 'resourceloader', $msg );
625 throw new MWException( $msg );
627 $style = file_get_contents( $localPath );
629 $style = CSSJanus
::transform( $style, true, false );
631 $dirname = dirname( $path );
632 if ( $dirname == '.' ) {
633 // If $path doesn't have a directory component, don't prepend a dot
636 $dir = $this->getLocalPath( $dirname );
637 $remoteDir = $this->getRemotePath( $dirname );
638 // Get and register local file references
639 $this->localFileRefs
= array_merge(
640 $this->localFileRefs
,
641 CSSMin
::getLocalFileReferences( $style, $dir )
643 return CSSMin
::remap(
644 $style, $dir, $remoteDir, true
649 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
650 * but returns 1 instead.
651 * @param $filename string File name
652 * @return int UNIX timestamp, or 1 if the file doesn't exist
654 protected static function safeFilemtime( $filename ) {
655 if ( file_exists( $filename ) ) {
656 return filemtime( $filename );
658 // We only ever map this function on an array if we're gonna call max() after,
659 // so return our standard minimum timestamps here. This is 1, not 0, because
660 // wfTimestamp(0) == NOW
666 * Get whether CSS for this module should be flipped
667 * @param $context ResourceLoaderContext
670 public function getFlip( $context ) {
671 return $context->getDirection() === 'rtl';