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