Remove $wgServer prepending from remote JS/CSS paths. It's not needed and breaks...
[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 /** String: Local base path, see __construct() */
31 protected $localBasePath = '';
32 /** String: Remote base path, see __construct() */
33 protected $remoteBasePath = '';
34 /**
35 * Array: List of paths to JavaScript files to always include
36 * @example array( [file-path], [file-path], ... )
37 */
38 protected $scripts = array();
39 /**
40 * Array: List of JavaScript files to include when using a specific language
41 * @example array( [language-code] => array( [file-path], [file-path], ... ), ... )
42 */
43 protected $languageScripts = array();
44 /**
45 * Array: List of JavaScript files to include when using a specific skin
46 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
47 */
48 protected $skinScripts = array();
49 /**
50 * Array: List of paths to JavaScript files to include in debug mode
51 * @example array( [skin-name] => array( [file-path], [file-path], ... ), ... )
52 */
53 protected $debugScripts = array();
54 /**
55 * Array: List of paths to JavaScript files to include in the startup module
56 * @example array( [file-path], [file-path], ... )
57 */
58 protected $loaderScripts = array();
59 /**
60 * Array: List of paths to CSS files to always include
61 * @example array( [file-path], [file-path], ... )
62 */
63 protected $styles = array();
64 /**
65 * Array: List of paths to CSS files to include when using specific skins
66 * @example array( [file-path], [file-path], ... )
67 */
68 protected $skinStyles = array();
69 /**
70 * Array: List of modules this module depends on
71 * @example array( [file-path], [file-path], ... )
72 */
73 protected $dependencies = array();
74 /**
75 * Array: List of message keys used by this module
76 * @example array( [message-key], [message-key], ... )
77 */
78 protected $messages = array();
79 /** String: Name of group to load this module in */
80 protected $group;
81 /** Boolean: Link to raw files in debug mode */
82 protected $debugRaw = true;
83 /**
84 * Array: Cache for mtime
85 * @example array( [hash] => [mtime], [hash] => [mtime], ... )
86 */
87 protected $modifiedTime = array();
88 /**
89 * Array: Place where readStyleFile() tracks file dependencies
90 * @example 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 $options Array: List of options; if not given or empty, an empty module will be
100 * constructed
101 * @param $localBasePath String: Base path to prepend to all local paths in $options. Defaults
102 * to $IP
103 * @param $remoteBasePath String: Base path to prepend to all remote paths in $options. Defaults
104 * to $wgScriptPath
105 *
106 * @example $options
107 * array(
108 * // Base path to prepend to all local paths in $options. Defaults to $IP
109 * 'localBasePath' => [base path],
110 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
111 * 'remoteBasePath' => [base path],
112 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
113 * 'remoteExtPath' => [base path],
114 * // Scripts to always include
115 * 'scripts' => [file path string or array of file path strings],
116 * // Scripts to include in specific language contexts
117 * 'languageScripts' => array(
118 * [language code] => [file path string or array of file path strings],
119 * ),
120 * // Scripts to include in specific skin contexts
121 * 'skinScripts' => array(
122 * [skin name] => [file path string or array of file path strings],
123 * ),
124 * // Scripts to include in debug contexts
125 * 'debugScripts' => [file path string or array of file path strings],
126 * // Scripts to include in the startup module
127 * 'loaderScripts' => [file path string or array of file path strings],
128 * // Modules which must be loaded before this module
129 * 'dependencies' => [modile name string or array of module name strings],
130 * // Styles to always load
131 * 'styles' => [file path string or array of file path strings],
132 * // Styles to include in specific skin contexts
133 * 'skinStyles' => array(
134 * [skin name] => [file path string or array of file path strings],
135 * ),
136 * // Messages to always load
137 * 'messages' => [array of message key strings],
138 * // Group which this module should be loaded together with
139 * 'group' => [group name string],
140 * )
141 */
142 public function __construct( $options = array(), $localBasePath = null,
143 $remoteBasePath = null )
144 {
145 global $IP, $wgScriptPath;
146 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
147 $this->remoteBasePath = $remoteBasePath === null ? $wgScriptPath : $remoteBasePath;
148
149 if ( isset( $options['remoteExtPath'] ) ) {
150 global $wgExtensionAssetsPath;
151 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
152 }
153
154 foreach ( $options as $member => $option ) {
155 switch ( $member ) {
156 // Lists of file paths
157 case 'scripts':
158 case 'debugScripts':
159 case 'loaderScripts':
160 case 'styles':
161 $this->{$member} = (array) $option;
162 break;
163 // Collated lists of file paths
164 case 'languageScripts':
165 case 'skinScripts':
166 case 'skinStyles':
167 if ( !is_array( $option ) ) {
168 throw new MWException(
169 "Invalid collated file path list error. " .
170 "'$option' given, array expected."
171 );
172 }
173 foreach ( $option as $key => $value ) {
174 if ( !is_string( $key ) ) {
175 throw new MWException(
176 "Invalid collated file path list key error. " .
177 "'$key' given, string expected."
178 );
179 }
180 $this->{$member}[$key] = (array) $value;
181 }
182 break;
183 // Lists of strings
184 case 'dependencies':
185 case 'messages':
186 $this->{$member} = (array) $option;
187 break;
188 // Single strings
189 case 'group':
190 case 'localBasePath':
191 case 'remoteBasePath':
192 $this->{$member} = (string) $option;
193 break;
194 // Single booleans
195 case 'debugRaw':
196 $this->{$member} = (bool) $option;
197 break;
198 }
199 }
200 }
201
202 /**
203 * Gets all scripts for a given context concatenated together.
204 *
205 * @param $context ResourceLoaderContext: Context in which to generate script
206 * @return String: JavaScript code for $context
207 */
208 public function getScript( ResourceLoaderContext $context ) {
209 $files = array_merge(
210 $this->scripts,
211 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
212 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
213 );
214 if ( $context->getDebug() ) {
215 $files = array_merge( $files, $this->debugScripts );
216 if ( $this->debugRaw ) {
217 $script = '';
218 foreach ( $files as $file ) {
219 $path = $this->getRemotePath( $file );
220 $script .= "\n\t" . Xml::encodeJsCall( 'mediaWiki.loader.load', array( $path ) );
221 }
222 return $script;
223 }
224 }
225 return $this->readScriptFiles( $files );
226 }
227
228 /**
229 * Gets loader script.
230 *
231 * @return String: JavaScript code to be added to startup module
232 */
233 public function getLoaderScript() {
234 if ( count( $this->loaderScripts ) == 0 ) {
235 return false;
236 }
237 return $this->readScriptFiles( $this->loaderScripts );
238 }
239
240 /**
241 * Gets all styles for a given context concatenated together.
242 *
243 * @param $context ResourceLoaderContext: Context in which to generate styles
244 * @return String: CSS code for $context
245 */
246 public function getStyles( ResourceLoaderContext $context ) {
247 // Merge general styles and skin specific styles, retaining media type collation
248 $styles = $this->readStyleFiles( $this->styles, $this->getFlip( $context ) );
249 $skinStyles = $this->readStyleFiles(
250 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
251 $this->getFlip( $context )
252 );
253
254 foreach ( $skinStyles as $media => $style ) {
255 if ( isset( $styles[$media] ) ) {
256 $styles[$media] .= $style;
257 } else {
258 $styles[$media] = $style;
259 }
260 }
261 // Collect referenced files
262 $this->localFileRefs = array_unique( $this->localFileRefs );
263 // If the list has been modified since last time we cached it, update the cache
264 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
265 $dbw = wfGetDB( DB_MASTER );
266 $dbw->replace( 'module_deps',
267 array( array( 'md_module', 'md_skin' ) ), array(
268 'md_module' => $this->getName(),
269 'md_skin' => $context->getSkin(),
270 'md_deps' => FormatJson::encode( $this->localFileRefs ),
271 )
272 );
273 }
274 return $styles;
275 }
276
277 /**
278 * Gets list of message keys used by this module.
279 *
280 * @return Array: List of message keys
281 */
282 public function getMessages() {
283 return $this->messages;
284 }
285
286 /**
287 * Gets the name of the group this module should be loaded in.
288 *
289 * @return String: Group name
290 */
291 public function getGroup() {
292 return $this->group;
293 }
294
295 /**
296 * Gets list of names of modules this module depends on.
297 *
298 * @return Array: List of module names
299 */
300 public function getDependencies() {
301 return $this->dependencies;
302 }
303
304 /**
305 * Get the last modified timestamp of this module.
306 *
307 * Last modified timestamps are calculated from the highest last modified
308 * timestamp of this module's constituent files as well as the files it
309 * depends on. This function is context-sensitive, only performing
310 * calculations on files relevant to the given language, skin and debug
311 * mode.
312 *
313 * @param $context ResourceLoaderContext: Context in which to calculate
314 * the modified time
315 * @return Integer: UNIX timestamp
316 * @see ResourceLoaderModule::getFileDependencies
317 */
318 public function getModifiedTime( ResourceLoaderContext $context ) {
319 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
320 return $this->modifiedTime[$context->getHash()];
321 }
322 wfProfileIn( __METHOD__ );
323
324 $files = array();
325
326 // Flatten style files into $files
327 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
328 foreach ( $styles as $styleFiles ) {
329 $files = array_merge( $files, $styleFiles );
330 }
331 $skinFiles = self::tryForKey(
332 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
333 $context->getSkin(),
334 'default'
335 );
336 foreach ( $skinFiles as $styleFiles ) {
337 $files = array_merge( $files, $styleFiles );
338 }
339
340 // Final merge, this should result in a master list of dependent files
341 $files = array_merge(
342 $files,
343 $this->scripts,
344 $context->getDebug() ? $this->debugScripts : array(),
345 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
346 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
347 $this->loaderScripts
348 );
349 $files = array_map( array( $this, 'getLocalPath' ), $files );
350 // File deps need to be treated separately because they're already prefixed
351 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
352
353 // If a module is nothing but a list of dependencies, we need to avoid
354 // giving max() an empty array
355 if ( count( $files ) === 0 ) {
356 return $this->modifiedTime[$context->getHash()] = 1;
357 }
358
359 wfProfileIn( __METHOD__.'-filemtime' );
360 $filesMtime = max( array_map( 'filemtime', $files ) );
361 wfProfileOut( __METHOD__.'-filemtime' );
362 $this->modifiedTime[$context->getHash()] = max(
363 $filesMtime,
364 $this->getMsgBlobMtime( $context->getLanguage() ) );
365 wfProfileOut( __METHOD__ );
366 return $this->modifiedTime[$context->getHash()];
367 }
368
369 /* Protected Members */
370
371 protected function getLocalPath( $path ) {
372 return "{$this->localBasePath}/$path";
373 }
374
375 protected function getRemotePath( $path ) {
376 return "{$this->remoteBasePath}/$path";
377 }
378
379 /**
380 * Collates file paths by option (where provided).
381 *
382 * @param $list Array: List of file paths in any combination of index/path
383 * or path/options pairs
384 * @param $option String: option name
385 * @param $default Mixed: default value if the option isn't set
386 * @return Array: List of file paths, collated by $option
387 */
388 protected static function collateFilePathListByOption( array $list, $option, $default ) {
389 $collatedFiles = array();
390 foreach ( (array) $list as $key => $value ) {
391 if ( is_int( $key ) ) {
392 // File name as the value
393 if ( !isset( $collatedFiles[$default] ) ) {
394 $collatedFiles[$default] = array();
395 }
396 $collatedFiles[$default][] = $value;
397 } else if ( is_array( $value ) ) {
398 // File name as the key, options array as the value
399 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
400 if ( !isset( $collatedFiles[$optionValue] ) ) {
401 $collatedFiles[$optionValue] = array();
402 }
403 $collatedFiles[$optionValue][] = $key;
404 }
405 }
406 return $collatedFiles;
407 }
408
409 /**
410 * Gets a list of element that match a key, optionally using a fallback key.
411 *
412 * @param $list Array: List of lists to select from
413 * @param $key String: Key to look for in $map
414 * @param $fallback String: Key to look for in $list if $key doesn't exist
415 * @return Array: List of elements from $map which matched $key or $fallback,
416 * or an empty list in case of no match
417 */
418 protected static function tryForKey( array $list, $key, $fallback = null ) {
419 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
420 return $list[$key];
421 } else if ( is_string( $fallback )
422 && isset( $list[$fallback] )
423 && is_array( $list[$fallback] ) )
424 {
425 return $list[$fallback];
426 }
427 return array();
428 }
429
430 /**
431 * Gets the contents of a list of JavaScript files.
432 *
433 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
434 * @return String: Concatenated and remapped JavaScript data from $scripts
435 */
436 protected function readScriptFiles( array $scripts ) {
437 if ( empty( $scripts ) ) {
438 return '';
439 }
440 $js = '';
441 foreach ( array_unique( $scripts ) as $fileName ) {
442 $localPath = $this->getLocalPath( $fileName );
443 $contents = file_get_contents( $localPath );
444 if ( $contents === false ) {
445 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
446 }
447 $js .= $contents . "\n";
448 }
449 return $js;
450 }
451
452 /**
453 * Gets the contents of a list of CSS files.
454 *
455 * @param $styles Array: List of file paths to styles to read, remap and concetenate
456 * @return Array: List of concatenated and remapped CSS data from $styles,
457 * keyed by media type
458 */
459 protected function readStyleFiles( array $styles, $flip ) {
460 if ( empty( $styles ) ) {
461 return array();
462 }
463 $styles = self::collateFilePathListByOption( $styles, 'media', 'all' );
464 foreach ( $styles as $media => $files ) {
465 $uniqueFiles = array_unique( $files );
466 $styles[$media] = implode(
467 "\n",
468 array_map(
469 array( $this, 'readStyleFile' ),
470 $uniqueFiles,
471 array_fill( 0, count( $uniqueFiles ), $flip )
472 )
473 );
474 }
475 return $styles;
476 }
477
478 /**
479 * Reads a style file.
480 *
481 * This method can be used as a callback for array_map()
482 *
483 * @param $path String: File path of script file to read
484 * @return String: CSS data in script file
485 */
486 protected function readStyleFile( $path, $flip ) {
487 $localPath = $this->getLocalPath( $path );
488 $style = file_get_contents( $localPath );
489 if ( $style === false ) {
490 throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
491 }
492 if ( $flip ) {
493 $style = CSSJanus::transform( $style, true, false );
494 }
495 $dirname = dirname( $path );
496 if ( $dirname == '.' ) {
497 // If $path doesn't have a directory component, don't prepend a dot
498 $dirname = '';
499 }
500 $dir = $this->getLocalPath( $dirname );
501 $remoteDir = $this->getRemotePath( $dirname );
502 // Get and register local file references
503 $this->localFileRefs = array_merge(
504 $this->localFileRefs,
505 CSSMin::getLocalFileReferences( $style, $dir ) );
506 return CSSMin::remap(
507 $style, $dir, $remoteDir, true
508 );
509 }
510 }