Merge "Follow-up I774a89d6 (2fabea7): use $this->msg() in HistoryAction"
[mediawiki.git] / includes / resourceloader / ResourceLoaderFileModule.php
blobf0892ec2a82daa849f4feed4c274e6ed5b534a31
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;
117 * Array: Cache for mtime
118 * @par Usage:
119 * @code
120 * array( [hash] => [mtime], [hash] => [mtime], ... )
121 * @endcode
123 protected $modifiedTime = array();
125 * Array: Place where readStyleFile() tracks file dependencies
126 * @par Usage:
127 * @code
128 * array( [file-path], [file-path], ... )
129 * @endcode
131 protected $localFileRefs = array();
133 /* Methods */
136 * Constructs a new module from an options array.
138 * @param $options Array: List of options; if not given or empty, an empty module will be
139 * constructed
140 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
141 * to $IP
142 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
143 * to $wgScriptPath
145 * Below is a description for the $options array:
146 * @par Construction options:
147 * @code
148 * array(
149 * // Base path to prepend to all local paths in $options. Defaults to $IP
150 * 'localBasePath' => [base path],
151 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
152 * 'remoteBasePath' => [base path],
153 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
154 * 'remoteExtPath' => [base path],
155 * // Scripts to always include
156 * 'scripts' => [file path string or array of file path strings],
157 * // Scripts to include in specific language contexts
158 * 'languageScripts' => array(
159 * [language code] => [file path string or array of file path strings],
160 * ),
161 * // Scripts to include in specific skin contexts
162 * 'skinScripts' => array(
163 * [skin name] => [file path string or array of file path strings],
164 * ),
165 * // Scripts to include in debug contexts
166 * 'debugScripts' => [file path string or array of file path strings],
167 * // Scripts to include in the startup module
168 * 'loaderScripts' => [file path string or array of file path strings],
169 * // Modules which must be loaded before this module
170 * 'dependencies' => [modile name string or array of module name strings],
171 * // Styles to always load
172 * 'styles' => [file path string or array of file path strings],
173 * // Styles to include in specific skin contexts
174 * 'skinStyles' => array(
175 * [skin name] => [file path string or array of file path strings],
176 * ),
177 * // Messages to always load
178 * 'messages' => [array of message key strings],
179 * // Group which this module should be loaded together with
180 * 'group' => [group name string],
181 * // Position on the page to load this module at
182 * 'position' => ['bottom' (default) or 'top']
184 * @endcode
186 public function __construct( $options = array(), $localBasePath = null,
187 $remoteBasePath = null )
189 global $IP, $wgScriptPath, $wgResourceBasePath;
190 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
191 if ( $remoteBasePath !== null ) {
192 $this->remoteBasePath = $remoteBasePath;
193 } else {
194 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
197 if ( isset( $options['remoteExtPath'] ) ) {
198 global $wgExtensionAssetsPath;
199 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
202 foreach ( $options as $member => $option ) {
203 switch ( $member ) {
204 // Lists of file paths
205 case 'scripts':
206 case 'debugScripts':
207 case 'loaderScripts':
208 case 'styles':
209 $this->{$member} = (array) $option;
210 break;
211 // Collated lists of file paths
212 case 'languageScripts':
213 case 'skinScripts':
214 case 'skinStyles':
215 if ( !is_array( $option ) ) {
216 throw new MWException(
217 "Invalid collated file path list error. " .
218 "'$option' given, array expected."
221 foreach ( $option as $key => $value ) {
222 if ( !is_string( $key ) ) {
223 throw new MWException(
224 "Invalid collated file path list key error. " .
225 "'$key' given, string expected."
228 $this->{$member}[$key] = (array) $value;
230 break;
231 // Lists of strings
232 case 'dependencies':
233 case 'messages':
234 $this->{$member} = (array) $option;
235 break;
236 // Single strings
237 case 'group':
238 case 'position':
239 case 'localBasePath':
240 case 'remoteBasePath':
241 $this->{$member} = (string) $option;
242 break;
243 // Single booleans
244 case 'debugRaw':
245 case 'raw':
246 $this->{$member} = (bool) $option;
247 break;
250 // Make sure the remote base path is a complete valid URL,
251 // but possibly protocol-relative to avoid cache pollution
252 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
256 * Gets all scripts for a given context concatenated together.
258 * @param $context ResourceLoaderContext: Context in which to generate script
259 * @return String: JavaScript code for $context
261 public function getScript( ResourceLoaderContext $context ) {
262 $files = $this->getScriptFiles( $context );
263 return $this->readScriptFiles( $files );
267 * @param $context ResourceLoaderContext
268 * @return array
270 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
271 $urls = array();
272 foreach ( $this->getScriptFiles( $context ) as $file ) {
273 $urls[] = $this->getRemotePath( $file );
275 return $urls;
279 * @return bool
281 public function supportsURLLoading() {
282 return $this->debugRaw;
286 * Gets loader script.
288 * @return String: JavaScript code to be added to startup module
290 public function getLoaderScript() {
291 if ( count( $this->loaderScripts ) == 0 ) {
292 return false;
294 return $this->readScriptFiles( $this->loaderScripts );
298 * Gets all styles for a given context concatenated together.
300 * @param $context ResourceLoaderContext: Context in which to generate styles
301 * @return String: CSS code for $context
303 public function getStyles( ResourceLoaderContext $context ) {
304 $styles = $this->readStyleFiles(
305 $this->getStyleFiles( $context ),
306 $this->getFlip( $context )
308 // Collect referenced files
309 $this->localFileRefs = array_unique( $this->localFileRefs );
310 // If the list has been modified since last time we cached it, update the cache
311 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) && !wfReadOnly() ) {
312 $dbw = wfGetDB( DB_MASTER );
313 $dbw->replace( 'module_deps',
314 array( array( 'md_module', 'md_skin' ) ), array(
315 'md_module' => $this->getName(),
316 'md_skin' => $context->getSkin(),
317 'md_deps' => FormatJson::encode( $this->localFileRefs ),
321 return $styles;
325 * @param $context ResourceLoaderContext
326 * @return array
328 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
329 $urls = array();
330 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
331 $urls[$mediaType] = array();
332 foreach ( $list as $file ) {
333 $urls[$mediaType][] = $this->getRemotePath( $file );
336 return $urls;
340 * Gets list of message keys used by this module.
342 * @return Array: List of message keys
344 public function getMessages() {
345 return $this->messages;
349 * Gets the name of the group this module should be loaded in.
351 * @return String: Group name
353 public function getGroup() {
354 return $this->group;
358 * @return string
360 public function getPosition() {
361 return $this->position;
365 * Gets list of names of modules this module depends on.
367 * @return Array: List of module names
369 public function getDependencies() {
370 return $this->dependencies;
374 * @return bool
376 public function isRaw() {
377 return $this->raw;
381 * Get the last modified timestamp of this module.
383 * Last modified timestamps are calculated from the highest last modified
384 * timestamp of this module's constituent files as well as the files it
385 * depends on. This function is context-sensitive, only performing
386 * calculations on files relevant to the given language, skin and debug
387 * mode.
389 * @param $context ResourceLoaderContext: Context in which to calculate
390 * the modified time
391 * @return Integer: UNIX timestamp
392 * @see ResourceLoaderModule::getFileDependencies
394 public function getModifiedTime( ResourceLoaderContext $context ) {
395 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
396 return $this->modifiedTime[$context->getHash()];
398 wfProfileIn( __METHOD__ );
400 $files = array();
402 // Flatten style files into $files
403 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
404 foreach ( $styles as $styleFiles ) {
405 $files = array_merge( $files, $styleFiles );
407 $skinFiles = self::tryForKey(
408 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
409 $context->getSkin(),
410 'default'
412 foreach ( $skinFiles as $styleFiles ) {
413 $files = array_merge( $files, $styleFiles );
416 // Final merge, this should result in a master list of dependent files
417 $files = array_merge(
418 $files,
419 $this->scripts,
420 $context->getDebug() ? $this->debugScripts : array(),
421 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
422 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
423 $this->loaderScripts
425 $files = array_map( array( $this, 'getLocalPath' ), $files );
426 // File deps need to be treated separately because they're already prefixed
427 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
429 // If a module is nothing but a list of dependencies, we need to avoid
430 // giving max() an empty array
431 if ( count( $files ) === 0 ) {
432 wfProfileOut( __METHOD__ );
433 return $this->modifiedTime[$context->getHash()] = 1;
436 wfProfileIn( __METHOD__.'-filemtime' );
437 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
438 wfProfileOut( __METHOD__.'-filemtime' );
439 $this->modifiedTime[$context->getHash()] = max(
440 $filesMtime,
441 $this->getMsgBlobMtime( $context->getLanguage() ) );
443 wfProfileOut( __METHOD__ );
444 return $this->modifiedTime[$context->getHash()];
447 /* Protected Methods */
450 * @param $path string
451 * @return string
453 protected function getLocalPath( $path ) {
454 return "{$this->localBasePath}/$path";
458 * @param $path string
459 * @return string
461 protected function getRemotePath( $path ) {
462 return "{$this->remoteBasePath}/$path";
466 * Collates file paths by option (where provided).
468 * @param $list Array: List of file paths in any combination of index/path
469 * or path/options pairs
470 * @param $option String: option name
471 * @param $default Mixed: default value if the option isn't set
472 * @return Array: List of file paths, collated by $option
474 protected static function collateFilePathListByOption( array $list, $option, $default ) {
475 $collatedFiles = array();
476 foreach ( (array) $list as $key => $value ) {
477 if ( is_int( $key ) ) {
478 // File name as the value
479 if ( !isset( $collatedFiles[$default] ) ) {
480 $collatedFiles[$default] = array();
482 $collatedFiles[$default][] = $value;
483 } elseif ( is_array( $value ) ) {
484 // File name as the key, options array as the value
485 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
486 if ( !isset( $collatedFiles[$optionValue] ) ) {
487 $collatedFiles[$optionValue] = array();
489 $collatedFiles[$optionValue][] = $key;
492 return $collatedFiles;
496 * Gets a list of element that match a key, optionally using a fallback key.
498 * @param $list Array: List of lists to select from
499 * @param $key String: Key to look for in $map
500 * @param $fallback String: Key to look for in $list if $key doesn't exist
501 * @return Array: List of elements from $map which matched $key or $fallback,
502 * or an empty list in case of no match
504 protected static function tryForKey( array $list, $key, $fallback = null ) {
505 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
506 return $list[$key];
507 } elseif ( is_string( $fallback )
508 && isset( $list[$fallback] )
509 && is_array( $list[$fallback] ) )
511 return $list[$fallback];
513 return array();
517 * Gets a list of file paths for all scripts in this module, in order of propper execution.
519 * @param $context ResourceLoaderContext: Context
520 * @return Array: List of file paths
522 protected function getScriptFiles( ResourceLoaderContext $context ) {
523 $files = array_merge(
524 $this->scripts,
525 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
526 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
528 if ( $context->getDebug() ) {
529 $files = array_merge( $files, $this->debugScripts );
531 return $files;
535 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
537 * @param $context ResourceLoaderContext: Context
538 * @return Array: List of file paths
540 protected function getStyleFiles( ResourceLoaderContext $context ) {
541 return array_merge_recursive(
542 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
543 self::collateFilePathListByOption(
544 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
550 * Gets the contents of a list of JavaScript files.
552 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
553 * @return String: Concatenated and remapped JavaScript data from $scripts
555 protected function readScriptFiles( array $scripts ) {
556 global $wgResourceLoaderValidateStaticJS;
557 if ( empty( $scripts ) ) {
558 return '';
560 $js = '';
561 foreach ( array_unique( $scripts ) as $fileName ) {
562 $localPath = $this->getLocalPath( $fileName );
563 if ( !file_exists( $localPath ) ) {
564 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
566 $contents = file_get_contents( $localPath );
567 if ( $wgResourceLoaderValidateStaticJS ) {
568 // Static files don't really need to be checked as often; unlike
569 // on-wiki module they shouldn't change unexpectedly without
570 // admin interference.
571 $contents = $this->validateScriptFile( $fileName, $contents );
573 $js .= $contents . "\n";
575 return $js;
579 * Gets the contents of a list of CSS files.
581 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
582 * concetenate
584 * @param $flip bool
586 * @return Array: List of concatenated and remapped CSS data from $styles,
587 * keyed by media type
589 protected function readStyleFiles( array $styles, $flip ) {
590 if ( empty( $styles ) ) {
591 return array();
593 foreach ( $styles as $media => $files ) {
594 $uniqueFiles = array_unique( $files );
595 $styles[$media] = implode(
596 "\n",
597 array_map(
598 array( $this, 'readStyleFile' ),
599 $uniqueFiles,
600 array_fill( 0, count( $uniqueFiles ), $flip )
604 return $styles;
608 * Reads a style file.
610 * This method can be used as a callback for array_map()
612 * @param $path String: File path of style file to read
613 * @param $flip bool
615 * @return String: CSS data in script file
616 * @throws MWException if the file doesn't exist
618 protected function readStyleFile( $path, $flip ) {
619 $localPath = $this->getLocalPath( $path );
620 if ( !file_exists( $localPath ) ) {
621 throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
623 $style = file_get_contents( $localPath );
624 if ( $flip ) {
625 $style = CSSJanus::transform( $style, true, false );
627 $dirname = dirname( $path );
628 if ( $dirname == '.' ) {
629 // If $path doesn't have a directory component, don't prepend a dot
630 $dirname = '';
632 $dir = $this->getLocalPath( $dirname );
633 $remoteDir = $this->getRemotePath( $dirname );
634 // Get and register local file references
635 $this->localFileRefs = array_merge(
636 $this->localFileRefs,
637 CSSMin::getLocalFileReferences( $style, $dir ) );
638 return CSSMin::remap(
639 $style, $dir, $remoteDir, true
644 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
645 * but returns 1 instead.
646 * @param $filename string File name
647 * @return int UNIX timestamp, or 1 if the file doesn't exist
649 protected static function safeFilemtime( $filename ) {
650 if ( file_exists( $filename ) ) {
651 return filemtime( $filename );
652 } else {
653 // We only ever map this function on an array if we're gonna call max() after,
654 // so return our standard minimum timestamps here. This is 1, not 0, because
655 // wfTimestamp(0) == NOW
656 return 1;
661 * Get whether CSS for this module should be flipped
662 * @param $context ResourceLoaderContext
663 * @return bool
665 public function getFlip( $context ) {
666 return $context->getDirection() === 'rtl';