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