Merge "Make "/*@noflip*/ /*@embed*/" annotation work"
[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 $wgScriptPath
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 $wgScriptPath
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 $wgScriptPath
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, $wgScriptPath, $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 $localBasePath = $localBasePath === null ? $IP : $localBasePath;
308 if ( $remoteBasePath === null ) {
309 $remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
310 }
311
312 if ( isset( $options['remoteExtPath'] ) ) {
313 global $wgExtensionAssetsPath;
314 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
315 }
316
317 if ( isset( $options['remoteSkinPath'] ) ) {
318 global $wgStylePath;
319 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
320 }
321
322 if ( array_key_exists( 'localBasePath', $options ) ) {
323 $localBasePath = (string)$options['localBasePath'];
324 }
325
326 if ( array_key_exists( 'remoteBasePath', $options ) ) {
327 $remoteBasePath = (string)$options['remoteBasePath'];
328 }
329
330 // Make sure the remote base path is a complete valid URL,
331 // but possibly protocol-relative to avoid cache pollution
332 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
333
334 return array( $localBasePath, $remoteBasePath );
335 }
336
337 /**
338 * Gets all scripts for a given context concatenated together.
339 *
340 * @param ResourceLoaderContext $context Context in which to generate script
341 * @return string JavaScript code for $context
342 */
343 public function getScript( ResourceLoaderContext $context ) {
344 $files = $this->getScriptFiles( $context );
345 return $this->readScriptFiles( $files );
346 }
347
348 /**
349 * @param ResourceLoaderContext $context
350 * @return array
351 */
352 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
353 $urls = array();
354 foreach ( $this->getScriptFiles( $context ) as $file ) {
355 $urls[] = $this->getRemotePath( $file );
356 }
357 return $urls;
358 }
359
360 /**
361 * @return bool
362 */
363 public function supportsURLLoading() {
364 return $this->debugRaw;
365 }
366
367 /**
368 * Get loader script.
369 *
370 * @return string|bool JavaScript code to be added to startup module
371 */
372 public function getLoaderScript() {
373 if ( count( $this->loaderScripts ) === 0 ) {
374 return false;
375 }
376 return $this->readScriptFiles( $this->loaderScripts );
377 }
378
379 /**
380 * Get all styles for a given context.
381 *
382 * @param ResourceLoaderContext $context
383 * @return array CSS code for $context as an associative array mapping media type to CSS text.
384 */
385 public function getStyles( ResourceLoaderContext $context ) {
386 $styles = $this->readStyleFiles(
387 $this->getStyleFiles( $context ),
388 $this->getFlip( $context )
389 );
390 // Collect referenced files
391 $this->localFileRefs = array_unique( $this->localFileRefs );
392 // If the list has been modified since last time we cached it, update the cache
393 try {
394 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
395 $dbw = wfGetDB( DB_MASTER );
396 $dbw->replace( 'module_deps',
397 array( array( 'md_module', 'md_skin' ) ), array(
398 'md_module' => $this->getName(),
399 'md_skin' => $context->getSkin(),
400 'md_deps' => FormatJson::encode( $this->localFileRefs ),
401 )
402 );
403 }
404 } catch ( Exception $e ) {
405 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
406 }
407 return $styles;
408 }
409
410 /**
411 * @param ResourceLoaderContext $context
412 * @return array
413 */
414 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
415 if ( $this->hasGeneratedStyles ) {
416 // Do the default behaviour of returning a url back to load.php
417 // but with only=styles.
418 return parent::getStyleURLsForDebug( $context );
419 }
420 // Our module consists entirely of real css files,
421 // in debug mode we can load those directly.
422 $urls = array();
423 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
424 $urls[$mediaType] = array();
425 foreach ( $list as $file ) {
426 $urls[$mediaType][] = $this->getRemotePath( $file );
427 }
428 }
429 return $urls;
430 }
431
432 /**
433 * Gets list of message keys used by this module.
434 *
435 * @return array List of message keys
436 */
437 public function getMessages() {
438 return $this->messages;
439 }
440
441 /**
442 * Gets the name of the group this module should be loaded in.
443 *
444 * @return string Group name
445 */
446 public function getGroup() {
447 return $this->group;
448 }
449
450 /**
451 * @return string
452 */
453 public function getPosition() {
454 return $this->position;
455 }
456
457 /**
458 * Gets list of names of modules this module depends on.
459 *
460 * @return array List of module names
461 */
462 public function getDependencies() {
463 return $this->dependencies;
464 }
465
466 /**
467 * Get the skip function.
468 *
469 * @return string|null
470 */
471 public function getSkipFunction() {
472 if ( !$this->skipFunction ) {
473 return null;
474 }
475
476 $localPath = $this->getLocalPath( $this->skipFunction );
477 if ( !file_exists( $localPath ) ) {
478 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
479 }
480 $contents = file_get_contents( $localPath );
481 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
482 $contents = $this->validateScriptFile( $localPath, $contents );
483 }
484 return $contents;
485 }
486
487 /**
488 * @return bool
489 */
490 public function isRaw() {
491 return $this->raw;
492 }
493
494 /**
495 * Get the last modified timestamp of this module.
496 *
497 * Last modified timestamps are calculated from the highest last modified
498 * timestamp of this module's constituent files as well as the files it
499 * depends on. This function is context-sensitive, only performing
500 * calculations on files relevant to the given language, skin and debug
501 * mode.
502 *
503 * @param ResourceLoaderContext $context Context in which to calculate
504 * the modified time
505 * @return int UNIX timestamp
506 * @see ResourceLoaderModule::getFileDependencies
507 */
508 public function getModifiedTime( ResourceLoaderContext $context ) {
509 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
510 return $this->modifiedTime[$context->getHash()];
511 }
512 wfProfileIn( __METHOD__ );
513
514 $files = array();
515
516 // Flatten style files into $files
517 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
518 foreach ( $styles as $styleFiles ) {
519 $files = array_merge( $files, $styleFiles );
520 }
521
522 $skinFiles = self::collateFilePathListByOption(
523 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
524 'media',
525 'all'
526 );
527 foreach ( $skinFiles as $styleFiles ) {
528 $files = array_merge( $files, $styleFiles );
529 }
530
531 // Final merge, this should result in a master list of dependent files
532 $files = array_merge(
533 $files,
534 $this->scripts,
535 $context->getDebug() ? $this->debugScripts : array(),
536 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
537 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
538 $this->loaderScripts
539 );
540 if ( $this->skipFunction ) {
541 $files[] = $this->skipFunction;
542 }
543 $files = array_map( array( $this, 'getLocalPath' ), $files );
544 // File deps need to be treated separately because they're already prefixed
545 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
546
547 // If a module is nothing but a list of dependencies, we need to avoid
548 // giving max() an empty array
549 if ( count( $files ) === 0 ) {
550 $this->modifiedTime[$context->getHash()] = 1;
551 wfProfileOut( __METHOD__ );
552 return $this->modifiedTime[$context->getHash()];
553 }
554
555 wfProfileIn( __METHOD__ . '-filemtime' );
556 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
557 wfProfileOut( __METHOD__ . '-filemtime' );
558
559 $this->modifiedTime[$context->getHash()] = max(
560 $filesMtime,
561 $this->getMsgBlobMtime( $context->getLanguage() ),
562 $this->getDefinitionMtime( $context )
563 );
564
565 wfProfileOut( __METHOD__ );
566 return $this->modifiedTime[$context->getHash()];
567 }
568
569 /**
570 * Get the definition summary for this module.
571 *
572 * @param ResourceLoaderContext $context
573 * @return array
574 */
575 public function getDefinitionSummary( ResourceLoaderContext $context ) {
576 $summary = array(
577 'class' => get_class( $this ),
578 );
579 foreach ( array(
580 'scripts',
581 'debugScripts',
582 'loaderScripts',
583 'styles',
584 'languageScripts',
585 'skinScripts',
586 'skinStyles',
587 'dependencies',
588 'messages',
589 'targets',
590 'group',
591 'position',
592 'skipFunction',
593 'localBasePath',
594 'remoteBasePath',
595 'debugRaw',
596 'raw',
597 ) as $member ) {
598 $summary[$member] = $this->{$member};
599 };
600 return $summary;
601 }
602
603 /* Protected Methods */
604
605 /**
606 * @param string|ResourceLoaderFilePath $path
607 * @return string
608 */
609 protected function getLocalPath( $path ) {
610 if ( $path instanceof ResourceLoaderFilePath ) {
611 return $path->getLocalPath();
612 }
613
614 return "{$this->localBasePath}/$path";
615 }
616
617 /**
618 * @param string|ResourceLoaderFilePath $path
619 * @return string
620 */
621 protected function getRemotePath( $path ) {
622 if ( $path instanceof ResourceLoaderFilePath ) {
623 return $path->getRemotePath();
624 }
625
626 return "{$this->remoteBasePath}/$path";
627 }
628
629 /**
630 * Infer the stylesheet language from a stylesheet file path.
631 *
632 * @since 1.22
633 * @param string $path
634 * @return string The stylesheet language name
635 */
636 public function getStyleSheetLang( $path ) {
637 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
638 }
639
640 /**
641 * Collates file paths by option (where provided).
642 *
643 * @param array $list List of file paths in any combination of index/path
644 * or path/options pairs
645 * @param string $option Option name
646 * @param mixed $default Default value if the option isn't set
647 * @return array List of file paths, collated by $option
648 */
649 protected static function collateFilePathListByOption( array $list, $option, $default ) {
650 $collatedFiles = array();
651 foreach ( (array)$list as $key => $value ) {
652 if ( is_int( $key ) ) {
653 // File name as the value
654 if ( !isset( $collatedFiles[$default] ) ) {
655 $collatedFiles[$default] = array();
656 }
657 $collatedFiles[$default][] = $value;
658 } elseif ( is_array( $value ) ) {
659 // File name as the key, options array as the value
660 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
661 if ( !isset( $collatedFiles[$optionValue] ) ) {
662 $collatedFiles[$optionValue] = array();
663 }
664 $collatedFiles[$optionValue][] = $key;
665 }
666 }
667 return $collatedFiles;
668 }
669
670 /**
671 * Get a list of element that match a key, optionally using a fallback key.
672 *
673 * @param array $list List of lists to select from
674 * @param string $key Key to look for in $map
675 * @param string $fallback Key to look for in $list if $key doesn't exist
676 * @return array List of elements from $map which matched $key or $fallback,
677 * or an empty list in case of no match
678 */
679 protected static function tryForKey( array $list, $key, $fallback = null ) {
680 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
681 return $list[$key];
682 } elseif ( is_string( $fallback )
683 && isset( $list[$fallback] )
684 && is_array( $list[$fallback] )
685 ) {
686 return $list[$fallback];
687 }
688 return array();
689 }
690
691 /**
692 * Get a list of file paths for all scripts in this module, in order of proper execution.
693 *
694 * @param ResourceLoaderContext $context
695 * @return array List of file paths
696 */
697 protected function getScriptFiles( ResourceLoaderContext $context ) {
698 $files = array_merge(
699 $this->scripts,
700 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
701 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
702 );
703 if ( $context->getDebug() ) {
704 $files = array_merge( $files, $this->debugScripts );
705 }
706
707 return array_unique( $files, SORT_REGULAR );
708 }
709
710 /**
711 * Get a list of file paths for all styles in this module, in order of proper inclusion.
712 *
713 * @param ResourceLoaderContext $context
714 * @return array List of file paths
715 */
716 public function getStyleFiles( ResourceLoaderContext $context ) {
717 return array_merge_recursive(
718 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
719 self::collateFilePathListByOption(
720 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
721 'media',
722 'all'
723 )
724 );
725 }
726
727 /**
728 * Gets a list of file paths for all skin styles in the module used by
729 * the skin.
730 *
731 * @param string $skinName The name of the skin
732 * @return array A list of file paths collated by media type
733 */
734 protected function getSkinStyleFiles( $skinName ) {
735 return self::collateFilePathListByOption(
736 self::tryForKey( $this->skinStyles, $skinName ),
737 'media',
738 'all'
739 );
740 }
741
742 /**
743 * Gets a list of file paths for all skin style files in the module,
744 * for all available skins.
745 *
746 * @return array A list of file paths collated by media type
747 */
748 protected function getAllSkinStyleFiles() {
749 $styleFiles = array();
750 $internalSkinNames = array_keys( Skin::getSkinNames() );
751 $internalSkinNames[] = 'default';
752
753 foreach ( $internalSkinNames as $internalSkinName ) {
754 $styleFiles = array_merge_recursive(
755 $styleFiles,
756 $this->getSkinStyleFiles( $internalSkinName )
757 );
758 }
759
760 return $styleFiles;
761 }
762
763 /**
764 * Returns all style files and all skin style files used by this module.
765 *
766 * @return array
767 */
768 public function getAllStyleFiles() {
769 $collatedStyleFiles = array_merge_recursive(
770 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
771 $this->getAllSkinStyleFiles()
772 );
773
774 $result = array();
775
776 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
777 foreach ( $styleFiles as $styleFile ) {
778 $result[] = $this->getLocalPath( $styleFile );
779 }
780 }
781
782 return $result;
783 }
784
785 /**
786 * Gets the contents of a list of JavaScript files.
787 *
788 * @param array $scripts List of file paths to scripts to read, remap and concetenate
789 * @throws MWException
790 * @return string Concatenated and remapped JavaScript data from $scripts
791 */
792 protected function readScriptFiles( array $scripts ) {
793 if ( empty( $scripts ) ) {
794 return '';
795 }
796 $js = '';
797 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
798 $localPath = $this->getLocalPath( $fileName );
799 if ( !file_exists( $localPath ) ) {
800 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
801 }
802 $contents = file_get_contents( $localPath );
803 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
804 // Static files don't really need to be checked as often; unlike
805 // on-wiki module they shouldn't change unexpectedly without
806 // admin interference.
807 $contents = $this->validateScriptFile( $fileName, $contents );
808 }
809 $js .= $contents . "\n";
810 }
811 return $js;
812 }
813
814 /**
815 * Gets the contents of a list of CSS files.
816 *
817 * @param array $styles List of media type/list of file paths pairs, to read, remap and
818 * concetenate
819 *
820 * @param bool $flip
821 *
822 * @throws MWException
823 * @return array List of concatenated and remapped CSS data from $styles,
824 * keyed by media type
825 */
826 public function readStyleFiles( array $styles, $flip ) {
827 if ( empty( $styles ) ) {
828 return array();
829 }
830 foreach ( $styles as $media => $files ) {
831 $uniqueFiles = array_unique( $files, SORT_REGULAR );
832 $styleFiles = array();
833 foreach ( $uniqueFiles as $file ) {
834 $styleFiles[] = $this->readStyleFile( $file, $flip );
835 }
836 $styles[$media] = implode( "\n", $styleFiles );
837 }
838 return $styles;
839 }
840
841 /**
842 * Reads a style file.
843 *
844 * This method can be used as a callback for array_map()
845 *
846 * @param string $path File path of style file to read
847 * @param bool $flip
848 *
849 * @return string CSS data in script file
850 * @throws MWException If the file doesn't exist
851 */
852 protected function readStyleFile( $path, $flip ) {
853 $localPath = $this->getLocalPath( $path );
854 $remotePath = $this->getRemotePath( $path );
855 if ( !file_exists( $localPath ) ) {
856 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
857 wfDebugLog( 'resourceloader', $msg );
858 throw new MWException( $msg );
859 }
860
861 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
862 $style = $this->compileLessFile( $localPath );
863 $this->hasGeneratedStyles = true;
864 } else {
865 $style = file_get_contents( $localPath );
866 }
867
868 if ( $flip ) {
869 $style = CSSJanus::transform( $style, true, false );
870 } else {
871 $style = CSSJanus::nullTransform( $style );
872 }
873 $localDir = dirname( $localPath );
874 $remoteDir = dirname( $remotePath );
875 // Get and register local file references
876 $this->localFileRefs = array_merge(
877 $this->localFileRefs,
878 CSSMin::getLocalFileReferences( $style, $localDir )
879 );
880 return CSSMin::remap(
881 $style, $localDir, $remoteDir, true
882 );
883 }
884
885 /**
886 * Get whether CSS for this module should be flipped
887 * @param ResourceLoaderContext $context
888 * @return bool
889 */
890 public function getFlip( $context ) {
891 return $context->getDirection() === 'rtl';
892 }
893
894 /**
895 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
896 *
897 * @return array Array of strings
898 */
899 public function getTargets() {
900 return $this->targets;
901 }
902
903 /**
904 * Compile a LESS file into CSS.
905 *
906 * Keeps track of all used files and adds them to localFileRefs.
907 *
908 * @since 1.22
909 * @throws Exception If lessc encounters a parse error
910 * @param string $fileName File path of LESS source
911 * @return string CSS source
912 */
913 protected function compileLessFile( $fileName ) {
914 $compiler = ResourceLoader::getLessCompiler( $this->getConfig() );
915 $result = $compiler->compileFile( $fileName );
916 $this->localFileRefs += array_keys( $compiler->allParsedFiles() );
917 return $result;
918 }
919 }