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