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