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