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