Merge "[FileBackend] Added tiny getContainerStoragePath() convenience function."
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * Resource loader module based on local JavaScript/CSS files.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
27 */
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29
30 /* Protected Members */
31
32 /** String: Local base path, see __construct() */
33 protected $localBasePath = '';
34 /** String: Remote base path, see __construct() */
35 protected $remoteBasePath = '';
36 /**
37 * Array: List of paths to JavaScript files to always include
38 * @par Usage:
39 * @code
40 * array( [file-path], [file-path], ... )
41 * @endcode
42 */
43 protected $scripts = array();
44 /**
45 * Array: List of JavaScript files to include when using a specific language
46 * @par Usage:
47 * @code
48 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
49 * @endcode
50 */
51 protected $languageScripts = array();
52 /**
53 * Array: List of JavaScript files to include when using a specific skin
54 * @par Usage:
55 * @code
56 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
57 * @endcode
58 */
59 protected $skinScripts = array();
60 /**
61 * Array: List of paths to JavaScript files to include in debug mode
62 * @par Usage:
63 * @code
64 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
65 * @endcode
66 */
67 protected $debugScripts = array();
68 /**
69 * Array: List of paths to JavaScript files to include in the startup module
70 * @par Usage:
71 * @code
72 * array( [file-path], [file-path], ... )
73 * @endcode
74 */
75 protected $loaderScripts = array();
76 /**
77 * Array: List of paths to CSS files to always include
78 * @par Usage:
79 * @code
80 * array( [file-path], [file-path], ... )
81 * @endcode
82 */
83 protected $styles = array();
84 /**
85 * Array: List of paths to CSS files to include when using specific skins
86 * @par Usage:
87 * @code
88 * array( [file-path], [file-path], ... )
89 * @endcode
90 */
91 protected $skinStyles = array();
92 /**
93 * Array: List of modules this module depends on
94 * @par Usage:
95 * @code
96 * array( [file-path], [file-path], ... )
97 * @endcode
98 */
99 protected $dependencies = array();
100 /**
101 * Array: List of message keys used by this module
102 * @par Usage:
103 * @code
104 * array( [message-key], [message-key], ... )
105 * @endcode
106 */
107 protected $messages = array();
108 /** String: Name of group to load this module in */
109 protected $group;
110 /** String: Position on the page to load this module at */
111 protected $position = 'bottom';
112 /** Boolean: Link to raw files in debug mode */
113 protected $debugRaw = true;
114 /** Boolean: Whether mw.loader.state() call should be omitted */
115 protected $raw = false;
116 /**
117 * Array: Cache for mtime
118 * @par Usage:
119 * @code
120 * array( [hash] => [mtime], [hash] => [mtime], ... )
121 * @endcode
122 */
123 protected $modifiedTime = array();
124 /**
125 * Array: Place where readStyleFile() tracks file dependencies
126 * @par Usage:
127 * @code
128 * array( [file-path], [file-path], ... )
129 * @endcode
130 */
131 protected $localFileRefs = array();
132
133 /* Methods */
134
135 /**
136 * Constructs a new module from an options array.
137 *
138 * @param $options Array: List of options; if not given or empty, an empty module will be
139 * constructed
140 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
141 * to $IP
142 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
143 * to $wgScriptPath
144 *
145 * Below is a description for the $options array:
146 * @throws MWException
147 * @par Construction options:
148 * @code
149 * array(
150 * // Base path to prepend to all local paths in $options. Defaults to $IP
151 * 'localBasePath' => [base path],
152 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
153 * 'remoteBasePath' => [base path],
154 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
155 * 'remoteExtPath' => [base path],
156 * // Scripts to always include
157 * 'scripts' => [file path string or array of file path strings],
158 * // Scripts to include in specific language contexts
159 * 'languageScripts' => array(
160 * [language code] => [file path string or array of file path strings],
161 * ),
162 * // Scripts to include in specific skin contexts
163 * 'skinScripts' => array(
164 * [skin name] => [file path string or array of file path strings],
165 * ),
166 * // Scripts to include in debug contexts
167 * 'debugScripts' => [file path string or array of file path strings],
168 * // Scripts to include in the startup module
169 * 'loaderScripts' => [file path string or array of file path strings],
170 * // Modules which must be loaded before this module
171 * 'dependencies' => [modile name string or array of module name strings],
172 * // Styles to always load
173 * 'styles' => [file path string or array of file path strings],
174 * // Styles to include in specific skin contexts
175 * 'skinStyles' => array(
176 * [skin name] => [file path string or array of file path strings],
177 * ),
178 * // Messages to always load
179 * 'messages' => [array of message key strings],
180 * // Group which this module should be loaded together with
181 * 'group' => [group name string],
182 * // Position on the page to load this module at
183 * 'position' => ['bottom' (default) or 'top']
184 * )
185 * @endcode
186 */
187 public function __construct( $options = array(), $localBasePath = null,
188 $remoteBasePath = null )
189 {
190 global $IP, $wgScriptPath, $wgResourceBasePath;
191 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
192 if ( $remoteBasePath !== null ) {
193 $this->remoteBasePath = $remoteBasePath;
194 } else {
195 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
196 }
197
198 if ( isset( $options['remoteExtPath'] ) ) {
199 global $wgExtensionAssetsPath;
200 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
201 }
202
203 foreach ( $options as $member => $option ) {
204 switch ( $member ) {
205 // Lists of file paths
206 case 'scripts':
207 case 'debugScripts':
208 case 'loaderScripts':
209 case 'styles':
210 $this->{$member} = (array) $option;
211 break;
212 // Collated lists of file paths
213 case 'languageScripts':
214 case 'skinScripts':
215 case 'skinStyles':
216 if ( !is_array( $option ) ) {
217 throw new MWException(
218 "Invalid collated file path list error. " .
219 "'$option' given, array expected."
220 );
221 }
222 foreach ( $option as $key => $value ) {
223 if ( !is_string( $key ) ) {
224 throw new MWException(
225 "Invalid collated file path list key error. " .
226 "'$key' given, string expected."
227 );
228 }
229 $this->{$member}[$key] = (array) $value;
230 }
231 break;
232 // Lists of strings
233 case 'dependencies':
234 case 'messages':
235 $this->{$member} = (array) $option;
236 break;
237 // Single strings
238 case 'group':
239 case 'position':
240 case 'localBasePath':
241 case 'remoteBasePath':
242 $this->{$member} = (string) $option;
243 break;
244 // Single booleans
245 case 'debugRaw':
246 case 'raw':
247 $this->{$member} = (bool) $option;
248 break;
249 }
250 }
251 // Make sure the remote base path is a complete valid URL,
252 // but possibly protocol-relative to avoid cache pollution
253 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
254 }
255
256 /**
257 * Gets all scripts for a given context concatenated together.
258 *
259 * @param $context ResourceLoaderContext: Context in which to generate script
260 * @return String: JavaScript code for $context
261 */
262 public function getScript( ResourceLoaderContext $context ) {
263 $files = $this->getScriptFiles( $context );
264 return $this->readScriptFiles( $files );
265 }
266
267 /**
268 * @param $context ResourceLoaderContext
269 * @return array
270 */
271 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
272 $urls = array();
273 foreach ( $this->getScriptFiles( $context ) as $file ) {
274 $urls[] = $this->getRemotePath( $file );
275 }
276 return $urls;
277 }
278
279 /**
280 * @return bool
281 */
282 public function supportsURLLoading() {
283 return $this->debugRaw;
284 }
285
286 /**
287 * Gets loader script.
288 *
289 * @return String: JavaScript code to be added to startup module
290 */
291 public function getLoaderScript() {
292 if ( count( $this->loaderScripts ) == 0 ) {
293 return false;
294 }
295 return $this->readScriptFiles( $this->loaderScripts );
296 }
297
298 /**
299 * Gets all styles for a given context concatenated together.
300 *
301 * @param $context ResourceLoaderContext: Context in which to generate styles
302 * @return String: CSS code for $context
303 */
304 public function getStyles( ResourceLoaderContext $context ) {
305 $styles = $this->readStyleFiles(
306 $this->getStyleFiles( $context ),
307 $this->getFlip( $context )
308 );
309 // Collect referenced files
310 $this->localFileRefs = array_unique( $this->localFileRefs );
311 // If the list has been modified since last time we cached it, update the cache
312 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) && !wfReadOnly() ) {
313 $dbw = wfGetDB( DB_MASTER );
314 $dbw->replace( 'module_deps',
315 array( array( 'md_module', 'md_skin' ) ), array(
316 'md_module' => $this->getName(),
317 'md_skin' => $context->getSkin(),
318 'md_deps' => FormatJson::encode( $this->localFileRefs ),
319 )
320 );
321 }
322 return $styles;
323 }
324
325 /**
326 * @param $context ResourceLoaderContext
327 * @return array
328 */
329 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
330 $urls = array();
331 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
332 $urls[$mediaType] = array();
333 foreach ( $list as $file ) {
334 $urls[$mediaType][] = $this->getRemotePath( $file );
335 }
336 }
337 return $urls;
338 }
339
340 /**
341 * Gets list of message keys used by this module.
342 *
343 * @return Array: List of message keys
344 */
345 public function getMessages() {
346 return $this->messages;
347 }
348
349 /**
350 * Gets the name of the group this module should be loaded in.
351 *
352 * @return String: Group name
353 */
354 public function getGroup() {
355 return $this->group;
356 }
357
358 /**
359 * @return string
360 */
361 public function getPosition() {
362 return $this->position;
363 }
364
365 /**
366 * Gets list of names of modules this module depends on.
367 *
368 * @return Array: List of module names
369 */
370 public function getDependencies() {
371 return $this->dependencies;
372 }
373
374 /**
375 * @return bool
376 */
377 public function isRaw() {
378 return $this->raw;
379 }
380
381 /**
382 * Get the last modified timestamp of this module.
383 *
384 * Last modified timestamps are calculated from the highest last modified
385 * timestamp of this module's constituent files as well as the files it
386 * depends on. This function is context-sensitive, only performing
387 * calculations on files relevant to the given language, skin and debug
388 * mode.
389 *
390 * @param $context ResourceLoaderContext: Context in which to calculate
391 * the modified time
392 * @return Integer: UNIX timestamp
393 * @see ResourceLoaderModule::getFileDependencies
394 */
395 public function getModifiedTime( ResourceLoaderContext $context ) {
396 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
397 return $this->modifiedTime[$context->getHash()];
398 }
399 wfProfileIn( __METHOD__ );
400
401 $files = array();
402
403 // Flatten style files into $files
404 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
405 foreach ( $styles as $styleFiles ) {
406 $files = array_merge( $files, $styleFiles );
407 }
408 $skinFiles = self::tryForKey(
409 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
410 $context->getSkin(),
411 'default'
412 );
413 foreach ( $skinFiles as $styleFiles ) {
414 $files = array_merge( $files, $styleFiles );
415 }
416
417 // Final merge, this should result in a master list of dependent files
418 $files = array_merge(
419 $files,
420 $this->scripts,
421 $context->getDebug() ? $this->debugScripts : array(),
422 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
423 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
424 $this->loaderScripts
425 );
426 $files = array_map( array( $this, 'getLocalPath' ), $files );
427 // File deps need to be treated separately because they're already prefixed
428 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
429
430 // If a module is nothing but a list of dependencies, we need to avoid
431 // giving max() an empty array
432 if ( count( $files ) === 0 ) {
433 wfProfileOut( __METHOD__ );
434 return $this->modifiedTime[$context->getHash()] = 1;
435 }
436
437 wfProfileIn( __METHOD__.'-filemtime' );
438 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
439 wfProfileOut( __METHOD__.'-filemtime' );
440 $this->modifiedTime[$context->getHash()] = max(
441 $filesMtime,
442 $this->getMsgBlobMtime( $context->getLanguage() ) );
443
444 wfProfileOut( __METHOD__ );
445 return $this->modifiedTime[$context->getHash()];
446 }
447
448 /* Protected Methods */
449
450 /**
451 * @param $path string
452 * @return string
453 */
454 protected function getLocalPath( $path ) {
455 return "{$this->localBasePath}/$path";
456 }
457
458 /**
459 * @param $path string
460 * @return string
461 */
462 protected function getRemotePath( $path ) {
463 return "{$this->remoteBasePath}/$path";
464 }
465
466 /**
467 * Collates file paths by option (where provided).
468 *
469 * @param $list Array: List of file paths in any combination of index/path
470 * or path/options pairs
471 * @param $option String: option name
472 * @param $default Mixed: default value if the option isn't set
473 * @return Array: List of file paths, collated by $option
474 */
475 protected static function collateFilePathListByOption( array $list, $option, $default ) {
476 $collatedFiles = array();
477 foreach ( (array) $list as $key => $value ) {
478 if ( is_int( $key ) ) {
479 // File name as the value
480 if ( !isset( $collatedFiles[$default] ) ) {
481 $collatedFiles[$default] = array();
482 }
483 $collatedFiles[$default][] = $value;
484 } elseif ( is_array( $value ) ) {
485 // File name as the key, options array as the value
486 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
487 if ( !isset( $collatedFiles[$optionValue] ) ) {
488 $collatedFiles[$optionValue] = array();
489 }
490 $collatedFiles[$optionValue][] = $key;
491 }
492 }
493 return $collatedFiles;
494 }
495
496 /**
497 * Gets a list of element that match a key, optionally using a fallback key.
498 *
499 * @param $list Array: List of lists to select from
500 * @param $key String: Key to look for in $map
501 * @param $fallback String: Key to look for in $list if $key doesn't exist
502 * @return Array: List of elements from $map which matched $key or $fallback,
503 * or an empty list in case of no match
504 */
505 protected static function tryForKey( array $list, $key, $fallback = null ) {
506 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
507 return $list[$key];
508 } elseif ( is_string( $fallback )
509 && isset( $list[$fallback] )
510 && is_array( $list[$fallback] ) )
511 {
512 return $list[$fallback];
513 }
514 return array();
515 }
516
517 /**
518 * Gets a list of file paths for all scripts in this module, in order of propper execution.
519 *
520 * @param $context ResourceLoaderContext: Context
521 * @return Array: List of file paths
522 */
523 protected function getScriptFiles( ResourceLoaderContext $context ) {
524 $files = array_merge(
525 $this->scripts,
526 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
527 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
528 );
529 if ( $context->getDebug() ) {
530 $files = array_merge( $files, $this->debugScripts );
531 }
532 return $files;
533 }
534
535 /**
536 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
537 *
538 * @param $context ResourceLoaderContext: Context
539 * @return Array: List of file paths
540 */
541 protected function getStyleFiles( ResourceLoaderContext $context ) {
542 return array_merge_recursive(
543 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
544 self::collateFilePathListByOption(
545 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
546 )
547 );
548 }
549
550 /**
551 * Gets the contents of a list of JavaScript files.
552 *
553 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
554 * @throws MWException
555 * @return String: Concatenated and remapped JavaScript data from $scripts
556 */
557 protected function readScriptFiles( array $scripts ) {
558 global $wgResourceLoaderValidateStaticJS;
559 if ( empty( $scripts ) ) {
560 return '';
561 }
562 $js = '';
563 foreach ( array_unique( $scripts ) as $fileName ) {
564 $localPath = $this->getLocalPath( $fileName );
565 if ( !file_exists( $localPath ) ) {
566 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
567 }
568 $contents = file_get_contents( $localPath );
569 if ( $wgResourceLoaderValidateStaticJS ) {
570 // Static files don't really need to be checked as often; unlike
571 // on-wiki module they shouldn't change unexpectedly without
572 // admin interference.
573 $contents = $this->validateScriptFile( $fileName, $contents );
574 }
575 $js .= $contents . "\n";
576 }
577 return $js;
578 }
579
580 /**
581 * Gets the contents of a list of CSS files.
582 *
583 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
584 * concetenate
585 *
586 * @param $flip bool
587 *
588 * @return Array: List of concatenated and remapped CSS data from $styles,
589 * keyed by media type
590 */
591 protected function readStyleFiles( array $styles, $flip ) {
592 if ( empty( $styles ) ) {
593 return array();
594 }
595 foreach ( $styles as $media => $files ) {
596 $uniqueFiles = array_unique( $files );
597 $styles[$media] = implode(
598 "\n",
599 array_map(
600 array( $this, 'readStyleFile' ),
601 $uniqueFiles,
602 array_fill( 0, count( $uniqueFiles ), $flip )
603 )
604 );
605 }
606 return $styles;
607 }
608
609 /**
610 * Reads a style file.
611 *
612 * This method can be used as a callback for array_map()
613 *
614 * @param $path String: File path of style file to read
615 * @param $flip bool
616 *
617 * @return String: CSS data in script file
618 * @throws MWException if the file doesn't exist
619 */
620 protected function readStyleFile( $path, $flip ) {
621 $localPath = $this->getLocalPath( $path );
622 if ( !file_exists( $localPath ) ) {
623 $msg = __METHOD__.": style file not found: \"$localPath\"";
624 wfDebugLog( 'resourceloader', $msg );
625 throw new MWException( $msg );
626 }
627 $style = file_get_contents( $localPath );
628 if ( $flip ) {
629 $style = CSSJanus::transform( $style, true, false );
630 }
631 $dirname = dirname( $path );
632 if ( $dirname == '.' ) {
633 // If $path doesn't have a directory component, don't prepend a dot
634 $dirname = '';
635 }
636 $dir = $this->getLocalPath( $dirname );
637 $remoteDir = $this->getRemotePath( $dirname );
638 // Get and register local file references
639 $this->localFileRefs = array_merge(
640 $this->localFileRefs,
641 CSSMin::getLocalFileReferences( $style, $dir )
642 );
643 return CSSMin::remap(
644 $style, $dir, $remoteDir, true
645 );
646 }
647
648 /**
649 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
650 * but returns 1 instead.
651 * @param $filename string File name
652 * @return int UNIX timestamp, or 1 if the file doesn't exist
653 */
654 protected static function safeFilemtime( $filename ) {
655 if ( file_exists( $filename ) ) {
656 return filemtime( $filename );
657 } else {
658 // We only ever map this function on an array if we're gonna call max() after,
659 // so return our standard minimum timestamps here. This is 1, not 0, because
660 // wfTimestamp(0) == NOW
661 return 1;
662 }
663 }
664
665 /**
666 * Get whether CSS for this module should be flipped
667 * @param $context ResourceLoaderContext
668 * @return bool
669 */
670 public function getFlip( $context ) {
671 return $context->getDirection() === 'rtl';
672 }
673 }