ef984002988fcce2db4e751cb67b83a22ff3cfce
[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 = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array();
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 = array( '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 = array();
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 = array();
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 = array(),
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 = array(),
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 // Make sure the remote base path is a complete valid URL,
345 // but possibly protocol-relative to avoid cache pollution
346 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
347
348 return array( $localBasePath, $remoteBasePath );
349 }
350
351 /**
352 * Gets all scripts for a given context concatenated together.
353 *
354 * @param ResourceLoaderContext $context Context in which to generate script
355 * @return string JavaScript code for $context
356 */
357 public function getScript( ResourceLoaderContext $context ) {
358 $files = $this->getScriptFiles( $context );
359 return $this->readScriptFiles( $files );
360 }
361
362 /**
363 * @param ResourceLoaderContext $context
364 * @return array
365 */
366 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
367 $urls = array();
368 foreach ( $this->getScriptFiles( $context ) as $file ) {
369 $urls[] = $this->getRemotePath( $file );
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 = array();
412 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
413 $urls[$mediaType] = array();
414 foreach ( $list as $file ) {
415 $urls[$mediaType][] = $this->getRemotePath( $file );
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 * @return string
441 */
442 public function getPosition() {
443 return $this->position;
444 }
445
446 /**
447 * Gets list of names of modules this module depends on.
448 * @param ResourceLoaderContext context
449 * @return array List of module names
450 */
451 public function getDependencies( ResourceLoaderContext $context = null ) {
452 return $this->dependencies;
453 }
454
455 /**
456 * Get the skip function.
457 * @return null|string
458 * @throws MWException
459 */
460 public function getSkipFunction() {
461 if ( !$this->skipFunction ) {
462 return null;
463 }
464
465 $localPath = $this->getLocalPath( $this->skipFunction );
466 if ( !file_exists( $localPath ) ) {
467 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
468 }
469 $contents = file_get_contents( $localPath );
470 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
471 $contents = $this->validateScriptFile( $localPath, $contents );
472 }
473 return $contents;
474 }
475
476 /**
477 * @return bool
478 */
479 public function isRaw() {
480 return $this->raw;
481 }
482
483 /**
484 * Disable module content versioning.
485 *
486 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
487 * involved with building the full module content inside a startup request.
488 *
489 * @return bool
490 */
491 public function enableModuleContentVersion() {
492 return false;
493 }
494
495 /**
496 * Helper method to gather file hashes for getDefinitionSummary.
497 *
498 * This function is context-sensitive, only computing hashes of files relevant to the
499 * given language, skin, etc.
500 *
501 * @see ResourceLoaderModule::getFileDependencies
502 * @param ResourceLoaderContext $context
503 * @return array
504 */
505 protected function getFileHashes( ResourceLoaderContext $context ) {
506 $files = array();
507
508 // Flatten style files into $files
509 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
510 foreach ( $styles as $styleFiles ) {
511 $files = array_merge( $files, $styleFiles );
512 }
513
514 $skinFiles = self::collateFilePathListByOption(
515 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
516 'media',
517 'all'
518 );
519 foreach ( $skinFiles as $styleFiles ) {
520 $files = array_merge( $files, $styleFiles );
521 }
522
523 // Final merge, this should result in a master list of dependent files
524 $files = array_merge(
525 $files,
526 $this->scripts,
527 $this->templates,
528 $context->getDebug() ? $this->debugScripts : array(),
529 $this->getLanguageScripts( $context->getLanguage() ),
530 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
531 );
532 if ( $this->skipFunction ) {
533 $files[] = $this->skipFunction;
534 }
535 $files = array_map( array( $this, 'getLocalPath' ), $files );
536 // File deps need to be treated separately because they're already prefixed
537 $files = array_merge( $files, $this->getFileDependencies( $context ) );
538 // Filter out any duplicates from getFileDependencies() and others.
539 // Most commonly introduced by compileLessFile(), which always includes the
540 // entry point Less file we already know about.
541 $files = array_values( array_unique( $files ) );
542
543 // Don't include keys or file paths here, only the hashes. Including that would needlessly
544 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
545 // Any significant ordering is already detected by the definition summary.
546 return array_map( array( __CLASS__, 'safeFileHash' ), $files );
547 }
548
549 /**
550 * Get the definition summary for this module.
551 *
552 * @param ResourceLoaderContext $context
553 * @return array
554 */
555 public function getDefinitionSummary( ResourceLoaderContext $context ) {
556 $summary = parent::getDefinitionSummary( $context );
557
558 $options = array();
559 foreach ( array(
560 // The following properties are omitted because they don't affect the module reponse:
561 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
562 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
563 // - remoteBasePath (Per T104950)
564 // - dependencies (provided via startup module)
565 // - targets
566 // - group (provided via startup module)
567 // - position (only used by OutputPage)
568 'scripts',
569 'debugScripts',
570 'styles',
571 'languageScripts',
572 'skinScripts',
573 'skinStyles',
574 'messages',
575 'templates',
576 'skipFunction',
577 'debugRaw',
578 'raw',
579 ) as $member ) {
580 $options[$member] = $this->{$member};
581 };
582
583 $summary[] = array(
584 'options' => $options,
585 'fileHashes' => $this->getFileHashes( $context ),
586 'msgBlobMtime' => $this->getMsgBlobMtime( $context->getLanguage() ),
587 );
588 return $summary;
589 }
590
591 /**
592 * @param string|ResourceLoaderFilePath $path
593 * @return string
594 */
595 protected function getLocalPath( $path ) {
596 if ( $path instanceof ResourceLoaderFilePath ) {
597 return $path->getLocalPath();
598 }
599
600 return "{$this->localBasePath}/$path";
601 }
602
603 /**
604 * @param string|ResourceLoaderFilePath $path
605 * @return string
606 */
607 protected function getRemotePath( $path ) {
608 if ( $path instanceof ResourceLoaderFilePath ) {
609 return $path->getRemotePath();
610 }
611
612 return "{$this->remoteBasePath}/$path";
613 }
614
615 /**
616 * Infer the stylesheet language from a stylesheet file path.
617 *
618 * @since 1.22
619 * @param string $path
620 * @return string The stylesheet language name
621 */
622 public function getStyleSheetLang( $path ) {
623 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
624 }
625
626 /**
627 * Collates file paths by option (where provided).
628 *
629 * @param array $list List of file paths in any combination of index/path
630 * or path/options pairs
631 * @param string $option Option name
632 * @param mixed $default Default value if the option isn't set
633 * @return array List of file paths, collated by $option
634 */
635 protected static function collateFilePathListByOption( array $list, $option, $default ) {
636 $collatedFiles = array();
637 foreach ( (array)$list as $key => $value ) {
638 if ( is_int( $key ) ) {
639 // File name as the value
640 if ( !isset( $collatedFiles[$default] ) ) {
641 $collatedFiles[$default] = array();
642 }
643 $collatedFiles[$default][] = $value;
644 } elseif ( is_array( $value ) ) {
645 // File name as the key, options array as the value
646 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
647 if ( !isset( $collatedFiles[$optionValue] ) ) {
648 $collatedFiles[$optionValue] = array();
649 }
650 $collatedFiles[$optionValue][] = $key;
651 }
652 }
653 return $collatedFiles;
654 }
655
656 /**
657 * Get a list of element that match a key, optionally using a fallback key.
658 *
659 * @param array $list List of lists to select from
660 * @param string $key Key to look for in $map
661 * @param string $fallback Key to look for in $list if $key doesn't exist
662 * @return array List of elements from $map which matched $key or $fallback,
663 * or an empty list in case of no match
664 */
665 protected static function tryForKey( array $list, $key, $fallback = null ) {
666 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
667 return $list[$key];
668 } elseif ( is_string( $fallback )
669 && isset( $list[$fallback] )
670 && is_array( $list[$fallback] )
671 ) {
672 return $list[$fallback];
673 }
674 return array();
675 }
676
677 /**
678 * Get a list of file paths for all scripts in this module, in order of proper execution.
679 *
680 * @param ResourceLoaderContext $context
681 * @return array List of file paths
682 */
683 protected function getScriptFiles( ResourceLoaderContext $context ) {
684 $files = array_merge(
685 $this->scripts,
686 $this->getLanguageScripts( $context->getLanguage() ),
687 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
688 );
689 if ( $context->getDebug() ) {
690 $files = array_merge( $files, $this->debugScripts );
691 }
692
693 return array_unique( $files, SORT_REGULAR );
694 }
695
696 /**
697 * Get the set of language scripts for the given language,
698 * possibly using a fallback language.
699 *
700 * @param string $lang
701 * @return array
702 */
703 private function getLanguageScripts( $lang ) {
704 $scripts = self::tryForKey( $this->languageScripts, $lang );
705 if ( $scripts ) {
706 return $scripts;
707 }
708 $fallbacks = Language::getFallbacksFor( $lang );
709 foreach ( $fallbacks as $lang ) {
710 $scripts = self::tryForKey( $this->languageScripts, $lang );
711 if ( $scripts ) {
712 return $scripts;
713 }
714 }
715
716 return array();
717 }
718
719 /**
720 * Get a list of file paths for all styles in this module, in order of proper inclusion.
721 *
722 * @param ResourceLoaderContext $context
723 * @return array List of file paths
724 */
725 public function getStyleFiles( ResourceLoaderContext $context ) {
726 return array_merge_recursive(
727 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
728 self::collateFilePathListByOption(
729 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
730 'media',
731 'all'
732 )
733 );
734 }
735
736 /**
737 * Gets a list of file paths for all skin styles in the module used by
738 * the skin.
739 *
740 * @param string $skinName The name of the skin
741 * @return array A list of file paths collated by media type
742 */
743 protected function getSkinStyleFiles( $skinName ) {
744 return self::collateFilePathListByOption(
745 self::tryForKey( $this->skinStyles, $skinName ),
746 'media',
747 'all'
748 );
749 }
750
751 /**
752 * Gets a list of file paths for all skin style files in the module,
753 * for all available skins.
754 *
755 * @return array A list of file paths collated by media type
756 */
757 protected function getAllSkinStyleFiles() {
758 $styleFiles = array();
759 $internalSkinNames = array_keys( Skin::getSkinNames() );
760 $internalSkinNames[] = 'default';
761
762 foreach ( $internalSkinNames as $internalSkinName ) {
763 $styleFiles = array_merge_recursive(
764 $styleFiles,
765 $this->getSkinStyleFiles( $internalSkinName )
766 );
767 }
768
769 return $styleFiles;
770 }
771
772 /**
773 * Returns all style files and all skin style files used by this module.
774 *
775 * @return array
776 */
777 public function getAllStyleFiles() {
778 $collatedStyleFiles = array_merge_recursive(
779 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
780 $this->getAllSkinStyleFiles()
781 );
782
783 $result = array();
784
785 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
786 foreach ( $styleFiles as $styleFile ) {
787 $result[] = $this->getLocalPath( $styleFile );
788 }
789 }
790
791 return $result;
792 }
793
794 /**
795 * Gets the contents of a list of JavaScript files.
796 *
797 * @param array $scripts List of file paths to scripts to read, remap and concetenate
798 * @throws MWException
799 * @return string Concatenated and remapped JavaScript data from $scripts
800 */
801 protected function readScriptFiles( array $scripts ) {
802 if ( empty( $scripts ) ) {
803 return '';
804 }
805 $js = '';
806 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
807 $localPath = $this->getLocalPath( $fileName );
808 if ( !file_exists( $localPath ) ) {
809 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
810 }
811 $contents = file_get_contents( $localPath );
812 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
813 // Static files don't really need to be checked as often; unlike
814 // on-wiki module they shouldn't change unexpectedly without
815 // admin interference.
816 $contents = $this->validateScriptFile( $fileName, $contents );
817 }
818 $js .= $contents . "\n";
819 }
820 return $js;
821 }
822
823 /**
824 * Gets the contents of a list of CSS files.
825 *
826 * @param array $styles List of media type/list of file paths pairs, to read, remap and
827 * concetenate
828 * @param bool $flip
829 * @param ResourceLoaderContext $context
830 *
831 * @throws MWException
832 * @return array List of concatenated and remapped CSS data from $styles,
833 * keyed by media type
834 *
835 * @since 1.27 Calling this method without a ResourceLoaderContext instance
836 * is deprecated.
837 */
838 public function readStyleFiles( array $styles, $flip, $context = null ) {
839 if ( $context === null ) {
840 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
841 $context = ResourceLoaderContext::newDummyContext();
842 }
843
844 if ( empty( $styles ) ) {
845 return array();
846 }
847 foreach ( $styles as $media => $files ) {
848 $uniqueFiles = array_unique( $files, SORT_REGULAR );
849 $styleFiles = array();
850 foreach ( $uniqueFiles as $file ) {
851 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
852 }
853 $styles[$media] = implode( "\n", $styleFiles );
854 }
855 return $styles;
856 }
857
858 /**
859 * Reads a style file.
860 *
861 * This method can be used as a callback for array_map()
862 *
863 * @param string $path File path of style file to read
864 * @param bool $flip
865 * @param ResourceLoaderContext $context
866 *
867 * @return string CSS data in script file
868 * @throws MWException If the file doesn't exist
869 */
870 protected function readStyleFile( $path, $flip, $context ) {
871 $localPath = $this->getLocalPath( $path );
872 $remotePath = $this->getRemotePath( $path );
873 if ( !file_exists( $localPath ) ) {
874 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
875 wfDebugLog( 'resourceloader', $msg );
876 throw new MWException( $msg );
877 }
878
879 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
880 $style = $this->compileLessFile( $localPath, $context );
881 $this->hasGeneratedStyles = true;
882 } else {
883 $style = file_get_contents( $localPath );
884 }
885
886 if ( $flip ) {
887 $style = CSSJanus::transform( $style, true, false );
888 }
889 $localDir = dirname( $localPath );
890 $remoteDir = dirname( $remotePath );
891 // Get and register local file references
892 $localFileRefs = CSSMin::getAllLocalFileReferences( $style, $localDir );
893 foreach ( $localFileRefs as $file ) {
894 if ( file_exists( $file ) ) {
895 $this->localFileRefs[] = $file;
896 } else {
897 $this->missingLocalFileRefs[] = $file;
898 }
899 }
900 return MemoizedCallable::call( 'CSSMin::remap',
901 array( $style, $localDir, $remoteDir, true ) );
902 }
903
904 /**
905 * Get whether CSS for this module should be flipped
906 * @param ResourceLoaderContext $context
907 * @return bool
908 */
909 public function getFlip( $context ) {
910 return $context->getDirection() === 'rtl';
911 }
912
913 /**
914 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
915 *
916 * @return array Array of strings
917 */
918 public function getTargets() {
919 return $this->targets;
920 }
921
922 /**
923 * Compile a LESS file into CSS.
924 *
925 * Keeps track of all used files and adds them to localFileRefs.
926 *
927 * @since 1.22
928 * @since 1.27 Added $context paramter.
929 * @throws Exception If less.php encounters a parse error
930 * @param string $fileName File path of LESS source
931 * @param ResourceLoaderContext $context Context in which to generate script
932 * @return string CSS source
933 */
934 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
935 static $cache;
936
937 if ( !$cache ) {
938 $cache = ObjectCache::newAccelerator( CACHE_ANYTHING );
939 }
940
941 // Construct a cache key from the LESS file name and a hash digest
942 // of the LESS variables used for compilation.
943 $vars = $this->getLessVars( $context );
944 ksort( $vars );
945 $varsHash = hash( 'md4', serialize( $vars ) );
946 $cacheKey = $cache->makeGlobalKey( 'LESS', $fileName, $varsHash );
947 $cachedCompile = $cache->get( $cacheKey );
948
949 // If we got a cached value, we have to validate it by getting a
950 // checksum of all the files that were loaded by the parser and
951 // ensuring it matches the cached entry's.
952 if ( isset( $cachedCompile['hash'] ) ) {
953 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
954 if ( $contentHash === $cachedCompile['hash'] ) {
955 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
956 return $cachedCompile['css'];
957 }
958 }
959
960 $compiler = ResourceLoader::getLessCompiler( $this->getConfig(), $vars );
961 $css = $compiler->parseFile( $fileName )->getCss();
962 $files = $compiler->AllParsedFiles();
963 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
964
965 $cache->set( $cacheKey, array(
966 'css' => $css,
967 'files' => $files,
968 'hash' => FileContentsHasher::getFileContentsHash( $files ),
969 ), 60 * 60 * 24 ); // 86400 seconds, or 24 hours.
970
971 return $css;
972 }
973
974 /**
975 * Takes named templates by the module and returns an array mapping.
976 * @return array of templates mapping template alias to content
977 * @throws MWException
978 */
979 public function getTemplates() {
980 $templates = array();
981
982 foreach ( $this->templates as $alias => $templatePath ) {
983 // Alias is optional
984 if ( is_int( $alias ) ) {
985 $alias = $templatePath;
986 }
987 $localPath = $this->getLocalPath( $templatePath );
988 if ( file_exists( $localPath ) ) {
989 $content = file_get_contents( $localPath );
990 $templates[$alias] = $content;
991 } else {
992 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
993 wfDebugLog( 'resourceloader', $msg );
994 throw new MWException( $msg );
995 }
996 }
997 return $templates;
998 }
999 }