Merge "Add SVG versions of enhanced recent changes collapse/show arrows"
[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
30 /* Protected Members */
31
32 /** String: Local base path, see __construct() */
33 protected $localBasePath = '';
34 /** String: Remote base path, see __construct() */
35 protected $remoteBasePath = '';
36 /**
37 * Array: List of paths to JavaScript files to always include
38 * @par Usage:
39 * @code
40 * array( [file-path], [file-path], ... )
41 * @endcode
42 */
43 protected $scripts = array();
44 /**
45 * Array: List of JavaScript files to include when using a specific language
46 * @par Usage:
47 * @code
48 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
49 * @endcode
50 */
51 protected $languageScripts = array();
52 /**
53 * Array: List of JavaScript files to include when using a specific skin
54 * @par Usage:
55 * @code
56 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
57 * @endcode
58 */
59 protected $skinScripts = array();
60 /**
61 * Array: List of paths to JavaScript files to include in debug mode
62 * @par Usage:
63 * @code
64 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
65 * @endcode
66 */
67 protected $debugScripts = array();
68 /**
69 * Array: List of paths to JavaScript files to include in the startup module
70 * @par Usage:
71 * @code
72 * array( [file-path], [file-path], ... )
73 * @endcode
74 */
75 protected $loaderScripts = array();
76 /**
77 * Array: List of paths to CSS files to always include
78 * @par Usage:
79 * @code
80 * array( [file-path], [file-path], ... )
81 * @endcode
82 */
83 protected $styles = array();
84 /**
85 * Array: List of paths to CSS files to include when using specific skins
86 * @par Usage:
87 * @code
88 * array( [file-path], [file-path], ... )
89 * @endcode
90 */
91 protected $skinStyles = array();
92 /**
93 * Array: List of modules this module depends on
94 * @par Usage:
95 * @code
96 * array( [file-path], [file-path], ... )
97 * @endcode
98 */
99 protected $dependencies = array();
100 /**
101 * Array: List of message keys used by this module
102 * @par Usage:
103 * @code
104 * array( [message-key], [message-key], ... )
105 * @endcode
106 */
107 protected $messages = array();
108 /** String: Name of group to load this module in */
109 protected $group;
110 /** String: Position on the page to load this module at */
111 protected $position = 'bottom';
112 /** Boolean: Link to raw files in debug mode */
113 protected $debugRaw = true;
114 /** Boolean: Whether mw.loader.state() call should be omitted */
115 protected $raw = false;
116 protected $targets = array( 'desktop' );
117
118 /**
119 * Boolean: Whether getStyleURLsForDebug should return raw file paths,
120 * or return load.php urls
121 */
122 protected $hasGeneratedStyles = false;
123
124 /**
125 * Array: Cache for mtime
126 * @par Usage:
127 * @code
128 * array( [hash] => [mtime], [hash] => [mtime], ... )
129 * @endcode
130 */
131 protected $modifiedTime = array();
132 /**
133 * Array: Place where readStyleFile() tracks file dependencies
134 * @par Usage:
135 * @code
136 * array( [file-path], [file-path], ... )
137 * @endcode
138 */
139 protected $localFileRefs = array();
140
141 /* Methods */
142
143 /**
144 * Constructs a new module from an options array.
145 *
146 * @param array $options List of options; if not given or empty, an empty module will be
147 * constructed
148 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
149 * to $IP
150 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
151 * to $wgScriptPath
152 *
153 * Below is a description for the $options array:
154 * @throws MWException
155 * @par Construction options:
156 * @code
157 * array(
158 * // Base path to prepend to all local paths in $options. Defaults to $IP
159 * 'localBasePath' => [base path],
160 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
161 * 'remoteBasePath' => [base path],
162 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
163 * 'remoteExtPath' => [base path],
164 * // Scripts to always include
165 * 'scripts' => [file path string or array of file path strings],
166 * // Scripts to include in specific language contexts
167 * 'languageScripts' => array(
168 * [language code] => [file path string or array of file path strings],
169 * ),
170 * // Scripts to include in specific skin contexts
171 * 'skinScripts' => array(
172 * [skin name] => [file path string or array of file path strings],
173 * ),
174 * // Scripts to include in debug contexts
175 * 'debugScripts' => [file path string or array of file path strings],
176 * // Scripts to include in the startup module
177 * 'loaderScripts' => [file path string or array of file path strings],
178 * // Modules which must be loaded before this module
179 * 'dependencies' => [module name string or array of module name strings],
180 * // Styles to always load
181 * 'styles' => [file path string or array of file path strings],
182 * // Styles to include in specific skin contexts
183 * 'skinStyles' => array(
184 * [skin name] => [file path string or array of file path strings],
185 * ),
186 * // Messages to always load
187 * 'messages' => [array of message key strings],
188 * // Group which this module should be loaded together with
189 * 'group' => [group name string],
190 * // Position on the page to load this module at
191 * 'position' => ['bottom' (default) or 'top']
192 * )
193 * @endcode
194 */
195 public function __construct( $options = array(), $localBasePath = null,
196 $remoteBasePath = null
197 ) {
198 global $IP, $wgScriptPath, $wgResourceBasePath;
199 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
200 if ( $remoteBasePath !== null ) {
201 $this->remoteBasePath = $remoteBasePath;
202 } else {
203 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
204 }
205
206 if ( isset( $options['remoteExtPath'] ) ) {
207 global $wgExtensionAssetsPath;
208 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
209 }
210
211 foreach ( $options as $member => $option ) {
212 switch ( $member ) {
213 // Lists of file paths
214 case 'scripts':
215 case 'debugScripts':
216 case 'loaderScripts':
217 case 'styles':
218 $this->{$member} = (array)$option;
219 break;
220 // Collated lists of file paths
221 case 'languageScripts':
222 case 'skinScripts':
223 case 'skinStyles':
224 if ( !is_array( $option ) ) {
225 throw new MWException(
226 "Invalid collated file path list error. " .
227 "'$option' given, array expected."
228 );
229 }
230 foreach ( $option as $key => $value ) {
231 if ( !is_string( $key ) ) {
232 throw new MWException(
233 "Invalid collated file path list key error. " .
234 "'$key' given, string expected."
235 );
236 }
237 $this->{$member}[$key] = (array)$value;
238 }
239 break;
240 // Lists of strings
241 case 'dependencies':
242 case 'messages':
243 case 'targets':
244 // Normalise
245 $option = array_values( array_unique( (array)$option ) );
246 sort( $option );
247
248 $this->{$member} = $option;
249 break;
250 // Single strings
251 case 'group':
252 case 'position':
253 case 'localBasePath':
254 case 'remoteBasePath':
255 $this->{$member} = (string)$option;
256 break;
257 // Single booleans
258 case 'debugRaw':
259 case 'raw':
260 $this->{$member} = (bool)$option;
261 break;
262 }
263 }
264 // Make sure the remote base path is a complete valid URL,
265 // but possibly protocol-relative to avoid cache pollution
266 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
267 }
268
269 /**
270 * Gets all scripts for a given context concatenated together.
271 *
272 * @param ResourceLoaderContext $context Context in which to generate script
273 * @return string: JavaScript code for $context
274 */
275 public function getScript( ResourceLoaderContext $context ) {
276 $files = $this->getScriptFiles( $context );
277 return $this->readScriptFiles( $files );
278 }
279
280 /**
281 * @param ResourceLoaderContext $context
282 * @return array
283 */
284 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
285 $urls = array();
286 foreach ( $this->getScriptFiles( $context ) as $file ) {
287 $urls[] = $this->getRemotePath( $file );
288 }
289 return $urls;
290 }
291
292 /**
293 * @return bool
294 */
295 public function supportsURLLoading() {
296 return $this->debugRaw;
297 }
298
299 /**
300 * Gets loader script.
301 *
302 * @return string: JavaScript code to be added to startup module
303 */
304 public function getLoaderScript() {
305 if ( count( $this->loaderScripts ) == 0 ) {
306 return false;
307 }
308 return $this->readScriptFiles( $this->loaderScripts );
309 }
310
311 /**
312 * Gets all styles for a given context concatenated together.
313 *
314 * @param ResourceLoaderContext $context Context in which to generate styles
315 * @return string: CSS code for $context
316 */
317 public function getStyles( ResourceLoaderContext $context ) {
318 $styles = $this->readStyleFiles(
319 $this->getStyleFiles( $context ),
320 $this->getFlip( $context )
321 );
322 // Collect referenced files
323 $this->localFileRefs = array_unique( $this->localFileRefs );
324 // If the list has been modified since last time we cached it, update the cache
325 try {
326 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
327 $dbw = wfGetDB( DB_MASTER );
328 $dbw->replace( 'module_deps',
329 array( array( 'md_module', 'md_skin' ) ), array(
330 'md_module' => $this->getName(),
331 'md_skin' => $context->getSkin(),
332 'md_deps' => FormatJson::encode( $this->localFileRefs ),
333 )
334 );
335 }
336 } catch ( Exception $e ) {
337 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
338 }
339 return $styles;
340 }
341
342 /**
343 * @param ResourceLoaderContext $context
344 * @return array
345 */
346 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
347 if ( $this->hasGeneratedStyles ) {
348 // Do the default behaviour of returning a url back to load.php
349 // but with only=styles.
350 return parent::getStyleURLsForDebug( $context );
351 }
352 // Our module consists entirely of real css files,
353 // in debug mode we can load those directly.
354 $urls = array();
355 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
356 $urls[$mediaType] = array();
357 foreach ( $list as $file ) {
358 $urls[$mediaType][] = $this->getRemotePath( $file );
359 }
360 }
361 return $urls;
362 }
363
364 /**
365 * Gets list of message keys used by this module.
366 *
367 * @return array: List of message keys
368 */
369 public function getMessages() {
370 return $this->messages;
371 }
372
373 /**
374 * Gets the name of the group this module should be loaded in.
375 *
376 * @return string: Group name
377 */
378 public function getGroup() {
379 return $this->group;
380 }
381
382 /**
383 * @return string
384 */
385 public function getPosition() {
386 return $this->position;
387 }
388
389 /**
390 * Gets list of names of modules this module depends on.
391 *
392 * @return array: List of module names
393 */
394 public function getDependencies() {
395 return $this->dependencies;
396 }
397
398 /**
399 * @return bool
400 */
401 public function isRaw() {
402 return $this->raw;
403 }
404
405 /**
406 * Get the last modified timestamp of this module.
407 *
408 * Last modified timestamps are calculated from the highest last modified
409 * timestamp of this module's constituent files as well as the files it
410 * depends on. This function is context-sensitive, only performing
411 * calculations on files relevant to the given language, skin and debug
412 * mode.
413 *
414 * @param ResourceLoaderContext $context Context in which to calculate
415 * the modified time
416 * @return int: UNIX timestamp
417 * @see ResourceLoaderModule::getFileDependencies
418 */
419 public function getModifiedTime( ResourceLoaderContext $context ) {
420 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
421 return $this->modifiedTime[$context->getHash()];
422 }
423 wfProfileIn( __METHOD__ );
424
425 $files = array();
426
427 // Flatten style files into $files
428 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
429 foreach ( $styles as $styleFiles ) {
430 $files = array_merge( $files, $styleFiles );
431 }
432 $skinFiles = self::tryForKey(
433 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
434 $context->getSkin(),
435 'default'
436 );
437 foreach ( $skinFiles as $styleFiles ) {
438 $files = array_merge( $files, $styleFiles );
439 }
440
441 // Final merge, this should result in a master list of dependent files
442 $files = array_merge(
443 $files,
444 $this->scripts,
445 $context->getDebug() ? $this->debugScripts : array(),
446 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
447 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
448 $this->loaderScripts
449 );
450 $files = array_map( array( $this, 'getLocalPath' ), $files );
451 // File deps need to be treated separately because they're already prefixed
452 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
453
454 // If a module is nothing but a list of dependencies, we need to avoid
455 // giving max() an empty array
456 if ( count( $files ) === 0 ) {
457 wfProfileOut( __METHOD__ );
458 return $this->modifiedTime[$context->getHash()] = 1;
459 }
460
461 wfProfileIn( __METHOD__ . '-filemtime' );
462 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
463 wfProfileOut( __METHOD__ . '-filemtime' );
464
465 $this->modifiedTime[$context->getHash()] = max(
466 $filesMtime,
467 $this->getMsgBlobMtime( $context->getLanguage() ),
468 $this->getDefinitionMtime( $context )
469 );
470
471 wfProfileOut( __METHOD__ );
472 return $this->modifiedTime[$context->getHash()];
473 }
474
475 /**
476 * Get the definition summary for this module.
477 *
478 * @return Array
479 */
480 public function getDefinitionSummary( ResourceLoaderContext $context ) {
481 $summary = array(
482 'class' => get_class( $this ),
483 );
484 foreach ( array(
485 'scripts',
486 'debugScripts',
487 'loaderScripts',
488 'styles',
489 'languageScripts',
490 'skinScripts',
491 'skinStyles',
492 'dependencies',
493 'messages',
494 'targets',
495 'group',
496 'position',
497 'localBasePath',
498 'remoteBasePath',
499 'debugRaw',
500 'raw',
501 ) as $member ) {
502 $summary[$member] = $this->{$member};
503 };
504 return $summary;
505 }
506
507 /* Protected Methods */
508
509 /**
510 * @param string $path
511 * @return string
512 */
513 protected function getLocalPath( $path ) {
514 return "{$this->localBasePath}/$path";
515 }
516
517 /**
518 * @param string $path
519 * @return string
520 */
521 protected function getRemotePath( $path ) {
522 return "{$this->remoteBasePath}/$path";
523 }
524
525 /**
526 * Infer the stylesheet language from a stylesheet file path.
527 *
528 * @since 1.22
529 * @param string $path
530 * @return string: the stylesheet language name
531 */
532 public function getStyleSheetLang( $path ) {
533 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
534 }
535
536 /**
537 * Collates file paths by option (where provided).
538 *
539 * @param array $list List of file paths in any combination of index/path
540 * or path/options pairs
541 * @param string $option option name
542 * @param mixed $default default value if the option isn't set
543 * @return array: List of file paths, collated by $option
544 */
545 protected static function collateFilePathListByOption( array $list, $option, $default ) {
546 $collatedFiles = array();
547 foreach ( (array)$list as $key => $value ) {
548 if ( is_int( $key ) ) {
549 // File name as the value
550 if ( !isset( $collatedFiles[$default] ) ) {
551 $collatedFiles[$default] = array();
552 }
553 $collatedFiles[$default][] = $value;
554 } elseif ( is_array( $value ) ) {
555 // File name as the key, options array as the value
556 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
557 if ( !isset( $collatedFiles[$optionValue] ) ) {
558 $collatedFiles[$optionValue] = array();
559 }
560 $collatedFiles[$optionValue][] = $key;
561 }
562 }
563 return $collatedFiles;
564 }
565
566 /**
567 * Gets a list of element that match a key, optionally using a fallback key.
568 *
569 * @param array $list List of lists to select from
570 * @param string $key Key to look for in $map
571 * @param string $fallback Key to look for in $list if $key doesn't exist
572 * @return array: List of elements from $map which matched $key or $fallback,
573 * or an empty list in case of no match
574 */
575 protected static function tryForKey( array $list, $key, $fallback = null ) {
576 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
577 return $list[$key];
578 } elseif ( is_string( $fallback )
579 && isset( $list[$fallback] )
580 && is_array( $list[$fallback] )
581 ) {
582 return $list[$fallback];
583 }
584 return array();
585 }
586
587 /**
588 * Gets a list of file paths for all scripts in this module, in order of propper execution.
589 *
590 * @param ResourceLoaderContext $context
591 * @return array: List of file paths
592 */
593 protected function getScriptFiles( ResourceLoaderContext $context ) {
594 $files = array_merge(
595 $this->scripts,
596 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
597 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
598 );
599 if ( $context->getDebug() ) {
600 $files = array_merge( $files, $this->debugScripts );
601 }
602
603 return array_unique( $files );
604 }
605
606 /**
607 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
608 *
609 * @param ResourceLoaderContext $context
610 * @return array: List of file paths
611 */
612 protected function getStyleFiles( ResourceLoaderContext $context ) {
613 return array_merge_recursive(
614 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
615 self::collateFilePathListByOption(
616 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
617 )
618 );
619 }
620
621 /**
622 * Returns all style files used by this module
623 * @return array
624 */
625 public function getAllStyleFiles() {
626 $files = array();
627 foreach ( (array)$this->styles as $key => $value ) {
628 if ( is_array( $value ) ) {
629 $path = $key;
630 } else {
631 $path = $value;
632 }
633 $files[] = $this->getLocalPath( $path );
634 }
635 return $files;
636 }
637
638 /**
639 * Gets the contents of a list of JavaScript files.
640 *
641 * @param array $scripts List of file paths to scripts to read, remap and concetenate
642 * @throws MWException
643 * @return string: Concatenated and remapped JavaScript data from $scripts
644 */
645 protected function readScriptFiles( array $scripts ) {
646 global $wgResourceLoaderValidateStaticJS;
647 if ( empty( $scripts ) ) {
648 return '';
649 }
650 $js = '';
651 foreach ( array_unique( $scripts ) as $fileName ) {
652 $localPath = $this->getLocalPath( $fileName );
653 if ( !file_exists( $localPath ) ) {
654 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
655 }
656 $contents = file_get_contents( $localPath );
657 if ( $wgResourceLoaderValidateStaticJS ) {
658 // Static files don't really need to be checked as often; unlike
659 // on-wiki module they shouldn't change unexpectedly without
660 // admin interference.
661 $contents = $this->validateScriptFile( $fileName, $contents );
662 }
663 $js .= $contents . "\n";
664 }
665 return $js;
666 }
667
668 /**
669 * Gets the contents of a list of CSS files.
670 *
671 * @param array $styles List of media type/list of file paths pairs, to read, remap and
672 * concetenate
673 *
674 * @param bool $flip
675 *
676 * @return array: List of concatenated and remapped CSS data from $styles,
677 * keyed by media type
678 */
679 protected function readStyleFiles( array $styles, $flip ) {
680 if ( empty( $styles ) ) {
681 return array();
682 }
683 foreach ( $styles as $media => $files ) {
684 $uniqueFiles = array_unique( $files );
685 $styles[$media] = implode(
686 "\n",
687 array_map(
688 array( $this, 'readStyleFile' ),
689 $uniqueFiles,
690 array_fill( 0, count( $uniqueFiles ), $flip )
691 )
692 );
693 }
694 return $styles;
695 }
696
697 /**
698 * Reads a style file.
699 *
700 * This method can be used as a callback for array_map()
701 *
702 * @param string $path File path of style file to read
703 * @param bool $flip
704 *
705 * @return string: CSS data in script file
706 * @throws MWException if the file doesn't exist
707 */
708 protected function readStyleFile( $path, $flip ) {
709 $localPath = $this->getLocalPath( $path );
710 if ( !file_exists( $localPath ) ) {
711 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
712 wfDebugLog( 'resourceloader', $msg );
713 throw new MWException( $msg );
714 }
715
716 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
717 $style = $this->compileLESSFile( $localPath );
718 $this->hasGeneratedStyles = true;
719 } else {
720 $style = file_get_contents( $localPath );
721 }
722
723 if ( $flip ) {
724 $style = CSSJanus::transform( $style, true, false );
725 }
726 $dirname = dirname( $path );
727 if ( $dirname == '.' ) {
728 // If $path doesn't have a directory component, don't prepend a dot
729 $dirname = '';
730 }
731 $dir = $this->getLocalPath( $dirname );
732 $remoteDir = $this->getRemotePath( $dirname );
733 // Get and register local file references
734 $this->localFileRefs = array_merge(
735 $this->localFileRefs,
736 CSSMin::getLocalFileReferences( $style, $dir )
737 );
738 return CSSMin::remap(
739 $style, $dir, $remoteDir, true
740 );
741 }
742
743 /**
744 * Get whether CSS for this module should be flipped
745 * @param ResourceLoaderContext $context
746 * @return bool
747 */
748 public function getFlip( $context ) {
749 return $context->getDirection() === 'rtl';
750 }
751
752 /**
753 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
754 *
755 * @return array of strings
756 */
757 public function getTargets() {
758 return $this->targets;
759 }
760
761 /**
762 * Generate a cache key for a LESS file.
763 *
764 * The cache key varies on the file name and the names and values of global
765 * LESS variables.
766 *
767 * @since 1.22
768 * @param string $fileName File name of root LESS file.
769 * @return string: Cache key
770 */
771 protected static function getLESSCacheKey( $fileName ) {
772 $vars = json_encode( ResourceLoader::getLESSVars() );
773 $hash = md5( $fileName . $vars );
774 return wfMemcKey( 'resourceloader', 'less', $hash );
775 }
776
777 /**
778 * Compile a LESS file into CSS.
779 *
780 * If invalid, returns replacement CSS source consisting of the compilation
781 * error message encoded as a comment. To save work, we cache a result object
782 * which comprises the compiled CSS and the names & mtimes of the files
783 * that were processed. lessphp compares the cached & current mtimes and
784 * recompiles as necessary.
785 *
786 * @since 1.22
787 * @throws Exception If Less encounters a parse error
788 * @throws MWException If Less compilation returns unexpection result
789 * @param string $fileName File path of LESS source
790 * @return string: CSS source
791 */
792 protected function compileLESSFile( $fileName ) {
793 $key = self::getLESSCacheKey( $fileName );
794 $cache = wfGetCache( CACHE_ANYTHING );
795
796 // The input to lessc. Either an associative array representing the
797 // cached results of a previous compilation, or the string file name if
798 // no cache result exists.
799 $source = $cache->get( $key );
800 if ( !is_array( $source ) || !isset( $source['root'] ) ) {
801 $source = $fileName;
802 }
803
804 $compiler = ResourceLoader::getLessCompiler();
805 $result = null;
806
807 $result = $compiler->cachedCompile( $source );
808
809 if ( !is_array( $result ) ) {
810 throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' );
811 }
812
813 $this->localFileRefs += array_keys( $result['files'] );
814 $cache->set( $key, $result );
815 return $result['compiled'];
816 }
817 }