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