Make travis notifications go to #mediawiki-feed
[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( $fileName, $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 * @return array
573 */
574 public function getDefinitionSummary( ResourceLoaderContext $context ) {
575 $summary = array(
576 'class' => get_class( $this ),
577 );
578 foreach ( array(
579 'scripts',
580 'debugScripts',
581 'loaderScripts',
582 'styles',
583 'languageScripts',
584 'skinScripts',
585 'skinStyles',
586 'dependencies',
587 'messages',
588 'targets',
589 'group',
590 'position',
591 'skipFunction',
592 'localBasePath',
593 'remoteBasePath',
594 'debugRaw',
595 'raw',
596 ) as $member ) {
597 $summary[$member] = $this->{$member};
598 };
599 return $summary;
600 }
601
602 /* Protected Methods */
603
604 /**
605 * @param string|ResourceLoaderFilePath $path
606 * @return string
607 */
608 protected function getLocalPath( $path ) {
609 if ( $path instanceof ResourceLoaderFilePath ) {
610 return $path->getLocalPath();
611 }
612
613 return "{$this->localBasePath}/$path";
614 }
615
616 /**
617 * @param string|ResourceLoaderFilePath $path
618 * @return string
619 */
620 protected function getRemotePath( $path ) {
621 if ( $path instanceof ResourceLoaderFilePath ) {
622 return $path->getRemotePath();
623 }
624
625 return "{$this->remoteBasePath}/$path";
626 }
627
628 /**
629 * Infer the stylesheet language from a stylesheet file path.
630 *
631 * @since 1.22
632 * @param string $path
633 * @return string The stylesheet language name
634 */
635 public function getStyleSheetLang( $path ) {
636 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
637 }
638
639 /**
640 * Collates file paths by option (where provided).
641 *
642 * @param array $list List of file paths in any combination of index/path
643 * or path/options pairs
644 * @param string $option Option name
645 * @param mixed $default Default value if the option isn't set
646 * @return array List of file paths, collated by $option
647 */
648 protected static function collateFilePathListByOption( array $list, $option, $default ) {
649 $collatedFiles = array();
650 foreach ( (array)$list as $key => $value ) {
651 if ( is_int( $key ) ) {
652 // File name as the value
653 if ( !isset( $collatedFiles[$default] ) ) {
654 $collatedFiles[$default] = array();
655 }
656 $collatedFiles[$default][] = $value;
657 } elseif ( is_array( $value ) ) {
658 // File name as the key, options array as the value
659 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
660 if ( !isset( $collatedFiles[$optionValue] ) ) {
661 $collatedFiles[$optionValue] = array();
662 }
663 $collatedFiles[$optionValue][] = $key;
664 }
665 }
666 return $collatedFiles;
667 }
668
669 /**
670 * Get a list of element that match a key, optionally using a fallback key.
671 *
672 * @param array $list List of lists to select from
673 * @param string $key Key to look for in $map
674 * @param string $fallback Key to look for in $list if $key doesn't exist
675 * @return array List of elements from $map which matched $key or $fallback,
676 * or an empty list in case of no match
677 */
678 protected static function tryForKey( array $list, $key, $fallback = null ) {
679 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
680 return $list[$key];
681 } elseif ( is_string( $fallback )
682 && isset( $list[$fallback] )
683 && is_array( $list[$fallback] )
684 ) {
685 return $list[$fallback];
686 }
687 return array();
688 }
689
690 /**
691 * Get a list of file paths for all scripts in this module, in order of proper execution.
692 *
693 * @param ResourceLoaderContext $context
694 * @return array List of file paths
695 */
696 protected function getScriptFiles( ResourceLoaderContext $context ) {
697 $files = array_merge(
698 $this->scripts,
699 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
700 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
701 );
702 if ( $context->getDebug() ) {
703 $files = array_merge( $files, $this->debugScripts );
704 }
705
706 return array_unique( $files, SORT_REGULAR );
707 }
708
709 /**
710 * Get a list of file paths for all styles in this module, in order of proper inclusion.
711 *
712 * @param ResourceLoaderContext $context
713 * @return array List of file paths
714 */
715 public function getStyleFiles( ResourceLoaderContext $context ) {
716 return array_merge_recursive(
717 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
718 self::collateFilePathListByOption(
719 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
720 'media',
721 'all'
722 )
723 );
724 }
725
726 /**
727 * Gets a list of file paths for all skin styles in the module used by
728 * the skin.
729 *
730 * @param string $skinName The name of the skin
731 * @return array A list of file paths collated by media type
732 */
733 protected function getSkinStyleFiles( $skinName ) {
734 return self::collateFilePathListByOption(
735 self::tryForKey( $this->skinStyles, $skinName ),
736 'media',
737 'all'
738 );
739 }
740
741 /**
742 * Gets a list of file paths for all skin style files in the module,
743 * for all available skins.
744 *
745 * @return array A list of file paths collated by media type
746 */
747 protected function getAllSkinStyleFiles() {
748 $styleFiles = array();
749 $internalSkinNames = array_keys( Skin::getSkinNames() );
750 $internalSkinNames[] = 'default';
751
752 foreach ( $internalSkinNames as $internalSkinName ) {
753 $styleFiles = array_merge_recursive(
754 $styleFiles,
755 $this->getSkinStyleFiles( $internalSkinName )
756 );
757 }
758
759 return $styleFiles;
760 }
761
762 /**
763 * Returns all style files and all skin style files used by this module.
764 *
765 * @return array
766 */
767 public function getAllStyleFiles() {
768 $collatedStyleFiles = array_merge_recursive(
769 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
770 $this->getAllSkinStyleFiles()
771 );
772
773 $result = array();
774
775 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
776 foreach ( $styleFiles as $styleFile ) {
777 $result[] = $this->getLocalPath( $styleFile );
778 }
779 }
780
781 return $result;
782 }
783
784 /**
785 * Gets the contents of a list of JavaScript files.
786 *
787 * @param array $scripts List of file paths to scripts to read, remap and concetenate
788 * @throws MWException
789 * @return string Concatenated and remapped JavaScript data from $scripts
790 */
791 protected function readScriptFiles( array $scripts ) {
792 if ( empty( $scripts ) ) {
793 return '';
794 }
795 $js = '';
796 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
797 $localPath = $this->getLocalPath( $fileName );
798 if ( !file_exists( $localPath ) ) {
799 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
800 }
801 $contents = file_get_contents( $localPath );
802 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
803 // Static files don't really need to be checked as often; unlike
804 // on-wiki module they shouldn't change unexpectedly without
805 // admin interference.
806 $contents = $this->validateScriptFile( $fileName, $contents );
807 }
808 $js .= $contents . "\n";
809 }
810 return $js;
811 }
812
813 /**
814 * Gets the contents of a list of CSS files.
815 *
816 * @param array $styles List of media type/list of file paths pairs, to read, remap and
817 * concetenate
818 *
819 * @param bool $flip
820 *
821 * @throws MWException
822 * @return array List of concatenated and remapped CSS data from $styles,
823 * keyed by media type
824 */
825 public function readStyleFiles( array $styles, $flip ) {
826 if ( empty( $styles ) ) {
827 return array();
828 }
829 foreach ( $styles as $media => $files ) {
830 $uniqueFiles = array_unique( $files, SORT_REGULAR );
831 $styleFiles = array();
832 foreach ( $uniqueFiles as $file ) {
833 $styleFiles[] = $this->readStyleFile( $file, $flip );
834 }
835 $styles[$media] = implode( "\n", $styleFiles );
836 }
837 return $styles;
838 }
839
840 /**
841 * Reads a style file.
842 *
843 * This method can be used as a callback for array_map()
844 *
845 * @param string $path File path of style file to read
846 * @param bool $flip
847 *
848 * @return string CSS data in script file
849 * @throws MWException If the file doesn't exist
850 */
851 protected function readStyleFile( $path, $flip ) {
852 $localPath = $this->getLocalPath( $path );
853 $remotePath = $this->getRemotePath( $path );
854 if ( !file_exists( $localPath ) ) {
855 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
856 wfDebugLog( 'resourceloader', $msg );
857 throw new MWException( $msg );
858 }
859
860 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
861 $style = $this->compileLESSFile( $localPath );
862 $this->hasGeneratedStyles = true;
863 } else {
864 $style = file_get_contents( $localPath );
865 }
866
867 if ( $flip ) {
868 $style = CSSJanus::transform( $style, true, false );
869 }
870 $localDir = dirname( $localPath );
871 $remoteDir = dirname( $remotePath );
872 // Get and register local file references
873 $this->localFileRefs = array_merge(
874 $this->localFileRefs,
875 CSSMin::getLocalFileReferences( $style, $localDir )
876 );
877 return CSSMin::remap(
878 $style, $localDir, $remoteDir, true
879 );
880 }
881
882 /**
883 * Get whether CSS for this module should be flipped
884 * @param ResourceLoaderContext $context
885 * @return bool
886 */
887 public function getFlip( $context ) {
888 return $context->getDirection() === 'rtl';
889 }
890
891 /**
892 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
893 *
894 * @return array Array of strings
895 */
896 public function getTargets() {
897 return $this->targets;
898 }
899
900 /**
901 * Generate a cache key for a LESS file.
902 *
903 * The cache key varies on the file name and the names and values of global
904 * LESS variables.
905 *
906 * @since 1.22
907 * @param string $fileName File name of root LESS file.
908 * @return string Cache key
909 */
910 protected function getLESSCacheKey( $fileName ) {
911 $vars = json_encode( ResourceLoader::getLESSVars( $this->getConfig() ) );
912 $hash = md5( $fileName . $vars );
913 return wfMemcKey( 'resourceloader', 'less', $hash );
914 }
915
916 /**
917 * Compile a LESS file into CSS.
918 *
919 * If invalid, returns replacement CSS source consisting of the compilation
920 * error message encoded as a comment. To save work, we cache a result object
921 * which comprises the compiled CSS and the names & mtimes of the files
922 * that were processed. lessphp compares the cached & current mtimes and
923 * recompiles as necessary.
924 *
925 * @since 1.22
926 * @throws Exception If Less encounters a parse error
927 * @throws MWException If Less compilation returns unexpection result
928 * @param string $fileName File path of LESS source
929 * @return string CSS source
930 */
931 protected function compileLESSFile( $fileName ) {
932 $key = $this->getLESSCacheKey( $fileName );
933 $cache = wfGetCache( CACHE_ANYTHING );
934
935 // The input to lessc. Either an associative array representing the
936 // cached results of a previous compilation, or the string file name if
937 // no cache result exists.
938 $source = $cache->get( $key );
939 if ( !is_array( $source ) || !isset( $source['root'] ) ) {
940 $source = $fileName;
941 }
942
943 $compiler = ResourceLoader::getLessCompiler( $this->getConfig() );
944 $result = null;
945
946 $result = $compiler->cachedCompile( $source );
947
948 if ( !is_array( $result ) ) {
949 throw new MWException( 'LESS compiler result has type '
950 . gettype( $result ) . '; array expected.' );
951 }
952
953 $this->localFileRefs += array_keys( $result['files'] );
954 $cache->set( $key, $result );
955 return $result['compiled'];
956 }
957 }