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