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