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
23 defined( 'MEDIAWIKI' ) ||
die( 1 );
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
38 * @format array( [file-path], [file-path], ... )
40 protected $scripts = array();
42 * @var {array} List of JavaScript files to include when using a specific language
43 * @format array( [language-code] => array( [file-path], [file-path], ... ), ... )
45 protected $languageScripts = array();
47 * @var {array} List of JavaScript files to include when using a specific skin
48 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
50 protected $skinScripts = array();
52 * @var {array} List of paths to JavaScript files to include in debug mode
53 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
55 protected $debugScripts = array();
57 * @var {array} List of paths to JavaScript files to include in the startup module
58 * @format array( [file-path], [file-path], ... )
60 protected $loaderScripts = array();
62 * @var {array} List of paths to CSS files to always include
63 * @format array( [file-path], [file-path], ... )
65 protected $styles = array();
67 * @var {array} List of paths to CSS files to include when using specific skins
68 * @format array( [file-path], [file-path], ... )
70 protected $skinStyles = array();
72 * @var {array} List of modules this module depends on
73 * @format array( [file-path], [file-path], ... )
75 protected $dependencies = array();
77 * @var {array} List of message keys used by this module
78 * @format array( [message-key], [message-key], ... )
80 protected $messages = array();
81 /** @var {string} Name of group to load this module in */
83 /** @var {boolean} Link to raw files in debug mode */
84 protected $debugRaw = true;
86 * @var {array} Cache for mtime
87 * @format array( [hash] => [mtime], [hash] => [mtime], ... )
89 protected $modifiedTime = array();
91 * @var {array} Place where readStyleFile() tracks file dependencies
92 * @format array( [file-path], [file-path], ... )
94 protected $localFileRefs = array();
99 * Constructs a new module from an options array.
101 * @param {array} $options Options array. If not given or empty, an empty module will be constructed
102 * @param {string} $localBasePath base path to prepend to all local paths in $options. Defaults to $IP
103 * @param {string} $remoteBasePath base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
107 * // Scripts to always include
108 * 'scripts' => [file path string or array of file path strings],
109 * // Scripts to include in specific language contexts
110 * 'languageScripts' => array(
111 * [language code] => [file path string or array of file path strings],
113 * // Scripts to include in specific skin contexts
114 * 'skinScripts' => array(
115 * [skin name] => [file path string or array of file path strings],
117 * // Scripts to include in debug contexts
118 * 'debugScripts' => [file path string or array of file path strings],
119 * // Scripts to include in the startup module
120 * 'loaderScripts' => [file path string or array of file path strings],
121 * // Modules which must be loaded before this module
122 * 'dependencies' => [modile name string or array of module name strings],
123 * // Styles to always load
124 * 'styles' => [file path string or array of file path strings],
125 * // Styles to include in specific skin contexts
126 * 'skinStyles' => array(
127 * [skin name] => [file path string or array of file path strings],
129 * // Messages to always load
130 * 'messages' => [array of message key strings],
131 * // Group which this module should be loaded together with
132 * 'group' => [group name string],
135 public function __construct( $options = array(), $localBasePath = null, $remoteBasePath = null ) {
136 global $IP, $wgScriptPath;
137 $this->localBasePath
= $localBasePath === null ?
$IP : $localBasePath;
138 $this->remoteBasePath
= $remoteBasePath === null ?
$wgScriptPath : $remoteBasePath;
139 foreach ( $options as $member => $option ) {
141 // Lists of file paths
144 case 'loaderScripts':
146 $this->{$member} = (array) $option;
148 // Collated lists of file paths
149 case 'languageScripts':
152 if ( !is_array( $option ) ) {
153 throw new MWException(
154 "Invalid collated file path list error. '$option' given, array expected."
157 foreach ( $option as $key => $value ) {
158 if ( !is_string( $key ) ) {
159 throw new MWException(
160 "Invalid collated file path list key error. '$key' given, string expected."
163 $this->{$member}[$key] = (array) $value;
169 $this->{$member} = (array) $option;
173 $this->{$member} = (string) $option;
177 $this->{$member} = (bool) $option;
184 * Gets all scripts for a given context concatenated together.
186 * @param {ResourceLoaderContext} $context Context in which to generate script
187 * @return {string} JavaScript code for $context
189 public function getScript( ResourceLoaderContext
$context ) {
192 $files = array_merge(
194 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
195 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' )
197 if ( $context->getDebug() ) {
198 $files = array_merge( $files, $this->debugScripts
);
199 if ( $this->debugRaw
) {
201 foreach ( $files as $file ) {
202 $path = FormatJson
::encode( $wgServer . $this->getRemotePath( $file ) );
203 $script .= "\n\tmediaWiki.loader.load( $path );";
208 return $this->readScriptFiles( $files );
212 * Gets loader script.
214 * @return {string} JavaScript code to be added to startup module
216 public function getLoaderScript() {
217 if ( count( $this->loaderScripts
) == 0 ) {
220 return $this->readScriptFiles( $this->loaderScripts
);
224 * Gets all styles for a given context concatenated together.
226 * @param {ResourceLoaderContext} $context Context in which to generate styles
227 * @return {string} CSS code for $context
229 public function getStyles( ResourceLoaderContext
$context ) {
230 // Merge general styles and skin specific styles, retaining media type collation
231 $styles = $this->readStyleFiles( $this->styles
);
232 $skinStyles = $this->readStyleFiles( self
::tryForKey( $this->skinStyles
, $context->getSkin(), 'default' ) );
234 foreach ( $skinStyles as $media => $style ) {
235 if ( isset( $styles[$media] ) ) {
236 $styles[$media] .= $style;
238 $styles[$media] = $style;
241 // Collect referenced files
242 $this->localFileRefs
= array_unique( $this->localFileRefs
);
243 // If the list has been modified since last time we cached it, update the cache
244 if ( $this->localFileRefs
!== $this->getFileDependencies( $context->getSkin() ) ) {
245 $dbw = wfGetDB( DB_MASTER
);
246 $dbw->replace( 'module_deps',
247 array( array( 'md_module', 'md_skin' ) ), array(
248 'md_module' => $this->getName(),
249 'md_skin' => $context->getSkin(),
250 'md_deps' => FormatJson
::encode( $this->localFileRefs
),
258 * Gets list of message keys used by this module.
260 * @return {array} List of message keys
262 public function getMessages() {
263 return $this->messages
;
267 * Gets the name of the group this module should be loaded in.
269 * @return {string} Group name
271 public function getGroup() {
276 * Gets list of names of modules this module depends on.
278 * @return {array} List of module names
280 public function getDependencies() {
281 return $this->dependencies
;
285 * Get the last modified timestamp of this module.
287 * Last modified timestamps are calculated from the highest last modified timestamp of this module's constituent
288 * files as well as the files it depends on. This function is context-sensitive, only performing calculations on
289 * files relevant to the given language, skin and debug mode.
291 * @param {ResourceLoaderContext} $context Context in which to calculate the modified time
292 * @return {integer} UNIX timestamp
293 * @see {ResourceLoaderModule::getFileDependencies}
295 public function getModifiedTime( ResourceLoaderContext
$context ) {
296 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
297 return $this->modifiedTime
[$context->getHash()];
299 wfProfileIn( __METHOD__
);
303 // Flatten style files into $files
304 $styles = self
::collateFilePathListByOption( $this->styles
, 'media', 'all' );
305 foreach ( $styles as $styleFiles ) {
306 $files = array_merge( $files, $styleFiles );
308 $skinFiles = self
::tryForKey(
309 self
::collateFilePathListByOption( $this->skinStyles
, 'media', 'all' ), $context->getSkin(), 'default'
311 foreach ( $skinFiles as $styleFiles ) {
312 $files = array_merge( $files, $styleFiles );
315 // Final merge, this should result in a master list of dependent files
316 $files = array_merge(
319 $context->getDebug() ?
$this->debugScripts
: array(),
320 self
::tryForKey( $this->languageScripts
, $context->getLanguage() ),
321 self
::tryForKey( $this->skinScripts
, $context->getSkin(), 'default' ),
324 $files = array_map( array( $this, 'getLocalPath' ), $files );
325 // File deps need to be treated separately because they're already prefixed
326 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
328 // If a module is nothing but a list of dependencies, we need to avoid giving max() an empty array
329 if ( count( $files ) === 0 ) {
330 return $this->modifiedTime
[$context->getHash()] = 1;
333 wfProfileIn( __METHOD__
.'-filemtime' );
334 $filesMtime = max( array_map( 'filemtime', $files ) );
335 wfProfileOut( __METHOD__
.'-filemtime' );
336 $this->modifiedTime
[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
337 wfProfileOut( __METHOD__
);
338 return $this->modifiedTime
[$context->getHash()];
341 /* Protected Members */
343 protected function getLocalPath( $path ) {
344 return "{$this->localBasePath}/$path";
347 protected function getRemotePath( $path ) {
348 return "{$this->remoteBasePath}/$path";
352 * Collates file paths by option (where provided).
354 * @param {array} $list List of file paths in any combination of index/path or path/options pairs
355 * @return {array} List of file paths, collated by $option
357 protected static function collateFilePathListByOption( array $list, $option, $default ) {
358 $collatedFiles = array();
359 foreach ( (array) $list as $key => $value ) {
360 if ( is_int( $key ) ) {
361 // File name as the value
362 if ( !isset( $collatedFiles[$default] ) ) {
363 $collatedFiles[$default] = array();
365 $collatedFiles[$default][] = $value;
366 } else if ( is_array( $value ) ) {
367 // File name as the key, options array as the value
368 $optionValue = isset( $value[$option] ) ?
$value[$option] : $default;
369 if ( !isset( $collatedFiles[$optionValue] ) ) {
370 $collatedFiles[$optionValue] = array();
372 $collatedFiles[$optionValue][] = $key;
375 return $collatedFiles;
379 * Gets a list of element that match a key, optionally using a fallback key.
381 * @param {array} $list List of lists to select from
382 * @param {string} $key Key to look for in $map
383 * @param {string} $fallback Key to look for in $list if $key doesn't exist
384 * @return {array} List of elements from $map which matched $key or $fallback, or an empty list in case of no match
386 protected static function tryForKey( array $list, $key, $fallback = null ) {
387 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
389 } else if ( is_string( $fallback ) && isset( $list[$fallback] ) && is_array( $list[$fallback] ) ) {
390 return $list[$fallback];
396 * Gets the contents of a list of JavaScript files.
398 * @param {array} $scripts List of file paths to scripts to read, remap and concetenate
399 * @return {string} Concatenated and remapped JavaScript data from $scripts
401 protected function readScriptFiles( array $scripts ) {
402 if ( empty( $scripts ) ) {
405 return implode( "\n", array_map( 'file_get_contents', array_map( array( $this, 'getLocalPath' ), array_unique( $scripts ) ) ) );
409 * Gets the contents of a list of CSS files.
411 * @param {array} $styles List of file paths to styles to read, remap and concetenate
412 * @return {array} List of concatenated and remapped CSS data from $styles, keyed by media type
414 protected function readStyleFiles( array $styles ) {
415 if ( empty( $styles ) ) {
418 $styles = self
::collateFilePathListByOption( $styles, 'media', 'all' );
419 foreach ( $styles as $media => $files ) {
420 $styles[$media] = implode(
421 "\n", array_map( array( $this, 'readStyleFile' ), array_unique( $files ) )
428 * Reads a style file.
430 * This method can be used as a callback for array_map()
432 * @param {string} $path File path of script file to read
433 * @return {string} CSS data in script file
435 protected function readStyleFile( $path ) {
436 $style = file_get_contents( $this->getLocalPath( $path ) );
437 $dir = $this->getLocalPath( dirname( $path ) );
438 $remoteDir = $this->getRemotePath( dirname( $path ) );
439 // Get and register local file references
440 $this->localFileRefs
= array_merge( $this->localFileRefs
, CSSMin
::getLocalFileReferences( $style, $dir ) );
441 return CSSMin
::remap(
442 $style, $dir, $remoteDir, true