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