Fix the fixme on r88053: dependency handling was broken in debug mode in certain...
[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 /** 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;
85 /**
86 * Array: Cache for mtime
87 * @example array( [hash] => [mtime], [hash] => [mtime], ... )
88 */
89 protected $modifiedTime = array();
90 /**
91 * Array: Place where readStyleFile() tracks file dependencies
92 * @example array( [file-path], [file-path], ... )
93 */
94 protected $localFileRefs = array();
95
96 /* Methods */
97
98 /**
99 * Constructs a new module from an options array.
100 *
101 * @param $options Array: List of options; if not given or empty, an empty module will be
102 * constructed
103 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
104 * to $IP
105 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
106 * to $wgScriptPath
107 *
108 * Below is a description for the $options array:
109 * @code
110 * 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],
122 * ),
123 * // Scripts to include in specific skin contexts
124 * 'skinScripts' => array(
125 * [skin name] => [file path string or array of file path strings],
126 * ),
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],
138 * ),
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']
145 * )
146 * @endcode
147 */
148 public function __construct( $options = array(), $localBasePath = null,
149 $remoteBasePath = null )
150 {
151 global $IP, $wgScriptPath;
152 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
153 $this->remoteBasePath = $remoteBasePath === null ? $wgScriptPath : $remoteBasePath;
154
155 if ( isset( $options['remoteExtPath'] ) ) {
156 global $wgExtensionAssetsPath;
157 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
158 }
159
160 foreach ( $options as $member => $option ) {
161 switch ( $member ) {
162 // Lists of file paths
163 case 'scripts':
164 case 'debugScripts':
165 case 'loaderScripts':
166 case 'styles':
167 $this->{$member} = (array) $option;
168 break;
169 // Collated lists of file paths
170 case 'languageScripts':
171 case 'skinScripts':
172 case 'skinStyles':
173 if ( !is_array( $option ) ) {
174 throw new MWException(
175 "Invalid collated file path list error. " .
176 "'$option' given, array expected."
177 );
178 }
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."
184 );
185 }
186 $this->{$member}[$key] = (array) $value;
187 }
188 break;
189 // Lists of strings
190 case 'dependencies':
191 case 'messages':
192 $this->{$member} = (array) $option;
193 break;
194 // Single strings
195 case 'group':
196 case 'position':
197 case 'localBasePath':
198 case 'remoteBasePath':
199 $this->{$member} = (string) $option;
200 break;
201 // Single booleans
202 case 'debugRaw':
203 $this->{$member} = (bool) $option;
204 break;
205 }
206 }
207 // Make sure the remote base path is a complete valid URL,
208 // but possibly protocol-relative to avoid cache pollution
209 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
210 }
211
212 /**
213 * Gets all scripts for a given context concatenated together.
214 *
215 * @param $context ResourceLoaderContext: Context in which to generate script
216 * @return String: JavaScript code for $context
217 */
218 public function getScript( ResourceLoaderContext $context ) {
219 $files = $this->getScriptFiles( $context );
220 return $this->readScriptFiles( $files );
221 }
222
223 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
224 $urls = array();
225 foreach ( $this->getScriptFiles( $context ) as $file ) {
226 $urls[] = $this->getRemotePath( $file );
227 }
228 return $urls;
229 }
230
231 public function supportsURLLoading() {
232 return $this->debugRaw;
233 }
234
235 /**
236 * Gets loader script.
237 *
238 * @return String: JavaScript code to be added to startup module
239 */
240 public function getLoaderScript() {
241 if ( count( $this->loaderScripts ) == 0 ) {
242 return false;
243 }
244 return $this->readScriptFiles( $this->loaderScripts );
245 }
246
247 /**
248 * Gets all styles for a given context concatenated together.
249 *
250 * @param $context ResourceLoaderContext: Context in which to generate styles
251 * @return String: CSS code for $context
252 */
253 public function getStyles( ResourceLoaderContext $context ) {
254 $styles = $this->readStyleFiles(
255 $this->getStyleFiles( $context ),
256 $this->getFlip( $context )
257 );
258 // Collect referenced files
259 $this->localFileRefs = array_unique( $this->localFileRefs );
260 // If the list has been modified since last time we cached it, update the cache
261 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
262 $dbw = wfGetDB( DB_MASTER );
263 $dbw->replace( 'module_deps',
264 array( array( 'md_module', 'md_skin' ) ), array(
265 'md_module' => $this->getName(),
266 'md_skin' => $context->getSkin(),
267 'md_deps' => FormatJson::encode( $this->localFileRefs ),
268 )
269 );
270 }
271 return $styles;
272 }
273
274 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
275 $urls = array();
276 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
277 $urls[$mediaType] = array();
278 foreach ( $list as $file ) {
279 $urls[$mediaType][] = $this->getRemotePath( $file );
280 }
281 }
282 return $urls;
283 }
284
285 /**
286 * Gets list of message keys used by this module.
287 *
288 * @return Array: List of message keys
289 */
290 public function getMessages() {
291 return $this->messages;
292 }
293
294 /**
295 * Gets the name of the group this module should be loaded in.
296 *
297 * @return String: Group name
298 */
299 public function getGroup() {
300 return $this->group;
301 }
302
303 /**
304 * @return string
305 */
306 public function getPosition() {
307 return $this->position;
308 }
309
310 /**
311 * Gets list of names of modules this module depends on.
312 *
313 * @return Array: List of module names
314 */
315 public function getDependencies() {
316 return $this->dependencies;
317 }
318
319 /**
320 * Get the last modified timestamp of this module.
321 *
322 * Last modified timestamps are calculated from the highest last modified
323 * timestamp of this module's constituent files as well as the files it
324 * depends on. This function is context-sensitive, only performing
325 * calculations on files relevant to the given language, skin and debug
326 * mode.
327 *
328 * @param $context ResourceLoaderContext: Context in which to calculate
329 * the modified time
330 * @return Integer: UNIX timestamp
331 * @see ResourceLoaderModule::getFileDependencies
332 */
333 public function getModifiedTime( ResourceLoaderContext $context ) {
334 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
335 return $this->modifiedTime[$context->getHash()];
336 }
337 wfProfileIn( __METHOD__ );
338
339 $files = array();
340
341 // Flatten style files into $files
342 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
343 foreach ( $styles as $styleFiles ) {
344 $files = array_merge( $files, $styleFiles );
345 }
346 $skinFiles = self::tryForKey(
347 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
348 $context->getSkin(),
349 'default'
350 );
351 foreach ( $skinFiles as $styleFiles ) {
352 $files = array_merge( $files, $styleFiles );
353 }
354
355 // Final merge, this should result in a master list of dependent files
356 $files = array_merge(
357 $files,
358 $this->scripts,
359 $context->getDebug() ? $this->debugScripts : array(),
360 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
361 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
362 $this->loaderScripts
363 );
364 $files = array_map( array( $this, 'getLocalPath' ), $files );
365 // File deps need to be treated separately because they're already prefixed
366 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
367
368 // If a module is nothing but a list of dependencies, we need to avoid
369 // giving max() an empty array
370 if ( count( $files ) === 0 ) {
371 wfProfileOut( __METHOD__ );
372 return $this->modifiedTime[$context->getHash()] = 1;
373 }
374
375 wfProfileIn( __METHOD__.'-filemtime' );
376 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
377 wfProfileOut( __METHOD__.'-filemtime' );
378 $this->modifiedTime[$context->getHash()] = max(
379 $filesMtime,
380 $this->getMsgBlobMtime( $context->getLanguage() ) );
381
382 wfProfileOut( __METHOD__ );
383 return $this->modifiedTime[$context->getHash()];
384 }
385
386 /* Protected Methods */
387
388 /**
389 * @param $path string
390 * @return string
391 */
392 protected function getLocalPath( $path ) {
393 return "{$this->localBasePath}/$path";
394 }
395
396 /**
397 * @param $path string
398 * @return string
399 */
400 protected function getRemotePath( $path ) {
401 return "{$this->remoteBasePath}/$path";
402 }
403
404 /**
405 * Collates file paths by option (where provided).
406 *
407 * @param $list Array: List of file paths in any combination of index/path
408 * or path/options pairs
409 * @param $option String: option name
410 * @param $default Mixed: default value if the option isn't set
411 * @return Array: List of file paths, collated by $option
412 */
413 protected static function collateFilePathListByOption( array $list, $option, $default ) {
414 $collatedFiles = array();
415 foreach ( (array) $list as $key => $value ) {
416 if ( is_int( $key ) ) {
417 // File name as the value
418 if ( !isset( $collatedFiles[$default] ) ) {
419 $collatedFiles[$default] = array();
420 }
421 $collatedFiles[$default][] = $value;
422 } elseif ( is_array( $value ) ) {
423 // File name as the key, options array as the value
424 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
425 if ( !isset( $collatedFiles[$optionValue] ) ) {
426 $collatedFiles[$optionValue] = array();
427 }
428 $collatedFiles[$optionValue][] = $key;
429 }
430 }
431 return $collatedFiles;
432 }
433
434 /**
435 * Gets a list of element that match a key, optionally using a fallback key.
436 *
437 * @param $list Array: List of lists to select from
438 * @param $key String: Key to look for in $map
439 * @param $fallback String: Key to look for in $list if $key doesn't exist
440 * @return Array: List of elements from $map which matched $key or $fallback,
441 * or an empty list in case of no match
442 */
443 protected static function tryForKey( array $list, $key, $fallback = null ) {
444 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
445 return $list[$key];
446 } elseif ( is_string( $fallback )
447 && isset( $list[$fallback] )
448 && is_array( $list[$fallback] ) )
449 {
450 return $list[$fallback];
451 }
452 return array();
453 }
454
455 /**
456 * Gets a list of file paths for all scripts in this module, in order of propper execution.
457 *
458 * @param $context ResourceLoaderContext: Context
459 * @return Array: List of file paths
460 */
461 protected function getScriptFiles( ResourceLoaderContext $context ) {
462 $files = array_merge(
463 $this->scripts,
464 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
465 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
466 );
467 if ( $context->getDebug() ) {
468 $files = array_merge( $files, $this->debugScripts );
469 }
470 return $files;
471 }
472
473 /**
474 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
475 *
476 * @param $context ResourceLoaderContext: Context
477 * @return Array: List of file paths
478 */
479 protected function getStyleFiles( ResourceLoaderContext $context ) {
480 return array_merge_recursive(
481 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
482 self::collateFilePathListByOption(
483 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
484 )
485 );
486 }
487
488 /**
489 * Gets the contents of a list of JavaScript files.
490 *
491 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
492 * @return String: Concatenated and remapped JavaScript data from $scripts
493 */
494 protected function readScriptFiles( array $scripts ) {
495 global $wgResourceLoaderValidateStaticJS;
496 if ( empty( $scripts ) ) {
497 return '';
498 }
499 $js = '';
500 foreach ( array_unique( $scripts ) as $fileName ) {
501 $localPath = $this->getLocalPath( $fileName );
502 if ( !file_exists( $localPath ) ) {
503 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
504 }
505 $contents = file_get_contents( $localPath );
506 if ( $wgResourceLoaderValidateStaticJS ) {
507 // Static files don't really need to be checked as often; unlike
508 // on-wiki module they shouldn't change unexpectedly without
509 // admin interference.
510 $contents = $this->validateScriptFile( $fileName, $contents );
511 }
512 $js .= $contents . "\n";
513 }
514 return $js;
515 }
516
517 /**
518 * Gets the contents of a list of CSS files.
519 *
520 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
521 * concetenate
522 *
523 * @param $flip bool
524 *
525 * @return Array: List of concatenated and remapped CSS data from $styles,
526 * keyed by media type
527 */
528 protected function readStyleFiles( array $styles, $flip ) {
529 if ( empty( $styles ) ) {
530 return array();
531 }
532 foreach ( $styles as $media => $files ) {
533 $uniqueFiles = array_unique( $files );
534 $styles[$media] = implode(
535 "\n",
536 array_map(
537 array( $this, 'readStyleFile' ),
538 $uniqueFiles,
539 array_fill( 0, count( $uniqueFiles ), $flip )
540 )
541 );
542 }
543 return $styles;
544 }
545
546 /**
547 * Reads a style file.
548 *
549 * This method can be used as a callback for array_map()
550 *
551 * @param $path String: File path of style file to read
552 * @param $flip bool
553 *
554 * @return String: CSS data in script file
555 * @throws MWException if the file doesn't exist
556 */
557 protected function readStyleFile( $path, $flip ) {
558 $localPath = $this->getLocalPath( $path );
559 if ( !file_exists( $localPath ) ) {
560 throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
561 }
562 $style = file_get_contents( $localPath );
563 if ( $flip ) {
564 $style = CSSJanus::transform( $style, true, false );
565 }
566 $dirname = dirname( $path );
567 if ( $dirname == '.' ) {
568 // If $path doesn't have a directory component, don't prepend a dot
569 $dirname = '';
570 }
571 $dir = $this->getLocalPath( $dirname );
572 $remoteDir = $this->getRemotePath( $dirname );
573 // Get and register local file references
574 $this->localFileRefs = array_merge(
575 $this->localFileRefs,
576 CSSMin::getLocalFileReferences( $style, $dir ) );
577 return CSSMin::remap(
578 $style, $dir, $remoteDir, true
579 );
580 }
581
582 /**
583 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
584 * but returns 1 instead.
585 * @param $filename string File name
586 * @return int UNIX timestamp, or 1 if the file doesn't exist
587 */
588 protected static function safeFilemtime( $filename ) {
589 if ( file_exists( $filename ) ) {
590 return filemtime( $filename );
591 } else {
592 // We only ever map this function on an array if we're gonna call max() after,
593 // so return our standard minimum timestamps here. This is 1, not 0, because
594 // wfTimestamp(0) == NOW
595 return 1;
596 }
597 }
598
599 /**
600 * Get whether CSS for this module should be flipped
601 * @param $context ResourceLoaderContext
602 * @return bool
603 */
604 public function getFlip( $context ) {
605 return $context->getDirection() === 'rtl';
606 }
607 }