Merge "Tweaked WikiPage::clear() comment a bit"
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blob7b8500187829114ae1b43b0dcde8de8d66480cbe
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 {
30 /* Protected Members */
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
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
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
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
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
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
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
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
99 protected $dependencies = array();
101 * Array: List of message keys used by this module
102 * @par Usage:
103 * @code
104 * array( [message-key], [message-key], ... )
105 * @endcode
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' );
119 * Boolean: Whether getStyleURLsForDebug should return raw file paths,
120 * or return load.php urls
122 protected $hasGeneratedStyles = false;
125 * Array: Cache for mtime
126 * @par Usage:
127 * @code
128 * array( [hash] => [mtime], [hash] => [mtime], ... )
129 * @endcode
131 protected $modifiedTime = array();
133 * Array: Place where readStyleFile() tracks file dependencies
134 * @par Usage:
135 * @code
136 * array( [file-path], [file-path], ... )
137 * @endcode
139 protected $localFileRefs = array();
141 /* Methods */
144 * Constructs a new module from an options array.
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
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']
193 * @endcode
195 public function __construct( $options = array(), $localBasePath = null,
196 $remoteBasePath = null
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;
206 if ( isset( $options['remoteExtPath'] ) ) {
207 global $wgExtensionAssetsPath;
208 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
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."
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."
237 $this->{$member}[$key] = (array)$value;
239 break;
240 // Lists of strings
241 case 'dependencies':
242 case 'messages':
243 case 'targets':
244 $this->{$member} = (array)$option;
245 break;
246 // Single strings
247 case 'group':
248 case 'position':
249 case 'localBasePath':
250 case 'remoteBasePath':
251 $this->{$member} = (string)$option;
252 break;
253 // Single booleans
254 case 'debugRaw':
255 case 'raw':
256 $this->{$member} = (bool)$option;
257 break;
260 // Make sure the remote base path is a complete valid URL,
261 // but possibly protocol-relative to avoid cache pollution
262 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
266 * Gets all scripts for a given context concatenated together.
268 * @param ResourceLoaderContext $context Context in which to generate script
269 * @return string: JavaScript code for $context
271 public function getScript( ResourceLoaderContext $context ) {
272 $files = $this->getScriptFiles( $context );
273 return $this->readScriptFiles( $files );
277 * @param ResourceLoaderContext $context
278 * @return array
280 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
281 $urls = array();
282 foreach ( $this->getScriptFiles( $context ) as $file ) {
283 $urls[] = $this->getRemotePath( $file );
285 return $urls;
289 * @return bool
291 public function supportsURLLoading() {
292 return $this->debugRaw;
296 * Gets loader script.
298 * @return string: JavaScript code to be added to startup module
300 public function getLoaderScript() {
301 if ( count( $this->loaderScripts ) == 0 ) {
302 return false;
304 return $this->readScriptFiles( $this->loaderScripts );
308 * Gets all styles for a given context concatenated together.
310 * @param ResourceLoaderContext $context Context in which to generate styles
311 * @return string: CSS code for $context
313 public function getStyles( ResourceLoaderContext $context ) {
314 $styles = $this->readStyleFiles(
315 $this->getStyleFiles( $context ),
316 $this->getFlip( $context )
318 // Collect referenced files
319 $this->localFileRefs = array_unique( $this->localFileRefs );
320 // If the list has been modified since last time we cached it, update the cache
321 try {
322 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
323 $dbw = wfGetDB( DB_MASTER );
324 $dbw->replace( 'module_deps',
325 array( array( 'md_module', 'md_skin' ) ), array(
326 'md_module' => $this->getName(),
327 'md_skin' => $context->getSkin(),
328 'md_deps' => FormatJson::encode( $this->localFileRefs ),
332 } catch ( Exception $e ) {
333 wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" );
335 return $styles;
339 * @param ResourceLoaderContext $context
340 * @return array
342 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
343 if ( $this->hasGeneratedStyles ) {
344 // Do the default behaviour of returning a url back to load.php
345 // but with only=styles.
346 return parent::getStyleURLsForDebug( $context );
348 // Our module consists entirely of real css files,
349 // in debug mode we can load those directly.
350 $urls = array();
351 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
352 $urls[$mediaType] = array();
353 foreach ( $list as $file ) {
354 $urls[$mediaType][] = $this->getRemotePath( $file );
357 return $urls;
361 * Gets list of message keys used by this module.
363 * @return array: List of message keys
365 public function getMessages() {
366 return $this->messages;
370 * Gets the name of the group this module should be loaded in.
372 * @return string: Group name
374 public function getGroup() {
375 return $this->group;
379 * @return string
381 public function getPosition() {
382 return $this->position;
386 * Gets list of names of modules this module depends on.
388 * @return array: List of module names
390 public function getDependencies() {
391 return $this->dependencies;
395 * @return bool
397 public function isRaw() {
398 return $this->raw;
402 * Get the last modified timestamp of this module.
404 * Last modified timestamps are calculated from the highest last modified
405 * timestamp of this module's constituent files as well as the files it
406 * depends on. This function is context-sensitive, only performing
407 * calculations on files relevant to the given language, skin and debug
408 * mode.
410 * @param ResourceLoaderContext $context Context in which to calculate
411 * the modified time
412 * @return int: UNIX timestamp
413 * @see ResourceLoaderModule::getFileDependencies
415 public function getModifiedTime( ResourceLoaderContext $context ) {
416 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
417 return $this->modifiedTime[$context->getHash()];
419 wfProfileIn( __METHOD__ );
421 $files = array();
423 // Flatten style files into $files
424 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
425 foreach ( $styles as $styleFiles ) {
426 $files = array_merge( $files, $styleFiles );
428 $skinFiles = self::tryForKey(
429 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
430 $context->getSkin(),
431 'default'
433 foreach ( $skinFiles as $styleFiles ) {
434 $files = array_merge( $files, $styleFiles );
437 // Final merge, this should result in a master list of dependent files
438 $files = array_merge(
439 $files,
440 $this->scripts,
441 $context->getDebug() ? $this->debugScripts : array(),
442 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
443 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
444 $this->loaderScripts
446 $files = array_map( array( $this, 'getLocalPath' ), $files );
447 // File deps need to be treated separately because they're already prefixed
448 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
450 // If a module is nothing but a list of dependencies, we need to avoid
451 // giving max() an empty array
452 if ( count( $files ) === 0 ) {
453 wfProfileOut( __METHOD__ );
454 return $this->modifiedTime[$context->getHash()] = 1;
457 wfProfileIn( __METHOD__ . '-filemtime' );
458 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
459 wfProfileOut( __METHOD__ . '-filemtime' );
460 $this->modifiedTime[$context->getHash()] = max(
461 $filesMtime,
462 $this->getMsgBlobMtime( $context->getLanguage() ) );
464 wfProfileOut( __METHOD__ );
465 return $this->modifiedTime[$context->getHash()];
468 /* Protected Methods */
471 * @param string $path
472 * @return string
474 protected function getLocalPath( $path ) {
475 return "{$this->localBasePath}/$path";
479 * @param string $path
480 * @return string
482 protected function getRemotePath( $path ) {
483 return "{$this->remoteBasePath}/$path";
487 * Infer the stylesheet language from a stylesheet file path.
489 * @since 1.22
490 * @param string $path
491 * @return string: the stylesheet language name
493 public function getStyleSheetLang( $path ) {
494 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
498 * Collates file paths by option (where provided).
500 * @param array $list List of file paths in any combination of index/path
501 * or path/options pairs
502 * @param string $option option name
503 * @param mixed $default default value if the option isn't set
504 * @return array: List of file paths, collated by $option
506 protected static function collateFilePathListByOption( array $list, $option, $default ) {
507 $collatedFiles = array();
508 foreach ( (array)$list as $key => $value ) {
509 if ( is_int( $key ) ) {
510 // File name as the value
511 if ( !isset( $collatedFiles[$default] ) ) {
512 $collatedFiles[$default] = array();
514 $collatedFiles[$default][] = $value;
515 } elseif ( is_array( $value ) ) {
516 // File name as the key, options array as the value
517 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
518 if ( !isset( $collatedFiles[$optionValue] ) ) {
519 $collatedFiles[$optionValue] = array();
521 $collatedFiles[$optionValue][] = $key;
524 return $collatedFiles;
528 * Gets a list of element that match a key, optionally using a fallback key.
530 * @param array $list List of lists to select from
531 * @param string $key Key to look for in $map
532 * @param string $fallback Key to look for in $list if $key doesn't exist
533 * @return array: List of elements from $map which matched $key or $fallback,
534 * or an empty list in case of no match
536 protected static function tryForKey( array $list, $key, $fallback = null ) {
537 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
538 return $list[$key];
539 } elseif ( is_string( $fallback )
540 && isset( $list[$fallback] )
541 && is_array( $list[$fallback] ) )
543 return $list[$fallback];
545 return array();
549 * Gets a list of file paths for all scripts in this module, in order of propper execution.
551 * @param ResourceLoaderContext $context
552 * @return array: List of file paths
554 protected function getScriptFiles( ResourceLoaderContext $context ) {
555 $files = array_merge(
556 $this->scripts,
557 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
558 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
560 if ( $context->getDebug() ) {
561 $files = array_merge( $files, $this->debugScripts );
564 return array_unique( $files );
568 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
570 * @param ResourceLoaderContext $context
571 * @return array: List of file paths
573 protected function getStyleFiles( ResourceLoaderContext $context ) {
574 return array_merge_recursive(
575 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
576 self::collateFilePathListByOption(
577 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
583 * Returns all style files used by this module
584 * @return array
586 public function getAllStyleFiles() {
587 $files = array();
588 foreach( (array)$this->styles as $key => $value ) {
589 if ( is_array( $value ) ) {
590 $path = $key;
591 } else {
592 $path = $value;
594 $files[] = $this->getLocalPath( $path );
596 return $files;
600 * Gets the contents of a list of JavaScript files.
602 * @param array $scripts List of file paths to scripts to read, remap and concetenate
603 * @throws MWException
604 * @return string: Concatenated and remapped JavaScript data from $scripts
606 protected function readScriptFiles( array $scripts ) {
607 global $wgResourceLoaderValidateStaticJS;
608 if ( empty( $scripts ) ) {
609 return '';
611 $js = '';
612 foreach ( array_unique( $scripts ) as $fileName ) {
613 $localPath = $this->getLocalPath( $fileName );
614 if ( !file_exists( $localPath ) ) {
615 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
617 $contents = file_get_contents( $localPath );
618 if ( $wgResourceLoaderValidateStaticJS ) {
619 // Static files don't really need to be checked as often; unlike
620 // on-wiki module they shouldn't change unexpectedly without
621 // admin interference.
622 $contents = $this->validateScriptFile( $fileName, $contents );
624 $js .= $contents . "\n";
626 return $js;
630 * Gets the contents of a list of CSS files.
632 * @param array $styles List of media type/list of file paths pairs, to read, remap and
633 * concetenate
635 * @param bool $flip
637 * @return array: List of concatenated and remapped CSS data from $styles,
638 * keyed by media type
640 protected function readStyleFiles( array $styles, $flip ) {
641 if ( empty( $styles ) ) {
642 return array();
644 foreach ( $styles as $media => $files ) {
645 $uniqueFiles = array_unique( $files );
646 $styles[$media] = implode(
647 "\n",
648 array_map(
649 array( $this, 'readStyleFile' ),
650 $uniqueFiles,
651 array_fill( 0, count( $uniqueFiles ), $flip )
655 return $styles;
659 * Reads a style file.
661 * This method can be used as a callback for array_map()
663 * @param string $path File path of style file to read
664 * @param bool $flip
666 * @return string: CSS data in script file
667 * @throws MWException if the file doesn't exist
669 protected function readStyleFile( $path, $flip ) {
670 $localPath = $this->getLocalPath( $path );
671 if ( !file_exists( $localPath ) ) {
672 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
673 wfDebugLog( 'resourceloader', $msg );
674 throw new MWException( $msg );
677 if ( $this->getStyleSheetLang( $path ) === 'less' ) {
678 $style = $this->compileLESSFile( $localPath );
679 $this->hasGeneratedStyles = true;
680 } else {
681 $style = file_get_contents( $localPath );
684 if ( $flip ) {
685 $style = CSSJanus::transform( $style, true, false );
687 $dirname = dirname( $path );
688 if ( $dirname == '.' ) {
689 // If $path doesn't have a directory component, don't prepend a dot
690 $dirname = '';
692 $dir = $this->getLocalPath( $dirname );
693 $remoteDir = $this->getRemotePath( $dirname );
694 // Get and register local file references
695 $this->localFileRefs = array_merge(
696 $this->localFileRefs,
697 CSSMin::getLocalFileReferences( $style, $dir )
699 return CSSMin::remap(
700 $style, $dir, $remoteDir, true
705 * Get whether CSS for this module should be flipped
706 * @param ResourceLoaderContext $context
707 * @return bool
709 public function getFlip( $context ) {
710 return $context->getDirection() === 'rtl';
714 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
716 * @return array of strings
718 public function getTargets() {
719 return $this->targets;
723 * Generate a cache key for a LESS file.
725 * The cache key varies on the file name and the names and values of global
726 * LESS variables.
728 * @since 1.22
729 * @param string $fileName File name of root LESS file.
730 * @return string: Cache key
732 protected static function getLESSCacheKey( $fileName ) {
733 $vars = json_encode( ResourceLoader::getLESSVars() );
734 $hash = md5( $fileName . $vars );
735 return wfMemcKey( 'resourceloader', 'less', $hash );
739 * Compile a LESS file into CSS.
741 * If invalid, returns replacement CSS source consisting of the compilation
742 * error message encoded as a comment. To save work, we cache a result object
743 * which comprises the compiled CSS and the names & mtimes of the files
744 * that were processed. lessphp compares the cached & current mtimes and
745 * recompiles as necessary.
747 * @since 1.22
748 * @throws Exception If Less encounters a parse error
749 * @throws MWException If Less compilation returns unexpection result
750 * @param string $fileName File path of LESS source
751 * @return string: CSS source
753 protected function compileLESSFile( $fileName ) {
754 $key = self::getLESSCacheKey( $fileName );
755 $cache = wfGetCache( CACHE_ANYTHING );
757 // The input to lessc. Either an associative array representing the
758 // cached results of a previous compilation, or the string file name if
759 // no cache result exists.
760 $source = $cache->get( $key );
761 if ( !is_array( $source ) || !isset( $source['root'] ) ) {
762 $source = $fileName;
765 $compiler = ResourceLoader::getLessCompiler();
766 $result = null;
768 $result = $compiler->cachedCompile( $source );
770 if ( !is_array( $result ) ) {
771 throw new MWException( 'LESS compiler result has type ' . gettype( $result ) . '; array expected.' );
774 $this->localFileRefs += array_keys( $result['files'] );
775 $cache->set( $key, $result );
776 return $result['compiled'];