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