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