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