Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * ResourceLoader 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 /** @var string Local base path, see __construct() */
31 protected $localBasePath = '';
32
33 /** @var string Remote base path, see __construct() */
34 protected $remoteBasePath = '';
35
36 /** @var array Saves a list of the templates named by the modules. */
37 protected $templates = [];
38
39 /**
40 * @var array List of paths to JavaScript files to always include
41 * @par Usage:
42 * @code
43 * [ [file-path], [file-path], ... ]
44 * @endcode
45 */
46 protected $scripts = [];
47
48 /**
49 * @var array List of JavaScript files to include when using a specific language
50 * @par Usage:
51 * @code
52 * [ [language-code] => [ [file-path], [file-path], ... ], ... ]
53 * @endcode
54 */
55 protected $languageScripts = [];
56
57 /**
58 * @var array List of JavaScript files to include when using a specific skin
59 * @par Usage:
60 * @code
61 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
62 * @endcode
63 */
64 protected $skinScripts = [];
65
66 /**
67 * @var array List of paths to JavaScript files to include in debug mode
68 * @par Usage:
69 * @code
70 * [ [skin-name] => [ [file-path], [file-path], ... ], ... ]
71 * @endcode
72 */
73 protected $debugScripts = [];
74
75 /**
76 * @var array List of paths to CSS files to always include
77 * @par Usage:
78 * @code
79 * [ [file-path], [file-path], ... ]
80 * @endcode
81 */
82 protected $styles = [];
83
84 /**
85 * @var array List of paths to CSS files to include when using specific skins
86 * @par Usage:
87 * @code
88 * [ [file-path], [file-path], ... ]
89 * @endcode
90 */
91 protected $skinStyles = [];
92
93 /**
94 * @var array List of modules this module depends on
95 * @par Usage:
96 * @code
97 * [ [file-path], [file-path], ... ]
98 * @endcode
99 */
100 protected $dependencies = [];
101
102 /**
103 * @var string File name containing the body of the skip function
104 */
105 protected $skipFunction = null;
106
107 /**
108 * @var array List of message keys used by this module
109 * @par Usage:
110 * @code
111 * [ [message-key], [message-key], ... ]
112 * @endcode
113 */
114 protected $messages = [];
115
116 /** @var string Name of group to load this module in */
117 protected $group;
118
119 /** @var bool Link to raw files in debug mode */
120 protected $debugRaw = true;
121
122 /** @var bool Whether mw.loader.state() call should be omitted */
123 protected $raw = false;
124
125 protected $targets = [ 'desktop' ];
126
127 /** @var bool Whether CSSJanus flipping should be skipped for this module */
128 protected $noflip = false;
129
130 /**
131 * @var bool Whether getStyleURLsForDebug should return raw file paths,
132 * or return load.php urls
133 */
134 protected $hasGeneratedStyles = false;
135
136 /**
137 * @var array Place where readStyleFile() tracks file dependencies
138 * @par Usage:
139 * @code
140 * [ [file-path], [file-path], ... ]
141 * @endcode
142 */
143 protected $localFileRefs = [];
144
145 /**
146 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
147 * Used in tests to detect missing dependencies.
148 */
149 protected $missingLocalFileRefs = [];
150
151 /**
152 * Constructs a new module from an options array.
153 *
154 * @param array $options List of options; if not given or empty, an empty module will be
155 * constructed
156 * @param string|null $localBasePath Base path to prepend to all local paths in $options.
157 * Defaults to $IP
158 * @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
159 * Defaults to $wgResourceBasePath
160 *
161 * Below is a description for the $options array:
162 * @throws InvalidArgumentException
163 * @par Construction options:
164 * @code
165 * [
166 * // Base path to prepend to all local paths in $options. Defaults to $IP
167 * 'localBasePath' => [base path],
168 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
169 * 'remoteBasePath' => [base path],
170 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
171 * 'remoteExtPath' => [base path],
172 * // Equivalent of remoteBasePath, but relative to $wgStylePath
173 * 'remoteSkinPath' => [base path],
174 * // Scripts to always include
175 * 'scripts' => [file path string or array of file path strings],
176 * // Scripts to include in specific language contexts
177 * 'languageScripts' => [
178 * [language code] => [file path string or array of file path strings],
179 * ],
180 * // Scripts to include in specific skin contexts
181 * 'skinScripts' => [
182 * [skin name] => [file path string or array of file path strings],
183 * ],
184 * // Scripts to include in debug contexts
185 * 'debugScripts' => [file path string or array of file path strings],
186 * // Modules which must be loaded before this module
187 * 'dependencies' => [module name string or array of module name strings],
188 * 'templates' => [
189 * [template alias with file.ext] => [file path to a template file],
190 * ],
191 * // Styles to always load
192 * 'styles' => [file path string or array of file path strings],
193 * // Styles to include in specific skin contexts
194 * 'skinStyles' => [
195 * [skin name] => [file path string or array of file path strings],
196 * ],
197 * // Messages to always load
198 * 'messages' => [array of message key strings],
199 * // Group which this module should be loaded together with
200 * 'group' => [group name string],
201 * // Function that, if it returns true, makes the loader skip this module.
202 * // The file must contain valid JavaScript for execution in a private function.
203 * // The file must not contain the "function () {" and "}" wrapper though.
204 * 'skipFunction' => [file path]
205 * ]
206 * @endcode
207 */
208 public function __construct(
209 $options = [],
210 $localBasePath = null,
211 $remoteBasePath = null
212 ) {
213 // Flag to decide whether to automagically add the mediawiki.template module
214 $hasTemplates = false;
215 // localBasePath and remoteBasePath both have unbelievably long fallback chains
216 // and need to be handled separately.
217 list( $this->localBasePath, $this->remoteBasePath ) =
218 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
219
220 // Extract, validate and normalise remaining options
221 foreach ( $options as $member => $option ) {
222 switch ( $member ) {
223 // Lists of file paths
224 case 'scripts':
225 case 'debugScripts':
226 case 'styles':
227 $this->{$member} = (array)$option;
228 break;
229 case 'templates':
230 $hasTemplates = true;
231 $this->{$member} = (array)$option;
232 break;
233 // Collated lists of file paths
234 case 'languageScripts':
235 case 'skinScripts':
236 case 'skinStyles':
237 if ( !is_array( $option ) ) {
238 throw new InvalidArgumentException(
239 "Invalid collated file path list error. " .
240 "'$option' given, array expected."
241 );
242 }
243 foreach ( $option as $key => $value ) {
244 if ( !is_string( $key ) ) {
245 throw new InvalidArgumentException(
246 "Invalid collated file path list key error. " .
247 "'$key' given, string expected."
248 );
249 }
250 $this->{$member}[$key] = (array)$value;
251 }
252 break;
253 case 'deprecated':
254 $this->deprecated = $option;
255 break;
256 // Lists of strings
257 case 'dependencies':
258 case 'messages':
259 case 'targets':
260 // Normalise
261 $option = array_values( array_unique( (array)$option ) );
262 sort( $option );
263
264 $this->{$member} = $option;
265 break;
266 // Single strings
267 case 'group':
268 case 'skipFunction':
269 $this->{$member} = (string)$option;
270 break;
271 // Single booleans
272 case 'debugRaw':
273 case 'raw':
274 case 'noflip':
275 $this->{$member} = (bool)$option;
276 break;
277 }
278 }
279 if ( $hasTemplates ) {
280 $this->dependencies[] = 'mediawiki.template';
281 // Ensure relevant template compiler module gets loaded
282 foreach ( $this->templates as $alias => $templatePath ) {
283 if ( is_int( $alias ) ) {
284 $alias = $templatePath;
285 }
286 $suffix = explode( '.', $alias );
287 $suffix = end( $suffix );
288 $compilerModule = 'mediawiki.template.' . $suffix;
289 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
290 $this->dependencies[] = $compilerModule;
291 }
292 }
293 }
294 }
295
296 /**
297 * Extract a pair of local and remote base paths from module definition information.
298 * Implementation note: the amount of global state used in this function is staggering.
299 *
300 * @param array $options Module definition
301 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
302 * to $IP
303 * @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
304 * to $wgResourceBasePath
305 * @return array Array( localBasePath, remoteBasePath )
306 */
307 public static function extractBasePaths(
308 $options = [],
309 $localBasePath = null,
310 $remoteBasePath = null
311 ) {
312 global $IP, $wgResourceBasePath;
313
314 // The different ways these checks are done, and their ordering, look very silly,
315 // but were preserved for backwards-compatibility just in case. Tread lightly.
316
317 if ( $localBasePath === null ) {
318 $localBasePath = $IP;
319 }
320 if ( $remoteBasePath === null ) {
321 $remoteBasePath = $wgResourceBasePath;
322 }
323
324 if ( isset( $options['remoteExtPath'] ) ) {
325 global $wgExtensionAssetsPath;
326 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
327 }
328
329 if ( isset( $options['remoteSkinPath'] ) ) {
330 global $wgStylePath;
331 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
332 }
333
334 if ( array_key_exists( 'localBasePath', $options ) ) {
335 $localBasePath = (string)$options['localBasePath'];
336 }
337
338 if ( array_key_exists( 'remoteBasePath', $options ) ) {
339 $remoteBasePath = (string)$options['remoteBasePath'];
340 }
341
342 return [ $localBasePath, $remoteBasePath ];
343 }
344
345 /**
346 * Gets all scripts for a given context concatenated together.
347 *
348 * @param ResourceLoaderContext $context Context in which to generate script
349 * @return string JavaScript code for $context
350 */
351 public function getScript( ResourceLoaderContext $context ) {
352 $files = $this->getScriptFiles( $context );
353 return $this->getDeprecationInformation() . $this->readScriptFiles( $files );
354 }
355
356 /**
357 * @param ResourceLoaderContext $context
358 * @return array
359 */
360 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
361 $urls = [];
362 foreach ( $this->getScriptFiles( $context ) as $file ) {
363 $urls[] = OutputPage::transformResourcePath(
364 $this->getConfig(),
365 $this->getRemotePath( $file )
366 );
367 }
368 return $urls;
369 }
370
371 /**
372 * @return bool
373 */
374 public function supportsURLLoading() {
375 return $this->debugRaw;
376 }
377
378 /**
379 * Get all styles for a given context.
380 *
381 * @param ResourceLoaderContext $context
382 * @return array CSS code for $context as an associative array mapping media type to CSS text.
383 */
384 public function getStyles( ResourceLoaderContext $context ) {
385 $styles = $this->readStyleFiles(
386 $this->getStyleFiles( $context ),
387 $this->getFlip( $context ),
388 $context
389 );
390 // Collect referenced files
391 $this->saveFileDependencies( $context, $this->localFileRefs );
392
393 return $styles;
394 }
395
396 /**
397 * @param ResourceLoaderContext $context
398 * @return array
399 */
400 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
401 if ( $this->hasGeneratedStyles ) {
402 // Do the default behaviour of returning a url back to load.php
403 // but with only=styles.
404 return parent::getStyleURLsForDebug( $context );
405 }
406 // Our module consists entirely of real css files,
407 // in debug mode we can load those directly.
408 $urls = [];
409 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
410 $urls[$mediaType] = [];
411 foreach ( $list as $file ) {
412 $urls[$mediaType][] = OutputPage::transformResourcePath(
413 $this->getConfig(),
414 $this->getRemotePath( $file )
415 );
416 }
417 }
418 return $urls;
419 }
420
421 /**
422 * Gets list of message keys used by this module.
423 *
424 * @return array List of message keys
425 */
426 public function getMessages() {
427 return $this->messages;
428 }
429
430 /**
431 * Gets the name of the group this module should be loaded in.
432 *
433 * @return string Group name
434 */
435 public function getGroup() {
436 return $this->group;
437 }
438
439 /**
440 * Gets list of names of modules this module depends on.
441 * @param ResourceLoaderContext|null $context
442 * @return array List of module names
443 */
444 public function getDependencies( ResourceLoaderContext $context = null ) {
445 return $this->dependencies;
446 }
447
448 /**
449 * Get the skip function.
450 * @return null|string
451 * @throws MWException
452 */
453 public function getSkipFunction() {
454 if ( !$this->skipFunction ) {
455 return null;
456 }
457
458 $localPath = $this->getLocalPath( $this->skipFunction );
459 if ( !file_exists( $localPath ) ) {
460 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
461 }
462 $contents = $this->stripBom( file_get_contents( $localPath ) );
463 return $contents;
464 }
465
466 /**
467 * @return bool
468 */
469 public function isRaw() {
470 return $this->raw;
471 }
472
473 /**
474 * Disable module content versioning.
475 *
476 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
477 * involved with building the full module content inside a startup request.
478 *
479 * @return bool
480 */
481 public function enableModuleContentVersion() {
482 return false;
483 }
484
485 /**
486 * Helper method for getDefinitionSummary.
487 *
488 * @see ResourceLoaderModule::getFileDependencies
489 * @param ResourceLoaderContext $context
490 * @return array
491 */
492 private function getFileHashes( ResourceLoaderContext $context ) {
493 $files = [];
494
495 // Flatten style files into $files
496 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
497 foreach ( $styles as $styleFiles ) {
498 $files = array_merge( $files, $styleFiles );
499 }
500
501 $skinFiles = self::collateFilePathListByOption(
502 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
503 'media',
504 'all'
505 );
506 foreach ( $skinFiles as $styleFiles ) {
507 $files = array_merge( $files, $styleFiles );
508 }
509
510 // Final merge, this should result in a master list of dependent files
511 $files = array_merge(
512 $files,
513 $this->scripts,
514 $this->templates,
515 $context->getDebug() ? $this->debugScripts : [],
516 $this->getLanguageScripts( $context->getLanguage() ),
517 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
518 );
519 if ( $this->skipFunction ) {
520 $files[] = $this->skipFunction;
521 }
522 $files = array_map( [ $this, 'getLocalPath' ], $files );
523 // File deps need to be treated separately because they're already prefixed
524 $files = array_merge( $files, $this->getFileDependencies( $context ) );
525 // Filter out any duplicates from getFileDependencies() and others.
526 // Most commonly introduced by compileLessFile(), which always includes the
527 // entry point Less file we already know about.
528 $files = array_values( array_unique( $files ) );
529
530 // Don't include keys or file paths here, only the hashes. Including that would needlessly
531 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
532 // Any significant ordering is already detected by the definition summary.
533 return array_map( [ __CLASS__, 'safeFileHash' ], $files );
534 }
535
536 /**
537 * Get the definition summary for this module.
538 *
539 * @param ResourceLoaderContext $context
540 * @return array
541 */
542 public function getDefinitionSummary( ResourceLoaderContext $context ) {
543 $summary = parent::getDefinitionSummary( $context );
544
545 $options = [];
546 foreach ( [
547 // The following properties are omitted because they don't affect the module reponse:
548 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
549 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
550 // - remoteBasePath (Per T104950)
551 // - dependencies (provided via startup module)
552 // - targets
553 // - group (provided via startup module)
554 'scripts',
555 'debugScripts',
556 'styles',
557 'languageScripts',
558 'skinScripts',
559 'skinStyles',
560 'messages',
561 'templates',
562 'skipFunction',
563 'debugRaw',
564 'raw',
565 ] as $member ) {
566 $options[$member] = $this->{$member};
567 };
568
569 $summary[] = [
570 'options' => $options,
571 'fileHashes' => $this->getFileHashes( $context ),
572 'messageBlob' => $this->getMessageBlob( $context ),
573 ];
574
575 $lessVars = $this->getLessVars( $context );
576 if ( $lessVars ) {
577 $summary[] = [ 'lessVars' => $lessVars ];
578 }
579
580 return $summary;
581 }
582
583 /**
584 * @param string|ResourceLoaderFilePath $path
585 * @return string
586 */
587 protected function getLocalPath( $path ) {
588 if ( $path instanceof ResourceLoaderFilePath ) {
589 return $path->getLocalPath();
590 }
591
592 return "{$this->localBasePath}/$path";
593 }
594
595 /**
596 * @param string|ResourceLoaderFilePath $path
597 * @return string
598 */
599 protected function getRemotePath( $path ) {
600 if ( $path instanceof ResourceLoaderFilePath ) {
601 return $path->getRemotePath();
602 }
603
604 return "{$this->remoteBasePath}/$path";
605 }
606
607 /**
608 * Infer the stylesheet language from a stylesheet file path.
609 *
610 * @since 1.22
611 * @param string $path
612 * @return string The stylesheet language name
613 */
614 public function getStyleSheetLang( $path ) {
615 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
616 }
617
618 /**
619 * Collates file paths by option (where provided).
620 *
621 * @param array $list List of file paths in any combination of index/path
622 * or path/options pairs
623 * @param string $option Option name
624 * @param mixed $default Default value if the option isn't set
625 * @return array List of file paths, collated by $option
626 */
627 protected static function collateFilePathListByOption( array $list, $option, $default ) {
628 $collatedFiles = [];
629 foreach ( (array)$list as $key => $value ) {
630 if ( is_int( $key ) ) {
631 // File name as the value
632 if ( !isset( $collatedFiles[$default] ) ) {
633 $collatedFiles[$default] = [];
634 }
635 $collatedFiles[$default][] = $value;
636 } elseif ( is_array( $value ) ) {
637 // File name as the key, options array as the value
638 $optionValue = $value[$option] ?? $default;
639 if ( !isset( $collatedFiles[$optionValue] ) ) {
640 $collatedFiles[$optionValue] = [];
641 }
642 $collatedFiles[$optionValue][] = $key;
643 }
644 }
645 return $collatedFiles;
646 }
647
648 /**
649 * Get a list of element that match a key, optionally using a fallback key.
650 *
651 * @param array $list List of lists to select from
652 * @param string $key Key to look for in $map
653 * @param string|null $fallback Key to look for in $list if $key doesn't exist
654 * @return array List of elements from $map which matched $key or $fallback,
655 * or an empty list in case of no match
656 */
657 protected static function tryForKey( array $list, $key, $fallback = null ) {
658 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
659 return $list[$key];
660 } elseif ( is_string( $fallback )
661 && isset( $list[$fallback] )
662 && is_array( $list[$fallback] )
663 ) {
664 return $list[$fallback];
665 }
666 return [];
667 }
668
669 /**
670 * Get a list of script file paths for this module, in order of proper execution.
671 *
672 * @param ResourceLoaderContext $context
673 * @return array List of file paths
674 */
675 private function getScriptFiles( ResourceLoaderContext $context ) {
676 $files = array_merge(
677 $this->scripts,
678 $this->getLanguageScripts( $context->getLanguage() ),
679 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
680 );
681 if ( $context->getDebug() ) {
682 $files = array_merge( $files, $this->debugScripts );
683 }
684
685 return array_unique( $files, SORT_REGULAR );
686 }
687
688 /**
689 * Get the set of language scripts for the given language,
690 * possibly using a fallback language.
691 *
692 * @param string $lang
693 * @return array
694 */
695 private function getLanguageScripts( $lang ) {
696 $scripts = self::tryForKey( $this->languageScripts, $lang );
697 if ( $scripts ) {
698 return $scripts;
699 }
700 $fallbacks = Language::getFallbacksFor( $lang );
701 foreach ( $fallbacks as $lang ) {
702 $scripts = self::tryForKey( $this->languageScripts, $lang );
703 if ( $scripts ) {
704 return $scripts;
705 }
706 }
707
708 return [];
709 }
710
711 /**
712 * Get a list of file paths for all styles in this module, in order of proper inclusion.
713 *
714 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
715 *
716 * @private
717 * @param ResourceLoaderContext $context
718 * @return array List of file paths
719 */
720 public function getStyleFiles( ResourceLoaderContext $context ) {
721 return array_merge_recursive(
722 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
723 self::collateFilePathListByOption(
724 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
725 'media',
726 'all'
727 )
728 );
729 }
730
731 /**
732 * Gets a list of file paths for all skin styles in the module used by
733 * the skin.
734 *
735 * @param string $skinName The name of the skin
736 * @return array A list of file paths collated by media type
737 */
738 protected function getSkinStyleFiles( $skinName ) {
739 return self::collateFilePathListByOption(
740 self::tryForKey( $this->skinStyles, $skinName ),
741 'media',
742 'all'
743 );
744 }
745
746 /**
747 * Gets a list of file paths for all skin style files in the module,
748 * for all available skins.
749 *
750 * @return array A list of file paths collated by media type
751 */
752 protected function getAllSkinStyleFiles() {
753 $styleFiles = [];
754 $internalSkinNames = array_keys( Skin::getSkinNames() );
755 $internalSkinNames[] = 'default';
756
757 foreach ( $internalSkinNames as $internalSkinName ) {
758 $styleFiles = array_merge_recursive(
759 $styleFiles,
760 $this->getSkinStyleFiles( $internalSkinName )
761 );
762 }
763
764 return $styleFiles;
765 }
766
767 /**
768 * Returns all style files and all skin style files used by this module.
769 *
770 * @return array
771 */
772 public function getAllStyleFiles() {
773 $collatedStyleFiles = array_merge_recursive(
774 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
775 $this->getAllSkinStyleFiles()
776 );
777
778 $result = [];
779
780 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
781 foreach ( $styleFiles as $styleFile ) {
782 $result[] = $this->getLocalPath( $styleFile );
783 }
784 }
785
786 return $result;
787 }
788
789 /**
790 * Get the contents of a list of JavaScript files. Helper for getScript().
791 *
792 * @param array $scripts List of file paths to scripts to read, remap and concetenate
793 * @return string Concatenated and remapped JavaScript data from $scripts
794 * @throws MWException
795 */
796 private function readScriptFiles( array $scripts ) {
797 if ( empty( $scripts ) ) {
798 return '';
799 }
800 $js = '';
801 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
802 $localPath = $this->getLocalPath( $fileName );
803 if ( !file_exists( $localPath ) ) {
804 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
805 }
806 $contents = $this->stripBom( file_get_contents( $localPath ) );
807 $js .= $contents . "\n";
808 }
809 return $js;
810 }
811
812 /**
813 * Get the contents of a list of CSS files.
814 *
815 * This is considered a private method. Exposed for internal use by WebInstallerOutput.
816 *
817 * @private
818 * @param array $styles Map of media type to file paths to read, remap, and concatenate
819 * @param bool $flip
820 * @param ResourceLoaderContext|null $context
821 * @return array List of concatenated and remapped CSS data from $styles,
822 * keyed by media type
823 * @throws MWException
824 * @since 1.27 Calling this method without a ResourceLoaderContext instance
825 * is deprecated.
826 */
827 public function readStyleFiles( array $styles, $flip, $context = null ) {
828 if ( $context === null ) {
829 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
830 $context = ResourceLoaderContext::newDummyContext();
831 }
832
833 if ( empty( $styles ) ) {
834 return [];
835 }
836 foreach ( $styles as $media => $files ) {
837 $uniqueFiles = array_unique( $files, SORT_REGULAR );
838 $styleFiles = [];
839 foreach ( $uniqueFiles as $file ) {
840 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
841 }
842 $styles[$media] = implode( "\n", $styleFiles );
843 }
844 return $styles;
845 }
846
847 /**
848 * Reads a style file.
849 *
850 * This method can be used as a callback for array_map()
851 *
852 * @param string $path File path of style file to read
853 * @param bool $flip
854 * @param ResourceLoaderContext $context
855 *
856 * @return string CSS data in script file
857 * @throws MWException If the file doesn't exist
858 */
859 protected function readStyleFile( $path, $flip, $context ) {
860 $localPath = $this->getLocalPath( $path );
861 $remotePath = $this->getRemotePath( $path );
862 if ( !file_exists( $localPath ) ) {
863 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
864 wfDebugLog( 'resourceloader', $msg );
865 throw new MWException( $msg );
866 }
867
868 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
869 $style = $this->compileLessFile( $localPath, $context );
870 $this->hasGeneratedStyles = true;
871 } else {
872 $style = $this->stripBom( file_get_contents( $localPath ) );
873 }
874
875 if ( $flip ) {
876 $style = CSSJanus::transform( $style, true, false );
877 }
878 $localDir = dirname( $localPath );
879 $remoteDir = dirname( $remotePath );
880 // Get and register local file references
881 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
882 foreach ( $localFileRefs as $file ) {
883 if ( file_exists( $file ) ) {
884 $this->localFileRefs[] = $file;
885 } else {
886 $this->missingLocalFileRefs[] = $file;
887 }
888 }
889 // Don't cache this call. remap() ensures data URIs embeds are up to date,
890 // and urls contain correct content hashes in their query string. (T128668)
891 return CSSMin::remap( $style, $localDir, $remoteDir, true );
892 }
893
894 /**
895 * Get whether CSS for this module should be flipped
896 * @param ResourceLoaderContext $context
897 * @return bool
898 */
899 public function getFlip( $context ) {
900 return $context->getDirection() === 'rtl' && !$this->noflip;
901 }
902
903 /**
904 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
905 *
906 * @return array Array of strings
907 */
908 public function getTargets() {
909 return $this->targets;
910 }
911
912 /**
913 * Get the module's load type.
914 *
915 * @since 1.28
916 * @return string
917 */
918 public function getType() {
919 $canBeStylesOnly = !(
920 // All options except 'styles', 'skinStyles' and 'debugRaw'
921 $this->scripts
922 || $this->debugScripts
923 || $this->templates
924 || $this->languageScripts
925 || $this->skinScripts
926 || $this->dependencies
927 || $this->messages
928 || $this->skipFunction
929 || $this->raw
930 );
931 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
932 }
933
934 /**
935 * Compile a LESS file into CSS.
936 *
937 * Keeps track of all used files and adds them to localFileRefs.
938 *
939 * @since 1.22
940 * @since 1.27 Added $context paramter.
941 * @throws Exception If less.php encounters a parse error
942 * @param string $fileName File path of LESS source
943 * @param ResourceLoaderContext $context Context in which to generate script
944 * @return string CSS source
945 */
946 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
947 static $cache;
948
949 if ( !$cache ) {
950 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
951 }
952
953 $vars = $this->getLessVars( $context );
954 // Construct a cache key from the LESS file name, and a hash digest
955 // of the LESS variables used for compilation.
956 ksort( $vars );
957 $varsHash = hash( 'md4', serialize( $vars ) );
958 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
959 $cachedCompile = $cache->get( $cacheKey );
960
961 // If we got a cached value, we have to validate it by getting a
962 // checksum of all the files that were loaded by the parser and
963 // ensuring it matches the cached entry's.
964 if ( isset( $cachedCompile['hash'] ) ) {
965 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
966 if ( $contentHash === $cachedCompile['hash'] ) {
967 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
968 return $cachedCompile['css'];
969 }
970 }
971
972 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
973 $css = $compiler->parseFile( $fileName )->getCss();
974 $files = $compiler->AllParsedFiles();
975 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
976
977 // Cache for 24 hours (86400 seconds).
978 $cache->set( $cacheKey, [
979 'css' => $css,
980 'files' => $files,
981 'hash' => FileContentsHasher::getFileContentsHash( $files ),
982 ], 3600 * 24 );
983
984 return $css;
985 }
986
987 /**
988 * Takes named templates by the module and returns an array mapping.
989 * @return array Templates mapping template alias to content
990 * @throws MWException
991 */
992 public function getTemplates() {
993 $templates = [];
994
995 foreach ( $this->templates as $alias => $templatePath ) {
996 // Alias is optional
997 if ( is_int( $alias ) ) {
998 $alias = $templatePath;
999 }
1000 $localPath = $this->getLocalPath( $templatePath );
1001 if ( file_exists( $localPath ) ) {
1002 $content = file_get_contents( $localPath );
1003 $templates[$alias] = $this->stripBom( $content );
1004 } else {
1005 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
1006 wfDebugLog( 'resourceloader', $msg );
1007 throw new MWException( $msg );
1008 }
1009 }
1010 return $templates;
1011 }
1012
1013 /**
1014 * Takes an input string and removes the UTF-8 BOM character if present
1015 *
1016 * We need to remove these after reading a file, because we concatenate our files and
1017 * the BOM character is not valid in the middle of a string.
1018 * We already assume UTF-8 everywhere, so this should be safe.
1019 *
1020 * @param string $input
1021 * @return string Input minus the intial BOM char
1022 */
1023 protected function stripBom( $input ) {
1024 if ( substr_compare( "\xef\xbb\xbf", $input, 0, 3 ) === 0 ) {
1025 return substr( $input, 3 );
1026 }
1027 return $input;
1028 }
1029 }