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