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