Merge "mediawiki.searchSuggest: Enable result caching"
[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( $options = array(), $localBasePath = null,
222 $remoteBasePath = null
223 ) {
224 global $IP, $wgScriptPath, $wgResourceBasePath;
225 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
226 if ( $remoteBasePath !== null ) {
227 $this->remoteBasePath = $remoteBasePath;
228 } else {
229 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
230 }
231
232 if ( isset( $options['remoteExtPath'] ) ) {
233 global $wgExtensionAssetsPath;
234 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
235 }
236
237 if ( isset( $options['remoteSkinPath'] ) ) {
238 global $wgStylePath;
239 $this->remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
240 }
241
242 foreach ( $options as $member => $option ) {
243 switch ( $member ) {
244 // Lists of file paths
245 case 'scripts':
246 case 'debugScripts':
247 case 'loaderScripts':
248 case 'styles':
249 $this->{$member} = (array)$option;
250 break;
251 // Collated lists of file paths
252 case 'languageScripts':
253 case 'skinScripts':
254 case 'skinStyles':
255 if ( !is_array( $option ) ) {
256 throw new MWException(
257 "Invalid collated file path list error. " .
258 "'$option' given, array expected."
259 );
260 }
261 foreach ( $option as $key => $value ) {
262 if ( !is_string( $key ) ) {
263 throw new MWException(
264 "Invalid collated file path list key error. " .
265 "'$key' given, string expected."
266 );
267 }
268 $this->{$member}[$key] = (array)$value;
269 }
270 break;
271 // Lists of strings
272 case 'dependencies':
273 case 'messages':
274 case 'targets':
275 // Normalise
276 $option = array_values( array_unique( (array)$option ) );
277 sort( $option );
278
279 $this->{$member} = $option;
280 break;
281 // Single strings
282 case 'group':
283 case 'position':
284 case 'localBasePath':
285 case 'remoteBasePath':
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 // Make sure the remote base path is a complete valid URL,
297 // but possibly protocol-relative to avoid cache pollution
298 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
299 }
300
301 /**
302 * Gets all scripts for a given context concatenated together.
303 *
304 * @param ResourceLoaderContext $context Context in which to generate script
305 * @return string JavaScript code for $context
306 */
307 public function getScript( ResourceLoaderContext $context ) {
308 $files = $this->getScriptFiles( $context );
309 return $this->readScriptFiles( $files );
310 }
311
312 /**
313 * @param ResourceLoaderContext $context
314 * @return array
315 */
316 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
317 $urls = array();
318 foreach ( $this->getScriptFiles( $context ) as $file ) {
319 $urls[] = $this->getRemotePath( $file );
320 }
321 return $urls;
322 }
323
324 /**
325 * @return bool
326 */
327 public function supportsURLLoading() {
328 return $this->debugRaw;
329 }
330
331 /**
332 * Get loader script.
333 *
334 * @return string|false JavaScript code to be added to startup module
335 */
336 public function getLoaderScript() {
337 if ( count( $this->loaderScripts ) === 0 ) {
338 return false;
339 }
340 return $this->readScriptFiles( $this->loaderScripts );
341 }
342
343 /**
344 * Get all styles for a given context.
345 *
346 * @param ResourceLoaderContext $context
347 * @return array CSS code for $context as an associative array mapping media type to CSS text.
348 */
349 public function getStyles( ResourceLoaderContext $context ) {
350 $styles = $this->readStyleFiles(
351 $this->getStyleFiles( $context ),
352 $this->getFlip( $context )
353 );
354 // Collect referenced files
355 $this->localFileRefs = array_unique( $this->localFileRefs );
356 // If the list has been modified since last time we cached it, update the cache
357 try {
358 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
359 $dbw = wfGetDB( DB_MASTER );
360 $dbw->replace( 'module_deps',
361 array( array( 'md_module', 'md_skin' ) ), array(
362 'md_module' => $this->getName(),
363 'md_skin' => $context->getSkin(),
364 'md_deps' => FormatJson::encode( $this->localFileRefs ),
365 )
366 );
367 }
368 } catch ( Exception $e ) {
369 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
370 }
371 return $styles;
372 }
373
374 /**
375 * @param ResourceLoaderContext $context
376 * @return array
377 */
378 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
379 if ( $this->hasGeneratedStyles ) {
380 // Do the default behaviour of returning a url back to load.php
381 // but with only=styles.
382 return parent::getStyleURLsForDebug( $context );
383 }
384 // Our module consists entirely of real css files,
385 // in debug mode we can load those directly.
386 $urls = array();
387 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
388 $urls[$mediaType] = array();
389 foreach ( $list as $file ) {
390 $urls[$mediaType][] = $this->getRemotePath( $file );
391 }
392 }
393 return $urls;
394 }
395
396 /**
397 * Gets list of message keys used by this module.
398 *
399 * @return array List of message keys
400 */
401 public function getMessages() {
402 return $this->messages;
403 }
404
405 /**
406 * Gets the name of the group this module should be loaded in.
407 *
408 * @return string Group name
409 */
410 public function getGroup() {
411 return $this->group;
412 }
413
414 /**
415 * @return string
416 */
417 public function getPosition() {
418 return $this->position;
419 }
420
421 /**
422 * Gets list of names of modules this module depends on.
423 *
424 * @return array List of module names
425 */
426 public function getDependencies() {
427 return $this->dependencies;
428 }
429
430 /**
431 * Get the skip function.
432 *
433 * @return string|null
434 */
435 public function getSkipFunction() {
436 if ( !$this->skipFunction ) {
437 return null;
438 }
439
440 global $wgResourceLoaderValidateStaticJS;
441 $localPath = $this->getLocalPath( $this->skipFunction );
442 if ( !file_exists( $localPath ) ) {
443 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
444 }
445 $contents = file_get_contents( $localPath );
446 if ( $wgResourceLoaderValidateStaticJS ) {
447 $contents = $this->validateScriptFile( $fileName, $contents );
448 }
449 return $contents;
450 }
451
452 /**
453 * @return bool
454 */
455 public function isRaw() {
456 return $this->raw;
457 }
458
459 /**
460 * Get the last modified timestamp of this module.
461 *
462 * Last modified timestamps are calculated from the highest last modified
463 * timestamp of this module's constituent files as well as the files it
464 * depends on. This function is context-sensitive, only performing
465 * calculations on files relevant to the given language, skin and debug
466 * mode.
467 *
468 * @param ResourceLoaderContext $context Context in which to calculate
469 * the modified time
470 * @return int UNIX timestamp
471 * @see ResourceLoaderModule::getFileDependencies
472 */
473 public function getModifiedTime( ResourceLoaderContext $context ) {
474 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
475 return $this->modifiedTime[$context->getHash()];
476 }
477 wfProfileIn( __METHOD__ );
478
479 $files = array();
480
481 // Flatten style files into $files
482 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
483 foreach ( $styles as $styleFiles ) {
484 $files = array_merge( $files, $styleFiles );
485 }
486
487 $skinFiles = self::collateFilePathListByOption(
488 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
489 'media',
490 'all'
491 );
492 foreach ( $skinFiles as $styleFiles ) {
493 $files = array_merge( $files, $styleFiles );
494 }
495
496 // Final merge, this should result in a master list of dependent files
497 $files = array_merge(
498 $files,
499 $this->scripts,
500 $context->getDebug() ? $this->debugScripts : array(),
501 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
502 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
503 $this->loaderScripts
504 );
505 if ( $this->skipFunction ) {
506 $files[] = $this->skipFunction;
507 }
508 $files = array_map( array( $this, 'getLocalPath' ), $files );
509 // File deps need to be treated separately because they're already prefixed
510 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
511
512 // If a module is nothing but a list of dependencies, we need to avoid
513 // giving max() an empty array
514 if ( count( $files ) === 0 ) {
515 $this->modifiedTime[$context->getHash()] = 1;
516 wfProfileOut( __METHOD__ );
517 return $this->modifiedTime[$context->getHash()];
518 }
519
520 wfProfileIn( __METHOD__ . '-filemtime' );
521 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
522 wfProfileOut( __METHOD__ . '-filemtime' );
523
524 $this->modifiedTime[$context->getHash()] = max(
525 $filesMtime,
526 $this->getMsgBlobMtime( $context->getLanguage() ),
527 $this->getDefinitionMtime( $context )
528 );
529
530 wfProfileOut( __METHOD__ );
531 return $this->modifiedTime[$context->getHash()];
532 }
533
534 /**
535 * Get the definition summary for this module.
536 *
537 * @return array
538 */
539 public function getDefinitionSummary( ResourceLoaderContext $context ) {
540 $summary = array(
541 'class' => get_class( $this ),
542 );
543 foreach ( array(
544 'scripts',
545 'debugScripts',
546 'loaderScripts',
547 'styles',
548 'languageScripts',
549 'skinScripts',
550 'skinStyles',
551 'dependencies',
552 'messages',
553 'targets',
554 'group',
555 'position',
556 'skipFunction',
557 'localBasePath',
558 'remoteBasePath',
559 'debugRaw',
560 'raw',
561 ) as $member ) {
562 $summary[$member] = $this->{$member};
563 };
564 return $summary;
565 }
566
567 /* Protected Methods */
568
569 /**
570 * @param string $path
571 * @return string
572 */
573 protected function getLocalPath( $path ) {
574 return "{$this->localBasePath}/$path";
575 }
576
577 /**
578 * @param string $path
579 * @return string
580 */
581 protected function getRemotePath( $path ) {
582 return "{$this->remoteBasePath}/$path";
583 }
584
585 /**
586 * Infer the stylesheet language from a stylesheet file path.
587 *
588 * @since 1.22
589 * @param string $path
590 * @return string The stylesheet language name
591 */
592 public function getStyleSheetLang( $path ) {
593 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
594 }
595
596 /**
597 * Collates file paths by option (where provided).
598 *
599 * @param array $list List of file paths in any combination of index/path
600 * or path/options pairs
601 * @param string $option Option name
602 * @param mixed $default Default value if the option isn't set
603 * @return array List of file paths, collated by $option
604 */
605 protected static function collateFilePathListByOption( array $list, $option, $default ) {
606 $collatedFiles = array();
607 foreach ( (array)$list as $key => $value ) {
608 if ( is_int( $key ) ) {
609 // File name as the value
610 if ( !isset( $collatedFiles[$default] ) ) {
611 $collatedFiles[$default] = array();
612 }
613 $collatedFiles[$default][] = $value;
614 } elseif ( is_array( $value ) ) {
615 // File name as the key, options array as the value
616 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
617 if ( !isset( $collatedFiles[$optionValue] ) ) {
618 $collatedFiles[$optionValue] = array();
619 }
620 $collatedFiles[$optionValue][] = $key;
621 }
622 }
623 return $collatedFiles;
624 }
625
626 /**
627 * Get a list of element that match a key, optionally using a fallback key.
628 *
629 * @param array $list List of lists to select from
630 * @param string $key Key to look for in $map
631 * @param string $fallback Key to look for in $list if $key doesn't exist
632 * @return array List of elements from $map which matched $key or $fallback,
633 * or an empty list in case of no match
634 */
635 protected static function tryForKey( array $list, $key, $fallback = null ) {
636 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
637 return $list[$key];
638 } elseif ( is_string( $fallback )
639 && isset( $list[$fallback] )
640 && is_array( $list[$fallback] )
641 ) {
642 return $list[$fallback];
643 }
644 return array();
645 }
646
647 /**
648 * Get a list of file paths for all scripts in this module, in order of proper execution.
649 *
650 * @param ResourceLoaderContext $context
651 * @return array List of file paths
652 */
653 protected function getScriptFiles( ResourceLoaderContext $context ) {
654 $files = array_merge(
655 $this->scripts,
656 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
657 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
658 );
659 if ( $context->getDebug() ) {
660 $files = array_merge( $files, $this->debugScripts );
661 }
662
663 return array_unique( $files );
664 }
665
666 /**
667 * Get a list of file paths for all styles in this module, in order of proper inclusion.
668 *
669 * @param ResourceLoaderContext $context
670 * @return array List of file paths
671 */
672 public function getStyleFiles( ResourceLoaderContext $context ) {
673 return array_merge_recursive(
674 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
675 self::collateFilePathListByOption(
676 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
677 'media',
678 'all'
679 )
680 );
681 }
682
683 /**
684 * Gets a list of file paths for all skin styles in the module used by
685 * the skin.
686 *
687 * @param string $skinName The name of the skin
688 * @return array A list of file paths collated by media type
689 */
690 protected function getSkinStyleFiles( $skinName ) {
691 return self::collateFilePathListByOption(
692 self::tryForKey( $this->skinStyles, $skinName ),
693 'media',
694 'all'
695 );
696 }
697
698 /**
699 * Gets a list of file paths for all skin style files in the module,
700 * for all available skins.
701 *
702 * @return array A list of file paths collated by media type
703 */
704 protected function getAllSkinStyleFiles() {
705 $styleFiles = array();
706 $internalSkinNames = array_keys( Skin::getSkinNames() );
707 $internalSkinNames[] = 'default';
708
709 foreach ( $internalSkinNames as $internalSkinName ) {
710 $styleFiles = array_merge_recursive(
711 $styleFiles,
712 $this->getSkinStyleFiles( $internalSkinName )
713 );
714 }
715
716 return $styleFiles;
717 }
718
719 /**
720 * Returns all style files and all skin style files used by this module.
721 *
722 * @return array
723 */
724 public function getAllStyleFiles() {
725 $collatedStyleFiles = array_merge_recursive(
726 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
727 $this->getAllSkinStyleFiles()
728 );
729
730 $result = array();
731
732 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
733 foreach ( $styleFiles as $styleFile ) {
734 $result[] = $this->getLocalPath( $styleFile );
735 }
736 }
737
738 return $result;
739 }
740
741 /**
742 * Gets the contents of a list of JavaScript files.
743 *
744 * @param array $scripts List of file paths to scripts to read, remap and concetenate
745 * @throws MWException
746 * @return string Concatenated and remapped JavaScript data from $scripts
747 */
748 protected function readScriptFiles( array $scripts ) {
749 global $wgResourceLoaderValidateStaticJS;
750 if ( empty( $scripts ) ) {
751 return '';
752 }
753 $js = '';
754 foreach ( array_unique( $scripts ) as $fileName ) {
755 $localPath = $this->getLocalPath( $fileName );
756 if ( !file_exists( $localPath ) ) {
757 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
758 }
759 $contents = file_get_contents( $localPath );
760 if ( $wgResourceLoaderValidateStaticJS ) {
761 // Static files don't really need to be checked as often; unlike
762 // on-wiki module they shouldn't change unexpectedly without
763 // admin interference.
764 $contents = $this->validateScriptFile( $fileName, $contents );
765 }
766 $js .= $contents . "\n";
767 }
768 return $js;
769 }
770
771 /**
772 * Gets the contents of a list of CSS files.
773 *
774 * @param array $styles List of media type/list of file paths pairs, to read, remap and
775 * concetenate
776 *
777 * @param bool $flip
778 *
779 * @throws MWException
780 * @return array List of concatenated and remapped CSS data from $styles,
781 * keyed by media type
782 */
783 public function readStyleFiles( array $styles, $flip ) {
784 if ( empty( $styles ) ) {
785 return array();
786 }
787 foreach ( $styles as $media => $files ) {
788 $uniqueFiles = array_unique( $files );
789 $styleFiles = array();
790 foreach ( $uniqueFiles as $file ) {
791 $styleFiles[] = $this->readStyleFile( $file, $flip );
792 }
793 $styles[$media] = implode( "\n", $styleFiles );
794 }
795 return $styles;
796 }
797
798 /**
799 * Reads a style file.
800 *
801 * This method can be used as a callback for array_map()
802 *
803 * @param string $path File path of style file to read
804 * @param bool $flip
805 *
806 * @return string CSS data in script file
807 * @throws MWException if the file doesn't exist
808 */
809 protected function readStyleFile( $path, $flip ) {
810 $localPath = $this->getLocalPath( $path );
811 if ( !file_exists( $localPath ) ) {
812 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
813 wfDebugLog( 'resourceloader', $msg );
814 throw new MWException( $msg );
815 }
816
817 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
818 $style = $this->compileLESSFile( $localPath );
819 $this->hasGeneratedStyles = true;
820 } else {
821 $style = file_get_contents( $localPath );
822 }
823
824 if ( $flip ) {
825 $style = CSSJanus::transform( $style, true, false );
826 }
827 $dirname = dirname( $path );
828 if ( $dirname == '.' ) {
829 // If $path doesn't have a directory component, don't prepend a dot
830 $dirname = '';
831 }
832 $dir = $this->getLocalPath( $dirname );
833 $remoteDir = $this->getRemotePath( $dirname );
834 // Get and register local file references
835 $this->localFileRefs = array_merge(
836 $this->localFileRefs,
837 CSSMin::getLocalFileReferences( $style, $dir )
838 );
839 return CSSMin::remap(
840 $style, $dir, $remoteDir, true
841 );
842 }
843
844 /**
845 * Get whether CSS for this module should be flipped
846 * @param ResourceLoaderContext $context
847 * @return bool
848 */
849 public function getFlip( $context ) {
850 return $context->getDirection() === 'rtl';
851 }
852
853 /**
854 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
855 *
856 * @return array Array of strings
857 */
858 public function getTargets() {
859 return $this->targets;
860 }
861
862 /**
863 * Generate a cache key for a LESS file.
864 *
865 * The cache key varies on the file name and the names and values of global
866 * LESS variables.
867 *
868 * @since 1.22
869 * @param string $fileName File name of root LESS file.
870 * @return string Cache key
871 */
872 protected static function getLESSCacheKey( $fileName ) {
873 $vars = json_encode( ResourceLoader::getLESSVars() );
874 $hash = md5( $fileName . $vars );
875 return wfMemcKey( 'resourceloader', 'less', $hash );
876 }
877
878 /**
879 * Compile a LESS file into CSS.
880 *
881 * If invalid, returns replacement CSS source consisting of the compilation
882 * error message encoded as a comment. To save work, we cache a result object
883 * which comprises the compiled CSS and the names & mtimes of the files
884 * that were processed. lessphp compares the cached & current mtimes and
885 * recompiles as necessary.
886 *
887 * @since 1.22
888 * @throws Exception If Less encounters a parse error
889 * @throws MWException If Less compilation returns unexpection result
890 * @param string $fileName File path of LESS source
891 * @return string CSS source
892 */
893 protected function compileLESSFile( $fileName ) {
894 $key = self::getLESSCacheKey( $fileName );
895 $cache = wfGetCache( CACHE_ANYTHING );
896
897 // The input to lessc. Either an associative array representing the
898 // cached results of a previous compilation, or the string file name if
899 // no cache result exists.
900 $source = $cache->get( $key );
901 if ( !is_array( $source ) || !isset( $source['root'] ) ) {
902 $source = $fileName;
903 }
904
905 $compiler = ResourceLoader::getLessCompiler();
906 $result = null;
907
908 $result = $compiler->cachedCompile( $source );
909
910 if ( !is_array( $result ) ) {
911 throw new MWException( 'LESS compiler result has type '
912 . gettype( $result ) . '; array expected.' );
913 }
914
915 $this->localFileRefs += array_keys( $result['files'] );
916 $cache->set( $key, $result );
917 return $result['compiled'];
918 }
919 }