5bffad73d63dfd48842e1e09ec95926214f05233
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 defined( 'MEDIAWIKI' ) || die( 1 );
24
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
27 */
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29
30 /* Protected Members */
31
32 /**
33 * @var {array} List of paths to JavaScript files to always include
34 * @format array( [file-path], [file-path], ... )
35 */
36 protected $scripts = array();
37 /**
38 * @var {array} List of JavaScript files to include when using a specific language
39 * @format array( [language-code] => array( [file-path], [file-path], ... ), ... )
40 */
41 protected $languageScripts = array();
42 /**
43 * @var {array} List of JavaScript files to include when using a specific skin
44 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
45 */
46 protected $skinScripts = array();
47 /**
48 * @var {array} List of paths to JavaScript files to include in debug mode
49 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
50 */
51 protected $debugScripts = array();
52 /**
53 * @var {array} List of paths to JavaScript files to include in the startup module
54 * @format array( [file-path], [file-path], ... )
55 */
56 protected $loaderScripts = array();
57 /**
58 * @var {array} List of paths to CSS files to always include
59 * @format array( [file-path], [file-path], ... )
60 */
61 protected $styles = array();
62 /**
63 * @var {array} List of paths to CSS files to include when using specific skins
64 * @format array( [file-path], [file-path], ... )
65 */
66 protected $skinStyles = array();
67 /**
68 * @var {array} List of modules this module depends on
69 * @format array( [file-path], [file-path], ... )
70 */
71 protected $dependencies = array();
72 /**
73 * @var {array} List of message keys used by this module
74 * @format array( [module-name], [module-name], ... )
75 */
76 protected $messages = array();
77 /**
78 * @var {string} Name of group this module should be loaded in
79 * @format array( [message-key], [message-key], ... )
80 */
81 protected $group;
82 /** @var {boolean} Link to raw files in debug mode */
83 protected $debugRaw = true;
84 /**
85 * @var {array} Cache for mtime
86 * @format array( [hash] => [mtime], [hash] => [mtime], ... )
87 */
88 protected $modifiedTime = array();
89
90 /* Methods */
91
92 /**
93 * Constructs a new module from an options array.
94 *
95 * @param {array} $options Options array. If not given or empty, an empty module will be constructed
96 * @param {string} $basePath base path to prepend to all paths in $options
97 *
98 * @format $options
99 * array(
100 * // Scripts to always include
101 * 'scripts' => [file path string or array of file path strings],
102 * // Scripts to include in specific language contexts
103 * 'languageScripts' => array(
104 * [language code] => [file path string or array of file path strings],
105 * ),
106 * // Scripts to include in specific skin contexts
107 * 'skinScripts' => array(
108 * [skin name] => [file path string or array of file path strings],
109 * ),
110 * // Scripts to include in debug contexts
111 * 'debugScripts' => [file path string or array of file path strings],
112 * // Scripts to include in the startup module
113 * 'loaderScripts' => [file path string or array of file path strings],
114 * // Modules which must be loaded before this module
115 * 'dependencies' => [modile name string or array of module name strings],
116 * // Styles to always load
117 * 'styles' => [file path string or array of file path strings],
118 * // Styles to include in specific skin contexts
119 * 'skinStyles' => array(
120 * [skin name] => [file path string or array of file path strings],
121 * ),
122 * // Messages to always load
123 * 'messages' => [array of message key strings],
124 * // Group which this module should be loaded together with
125 * 'group' => [group name string],
126 * )
127 */
128 public function __construct( $options = array(), $basePath = null ) {
129 foreach ( $options as $member => $option ) {
130 switch ( $member ) {
131 // Lists of file paths
132 case 'scripts':
133 case 'debugScripts':
134 case 'loaderScripts':
135 case 'styles':
136 $this->{$member} = self::prefixFilePathList( (array) $option, $basePath );
137 break;
138 // Collated lists of file paths
139 case 'languageScripts':
140 case 'skinScripts':
141 case 'skinStyles':
142 if ( !is_array( $option ) ) {
143 throw new MWException(
144 "Invalid collated file path list error. '$option' given, array expected."
145 );
146 }
147 foreach ( $option as $key => $value ) {
148 if ( !is_string( $key ) ) {
149 throw new MWException(
150 "Invalid collated file path list key error. '$key' given, string expected."
151 );
152 }
153 $this->{$member}[$key] = self::prefixFilePathList( (array) $value, $basePath );
154 }
155 break;
156 // Lists of strings
157 case 'dependencies':
158 case 'messages':
159 $this->{$member} = (array) $option;
160 break;
161 // Single strings
162 case 'group':
163 $this->{$member} = (string) $option;
164 break;
165 // Single booleans
166 case 'debugRaw':
167 $this->{$member} = (bool) $option;
168 break;
169 }
170 }
171 }
172
173 /**
174 * Gets all scripts for a given context concatenated together.
175 *
176 * @param {ResourceLoaderContext} $context Context in which to generate script
177 * @return {string} JavaScript code for $context
178 */
179 public function getScript( ResourceLoaderContext $context ) {
180 global $wgServer, $wgScriptPath;
181
182 $files = array_merge(
183 $this->scripts,
184 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
185 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
186 );
187 if ( $context->getDebug() ) {
188 $files = array_merge( $files, $this->debugScripts );
189 if ( $this->debugRaw ) {
190 $script = '';
191 foreach ( $files as $file ) {
192 $path = FormatJson::encode( "$wgServer$wgScriptPath/$file" );
193 $script .= "\n\tmediaWiki.loader.load( $path );";
194 }
195 return $script;
196 }
197 }
198 return self::readScriptFiles( $files );
199 }
200
201 /**
202 * Gets loader script.
203 *
204 * @return {string} JavaScript code to be added to startup module
205 */
206 public function getLoaderScript() {
207 if ( count( $this->loaderScripts ) == 0 ) {
208 return false;
209 }
210 return self::readScriptFiles( $this->loaderScripts );
211 }
212
213 /**
214 * Gets all styles for a given context concatenated together.
215 *
216 * @param {ResourceLoaderContext} $context Context in which to generate styles
217 * @return {string} CSS code for $context
218 */
219 public function getStyles( ResourceLoaderContext $context ) {
220 // Merge general styles and skin specific styles, retaining media type collation
221 $styles = self::readStyleFiles( $this->styles );
222 $skinStyles = self::readStyleFiles( self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ) );
223
224 foreach ( $skinStyles as $media => $style ) {
225 if ( isset( $styles[$media] ) ) {
226 $styles[$media] .= $style;
227 } else {
228 $styles[$media] = $style;
229 }
230 }
231 // Collect referenced files
232 $files = array();
233 foreach ( $styles as /* $media => */ $style ) {
234 $files = array_merge( $files, CSSMin::getLocalFileReferences( $style ) );
235 }
236 // If the list has been modified since last time we cached it, update the cache
237 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
238 $dbw = wfGetDB( DB_MASTER );
239 $dbw->replace( 'module_deps',
240 array( array( 'md_module', 'md_skin' ) ), array(
241 'md_module' => $this->getName(),
242 'md_skin' => $context->getSkin(),
243 'md_deps' => FormatJson::encode( $files ),
244 )
245 );
246 }
247 return $styles;
248 }
249
250 /**
251 * Gets list of message keys used by this module.
252 *
253 * @return {array} List of message keys
254 */
255 public function getMessages() {
256 return $this->messages;
257 }
258
259 /**
260 * Gets the name of the group this module should be loaded in.
261 *
262 * @return {string} Group name
263 */
264 public function getGroup() {
265 return $this->group;
266 }
267
268 /**
269 * Gets list of names of modules this module depends on.
270 *
271 * @return {array} List of module names
272 */
273 public function getDependencies() {
274 return $this->dependencies;
275 }
276
277 /**
278 * Get the last modified timestamp of this module.
279 *
280 * Last modified timestamps are calculated from the highest last modified timestamp of this module's constituent
281 * files as well as the files it depends on. This function is context-sensitive, only performing calculations on
282 * files relevant to the given language, skin and debug mode.
283 *
284 * @param {ResourceLoaderContext} $context Context in which to calculate the modified time
285 * @return {integer} UNIX timestamp
286 * @see {ResourceLoaderModule::getFileDependencies}
287 */
288 public function getModifiedTime( ResourceLoaderContext $context ) {
289 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
290 return $this->modifiedTime[$context->getHash()];
291 }
292 wfProfileIn( __METHOD__ );
293
294 $files = array();
295
296 // Flatten style files into $files
297 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
298 foreach ( $styles as $styleFiles ) {
299 $files = array_merge( $files, $styleFiles );
300 }
301 $skinFiles = self::tryForKey(
302 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ), $context->getSkin(), 'default'
303 );
304 foreach ( $skinFiles as $styleFiles ) {
305 $files = array_merge( $files, $styleFiles );
306 }
307
308 // Final merge, this should result in a master list of dependent files
309 $files = array_merge(
310 $files,
311 $this->scripts,
312 $context->getDebug() ? $this->debugScripts : array(),
313 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
314 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
315 $this->loaderScripts,
316 $this->getFileDependencies( $context->getSkin() )
317 );
318
319 // If a module is nothing but a list of dependencies, we need to avoid giving max() an empty array
320 if ( count( $files ) === 0 ) {
321 return $this->modifiedTime[$context->getHash()] = 1;
322 }
323
324 wfProfileIn( __METHOD__.'-filemtime' );
325 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__, 'resolveFilePath' ), $files ) ) );
326 wfProfileOut( __METHOD__.'-filemtime' );
327 $this->modifiedTime[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
328 wfProfileOut( __METHOD__ );
329 return $this->modifiedTime[$context->getHash()];
330 }
331
332 /* Protected Members */
333
334 /**
335 * Prefixes each file path in a list.
336 *
337 * @param {array} $list List of file paths in any combination of index/path or path/options pairs
338 * @param {string} $prefix String to prepend to each file path in $list
339 * @return {array} List of prefixed file paths
340 */
341 protected static function prefixFilePathList( array $list, $prefix ) {
342 $prefixed = array();
343 foreach ( $list as $key => $value ) {
344 if ( is_string( $key ) && is_array( $value ) ) {
345 // array( [path] => array( [options] ) )
346 $prefixed[$prefix . $key] = $value;
347 } else if ( is_int( $key ) && is_string( $value ) ) {
348 // array( [path] )
349 $prefixed[$key] = $prefix . $value;
350 } else {
351 throw new MWException( "Invalid file path list error. '$key' => '$value' given." );
352 }
353 }
354 return $prefixed;
355 }
356
357 /**
358 * Collates file paths by option (where provided).
359 *
360 * @param {array} $list List of file paths in any combination of index/path or path/options pairs
361 * @return {array} List of file paths, collated by $option
362 */
363 protected static function collateFilePathListByOption( array $list, $option, $default ) {
364 $collatedFiles = array();
365 foreach ( (array) $list as $key => $value ) {
366 if ( is_int( $key ) ) {
367 // File name as the value
368 if ( !isset( $collatedFiles[$default] ) ) {
369 $collatedFiles[$default] = array();
370 }
371 $collatedFiles[$default][] = $value;
372 } else if ( is_array( $value ) ) {
373 // File name as the key, options array as the value
374 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
375 if ( !isset( $collatedFiles[$optionValue] ) ) {
376 $collatedFiles[$optionValue] = array();
377 }
378 $collatedFiles[$optionValue][] = $key;
379 }
380 }
381 return $collatedFiles;
382 }
383
384 /**
385 * Gets a list of element that match a key, optionally using a fallback key.
386 *
387 * @param {array} $list List of lists to select from
388 * @param {string} $key Key to look for in $map
389 * @param {string} $fallback Key to look for in $list if $key doesn't exist
390 * @return {array} List of elements from $map which matched $key or $fallback, or an empty list in case of no match
391 */
392 protected static function tryForKey( array $list, $key, $fallback = null ) {
393 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
394 return $list[$key];
395 } else if ( is_string( $fallback ) && isset( $list[$fallback] ) && is_array( $list[$fallback] ) ) {
396 return $list[$fallback];
397 }
398 return array();
399 }
400
401 /**
402 * Gets the contents of a list of JavaScript files.
403 *
404 * @param {array} $scripts List of file paths to scripts to read, remap and concetenate
405 * @return {string} Concatenated and remapped JavaScript data from $scripts
406 */
407 protected static function readScriptFiles( array $scripts ) {
408 if ( empty( $scripts ) ) {
409 return '';
410 }
411 return implode( "\n", array_map( array( __CLASS__, 'readScriptFile' ), array_unique( $scripts ) ) );
412 }
413
414 /**
415 * Gets the contents of a list of CSS files.
416 *
417 * @param {array} $styles List of file paths to styles to read, remap and concetenate
418 * @return {array} List of concatenated and remapped CSS data from $styles, keyed by media type
419 */
420 protected static function readStyleFiles( array $styles ) {
421 if ( empty( $styles ) ) {
422 return array();
423 }
424 $styles = self::collateFilePathListByOption( $styles, 'media', 'all' );
425 foreach ( $styles as $media => $files ) {
426 $styles[$media] = implode(
427 "\n", array_map( array( __CLASS__, 'readStyleFile' ), array_unique( $files ) )
428 );
429 }
430 return $styles;
431 }
432
433 /**
434 * Reads a script file.
435 *
436 * This method can be used as a callback for array_map()
437 *
438 * @param {string} $path File path of script file to read
439 * @return {string} JavaScript data in script file
440 */
441 protected static function readScriptFile( $path ) {
442 global $IP;
443
444 return file_get_contents( "$IP/$path" );
445 }
446
447 /**
448 * Reads a style file.
449 *
450 * This method can be used as a callback for array_map()
451 *
452 * @param {string} $path File path of script file to read
453 * @return {string} CSS data in script file
454 */
455 protected static function readStyleFile( $path ) {
456 global $wgScriptPath, $IP;
457
458 return CSSMin::remap(
459 file_get_contents( "$IP/$path" ), dirname( "$IP/$path" ), $wgScriptPath . '/' . dirname( $path ), true
460 );
461 }
462
463 /**
464 * Resolves a file name.
465 *
466 * This method can be used as a callback for array_map()
467 *
468 * @param {string} $path File path to resolve
469 * @return {string} Absolute file path
470 */
471 protected static function resolveFilePath( $path ) {
472 global $IP;
473
474 return "$IP/$path";
475 }
476 }