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