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