MWException: Don't send headers multiple times
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blob382bdd9d96c5bffe7debc069a83497b6d341504a
1 <?php
2 /**
3 * Resource loader module based on local JavaScript/CSS files.
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.
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.
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
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29 /* Protected Members */
31 /** @var string Local base path, see __construct() */
32 protected $localBasePath = '';
34 /** @var string Remote base path, see __construct() */
35 protected $remoteBasePath = '';
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
44 protected $scripts = array();
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
53 protected $languageScripts = array();
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
62 protected $skinScripts = array();
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
71 protected $debugScripts = array();
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
80 protected $loaderScripts = array();
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
89 protected $styles = array();
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
98 protected $skinStyles = array();
101 * @var array List of modules this module depends on
102 * @par Usage:
103 * @code
104 * array( [file-path], [file-path], ... )
105 * @endcode
107 protected $dependencies = array();
110 * @var array List of message keys used by this module
111 * @par Usage:
112 * @code
113 * array( [message-key], [message-key], ... )
114 * @endcode
116 protected $messages = array();
118 /** @var string Name of group to load this module in */
119 protected $group;
121 /** @var string Position on the page to load this module at */
122 protected $position = 'bottom';
124 /** @var bool Link to raw files in debug mode */
125 protected $debugRaw = true;
127 /** @var bool Whether mw.loader.state() call should be omitted */
128 protected $raw = false;
130 protected $targets = array( 'desktop' );
133 * @var bool Whether getStyleURLsForDebug should return raw file paths,
134 * or return load.php urls
136 protected $hasGeneratedStyles = false;
139 * @var array Cache for mtime
140 * @par Usage:
141 * @code
142 * array( [hash] => [mtime], [hash] => [mtime], ... )
143 * @endcode
145 protected $modifiedTime = array();
148 * @var array Place where readStyleFile() tracks file dependencies
149 * @par Usage:
150 * @code
151 * array( [file-path], [file-path], ... )
152 * @endcode
154 protected $localFileRefs = array();
156 /* Methods */
159 * Constructs a new module from an options array.
161 * @param array $options List of options; if not given or empty, an empty module will be
162 * constructed
163 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
164 * to $IP
165 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
166 * to $wgScriptPath
168 * Below is a description for the $options array:
169 * @throws MWException
170 * @par Construction options:
171 * @code
172 * array(
173 * // Base path to prepend to all local paths in $options. Defaults to $IP
174 * 'localBasePath' => [base path],
175 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
176 * 'remoteBasePath' => [base path],
177 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
178 * 'remoteExtPath' => [base path],
179 * // Scripts to always include
180 * 'scripts' => [file path string or array of file path strings],
181 * // Scripts to include in specific language contexts
182 * 'languageScripts' => array(
183 * [language code] => [file path string or array of file path strings],
184 * ),
185 * // Scripts to include in specific skin contexts
186 * 'skinScripts' => array(
187 * [skin name] => [file path string or array of file path strings],
188 * ),
189 * // Scripts to include in debug contexts
190 * 'debugScripts' => [file path string or array of file path strings],
191 * // Scripts to include in the startup module
192 * 'loaderScripts' => [file path string or array of file path strings],
193 * // Modules which must be loaded before this module
194 * 'dependencies' => [module name string or array of module name strings],
195 * // Styles to always load
196 * 'styles' => [file path string or array of file path strings],
197 * // Styles to include in specific skin contexts
198 * 'skinStyles' => array(
199 * [skin name] => [file path string or array of file path strings],
200 * ),
201 * // Messages to always load
202 * 'messages' => [array of message key strings],
203 * // Group which this module should be loaded together with
204 * 'group' => [group name string],
205 * // Position on the page to load this module at
206 * 'position' => ['bottom' (default) or 'top']
208 * @endcode
210 public function __construct( $options = array(), $localBasePath = null,
211 $remoteBasePath = null
213 global $IP, $wgScriptPath, $wgResourceBasePath;
214 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
215 if ( $remoteBasePath !== null ) {
216 $this->remoteBasePath = $remoteBasePath;
217 } else {
218 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
221 if ( isset( $options['remoteExtPath'] ) ) {
222 global $wgExtensionAssetsPath;
223 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
226 foreach ( $options as $member => $option ) {
227 switch ( $member ) {
228 // Lists of file paths
229 case 'scripts':
230 case 'debugScripts':
231 case 'loaderScripts':
232 case 'styles':
233 $this->{$member} = (array)$option;
234 break;
235 // Collated lists of file paths
236 case 'languageScripts':
237 case 'skinScripts':
238 case 'skinStyles':
239 if ( !is_array( $option ) ) {
240 throw new MWException(
241 "Invalid collated file path list error. " .
242 "'$option' given, array expected."
245 foreach ( $option as $key => $value ) {
246 if ( !is_string( $key ) ) {
247 throw new MWException(
248 "Invalid collated file path list key error. " .
249 "'$key' given, string expected."
252 $this->{$member}[$key] = (array)$value;
254 break;
255 // Lists of strings
256 case 'dependencies':
257 case 'messages':
258 case 'targets':
259 // Normalise
260 $option = array_values( array_unique( (array)$option ) );
261 sort( $option );
263 $this->{$member} = $option;
264 break;
265 // Single strings
266 case 'group':
267 case 'position':
268 case 'localBasePath':
269 case 'remoteBasePath':
270 $this->{$member} = (string)$option;
271 break;
272 // Single booleans
273 case 'debugRaw':
274 case 'raw':
275 $this->{$member} = (bool)$option;
276 break;
279 // Make sure the remote base path is a complete valid URL,
280 // but possibly protocol-relative to avoid cache pollution
281 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
285 * Gets all scripts for a given context concatenated together.
287 * @param ResourceLoaderContext $context Context in which to generate script
288 * @return string JavaScript code for $context
290 public function getScript( ResourceLoaderContext $context ) {
291 $files = $this->getScriptFiles( $context );
292 return $this->readScriptFiles( $files );
296 * @param ResourceLoaderContext $context
297 * @return array
299 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
300 $urls = array();
301 foreach ( $this->getScriptFiles( $context ) as $file ) {
302 $urls[] = $this->getRemotePath( $file );
304 return $urls;
308 * @return bool
310 public function supportsURLLoading() {
311 return $this->debugRaw;
315 * Gets loader script.
317 * @return string JavaScript code to be added to startup module
319 public function getLoaderScript() {
320 if ( count( $this->loaderScripts ) == 0 ) {
321 return false;
323 return $this->readScriptFiles( $this->loaderScripts );
327 * Gets all styles for a given context concatenated together.
329 * @param ResourceLoaderContext $context Context in which to generate styles
330 * @return string CSS code for $context
332 public function getStyles( ResourceLoaderContext $context ) {
333 $styles = $this->readStyleFiles(
334 $this->getStyleFiles( $context ),
335 $this->getFlip( $context )
337 // Collect referenced files
338 $this->localFileRefs = array_unique( $this->localFileRefs );
339 // If the list has been modified since last time we cached it, update the cache
340 try {
341 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
342 $dbw = wfGetDB( DB_MASTER );
343 $dbw->replace( 'module_deps',
344 array( array( 'md_module', 'md_skin' ) ), array(
345 'md_module' => $this->getName(),
346 'md_skin' => $context->getSkin(),
347 'md_deps' => FormatJson::encode( $this->localFileRefs ),
351 } catch ( Exception $e ) {
352 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
354 return $styles;
358 * @param ResourceLoaderContext $context
359 * @return array
361 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
362 if ( $this->hasGeneratedStyles ) {
363 // Do the default behaviour of returning a url back to load.php
364 // but with only=styles.
365 return parent::getStyleURLsForDebug( $context );
367 // Our module consists entirely of real css files,
368 // in debug mode we can load those directly.
369 $urls = array();
370 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
371 $urls[$mediaType] = array();
372 foreach ( $list as $file ) {
373 $urls[$mediaType][] = $this->getRemotePath( $file );
376 return $urls;
380 * Gets list of message keys used by this module.
382 * @return array List of message keys
384 public function getMessages() {
385 return $this->messages;
389 * Gets the name of the group this module should be loaded in.
391 * @return string Group name
393 public function getGroup() {
394 return $this->group;
398 * @return string
400 public function getPosition() {
401 return $this->position;
405 * Gets list of names of modules this module depends on.
407 * @return array List of module names
409 public function getDependencies() {
410 return $this->dependencies;
414 * @return bool
416 public function isRaw() {
417 return $this->raw;
421 * Get the last modified timestamp of this module.
423 * Last modified timestamps are calculated from the highest last modified
424 * timestamp of this module's constituent files as well as the files it
425 * depends on. This function is context-sensitive, only performing
426 * calculations on files relevant to the given language, skin and debug
427 * mode.
429 * @param ResourceLoaderContext $context Context in which to calculate
430 * the modified time
431 * @return int UNIX timestamp
432 * @see ResourceLoaderModule::getFileDependencies
434 public function getModifiedTime( ResourceLoaderContext $context ) {
435 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
436 return $this->modifiedTime[$context->getHash()];
438 wfProfileIn( __METHOD__ );
440 $files = array();
442 // Flatten style files into $files
443 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
444 foreach ( $styles as $styleFiles ) {
445 $files = array_merge( $files, $styleFiles );
448 $skinFiles = self::collateFilePathListByOption(
449 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
450 'media',
451 'all'
453 foreach ( $skinFiles as $styleFiles ) {
454 $files = array_merge( $files, $styleFiles );
457 // Final merge, this should result in a master list of dependent files
458 $files = array_merge(
459 $files,
460 $this->scripts,
461 $context->getDebug() ? $this->debugScripts : array(),
462 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
463 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
464 $this->loaderScripts
466 $files = array_map( array( $this, 'getLocalPath' ), $files );
467 // File deps need to be treated separately because they're already prefixed
468 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
470 // If a module is nothing but a list of dependencies, we need to avoid
471 // giving max() an empty array
472 if ( count( $files ) === 0 ) {
473 $this->modifiedTime[$context->getHash()] = 1;
474 wfProfileOut( __METHOD__ );
475 return $this->modifiedTime[$context->getHash()];
478 wfProfileIn( __METHOD__ . '-filemtime' );
479 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
480 wfProfileOut( __METHOD__ . '-filemtime' );
482 $this->modifiedTime[$context->getHash()] = max(
483 $filesMtime,
484 $this->getMsgBlobMtime( $context->getLanguage() ),
485 $this->getDefinitionMtime( $context )
488 wfProfileOut( __METHOD__ );
489 return $this->modifiedTime[$context->getHash()];
493 * Get the definition summary for this module.
495 * @return array
497 public function getDefinitionSummary( ResourceLoaderContext $context ) {
498 $summary = array(
499 'class' => get_class( $this ),
501 foreach ( array(
502 'scripts',
503 'debugScripts',
504 'loaderScripts',
505 'styles',
506 'languageScripts',
507 'skinScripts',
508 'skinStyles',
509 'dependencies',
510 'messages',
511 'targets',
512 'group',
513 'position',
514 'localBasePath',
515 'remoteBasePath',
516 'debugRaw',
517 'raw',
518 ) as $member ) {
519 $summary[$member] = $this->{$member};
521 return $summary;
524 /* Protected Methods */
527 * @param string $path
528 * @return string
530 protected function getLocalPath( $path ) {
531 return "{$this->localBasePath}/$path";
535 * @param string $path
536 * @return string
538 protected function getRemotePath( $path ) {
539 return "{$this->remoteBasePath}/$path";
543 * Infer the stylesheet language from a stylesheet file path.
545 * @since 1.22
546 * @param string $path
547 * @return string The stylesheet language name
549 public function getStyleSheetLang( $path ) {
550 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
554 * Collates file paths by option (where provided).
556 * @param array $list List of file paths in any combination of index/path
557 * or path/options pairs
558 * @param string $option Option name
559 * @param mixed $default Default value if the option isn't set
560 * @return array List of file paths, collated by $option
562 protected static function collateFilePathListByOption( array $list, $option, $default ) {
563 $collatedFiles = array();
564 foreach ( (array)$list as $key => $value ) {
565 if ( is_int( $key ) ) {
566 // File name as the value
567 if ( !isset( $collatedFiles[$default] ) ) {
568 $collatedFiles[$default] = array();
570 $collatedFiles[$default][] = $value;
571 } elseif ( is_array( $value ) ) {
572 // File name as the key, options array as the value
573 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
574 if ( !isset( $collatedFiles[$optionValue] ) ) {
575 $collatedFiles[$optionValue] = array();
577 $collatedFiles[$optionValue][] = $key;
580 return $collatedFiles;
584 * Gets a list of element that match a key, optionally using a fallback key.
586 * @param array $list List of lists to select from
587 * @param string $key Key to look for in $map
588 * @param string $fallback Key to look for in $list if $key doesn't exist
589 * @return array List of elements from $map which matched $key or $fallback,
590 * or an empty list in case of no match
592 protected static function tryForKey( array $list, $key, $fallback = null ) {
593 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
594 return $list[$key];
595 } elseif ( is_string( $fallback )
596 && isset( $list[$fallback] )
597 && is_array( $list[$fallback] )
599 return $list[$fallback];
601 return array();
605 * Gets a list of file paths for all scripts in this module, in order of propper execution.
607 * @param ResourceLoaderContext $context
608 * @return array List of file paths
610 protected function getScriptFiles( ResourceLoaderContext $context ) {
611 $files = array_merge(
612 $this->scripts,
613 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
614 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
616 if ( $context->getDebug() ) {
617 $files = array_merge( $files, $this->debugScripts );
620 return array_unique( $files );
624 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
626 * @param ResourceLoaderContext $context
627 * @return array List of file paths
629 protected function getStyleFiles( ResourceLoaderContext $context ) {
630 return array_merge_recursive(
631 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
632 self::collateFilePathListByOption(
633 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
634 'media',
635 'all'
641 * Returns all style files used by this module
642 * @return array
644 public function getAllStyleFiles() {
645 $files = array();
646 foreach ( (array)$this->styles as $key => $value ) {
647 if ( is_array( $value ) ) {
648 $path = $key;
649 } else {
650 $path = $value;
652 $files[] = $this->getLocalPath( $path );
654 return $files;
658 * Gets the contents of a list of JavaScript files.
660 * @param array $scripts List of file paths to scripts to read, remap and concetenate
661 * @throws MWException
662 * @return string Concatenated and remapped JavaScript data from $scripts
664 protected function readScriptFiles( array $scripts ) {
665 global $wgResourceLoaderValidateStaticJS;
666 if ( empty( $scripts ) ) {
667 return '';
669 $js = '';
670 foreach ( array_unique( $scripts ) as $fileName ) {
671 $localPath = $this->getLocalPath( $fileName );
672 if ( !file_exists( $localPath ) ) {
673 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
675 $contents = file_get_contents( $localPath );
676 if ( $wgResourceLoaderValidateStaticJS ) {
677 // Static files don't really need to be checked as often; unlike
678 // on-wiki module they shouldn't change unexpectedly without
679 // admin interference.
680 $contents = $this->validateScriptFile( $fileName, $contents );
682 $js .= $contents . "\n";
684 return $js;
688 * Gets the contents of a list of CSS files.
690 * @param array $styles List of media type/list of file paths pairs, to read, remap and
691 * concetenate
693 * @param bool $flip
695 * @throws MWException
696 * @return array List of concatenated and remapped CSS data from $styles,
697 * keyed by media type
699 protected function readStyleFiles( array $styles, $flip ) {
700 if ( empty( $styles ) ) {
701 return array();
703 foreach ( $styles as $media => $files ) {
704 $uniqueFiles = array_unique( $files );
705 $styleFiles = array();
706 foreach ( $uniqueFiles as $file ) {
707 $styleFiles[] = $this->readStyleFile( $file, $flip );
709 $styles[$media] = implode( "\n", $styleFiles );
711 return $styles;
715 * Reads a style file.
717 * This method can be used as a callback for array_map()
719 * @param string $path File path of style file to read
720 * @param bool $flip
722 * @return string CSS data in script file
723 * @throws MWException if the file doesn't exist
725 protected function readStyleFile( $path, $flip ) {
726 $localPath = $this->getLocalPath( $path );
727 if ( !file_exists( $localPath ) ) {
728 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
729 wfDebugLog( 'resourceloader', $msg );
730 throw new MWException( $msg );
733 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
734 $style = $this->compileLESSFile( $localPath );
735 $this->hasGeneratedStyles = true;
736 } else {
737 $style = file_get_contents( $localPath );
740 if ( $flip ) {
741 $style = CSSJanus::transform( $style, true, false );
743 $dirname = dirname( $path );
744 if ( $dirname == '.' ) {
745 // If $path doesn't have a directory component, don't prepend a dot
746 $dirname = '';
748 $dir = $this->getLocalPath( $dirname );
749 $remoteDir = $this->getRemotePath( $dirname );
750 // Get and register local file references
751 $this->localFileRefs = array_merge(
752 $this->localFileRefs,
753 CSSMin::getLocalFileReferences( $style, $dir )
755 return CSSMin::remap(
756 $style, $dir, $remoteDir, true
761 * Get whether CSS for this module should be flipped
762 * @param ResourceLoaderContext $context
763 * @return bool
765 public function getFlip( $context ) {
766 return $context->getDirection() === 'rtl';
770 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
772 * @return array Array of strings
774 public function getTargets() {
775 return $this->targets;
779 * Generate a cache key for a LESS file.
781 * The cache key varies on the file name and the names and values of global
782 * LESS variables.
784 * @since 1.22
785 * @param string $fileName File name of root LESS file.
786 * @return string Cache key
788 protected static function getLESSCacheKey( $fileName ) {
789 $vars = json_encode( ResourceLoader::getLESSVars() );
790 $hash = md5( $fileName . $vars );
791 return wfMemcKey( 'resourceloader', 'less', $hash );
795 * Compile a LESS file into CSS.
797 * If invalid, returns replacement CSS source consisting of the compilation
798 * error message encoded as a comment. To save work, we cache a result object
799 * which comprises the compiled CSS and the names & mtimes of the files
800 * that were processed. lessphp compares the cached & current mtimes and
801 * recompiles as necessary.
803 * @since 1.22
804 * @throws Exception If Less encounters a parse error
805 * @throws MWException If Less compilation returns unexpection result
806 * @param string $fileName File path of LESS source
807 * @return string CSS source
809 protected function compileLESSFile( $fileName ) {
810 $key = self::getLESSCacheKey( $fileName );
811 $cache = wfGetCache( CACHE_ANYTHING );
813 // The input to lessc. Either an associative array representing the
814 // cached results of a previous compilation, or the string file name if
815 // no cache result exists.
816 $source = $cache->get( $key );
817 if ( !is_array( $source ) || !isset( $source['root'] ) ) {
818 $source = $fileName;
821 $compiler = ResourceLoader::getLessCompiler();
822 $result = null;
824 $result = $compiler->cachedCompile( $source );
826 if ( !is_array( $result ) ) {
827 throw new MWException( 'LESS compiler result has type '
828 . gettype( $result ) . '; array expected.' );
831 $this->localFileRefs += array_keys( $result['files'] );
832 $cache->set( $key, $result );
833 return $result['compiled'];