Resource loader minor changes. Fix for r73668 etc.
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 /**
24 * ResourceLoader module based on local JavaScript/CSS files.
25 */
26 class ResourceLoaderFileModule extends ResourceLoaderModule {
27
28 /* Protected Members */
29
30 /** @var {string} Local base path, see __construct() */
31 protected $localBasePath = '';
32 /** @var {string} Remote base path, see __construct() */
33 protected $remoteBasePath = '';
34 /**
35 * @var {array} List of paths to JavaScript files to always include
36 * @format array( [file-path], [file-path], ... )
37 */
38 protected $scripts = array();
39 /**
40 * @var {array} List of JavaScript files to include when using a specific language
41 * @format array( [language-code] => array( [file-path], [file-path], ... ), ... )
42 */
43 protected $languageScripts = array();
44 /**
45 * @var {array} List of JavaScript files to include when using a specific skin
46 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
47 */
48 protected $skinScripts = array();
49 /**
50 * @var {array} List of paths to JavaScript files to include in debug mode
51 * @format array( [skin-name] => array( [file-path], [file-path], ... ), ... )
52 */
53 protected $debugScripts = array();
54 /**
55 * @var {array} List of paths to JavaScript files to include in the startup module
56 * @format array( [file-path], [file-path], ... )
57 */
58 protected $loaderScripts = array();
59 /**
60 * @var {array} List of paths to CSS files to always include
61 * @format array( [file-path], [file-path], ... )
62 */
63 protected $styles = array();
64 /**
65 * @var {array} List of paths to CSS files to include when using specific skins
66 * @format array( [file-path], [file-path], ... )
67 */
68 protected $skinStyles = array();
69 /**
70 * @var {array} List of modules this module depends on
71 * @format array( [file-path], [file-path], ... )
72 */
73 protected $dependencies = array();
74 /**
75 * @var {array} List of message keys used by this module
76 * @format array( [message-key], [message-key], ... )
77 */
78 protected $messages = array();
79 /** @var {string} Name of group to load this module in */
80 protected $group;
81 /** @var {boolean} Link to raw files in debug mode */
82 protected $debugRaw = true;
83 /**
84 * @var {array} Cache for mtime
85 * @format array( [hash] => [mtime], [hash] => [mtime], ... )
86 */
87 protected $modifiedTime = array();
88 /**
89 * @var {array} Place where readStyleFile() tracks file dependencies
90 * @format array( [file-path], [file-path], ... )
91 */
92 protected $localFileRefs = array();
93
94 /* Methods */
95
96 /**
97 * Constructs a new module from an options array.
98 *
99 * @param {array} $options Options array. If not given or empty, an empty module will be constructed
100 * @param {string} $localBasePath base path to prepend to all local paths in $options. Defaults to $IP
101 * @param {string} $remoteBasePath base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
102 *
103 * @format $options
104 * array(
105 * // Scripts to always include
106 * 'scripts' => [file path string or array of file path strings],
107 * // Scripts to include in specific language contexts
108 * 'languageScripts' => array(
109 * [language code] => [file path string or array of file path strings],
110 * ),
111 * // Scripts to include in specific skin contexts
112 * 'skinScripts' => array(
113 * [skin name] => [file path string or array of file path strings],
114 * ),
115 * // Scripts to include in debug contexts
116 * 'debugScripts' => [file path string or array of file path strings],
117 * // Scripts to include in the startup module
118 * 'loaderScripts' => [file path string or array of file path strings],
119 * // Modules which must be loaded before this module
120 * 'dependencies' => [modile name string or array of module name strings],
121 * // Styles to always load
122 * 'styles' => [file path string or array of file path strings],
123 * // Styles to include in specific skin contexts
124 * 'skinStyles' => array(
125 * [skin name] => [file path string or array of file path strings],
126 * ),
127 * // Messages to always load
128 * 'messages' => [array of message key strings],
129 * // Group which this module should be loaded together with
130 * 'group' => [group name string],
131 * )
132 */
133 public function __construct( $options = array(), $localBasePath = null, $remoteBasePath = null ) {
134 global $IP, $wgScriptPath;
135 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
136 $this->remoteBasePath = $remoteBasePath === null ? $wgScriptPath : $remoteBasePath;
137 foreach ( $options as $member => $option ) {
138 switch ( $member ) {
139 // Lists of file paths
140 case 'scripts':
141 case 'debugScripts':
142 case 'loaderScripts':
143 case 'styles':
144 $this->{$member} = (array) $option;
145 break;
146 // Collated lists of file paths
147 case 'languageScripts':
148 case 'skinScripts':
149 case 'skinStyles':
150 if ( !is_array( $option ) ) {
151 throw new MWException(
152 "Invalid collated file path list error. '$option' given, array expected."
153 );
154 }
155 foreach ( $option as $key => $value ) {
156 if ( !is_string( $key ) ) {
157 throw new MWException(
158 "Invalid collated file path list key error. '$key' given, string expected."
159 );
160 }
161 $this->{$member}[$key] = (array) $value;
162 }
163 break;
164 // Lists of strings
165 case 'dependencies':
166 case 'messages':
167 $this->{$member} = (array) $option;
168 break;
169 // Single strings
170 case 'group':
171 $this->{$member} = (string) $option;
172 break;
173 // Single booleans
174 case 'debugRaw':
175 $this->{$member} = (bool) $option;
176 break;
177 }
178 }
179 }
180
181 /**
182 * Gets all scripts for a given context concatenated together.
183 *
184 * @param {ResourceLoaderContext} $context Context in which to generate script
185 * @return {string} JavaScript code for $context
186 */
187 public function getScript( ResourceLoaderContext $context ) {
188 global $wgServer;
189
190 $files = array_merge(
191 $this->scripts,
192 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
193 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
194 );
195 if ( $context->getDebug() ) {
196 $files = array_merge( $files, $this->debugScripts );
197 if ( $this->debugRaw ) {
198 $script = '';
199 foreach ( $files as $file ) {
200 $path = FormatJson::encode( $wgServer . $this->getRemotePath( $file ) );
201 $script .= "\n\tmediaWiki.loader.load( $path );";
202 }
203 return $script;
204 }
205 }
206 return $this->readScriptFiles( $files );
207 }
208
209 /**
210 * Gets loader script.
211 *
212 * @return {string} JavaScript code to be added to startup module
213 */
214 public function getLoaderScript() {
215 if ( count( $this->loaderScripts ) == 0 ) {
216 return false;
217 }
218 return $this->readScriptFiles( $this->loaderScripts );
219 }
220
221 /**
222 * Gets all styles for a given context concatenated together.
223 *
224 * @param {ResourceLoaderContext} $context Context in which to generate styles
225 * @return {string} CSS code for $context
226 */
227 public function getStyles( ResourceLoaderContext $context ) {
228 // Merge general styles and skin specific styles, retaining media type collation
229 $styles = $this->readStyleFiles( $this->styles );
230 $skinStyles = $this->readStyleFiles( self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ) );
231
232 foreach ( $skinStyles as $media => $style ) {
233 if ( isset( $styles[$media] ) ) {
234 $styles[$media] .= $style;
235 } else {
236 $styles[$media] = $style;
237 }
238 }
239 // Collect referenced files
240 $this->localFileRefs = array_unique( $this->localFileRefs );
241 // If the list has been modified since last time we cached it, update the cache
242 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
243 $dbw = wfGetDB( DB_MASTER );
244 $dbw->replace( 'module_deps',
245 array( array( 'md_module', 'md_skin' ) ), array(
246 'md_module' => $this->getName(),
247 'md_skin' => $context->getSkin(),
248 'md_deps' => FormatJson::encode( $this->localFileRefs ),
249 )
250 );
251 }
252 return $styles;
253 }
254
255 /**
256 * Gets list of message keys used by this module.
257 *
258 * @return {array} List of message keys
259 */
260 public function getMessages() {
261 return $this->messages;
262 }
263
264 /**
265 * Gets the name of the group this module should be loaded in.
266 *
267 * @return {string} Group name
268 */
269 public function getGroup() {
270 return $this->group;
271 }
272
273 /**
274 * Gets list of names of modules this module depends on.
275 *
276 * @return {array} List of module names
277 */
278 public function getDependencies() {
279 return $this->dependencies;
280 }
281
282 /**
283 * Get the last modified timestamp of this module.
284 *
285 * Last modified timestamps are calculated from the highest last modified timestamp of this module's constituent
286 * files as well as the files it depends on. This function is context-sensitive, only performing calculations on
287 * files relevant to the given language, skin and debug mode.
288 *
289 * @param {ResourceLoaderContext} $context Context in which to calculate the modified time
290 * @return {integer} UNIX timestamp
291 * @see {ResourceLoaderModule::getFileDependencies}
292 */
293 public function getModifiedTime( ResourceLoaderContext $context ) {
294 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
295 return $this->modifiedTime[$context->getHash()];
296 }
297 wfProfileIn( __METHOD__ );
298
299 $files = array();
300
301 // Flatten style files into $files
302 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
303 foreach ( $styles as $styleFiles ) {
304 $files = array_merge( $files, $styleFiles );
305 }
306 $skinFiles = self::tryForKey(
307 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ), $context->getSkin(), 'default'
308 );
309 foreach ( $skinFiles as $styleFiles ) {
310 $files = array_merge( $files, $styleFiles );
311 }
312
313 // Final merge, this should result in a master list of dependent files
314 $files = array_merge(
315 $files,
316 $this->scripts,
317 $context->getDebug() ? $this->debugScripts : array(),
318 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
319 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
320 $this->loaderScripts
321 );
322 $files = array_map( array( $this, 'getLocalPath' ), $files );
323 // File deps need to be treated separately because they're already prefixed
324 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
325
326 // If a module is nothing but a list of dependencies, we need to avoid giving max() an empty array
327 if ( count( $files ) === 0 ) {
328 return $this->modifiedTime[$context->getHash()] = 1;
329 }
330
331 wfProfileIn( __METHOD__.'-filemtime' );
332 $filesMtime = max( array_map( 'filemtime', $files ) );
333 wfProfileOut( __METHOD__.'-filemtime' );
334 $this->modifiedTime[$context->getHash()] = max( $filesMtime, $this->getMsgBlobMtime( $context->getLanguage() ) );
335 wfProfileOut( __METHOD__ );
336 return $this->modifiedTime[$context->getHash()];
337 }
338
339 /* Protected Members */
340
341 protected function getLocalPath( $path ) {
342 return "{$this->localBasePath}/$path";
343 }
344
345 protected function getRemotePath( $path ) {
346 return "{$this->remoteBasePath}/$path";
347 }
348
349 /**
350 * Collates file paths by option (where provided).
351 *
352 * @param {array} $list List of file paths in any combination of index/path or path/options pairs
353 * @return {array} List of file paths, collated by $option
354 */
355 protected static function collateFilePathListByOption( array $list, $option, $default ) {
356 $collatedFiles = array();
357 foreach ( (array) $list as $key => $value ) {
358 if ( is_int( $key ) ) {
359 // File name as the value
360 if ( !isset( $collatedFiles[$default] ) ) {
361 $collatedFiles[$default] = array();
362 }
363 $collatedFiles[$default][] = $value;
364 } else if ( is_array( $value ) ) {
365 // File name as the key, options array as the value
366 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
367 if ( !isset( $collatedFiles[$optionValue] ) ) {
368 $collatedFiles[$optionValue] = array();
369 }
370 $collatedFiles[$optionValue][] = $key;
371 }
372 }
373 return $collatedFiles;
374 }
375
376 /**
377 * Gets a list of element that match a key, optionally using a fallback key.
378 *
379 * @param {array} $list List of lists to select from
380 * @param {string} $key Key to look for in $map
381 * @param {string} $fallback Key to look for in $list if $key doesn't exist
382 * @return {array} List of elements from $map which matched $key or $fallback, or an empty list in case of no match
383 */
384 protected static function tryForKey( array $list, $key, $fallback = null ) {
385 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
386 return $list[$key];
387 } else if ( is_string( $fallback ) && isset( $list[$fallback] ) && is_array( $list[$fallback] ) ) {
388 return $list[$fallback];
389 }
390 return array();
391 }
392
393 /**
394 * Gets the contents of a list of JavaScript files.
395 *
396 * @param {array} $scripts List of file paths to scripts to read, remap and concetenate
397 * @return {string} Concatenated and remapped JavaScript data from $scripts
398 */
399 protected function readScriptFiles( array $scripts ) {
400 if ( empty( $scripts ) ) {
401 return '';
402 }
403 return implode( "\n", array_map( 'file_get_contents', array_map( array( $this, 'getLocalPath' ), array_unique( $scripts ) ) ) );
404 }
405
406 /**
407 * Gets the contents of a list of CSS files.
408 *
409 * @param {array} $styles List of file paths to styles to read, remap and concetenate
410 * @return {array} List of concatenated and remapped CSS data from $styles, keyed by media type
411 */
412 protected function readStyleFiles( array $styles ) {
413 if ( empty( $styles ) ) {
414 return array();
415 }
416 $styles = self::collateFilePathListByOption( $styles, 'media', 'all' );
417 foreach ( $styles as $media => $files ) {
418 $styles[$media] = implode(
419 "\n", array_map( array( $this, 'readStyleFile' ), array_unique( $files ) )
420 );
421 }
422 return $styles;
423 }
424
425 /**
426 * Reads a style file.
427 *
428 * This method can be used as a callback for array_map()
429 *
430 * @param {string} $path File path of script file to read
431 * @return {string} CSS data in script file
432 */
433 protected function readStyleFile( $path ) {
434 $style = file_get_contents( $this->getLocalPath( $path ) );
435 $dir = $this->getLocalPath( dirname( $path ) );
436 $remoteDir = $this->getRemotePath( dirname( $path ) );
437 // Get and register local file references
438 $this->localFileRefs = array_merge( $this->localFileRefs, CSSMin::getLocalFileReferences( $style, $dir ) );
439 return CSSMin::remap(
440 $style, $dir, $remoteDir, true
441 );
442 }
443 }