ca215d5e10d98f357a3dbef8e3d52a6fd7187258
[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 // but possibly protocol-relative to avoid cache pollution
209 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
210 }
211
212 /**
213 * Gets all scripts for a given context concatenated together.
214 *
215 * @param $context ResourceLoaderContext: Context in which to generate script
216 * @return String: JavaScript code for $context
217 */
218 public function getScript( ResourceLoaderContext $context ) {
219 $files = $this->getScriptFiles( $context );
220 if ( $context->getDebug() && $this->debugRaw ) {
221 $urls = array();
222 foreach ( $this->getScriptFiles( $context ) as $file ) {
223 $urls[] = $this->getRemotePath( $file );
224 }
225 return $urls;
226 }
227 return $this->readScriptFiles( $files );
228 }
229
230 /**
231 * Gets loader script.
232 *
233 * @return String: JavaScript code to be added to startup module
234 */
235 public function getLoaderScript() {
236 if ( count( $this->loaderScripts ) == 0 ) {
237 return false;
238 }
239 return $this->readScriptFiles( $this->loaderScripts );
240 }
241
242 /**
243 * Gets all styles for a given context concatenated together.
244 *
245 * @param $context ResourceLoaderContext: Context in which to generate styles
246 * @return String: CSS code for $context
247 */
248 public function getStyles( ResourceLoaderContext $context ) {
249 $styles = $this->readStyleFiles(
250 $this->getStyleFiles( $context ),
251 $this->getFlip( $context )
252 );
253 if ( !$context->getOnly() && $context->getDebug() && $this->debugRaw ) {
254 $urls = array();
255 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
256 $urls[$mediaType] = array();
257 foreach ( $list as $file ) {
258 $urls[$mediaType][] = $this->getRemotePath( $file );
259 }
260 }
261 return $urls;
262 }
263 // Collect referenced files
264 $this->localFileRefs = array_unique( $this->localFileRefs );
265 // If the list has been modified since last time we cached it, update the cache
266 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
267 $dbw = wfGetDB( DB_MASTER );
268 $dbw->replace( 'module_deps',
269 array( array( 'md_module', 'md_skin' ) ), array(
270 'md_module' => $this->getName(),
271 'md_skin' => $context->getSkin(),
272 'md_deps' => FormatJson::encode( $this->localFileRefs ),
273 )
274 );
275 }
276 return $styles;
277 }
278
279 /**
280 * Gets list of message keys used by this module.
281 *
282 * @return Array: List of message keys
283 */
284 public function getMessages() {
285 return $this->messages;
286 }
287
288 /**
289 * Gets the name of the group this module should be loaded in.
290 *
291 * @return String: Group name
292 */
293 public function getGroup() {
294 return $this->group;
295 }
296
297 /**
298 * @return string
299 */
300 public function getPosition() {
301 return $this->position;
302 }
303
304 /**
305 * Gets list of names of modules this module depends on.
306 *
307 * @return Array: List of module names
308 */
309 public function getDependencies() {
310 return $this->dependencies;
311 }
312
313 /**
314 * Get the last modified timestamp of this module.
315 *
316 * Last modified timestamps are calculated from the highest last modified
317 * timestamp of this module's constituent files as well as the files it
318 * depends on. This function is context-sensitive, only performing
319 * calculations on files relevant to the given language, skin and debug
320 * mode.
321 *
322 * @param $context ResourceLoaderContext: Context in which to calculate
323 * the modified time
324 * @return Integer: UNIX timestamp
325 * @see ResourceLoaderModule::getFileDependencies
326 */
327 public function getModifiedTime( ResourceLoaderContext $context ) {
328 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
329 return $this->modifiedTime[$context->getHash()];
330 }
331 wfProfileIn( __METHOD__ );
332
333 $files = array();
334
335 // Flatten style files into $files
336 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
337 foreach ( $styles as $styleFiles ) {
338 $files = array_merge( $files, $styleFiles );
339 }
340 $skinFiles = self::tryForKey(
341 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
342 $context->getSkin(),
343 'default'
344 );
345 foreach ( $skinFiles as $styleFiles ) {
346 $files = array_merge( $files, $styleFiles );
347 }
348
349 // Final merge, this should result in a master list of dependent files
350 $files = array_merge(
351 $files,
352 $this->scripts,
353 $context->getDebug() ? $this->debugScripts : array(),
354 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
355 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
356 $this->loaderScripts
357 );
358 $files = array_map( array( $this, 'getLocalPath' ), $files );
359 // File deps need to be treated separately because they're already prefixed
360 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
361
362 // If a module is nothing but a list of dependencies, we need to avoid
363 // giving max() an empty array
364 if ( count( $files ) === 0 ) {
365 wfProfileOut( __METHOD__ );
366 return $this->modifiedTime[$context->getHash()] = 1;
367 }
368
369 wfProfileIn( __METHOD__.'-filemtime' );
370 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
371 wfProfileOut( __METHOD__.'-filemtime' );
372 $this->modifiedTime[$context->getHash()] = max(
373 $filesMtime,
374 $this->getMsgBlobMtime( $context->getLanguage() ) );
375
376 wfProfileOut( __METHOD__ );
377 return $this->modifiedTime[$context->getHash()];
378 }
379
380 /* Protected Methods */
381
382 /**
383 * @param $path string
384 * @return string
385 */
386 protected function getLocalPath( $path ) {
387 return "{$this->localBasePath}/$path";
388 }
389
390 /**
391 * @param $path string
392 * @return string
393 */
394 protected function getRemotePath( $path ) {
395 return "{$this->remoteBasePath}/$path";
396 }
397
398 /**
399 * Collates file paths by option (where provided).
400 *
401 * @param $list Array: List of file paths in any combination of index/path
402 * or path/options pairs
403 * @param $option String: option name
404 * @param $default Mixed: default value if the option isn't set
405 * @return Array: List of file paths, collated by $option
406 */
407 protected static function collateFilePathListByOption( array $list, $option, $default ) {
408 $collatedFiles = array();
409 foreach ( (array) $list as $key => $value ) {
410 if ( is_int( $key ) ) {
411 // File name as the value
412 if ( !isset( $collatedFiles[$default] ) ) {
413 $collatedFiles[$default] = array();
414 }
415 $collatedFiles[$default][] = $value;
416 } elseif ( is_array( $value ) ) {
417 // File name as the key, options array as the value
418 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
419 if ( !isset( $collatedFiles[$optionValue] ) ) {
420 $collatedFiles[$optionValue] = array();
421 }
422 $collatedFiles[$optionValue][] = $key;
423 }
424 }
425 return $collatedFiles;
426 }
427
428 /**
429 * Gets a list of element that match a key, optionally using a fallback key.
430 *
431 * @param $list Array: List of lists to select from
432 * @param $key String: Key to look for in $map
433 * @param $fallback String: Key to look for in $list if $key doesn't exist
434 * @return Array: List of elements from $map which matched $key or $fallback,
435 * or an empty list in case of no match
436 */
437 protected static function tryForKey( array $list, $key, $fallback = null ) {
438 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
439 return $list[$key];
440 } elseif ( is_string( $fallback )
441 && isset( $list[$fallback] )
442 && is_array( $list[$fallback] ) )
443 {
444 return $list[$fallback];
445 }
446 return array();
447 }
448
449 /**
450 * Gets a list of file paths for all scripts in this module, in order of propper execution.
451 *
452 * @param $context ResourceLoaderContext: Context
453 * @return Array: List of file paths
454 */
455 protected function getScriptFiles( ResourceLoaderContext $context ) {
456 $files = array_merge(
457 $this->scripts,
458 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
459 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
460 );
461 if ( $context->getDebug() ) {
462 $files = array_merge( $files, $this->debugScripts );
463 }
464 return $files;
465 }
466
467 /**
468 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
469 *
470 * @param $context ResourceLoaderContext: Context
471 * @return Array: List of file paths
472 */
473 protected function getStyleFiles( ResourceLoaderContext $context ) {
474 return array_merge_recursive(
475 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
476 self::collateFilePathListByOption(
477 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
478 )
479 );
480 }
481
482 /**
483 * Gets the contents of a list of JavaScript files.
484 *
485 * @param $scripts Array: List of file paths to scripts to read, remap and concetenate
486 * @return String: Concatenated and remapped JavaScript data from $scripts
487 */
488 protected function readScriptFiles( array $scripts ) {
489 global $wgResourceLoaderValidateStaticJS;
490 if ( empty( $scripts ) ) {
491 return '';
492 }
493 $js = '';
494 foreach ( array_unique( $scripts ) as $fileName ) {
495 $localPath = $this->getLocalPath( $fileName );
496 if ( !file_exists( $localPath ) ) {
497 throw new MWException( __METHOD__.": script file not found: \"$localPath\"" );
498 }
499 $contents = file_get_contents( $localPath );
500 if ( $wgResourceLoaderValidateStaticJS ) {
501 // Static files don't really need to be checked as often; unlike
502 // on-wiki module they shouldn't change unexpectedly without
503 // admin interference.
504 $contents = $this->validateScriptFile( $fileName, $contents );
505 }
506 $js .= $contents . "\n";
507 }
508 return $js;
509 }
510
511 /**
512 * Gets the contents of a list of CSS files.
513 *
514 * @param $styles Array: List of media type/list of file paths pairs, to read, remap and
515 * concetenate
516 *
517 * @param $flip bool
518 *
519 * @return Array: List of concatenated and remapped CSS data from $styles,
520 * keyed by media type
521 */
522 protected function readStyleFiles( array $styles, $flip ) {
523 if ( empty( $styles ) ) {
524 return array();
525 }
526 foreach ( $styles as $media => $files ) {
527 $uniqueFiles = array_unique( $files );
528 $styles[$media] = implode(
529 "\n",
530 array_map(
531 array( $this, 'readStyleFile' ),
532 $uniqueFiles,
533 array_fill( 0, count( $uniqueFiles ), $flip )
534 )
535 );
536 }
537 return $styles;
538 }
539
540 /**
541 * Reads a style file.
542 *
543 * This method can be used as a callback for array_map()
544 *
545 * @param $path String: File path of style file to read
546 * @param $flip bool
547 *
548 * @return String: CSS data in script file
549 * @throws MWException if the file doesn't exist
550 */
551 protected function readStyleFile( $path, $flip ) {
552 $localPath = $this->getLocalPath( $path );
553 if ( !file_exists( $localPath ) ) {
554 throw new MWException( __METHOD__.": style file not found: \"$localPath\"" );
555 }
556 $style = file_get_contents( $localPath );
557 if ( $flip ) {
558 $style = CSSJanus::transform( $style, true, false );
559 }
560 $dirname = dirname( $path );
561 if ( $dirname == '.' ) {
562 // If $path doesn't have a directory component, don't prepend a dot
563 $dirname = '';
564 }
565 $dir = $this->getLocalPath( $dirname );
566 $remoteDir = $this->getRemotePath( $dirname );
567 // Get and register local file references
568 $this->localFileRefs = array_merge(
569 $this->localFileRefs,
570 CSSMin::getLocalFileReferences( $style, $dir ) );
571 return CSSMin::remap(
572 $style, $dir, $remoteDir, true
573 );
574 }
575
576 /**
577 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist
578 * but returns 1 instead.
579 * @param $filename string File name
580 * @return int UNIX timestamp, or 1 if the file doesn't exist
581 */
582 protected static function safeFilemtime( $filename ) {
583 if ( file_exists( $filename ) ) {
584 return filemtime( $filename );
585 } else {
586 // We only ever map this function on an array if we're gonna call max() after,
587 // so return our standard minimum timestamps here. This is 1, not 0, because
588 // wfTimestamp(0) == NOW
589 return 1;
590 }
591 }
592
593 /**
594 * Get whether CSS for this module should be flipped
595 * @param $context ResourceLoaderContext
596 * @return bool
597 */
598 public function getFlip( $context ) {
599 return $context->getDirection() === 'rtl';
600 }
601 }