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