3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Trevor Parscal
20 * @author Roan Kattouw
24 * ResourceLoader module based on local JavaScript/CSS files.
26 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
28 /* Protected Members */
30 /** String: Local base path, see __construct() */
31 protected $localBasePath = '';
32 /** String: Remote base path, see __construct() */
33 protected $remoteBasePath = '';
35 * Array: List of paths to JavaScript files to always include
36 * @example array( [file-path], [file-path], ... )
38 protected $scripts = array();
40 * Array: List of JavaScript files to include when using a specific language
41 * @example array( [language-code] => array( [file-path], [file-path], ... ), ... )
43 protected $languageScripts = array();
45 * Array: List of JavaScript files to include when using a specific skin
46 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
48 protected $skinScripts = array();
50 * Array: List of paths to JavaScript files to include in debug mode
51 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
53 protected $debugScripts = array();
55 * Array: List of paths to JavaScript files to include in the startup module
56 * @example array( [file-path], [file-path], ... )
58 protected $loaderScripts = array();
60 * Array: List of paths to CSS files to always include
61 * @example array( [file-path], [file-path], ... )
63 protected $styles = array();
65 * Array: List of paths to CSS files to include when using specific skins
66 * @example array( [file-path], [file-path], ... )
68 protected $skinStyles = array();
70 * Array: List of modules this module depends on
71 * @example array( [file-path], [file-path], ... )
73 protected $dependencies = array();
75 * Array: List of message keys used by this module
76 * @example array( [message-key], [message-key], ... )
78 protected $messages = array();
79 /** String: Name of group to load this module in */
81 /** String: Position on the page to load this module at */
82 protected $position = 'bottom';
83 /** Boolean: Link to raw files in debug mode */
84 protected $debugRaw = true;
86 * Array: Cache for mtime
87 * @example array( [hash] => [mtime], [hash] => [mtime], ... )
89 protected $modifiedTime = array();
91 * Array: Place where readStyleFile() tracks file dependencies
92 * @example array( [file-path], [file-path], ... )
94 protected $localFileRefs = array();
99 * Constructs a new module from an options array.
101 * @param $options Array: List of options; if not given or empty, an empty module will be
103 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
105 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
108 * Below is a description for the $options array:
111 * // Base path to prepend to all local paths in $options. Defaults to $IP
112 * 'localBasePath' => [base path],
113 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
114 * 'remoteBasePath' => [base path],
115 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
116 * 'remoteExtPath' => [base path],
117 * // Scripts to always include
118 * 'scripts' => [file path string or array of file path strings],
119 * // Scripts to include in specific language contexts
120 * 'languageScripts' => array(
121 * [language code] => [file path string or array of file path strings],
123 * // Scripts to include in specific skin contexts
124 * 'skinScripts' => array(
125 * [skin name] => [file path string or array of file path strings],
127 * // Scripts to include in debug contexts
128 * 'debugScripts' => [file path string or array of file path strings],
129 * // Scripts to include in the startup module
130 * 'loaderScripts' => [file path string or array of file path strings],
131 * // Modules which must be loaded before this module
132 * 'dependencies' => [modile name string or array of module name strings],
133 * // Styles to always load
134 * 'styles' => [file path string or array of file path strings],
135 * // Styles to include in specific skin contexts
136 * 'skinStyles' => array(
137 * [skin name] => [file path string or array of file path strings],
139 * // Messages to always load
140 * 'messages' => [array of message key strings],
141 * // Group which this module should be loaded together with
142 * 'group' => [group name string],
143 * // Position on the page to load this module at
144 * 'position' => ['bottom' (default) or 'top']
148 public function __construct( $options = array(), $localBasePath = null,
149 $remoteBasePath = null )
151 global $IP, $wgScriptPath;
152 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
153 $this->remoteBasePath
= $remoteBasePath === null ?
$wgScriptPath : $remoteBasePath;
155 if ( isset( $options['remoteExtPath'] ) ) {
156 global $wgExtensionAssetsPath;
157 $this->remoteBasePath
= $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
160 foreach ( $options as $member => $option ) {
162 // Lists of file paths
165 case 'loaderScripts':
167 $this->{$member} = (array) $option;
169 // Collated lists of file paths
170 case 'languageScripts':
173 if ( !is_array( $option ) ) {
174 throw new MWException(
175 "Invalid collated file path list error. " .
176 "'$option' given, array expected."
179 foreach ( $option as $key => $value ) {
180 if ( !is_string( $key ) ) {
181 throw new MWException(
182 "Invalid collated file path list key error. " .
183 "'$key' given, string expected."
186 $this->{$member}[$key] = (array) $value;
192 $this->{$member} = (array) $option;
197 case 'localBasePath':
198 case 'remoteBasePath':
199 $this->{$member} = (string) $option;
203 $this->{$member} = (bool) $option;
207 // Make sure the remote base path is a complete valid url
208 $this->remoteBasePath
= wfExpandUrl( $this->remoteBasePath
);
212 * Gets all scripts for a given context concatenated together.
214 * @param $context ResourceLoaderContext: Context in which to generate script
215 * @return String: JavaScript code for $context
217 public function getScript( ResourceLoaderContext
$context ) {
218 $files = $this->getScriptFiles( $context );
219 if ( $context->getDebug() && $this->debugRaw
) {
221 foreach ( $this->getScriptFiles( $context ) as $file ) {
222 $urls[] = $this->getRemotePath( $file );
226 return $this->readScriptFiles( $files );
230 * Gets loader script.
232 * @return String: JavaScript code to be added to startup module
234 public function getLoaderScript() {
235 if ( count( $this->loaderScripts
) == 0 ) {
238 return $this->readScriptFiles( $this->loaderScripts
);
242 * Gets all styles for a given context concatenated together.
244 * @param $context ResourceLoaderContext: Context in which to generate styles
245 * @return String: CSS code for $context
247 public function getStyles( ResourceLoaderContext
$context ) {
248 $styles = $this->readStyleFiles(
249 $this->getStyleFiles( $context ),
250 $this->getFlip( $context )
252 if ( !$context->getOnly() && $context->getDebug() && $this->debugRaw
) {
254 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
255 $urls[$mediaType] = array();
256 foreach ( $list as $file ) {
257 $urls[$mediaType][] = $this->getRemotePath( $file );
262 // Collect referenced files
263 $this->localFileRefs
= array_unique( $this->localFileRefs
);
264 // If the list has been modified since last time we cached it, update the cache
265 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
266 $dbw = wfGetDB( DB_MASTER
);
267 $dbw->replace( 'module_deps',
268 array( array( 'md_module', 'md_skin' ) ), array(
269 'md_module' => $this->getName(),
270 'md_skin' => $context->getSkin(),
271 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
279 * Gets list of message keys used by this module.
281 * @return Array: List of message keys
283 public function getMessages() {
284 return $this->messages
;
288 * Gets the name of the group this module should be loaded in.
290 * @return String: Group name
292 public function getGroup() {
299 public function getPosition() {
300 return $this->position
;
304 * Gets list of names of modules this module depends on.
306 * @return Array: List of module names
308 public function getDependencies() {
309 return $this->dependencies
;
313 * Get the last modified timestamp of this module.
315 * Last modified timestamps are calculated from the highest last modified
316 * timestamp of this module's constituent files as well as the files it
317 * depends on. This function is context-sensitive, only performing
318 * calculations on files relevant to the given language, skin and debug
321 * @param $context ResourceLoaderContext: Context in which to calculate
323 * @return Integer: UNIX timestamp
324 * @see ResourceLoaderModule::getFileDependencies
326 public function getModifiedTime( ResourceLoaderContext
$context ) {
327 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
328 return $this->modifiedTime
[$context->getHash()];
330 wfProfileIn( __METHOD__
);
334 // Flatten style files into $files
335 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
336 foreach ( $styles as $styleFiles ) {
337 $files = array_merge( $files, $styleFiles );
339 $skinFiles = self
::tryForKey(
340 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ),
344 foreach ( $skinFiles as $styleFiles ) {
345 $files = array_merge( $files, $styleFiles );
348 // Final merge, this should result in a master list of dependent files
349 $files = array_merge(
352 $context->getDebug() ?
$this->debugScripts
: array(),
353 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
354 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
357 $files = array_map( array( $this, 'getLocalPath' ), $files );
358 // File deps need to be treated separately because they're already prefixed
359 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
361 // If a module is nothing but a list of dependencies, we need to avoid
362 // giving max() an empty array
363 if ( count( $files ) === 0 ) {
364 wfProfileOut( __METHOD__
);
365 return $this->modifiedTime
[$context->getHash()] = 1;
368 wfProfileIn( __METHOD__
.'-filemtime' );
369 $filesMtime = max( array_map( 'filemtime', $files ) );
370 wfProfileOut( __METHOD__
.'-filemtime' );
371 $this->modifiedTime
[$context->getHash()] = max(
373 $this->getMsgBlobMtime( $context->getLanguage() ) );
375 wfProfileOut( __METHOD__
);
376 return $this->modifiedTime
[$context->getHash()];
379 /* Protected Methods */
382 * @param $path string
385 protected function getLocalPath( $path ) {
386 return "{$this->localBasePath}/$path";
390 * @param $path string
393 protected function getRemotePath( $path ) {
394 return "{$this->remoteBasePath}/$path";
398 * Collates file paths by option (where provided).
400 * @param $list Array: List of file paths in any combination of index/path
401 * or path/options pairs
402 * @param $option String: option name
403 * @param $default Mixed: default value if the option isn't set
404 * @return Array: List of file paths, collated by $option
406 protected static function collateFilePathListByOption( array $list, $option, $default ) {
407 $collatedFiles = array();
408 foreach ( (array) $list as $key => $value ) {
409 if ( is_int( $key ) ) {
410 // File name as the value
411 if ( !isset( $collatedFiles[$default] ) ) {
412 $collatedFiles[$default] = array();
414 $collatedFiles[$default][] = $value;
415 } elseif ( is_array( $value ) ) {
416 // File name as the key, options array as the value
417 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
418 if ( !isset( $collatedFiles[$optionValue] ) ) {
419 $collatedFiles[$optionValue] = array();
421 $collatedFiles[$optionValue][] = $key;
424 return $collatedFiles;
428 * Gets a list of element that match a key, optionally using a fallback key.
430 * @param $list Array: List of lists to select from
431 * @param $key String: Key to look for in $map
432 * @param $fallback String: Key to look for in $list if $key doesn't exist
433 * @return Array: List of elements from $map which matched $key or $fallback,
434 * or an empty list in case of no match
436 protected static function tryForKey( array $list, $key, $fallback = null ) {
437 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
439 } elseif ( is_string( $fallback )
440 && isset( $list[$fallback] )
441 && is_array( $list[$fallback] ) )
443 return $list[$fallback];
449 * Gets a list of file paths for all scripts in this module, in order of propper execution.
451 * @param $context ResourceLoaderContext: Context
452 * @return Array: List of file paths
454 protected function getScriptFiles( ResourceLoaderContext
$context ) {
455 $files = array_merge(
457 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
458 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
460 if ( $context->getDebug() ) {
461 $files = array_merge( $files, $this->debugScripts
);
467 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
469 * @param $context ResourceLoaderContext: Context
470 * @return Array: List of file paths
472 protected function getStyleFiles( ResourceLoaderContext
$context ) {
473 return array_merge_recursive(
474 self
::collateFilePathListByOption( $this->styles
, 'media', 'all' ),
475 self
::collateFilePathListByOption(
476 self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ), 'media', 'all'
482 * Gets the contents of a list of JavaScript files.
484 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
485 * @return String: Concatenated and remapped JavaScript data from $scripts
487 protected function readScriptFiles( array $scripts ) {
488 if ( empty( $scripts ) ) {
492 foreach ( array_unique( $scripts ) as $fileName ) {
493 $localPath = $this->getLocalPath( $fileName );
494 $contents = file_get_contents( $localPath );
495 if ( $contents === false ) {
496 throw new MWException( __METHOD__
.": script file not found: \"$localPath\"" );
498 $contents = $this->validateScriptFile( $fileName, $contents );
499 $js .= $contents . "\n";
505 * Gets the contents of a list of CSS files.
507 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
512 * @return Array: List of concatenated and remapped CSS data from $styles,
513 * keyed by media type
515 protected function readStyleFiles( array $styles, $flip ) {
516 if ( empty( $styles ) ) {
519 foreach ( $styles as $media => $files ) {
520 $uniqueFiles = array_unique( $files );
521 $styles[$media] = implode(
524 array( $this, 'readStyleFile' ),
526 array_fill( 0, count( $uniqueFiles ), $flip )
534 * Reads a style file.
536 * This method can be used as a callback for array_map()
538 * @param $path String: File path of script file to read
541 * @return String: CSS data in script file
543 protected function readStyleFile( $path, $flip ) {
544 $localPath = $this->getLocalPath( $path );
545 $style = file_get_contents( $localPath );
546 if ( $style === false ) {
547 throw new MWException( __METHOD__
.": style file not found: \"$localPath\"" );
550 $style = CSSJanus
::transform( $style, true, false );
552 $dirname = dirname( $path );
553 if ( $dirname == '.' ) {
554 // If $path doesn't have a directory component, don't prepend a dot
557 $dir = $this->getLocalPath( $dirname );
558 $remoteDir = $this->getRemotePath( $dirname );
559 // Get and register local file references
560 $this->localFileRefs
= array_merge(
561 $this->localFileRefs
,
562 CSSMin
::getLocalFileReferences( $style, $dir ) );
563 return CSSMin
::remap(
564 $style, $dir, $remoteDir, true
569 * Get whether CSS for this module should be flipped
570 * @param $context ResourceLoaderContext
573 public function getFlip( $context ) {
574 return $context->getDirection() === 'rtl';