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