Merge "Http::getProxy() method to get proxy configuration"
[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 * array( [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 * array( [language-code] => array( [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 * array( [skin-name] => array( [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 * array( [skin-name] => array( [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 * array( [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 * array( [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 * array( [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 * array( [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 string Position on the page to load this module at */
121 protected $position = 'bottom';
122
123 /** @var bool Link to raw files in debug mode */
124 protected $debugRaw = true;
125
126 /** @var bool Whether mw.loader.state() call should be omitted */
127 protected $raw = false;
128
129 protected $targets = [ 'desktop' ];
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 * array( [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 * array(
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' => array(
181 * [language code] => [file path string or array of file path strings],
182 * ),
183 * // Scripts to include in specific skin contexts
184 * 'skinScripts' => array(
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' => array(
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' => array(
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 * // Position on the page to load this module at
205 * 'position' => ['bottom' (default) or 'top']
206 * // Function that, if it returns true, makes the loader skip this module.
207 * // The file must contain valid JavaScript for execution in a private function.
208 * // The file must not contain the "function () {" and "}" wrapper though.
209 * 'skipFunction' => [file path]
210 * )
211 * @endcode
212 */
213 public function __construct(
214 $options = [],
215 $localBasePath = null,
216 $remoteBasePath = null
217 ) {
218 // Flag to decide whether to automagically add the mediawiki.template module
219 $hasTemplates = false;
220 // localBasePath and remoteBasePath both have unbelievably long fallback chains
221 // and need to be handled separately.
222 list( $this->localBasePath, $this->remoteBasePath ) =
223 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
224
225 // Extract, validate and normalise remaining options
226 foreach ( $options as $member => $option ) {
227 switch ( $member ) {
228 // Lists of file paths
229 case 'scripts':
230 case 'debugScripts':
231 case 'styles':
232 $this->{$member} = (array)$option;
233 break;
234 case 'templates':
235 $hasTemplates = true;
236 $this->{$member} = (array)$option;
237 break;
238 // Collated lists of file paths
239 case 'languageScripts':
240 case 'skinScripts':
241 case 'skinStyles':
242 if ( !is_array( $option ) ) {
243 throw new InvalidArgumentException(
244 "Invalid collated file path list error. " .
245 "'$option' given, array expected."
246 );
247 }
248 foreach ( $option as $key => $value ) {
249 if ( !is_string( $key ) ) {
250 throw new InvalidArgumentException(
251 "Invalid collated file path list key error. " .
252 "'$key' given, string expected."
253 );
254 }
255 $this->{$member}[$key] = (array)$value;
256 }
257 break;
258 // Lists of strings
259 case 'dependencies':
260 case 'messages':
261 case 'targets':
262 // Normalise
263 $option = array_values( array_unique( (array)$option ) );
264 sort( $option );
265
266 $this->{$member} = $option;
267 break;
268 // Single strings
269 case 'position':
270 case 'group':
271 case 'skipFunction':
272 $this->{$member} = (string)$option;
273 break;
274 // Single booleans
275 case 'debugRaw':
276 case 'raw':
277 $this->{$member} = (bool)$option;
278 break;
279 }
280 }
281 if ( $hasTemplates ) {
282 $this->dependencies[] = 'mediawiki.template';
283 // Ensure relevant template compiler module gets loaded
284 foreach ( $this->templates as $alias => $templatePath ) {
285 if ( is_int( $alias ) ) {
286 $alias = $templatePath;
287 }
288 $suffix = explode( '.', $alias );
289 $suffix = end( $suffix );
290 $compilerModule = 'mediawiki.template.' . $suffix;
291 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
292 $this->dependencies[] = $compilerModule;
293 }
294 }
295 }
296 }
297
298 /**
299 * Extract a pair of local and remote base paths from module definition information.
300 * Implementation note: the amount of global state used in this function is staggering.
301 *
302 * @param array $options Module definition
303 * @param string $localBasePath Path to use if not provided in module definition. Defaults
304 * to $IP
305 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
306 * to $wgResourceBasePath
307 * @return array Array( localBasePath, remoteBasePath )
308 */
309 public static function extractBasePaths(
310 $options = [],
311 $localBasePath = null,
312 $remoteBasePath = null
313 ) {
314 global $IP, $wgResourceBasePath;
315
316 // The different ways these checks are done, and their ordering, look very silly,
317 // but were preserved for backwards-compatibility just in case. Tread lightly.
318
319 if ( $localBasePath === null ) {
320 $localBasePath = $IP;
321 }
322 if ( $remoteBasePath === null ) {
323 $remoteBasePath = $wgResourceBasePath;
324 }
325
326 if ( isset( $options['remoteExtPath'] ) ) {
327 global $wgExtensionAssetsPath;
328 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
329 }
330
331 if ( isset( $options['remoteSkinPath'] ) ) {
332 global $wgStylePath;
333 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
334 }
335
336 if ( array_key_exists( 'localBasePath', $options ) ) {
337 $localBasePath = (string)$options['localBasePath'];
338 }
339
340 if ( array_key_exists( 'remoteBasePath', $options ) ) {
341 $remoteBasePath = (string)$options['remoteBasePath'];
342 }
343
344 return [ $localBasePath, $remoteBasePath ];
345 }
346
347 /**
348 * Gets all scripts for a given context concatenated together.
349 *
350 * @param ResourceLoaderContext $context Context in which to generate script
351 * @return string JavaScript code for $context
352 */
353 public function getScript( ResourceLoaderContext $context ) {
354 $files = $this->getScriptFiles( $context );
355 return $this->readScriptFiles( $files );
356 }
357
358 /**
359 * @param ResourceLoaderContext $context
360 * @return array
361 */
362 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
363 $urls = [];
364 foreach ( $this->getScriptFiles( $context ) as $file ) {
365 $urls[] = OutputPage::transformResourcePath(
366 $this->getConfig(),
367 $this->getRemotePath( $file )
368 );
369 }
370 return $urls;
371 }
372
373 /**
374 * @return bool
375 */
376 public function supportsURLLoading() {
377 return $this->debugRaw;
378 }
379
380 /**
381 * Get all styles for a given context.
382 *
383 * @param ResourceLoaderContext $context
384 * @return array CSS code for $context as an associative array mapping media type to CSS text.
385 */
386 public function getStyles( ResourceLoaderContext $context ) {
387 $styles = $this->readStyleFiles(
388 $this->getStyleFiles( $context ),
389 $this->getFlip( $context ),
390 $context
391 );
392 // Collect referenced files
393 $this->saveFileDependencies( $context, $this->localFileRefs );
394
395 return $styles;
396 }
397
398 /**
399 * @param ResourceLoaderContext $context
400 * @return array
401 */
402 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
403 if ( $this->hasGeneratedStyles ) {
404 // Do the default behaviour of returning a url back to load.php
405 // but with only=styles.
406 return parent::getStyleURLsForDebug( $context );
407 }
408 // Our module consists entirely of real css files,
409 // in debug mode we can load those directly.
410 $urls = [];
411 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
412 $urls[$mediaType] = [];
413 foreach ( $list as $file ) {
414 $urls[$mediaType][] = OutputPage::transformResourcePath(
415 $this->getConfig(),
416 $this->getRemotePath( $file )
417 );
418 }
419 }
420 return $urls;
421 }
422
423 /**
424 * Gets list of message keys used by this module.
425 *
426 * @return array List of message keys
427 */
428 public function getMessages() {
429 return $this->messages;
430 }
431
432 /**
433 * Gets the name of the group this module should be loaded in.
434 *
435 * @return string Group name
436 */
437 public function getGroup() {
438 return $this->group;
439 }
440
441 /**
442 * @return string
443 */
444 public function getPosition() {
445 return $this->position;
446 }
447
448 /**
449 * Gets list of names of modules this module depends on.
450 * @param ResourceLoaderContext|null $context
451 * @return array List of module names
452 */
453 public function getDependencies( ResourceLoaderContext $context = null ) {
454 return $this->dependencies;
455 }
456
457 /**
458 * Get the skip function.
459 * @return null|string
460 * @throws MWException
461 */
462 public function getSkipFunction() {
463 if ( !$this->skipFunction ) {
464 return null;
465 }
466
467 $localPath = $this->getLocalPath( $this->skipFunction );
468 if ( !file_exists( $localPath ) ) {
469 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
470 }
471 $contents = file_get_contents( $localPath );
472 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
473 $contents = $this->validateScriptFile( $localPath, $contents );
474 }
475 return $contents;
476 }
477
478 /**
479 * @return bool
480 */
481 public function isRaw() {
482 return $this->raw;
483 }
484
485 /**
486 * Disable module content versioning.
487 *
488 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
489 * involved with building the full module content inside a startup request.
490 *
491 * @return bool
492 */
493 public function enableModuleContentVersion() {
494 return false;
495 }
496
497 /**
498 * Helper method to gather file hashes for getDefinitionSummary.
499 *
500 * This function is context-sensitive, only computing hashes of files relevant to the
501 * given language, skin, etc.
502 *
503 * @see ResourceLoaderModule::getFileDependencies
504 * @param ResourceLoaderContext $context
505 * @return array
506 */
507 protected function getFileHashes( ResourceLoaderContext $context ) {
508 $files = [];
509
510 // Flatten style files into $files
511 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
512 foreach ( $styles as $styleFiles ) {
513 $files = array_merge( $files, $styleFiles );
514 }
515
516 $skinFiles = self::collateFilePathListByOption(
517 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
518 'media',
519 'all'
520 );
521 foreach ( $skinFiles as $styleFiles ) {
522 $files = array_merge( $files, $styleFiles );
523 }
524
525 // Final merge, this should result in a master list of dependent files
526 $files = array_merge(
527 $files,
528 $this->scripts,
529 $this->templates,
530 $context->getDebug() ? $this->debugScripts : [],
531 $this->getLanguageScripts( $context->getLanguage() ),
532 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
533 );
534 if ( $this->skipFunction ) {
535 $files[] = $this->skipFunction;
536 }
537 $files = array_map( [ $this, 'getLocalPath' ], $files );
538 // File deps need to be treated separately because they're already prefixed
539 $files = array_merge( $files, $this->getFileDependencies( $context ) );
540 // Filter out any duplicates from getFileDependencies() and others.
541 // Most commonly introduced by compileLessFile(), which always includes the
542 // entry point Less file we already know about.
543 $files = array_values( array_unique( $files ) );
544
545 // Don't include keys or file paths here, only the hashes. Including that would needlessly
546 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
547 // Any significant ordering is already detected by the definition summary.
548 return array_map( [ __CLASS__, 'safeFileHash' ], $files );
549 }
550
551 /**
552 * Get the definition summary for this module.
553 *
554 * @param ResourceLoaderContext $context
555 * @return array
556 */
557 public function getDefinitionSummary( ResourceLoaderContext $context ) {
558 $summary = parent::getDefinitionSummary( $context );
559
560 $options = [];
561 foreach ( [
562 // The following properties are omitted because they don't affect the module reponse:
563 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
564 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
565 // - remoteBasePath (Per T104950)
566 // - dependencies (provided via startup module)
567 // - targets
568 // - group (provided via startup module)
569 // - position (only used by OutputPage)
570 'scripts',
571 'debugScripts',
572 'styles',
573 'languageScripts',
574 'skinScripts',
575 'skinStyles',
576 'messages',
577 'templates',
578 'skipFunction',
579 'debugRaw',
580 'raw',
581 ] as $member ) {
582 $options[$member] = $this->{$member};
583 };
584
585 $summary[] = [
586 'options' => $options,
587 'fileHashes' => $this->getFileHashes( $context ),
588 'messageBlob' => $this->getMessageBlob( $context ),
589 ];
590 return $summary;
591 }
592
593 /**
594 * @param string|ResourceLoaderFilePath $path
595 * @return string
596 */
597 protected function getLocalPath( $path ) {
598 if ( $path instanceof ResourceLoaderFilePath ) {
599 return $path->getLocalPath();
600 }
601
602 return "{$this->localBasePath}/$path";
603 }
604
605 /**
606 * @param string|ResourceLoaderFilePath $path
607 * @return string
608 */
609 protected function getRemotePath( $path ) {
610 if ( $path instanceof ResourceLoaderFilePath ) {
611 return $path->getRemotePath();
612 }
613
614 return "{$this->remoteBasePath}/$path";
615 }
616
617 /**
618 * Infer the stylesheet language from a stylesheet file path.
619 *
620 * @since 1.22
621 * @param string $path
622 * @return string The stylesheet language name
623 */
624 public function getStyleSheetLang( $path ) {
625 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
626 }
627
628 /**
629 * Collates file paths by option (where provided).
630 *
631 * @param array $list List of file paths in any combination of index/path
632 * or path/options pairs
633 * @param string $option Option name
634 * @param mixed $default Default value if the option isn't set
635 * @return array List of file paths, collated by $option
636 */
637 protected static function collateFilePathListByOption( array $list, $option, $default ) {
638 $collatedFiles = [];
639 foreach ( (array)$list as $key => $value ) {
640 if ( is_int( $key ) ) {
641 // File name as the value
642 if ( !isset( $collatedFiles[$default] ) ) {
643 $collatedFiles[$default] = [];
644 }
645 $collatedFiles[$default][] = $value;
646 } elseif ( is_array( $value ) ) {
647 // File name as the key, options array as the value
648 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
649 if ( !isset( $collatedFiles[$optionValue] ) ) {
650 $collatedFiles[$optionValue] = [];
651 }
652 $collatedFiles[$optionValue][] = $key;
653 }
654 }
655 return $collatedFiles;
656 }
657
658 /**
659 * Get a list of element that match a key, optionally using a fallback key.
660 *
661 * @param array $list List of lists to select from
662 * @param string $key Key to look for in $map
663 * @param string $fallback Key to look for in $list if $key doesn't exist
664 * @return array List of elements from $map which matched $key or $fallback,
665 * or an empty list in case of no match
666 */
667 protected static function tryForKey( array $list, $key, $fallback = null ) {
668 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
669 return $list[$key];
670 } elseif ( is_string( $fallback )
671 && isset( $list[$fallback] )
672 && is_array( $list[$fallback] )
673 ) {
674 return $list[$fallback];
675 }
676 return [];
677 }
678
679 /**
680 * Get a list of file paths for all scripts in this module, in order of proper execution.
681 *
682 * @param ResourceLoaderContext $context
683 * @return array List of file paths
684 */
685 protected function getScriptFiles( ResourceLoaderContext $context ) {
686 $files = array_merge(
687 $this->scripts,
688 $this->getLanguageScripts( $context->getLanguage() ),
689 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
690 );
691 if ( $context->getDebug() ) {
692 $files = array_merge( $files, $this->debugScripts );
693 }
694
695 return array_unique( $files, SORT_REGULAR );
696 }
697
698 /**
699 * Get the set of language scripts for the given language,
700 * possibly using a fallback language.
701 *
702 * @param string $lang
703 * @return array
704 */
705 private function getLanguageScripts( $lang ) {
706 $scripts = self::tryForKey( $this->languageScripts, $lang );
707 if ( $scripts ) {
708 return $scripts;
709 }
710 $fallbacks = Language::getFallbacksFor( $lang );
711 foreach ( $fallbacks as $lang ) {
712 $scripts = self::tryForKey( $this->languageScripts, $lang );
713 if ( $scripts ) {
714 return $scripts;
715 }
716 }
717
718 return [];
719 }
720
721 /**
722 * Get a list of file paths for all styles in this module, in order of proper inclusion.
723 *
724 * @param ResourceLoaderContext $context
725 * @return array List of file paths
726 */
727 public function getStyleFiles( ResourceLoaderContext $context ) {
728 return array_merge_recursive(
729 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
730 self::collateFilePathListByOption(
731 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
732 'media',
733 'all'
734 )
735 );
736 }
737
738 /**
739 * Gets a list of file paths for all skin styles in the module used by
740 * the skin.
741 *
742 * @param string $skinName The name of the skin
743 * @return array A list of file paths collated by media type
744 */
745 protected function getSkinStyleFiles( $skinName ) {
746 return self::collateFilePathListByOption(
747 self::tryForKey( $this->skinStyles, $skinName ),
748 'media',
749 'all'
750 );
751 }
752
753 /**
754 * Gets a list of file paths for all skin style files in the module,
755 * for all available skins.
756 *
757 * @return array A list of file paths collated by media type
758 */
759 protected function getAllSkinStyleFiles() {
760 $styleFiles = [];
761 $internalSkinNames = array_keys( Skin::getSkinNames() );
762 $internalSkinNames[] = 'default';
763
764 foreach ( $internalSkinNames as $internalSkinName ) {
765 $styleFiles = array_merge_recursive(
766 $styleFiles,
767 $this->getSkinStyleFiles( $internalSkinName )
768 );
769 }
770
771 return $styleFiles;
772 }
773
774 /**
775 * Returns all style files and all skin style files used by this module.
776 *
777 * @return array
778 */
779 public function getAllStyleFiles() {
780 $collatedStyleFiles = array_merge_recursive(
781 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
782 $this->getAllSkinStyleFiles()
783 );
784
785 $result = [];
786
787 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
788 foreach ( $styleFiles as $styleFile ) {
789 $result[] = $this->getLocalPath( $styleFile );
790 }
791 }
792
793 return $result;
794 }
795
796 /**
797 * Gets the contents of a list of JavaScript files.
798 *
799 * @param array $scripts List of file paths to scripts to read, remap and concetenate
800 * @throws MWException
801 * @return string Concatenated and remapped JavaScript data from $scripts
802 */
803 protected function readScriptFiles( array $scripts ) {
804 if ( empty( $scripts ) ) {
805 return '';
806 }
807 $js = '';
808 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
809 $localPath = $this->getLocalPath( $fileName );
810 if ( !file_exists( $localPath ) ) {
811 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
812 }
813 $contents = file_get_contents( $localPath );
814 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
815 // Static files don't really need to be checked as often; unlike
816 // on-wiki module they shouldn't change unexpectedly without
817 // admin interference.
818 $contents = $this->validateScriptFile( $fileName, $contents );
819 }
820 $js .= $contents . "\n";
821 }
822 return $js;
823 }
824
825 /**
826 * Gets the contents of a list of CSS files.
827 *
828 * @param array $styles List of media type/list of file paths pairs, to read, remap and
829 * concetenate
830 * @param bool $flip
831 * @param ResourceLoaderContext $context
832 *
833 * @throws MWException
834 * @return array List of concatenated and remapped CSS data from $styles,
835 * keyed by media type
836 *
837 * @since 1.27 Calling this method without a ResourceLoaderContext instance
838 * is deprecated.
839 */
840 public function readStyleFiles( array $styles, $flip, $context = null ) {
841 if ( $context === null ) {
842 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
843 $context = ResourceLoaderContext::newDummyContext();
844 }
845
846 if ( empty( $styles ) ) {
847 return [];
848 }
849 foreach ( $styles as $media => $files ) {
850 $uniqueFiles = array_unique( $files, SORT_REGULAR );
851 $styleFiles = [];
852 foreach ( $uniqueFiles as $file ) {
853 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
854 }
855 $styles[$media] = implode( "\n", $styleFiles );
856 }
857 return $styles;
858 }
859
860 /**
861 * Reads a style file.
862 *
863 * This method can be used as a callback for array_map()
864 *
865 * @param string $path File path of style file to read
866 * @param bool $flip
867 * @param ResourceLoaderContext $context
868 *
869 * @return string CSS data in script file
870 * @throws MWException If the file doesn't exist
871 */
872 protected function readStyleFile( $path, $flip, $context ) {
873 $localPath = $this->getLocalPath( $path );
874 $remotePath = $this->getRemotePath( $path );
875 if ( !file_exists( $localPath ) ) {
876 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
877 wfDebugLog( 'resourceloader', $msg );
878 throw new MWException( $msg );
879 }
880
881 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
882 $style = $this->compileLessFile( $localPath, $context );
883 $this->hasGeneratedStyles = true;
884 } else {
885 $style = file_get_contents( $localPath );
886 }
887
888 if ( $flip ) {
889 $style = CSSJanus::transform( $style, true, false );
890 }
891 $localDir = dirname( $localPath );
892 $remoteDir = dirname( $remotePath );
893 // Get and register local file references
894 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
895 foreach ( $localFileRefs as $file ) {
896 if ( file_exists( $file ) ) {
897 $this->localFileRefs[] = $file;
898 } else {
899 $this->missingLocalFileRefs[] = $file;
900 }
901 }
902 // Don't cache this call. remap() ensures data URIs embeds are up to date,
903 // and urls contain correct content hashes in their query string. (T128668)
904 return CSSMin::remap( $style, $localDir, $remoteDir, true );
905 }
906
907 /**
908 * Get whether CSS for this module should be flipped
909 * @param ResourceLoaderContext $context
910 * @return bool
911 */
912 public function getFlip( $context ) {
913 return $context->getDirection() === 'rtl';
914 }
915
916 /**
917 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
918 *
919 * @return array Array of strings
920 */
921 public function getTargets() {
922 return $this->targets;
923 }
924
925 /**
926 * Compile a LESS file into CSS.
927 *
928 * Keeps track of all used files and adds them to localFileRefs.
929 *
930 * @since 1.22
931 * @since 1.27 Added $context paramter.
932 * @throws Exception If less.php encounters a parse error
933 * @param string $fileName File path of LESS source
934 * @param ResourceLoaderContext $context Context in which to generate script
935 * @return string CSS source
936 */
937 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
938 static $cache;
939
940 if ( !$cache ) {
941 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
942 }
943
944 // Construct a cache key from the LESS file name and a hash digest
945 // of the LESS variables used for compilation.
946 $vars = $this->getLessVars( $context );
947 ksort( $vars );
948 $varsHash = hash( 'md4', serialize( $vars ) );
949 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
950 $cachedCompile = $cache->get( $cacheKey );
951
952 // If we got a cached value, we have to validate it by getting a
953 // checksum of all the files that were loaded by the parser and
954 // ensuring it matches the cached entry's.
955 if ( isset( $cachedCompile['hash'] ) ) {
956 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
957 if ( $contentHash === $cachedCompile['hash'] ) {
958 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
959 return $cachedCompile['css'];
960 }
961 }
962
963 $compiler = $context->getResourceLoader()->getLessCompiler( $vars );
964 $css = $compiler->parseFile( $fileName )->getCss();
965 $files = $compiler->AllParsedFiles();
966 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
967
968 $cache->set( $cacheKey, [
969 'css' => $css,
970 'files' => $files,
971 'hash' => FileContentsHasher::getFileContentsHash( $files ),
972 ], 60 * 60 * 24 ); // 86400 seconds, or 24 hours.
973
974 return $css;
975 }
976
977 /**
978 * Takes named templates by the module and returns an array mapping.
979 * @return array of templates mapping template alias to content
980 * @throws MWException
981 */
982 public function getTemplates() {
983 $templates = [];
984
985 foreach ( $this->templates as $alias => $templatePath ) {
986 // Alias is optional
987 if ( is_int( $alias ) ) {
988 $alias = $templatePath;
989 }
990 $localPath = $this->getLocalPath( $templatePath );
991 if ( file_exists( $localPath ) ) {
992 $content = file_get_contents( $localPath );
993 $templates[$alias] = $content;
994 } else {
995 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
996 wfDebugLog( 'resourceloader', $msg );
997 throw new MWException( $msg );
998 }
999 }
1000 return $templates;
1001 }
1002 }