Merge changes Icdd8f392,Ied13e5ab
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * Resource loader module based on local JavaScript/CSS files.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
27 */
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29
30 /* Protected Members */
31
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
42 */
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
50 */
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
58 */
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
66 */
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
74 */
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
82 */
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
90 */
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
98 */
99 protected $dependencies = array();
100 /**
101 * Array: List of message keys used by this module
102 * @par Usage:
103 * @code
104 * array( [message-key], [message-key], ... )
105 * @endcode
106 */
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;
116 protected $targets = array( 'desktop' );
117
118 /**
119 * Array: Cache for mtime
120 * @par Usage:
121 * @code
122 * array( [hash] => [mtime], [hash] => [mtime], ... )
123 * @endcode
124 */
125 protected $modifiedTime = array();
126 /**
127 * Array: Place where readStyleFile() tracks file dependencies
128 * @par Usage:
129 * @code
130 * array( [file-path], [file-path], ... )
131 * @endcode
132 */
133 protected $localFileRefs = array();
134
135 /* Methods */
136
137 /**
138 * Constructs a new module from an options array.
139 *
140 * @param array $options List of options; if not given or empty, an empty module will be
141 * constructed
142 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
143 * to $IP
144 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
145 * to $wgScriptPath
146 *
147 * Below is a description for the $options array:
148 * @throws MWException
149 * @par Construction options:
150 * @code
151 * array(
152 * // Base path to prepend to all local paths in $options. Defaults to $IP
153 * 'localBasePath' => [base path],
154 * // Base path to prepend to all remote paths in $options. Defaults to $wgScriptPath
155 * 'remoteBasePath' => [base path],
156 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
157 * 'remoteExtPath' => [base path],
158 * // Scripts to always include
159 * 'scripts' => [file path string or array of file path strings],
160 * // Scripts to include in specific language contexts
161 * 'languageScripts' => array(
162 * [language code] => [file path string or array of file path strings],
163 * ),
164 * // Scripts to include in specific skin contexts
165 * 'skinScripts' => array(
166 * [skin name] => [file path string or array of file path strings],
167 * ),
168 * // Scripts to include in debug contexts
169 * 'debugScripts' => [file path string or array of file path strings],
170 * // Scripts to include in the startup module
171 * 'loaderScripts' => [file path string or array of file path strings],
172 * // Modules which must be loaded before this module
173 * 'dependencies' => [module name string or array of module name strings],
174 * // Styles to always load
175 * 'styles' => [file path string or array of file path strings],
176 * // Styles to include in specific skin contexts
177 * 'skinStyles' => array(
178 * [skin name] => [file path string or array of file path strings],
179 * ),
180 * // Messages to always load
181 * 'messages' => [array of message key strings],
182 * // Group which this module should be loaded together with
183 * 'group' => [group name string],
184 * // Position on the page to load this module at
185 * 'position' => ['bottom' (default) or 'top']
186 * )
187 * @endcode
188 */
189 public function __construct( $options = array(), $localBasePath = null,
190 $remoteBasePath = null
191 ) {
192 global $IP, $wgScriptPath, $wgResourceBasePath;
193 $this->localBasePath = $localBasePath === null ? $IP : $localBasePath;
194 if ( $remoteBasePath !== null ) {
195 $this->remoteBasePath = $remoteBasePath;
196 } else {
197 $this->remoteBasePath = $wgResourceBasePath === null ? $wgScriptPath : $wgResourceBasePath;
198 }
199
200 if ( isset( $options['remoteExtPath'] ) ) {
201 global $wgExtensionAssetsPath;
202 $this->remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
203 }
204
205 foreach ( $options as $member => $option ) {
206 switch ( $member ) {
207 // Lists of file paths
208 case 'scripts':
209 case 'debugScripts':
210 case 'loaderScripts':
211 case 'styles':
212 $this->{$member} = (array)$option;
213 break;
214 // Collated lists of file paths
215 case 'languageScripts':
216 case 'skinScripts':
217 case 'skinStyles':
218 if ( !is_array( $option ) ) {
219 throw new MWException(
220 "Invalid collated file path list error. " .
221 "'$option' given, array expected."
222 );
223 }
224 foreach ( $option as $key => $value ) {
225 if ( !is_string( $key ) ) {
226 throw new MWException(
227 "Invalid collated file path list key error. " .
228 "'$key' given, string expected."
229 );
230 }
231 $this->{$member}[$key] = (array)$value;
232 }
233 break;
234 // Lists of strings
235 case 'dependencies':
236 case 'messages':
237 case 'targets':
238 $this->{$member} = (array)$option;
239 break;
240 // Single strings
241 case 'group':
242 case 'position':
243 case 'localBasePath':
244 case 'remoteBasePath':
245 $this->{$member} = (string)$option;
246 break;
247 // Single booleans
248 case 'debugRaw':
249 case 'raw':
250 $this->{$member} = (bool)$option;
251 break;
252 }
253 }
254 // Make sure the remote base path is a complete valid URL,
255 // but possibly protocol-relative to avoid cache pollution
256 $this->remoteBasePath = wfExpandUrl( $this->remoteBasePath, PROTO_RELATIVE );
257 }
258
259 /**
260 * Gets all scripts for a given context concatenated together.
261 *
262 * @param $context ResourceLoaderContext: Context in which to generate script
263 * @return String: JavaScript code for $context
264 */
265 public function getScript( ResourceLoaderContext $context ) {
266 $files = $this->getScriptFiles( $context );
267 return $this->readScriptFiles( $files );
268 }
269
270 /**
271 * @param $context ResourceLoaderContext
272 * @return array
273 */
274 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
275 $urls = array();
276 foreach ( $this->getScriptFiles( $context ) as $file ) {
277 $urls[] = $this->getRemotePath( $file );
278 }
279 return $urls;
280 }
281
282 /**
283 * @return bool
284 */
285 public function supportsURLLoading() {
286 return $this->debugRaw;
287 }
288
289 /**
290 * Gets loader script.
291 *
292 * @return String: JavaScript code to be added to startup module
293 */
294 public function getLoaderScript() {
295 if ( count( $this->loaderScripts ) == 0 ) {
296 return false;
297 }
298 return $this->readScriptFiles( $this->loaderScripts );
299 }
300
301 /**
302 * Gets all styles for a given context concatenated together.
303 *
304 * @param $context ResourceLoaderContext: Context in which to generate styles
305 * @return String: CSS code for $context
306 */
307 public function getStyles( ResourceLoaderContext $context ) {
308 $styles = $this->readStyleFiles(
309 $this->getStyleFiles( $context ),
310 $this->getFlip( $context )
311 );
312 // Collect referenced files
313 $this->localFileRefs = array_unique( $this->localFileRefs );
314 // If the list has been modified since last time we cached it, update the cache
315 try {
316 if ( $this->localFileRefs !== $this->getFileDependencies( $context->getSkin() ) ) {
317 $dbw = wfGetDB( DB_MASTER );
318 $dbw->replace( 'module_deps',
319 array( array( 'md_module', 'md_skin' ) ), array(
320 'md_module' => $this->getName(),
321 'md_skin' => $context->getSkin(),
322 'md_deps' => FormatJson::encode( $this->localFileRefs ),
323 )
324 );
325 }
326 } catch ( Exception $e ) {
327 wfDebug( __METHOD__ . " failed to update DB: $e\n" );
328 }
329 return $styles;
330 }
331
332 /**
333 * @param $context ResourceLoaderContext
334 * @return array
335 */
336 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
337 $urls = array();
338 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
339 $urls[$mediaType] = array();
340 foreach ( $list as $file ) {
341 $urls[$mediaType][] = $this->getRemotePath( $file );
342 }
343 }
344 return $urls;
345 }
346
347 /**
348 * Gets list of message keys used by this module.
349 *
350 * @return Array: List of message keys
351 */
352 public function getMessages() {
353 return $this->messages;
354 }
355
356 /**
357 * Gets the name of the group this module should be loaded in.
358 *
359 * @return String: Group name
360 */
361 public function getGroup() {
362 return $this->group;
363 }
364
365 /**
366 * @return string
367 */
368 public function getPosition() {
369 return $this->position;
370 }
371
372 /**
373 * Gets list of names of modules this module depends on.
374 *
375 * @return Array: List of module names
376 */
377 public function getDependencies() {
378 return $this->dependencies;
379 }
380
381 /**
382 * @return bool
383 */
384 public function isRaw() {
385 return $this->raw;
386 }
387
388 /**
389 * Get the last modified timestamp of this module.
390 *
391 * Last modified timestamps are calculated from the highest last modified
392 * timestamp of this module's constituent files as well as the files it
393 * depends on. This function is context-sensitive, only performing
394 * calculations on files relevant to the given language, skin and debug
395 * mode.
396 *
397 * @param $context ResourceLoaderContext: Context in which to calculate
398 * the modified time
399 * @return Integer: UNIX timestamp
400 * @see ResourceLoaderModule::getFileDependencies
401 */
402 public function getModifiedTime( ResourceLoaderContext $context ) {
403 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
404 return $this->modifiedTime[$context->getHash()];
405 }
406 wfProfileIn( __METHOD__ );
407
408 $files = array();
409
410 // Flatten style files into $files
411 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
412 foreach ( $styles as $styleFiles ) {
413 $files = array_merge( $files, $styleFiles );
414 }
415 $skinFiles = self::tryForKey(
416 self::collateFilePathListByOption( $this->skinStyles, 'media', 'all' ),
417 $context->getSkin(),
418 'default'
419 );
420 foreach ( $skinFiles as $styleFiles ) {
421 $files = array_merge( $files, $styleFiles );
422 }
423
424 // Final merge, this should result in a master list of dependent files
425 $files = array_merge(
426 $files,
427 $this->scripts,
428 $context->getDebug() ? $this->debugScripts : array(),
429 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
430 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
431 $this->loaderScripts
432 );
433 $files = array_map( array( $this, 'getLocalPath' ), $files );
434 // File deps need to be treated separately because they're already prefixed
435 $files = array_merge( $files, $this->getFileDependencies( $context->getSkin() ) );
436
437 // If a module is nothing but a list of dependencies, we need to avoid
438 // giving max() an empty array
439 if ( count( $files ) === 0 ) {
440 wfProfileOut( __METHOD__ );
441 return $this->modifiedTime[$context->getHash()] = 1;
442 }
443
444 wfProfileIn( __METHOD__ . '-filemtime' );
445 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
446 wfProfileOut( __METHOD__ . '-filemtime' );
447 $this->modifiedTime[$context->getHash()] = max(
448 $filesMtime,
449 $this->getMsgBlobMtime( $context->getLanguage() ) );
450
451 wfProfileOut( __METHOD__ );
452 return $this->modifiedTime[$context->getHash()];
453 }
454
455 /* Protected Methods */
456
457 /**
458 * @param $path string
459 * @return string
460 */
461 protected function getLocalPath( $path ) {
462 return "{$this->localBasePath}/$path";
463 }
464
465 /**
466 * @param $path string
467 * @return string
468 */
469 protected function getRemotePath( $path ) {
470 return "{$this->remoteBasePath}/$path";
471 }
472
473 /**
474 * Collates file paths by option (where provided).
475 *
476 * @param array $list List of file paths in any combination of index/path
477 * or path/options pairs
478 * @param string $option option name
479 * @param $default Mixed: default value if the option isn't set
480 * @return Array: List of file paths, collated by $option
481 */
482 protected static function collateFilePathListByOption( array $list, $option, $default ) {
483 $collatedFiles = array();
484 foreach ( (array)$list as $key => $value ) {
485 if ( is_int( $key ) ) {
486 // File name as the value
487 if ( !isset( $collatedFiles[$default] ) ) {
488 $collatedFiles[$default] = array();
489 }
490 $collatedFiles[$default][] = $value;
491 } elseif ( is_array( $value ) ) {
492 // File name as the key, options array as the value
493 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
494 if ( !isset( $collatedFiles[$optionValue] ) ) {
495 $collatedFiles[$optionValue] = array();
496 }
497 $collatedFiles[$optionValue][] = $key;
498 }
499 }
500 return $collatedFiles;
501 }
502
503 /**
504 * Gets a list of element that match a key, optionally using a fallback key.
505 *
506 * @param array $list List of lists to select from
507 * @param string $key Key to look for in $map
508 * @param string $fallback Key to look for in $list if $key doesn't exist
509 * @return Array: List of elements from $map which matched $key or $fallback,
510 * or an empty list in case of no match
511 */
512 protected static function tryForKey( array $list, $key, $fallback = null ) {
513 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
514 return $list[$key];
515 } elseif ( is_string( $fallback )
516 && isset( $list[$fallback] )
517 && is_array( $list[$fallback] ) )
518 {
519 return $list[$fallback];
520 }
521 return array();
522 }
523
524 /**
525 * Gets a list of file paths for all scripts in this module, in order of propper execution.
526 *
527 * @param $context ResourceLoaderContext: Context
528 * @return Array: List of file paths
529 */
530 protected function getScriptFiles( ResourceLoaderContext $context ) {
531 $files = array_merge(
532 $this->scripts,
533 self::tryForKey( $this->languageScripts, $context->getLanguage() ),
534 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
535 );
536 if ( $context->getDebug() ) {
537 $files = array_merge( $files, $this->debugScripts );
538 }
539
540 return array_unique( $files );
541 }
542
543 /**
544 * Gets a list of file paths for all styles in this module, in order of propper inclusion.
545 *
546 * @param $context ResourceLoaderContext: Context
547 * @return Array: List of file paths
548 */
549 protected function getStyleFiles( ResourceLoaderContext $context ) {
550 return array_merge_recursive(
551 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
552 self::collateFilePathListByOption(
553 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ), 'media', 'all'
554 )
555 );
556 }
557
558 /**
559 * Gets the contents of a list of JavaScript files.
560 *
561 * @param array $scripts List of file paths to scripts to read, remap and concetenate
562 * @throws MWException
563 * @return String: Concatenated and remapped JavaScript data from $scripts
564 */
565 protected function readScriptFiles( array $scripts ) {
566 global $wgResourceLoaderValidateStaticJS;
567 if ( empty( $scripts ) ) {
568 return '';
569 }
570 $js = '';
571 foreach ( array_unique( $scripts ) as $fileName ) {
572 $localPath = $this->getLocalPath( $fileName );
573 if ( !file_exists( $localPath ) ) {
574 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
575 }
576 $contents = file_get_contents( $localPath );
577 if ( $wgResourceLoaderValidateStaticJS ) {
578 // Static files don't really need to be checked as often; unlike
579 // on-wiki module they shouldn't change unexpectedly without
580 // admin interference.
581 $contents = $this->validateScriptFile( $fileName, $contents );
582 }
583 $js .= $contents . "\n";
584 }
585 return $js;
586 }
587
588 /**
589 * Gets the contents of a list of CSS files.
590 *
591 * @param array $styles List of media type/list of file paths pairs, to read, remap and
592 * concetenate
593 *
594 * @param $flip bool
595 *
596 * @return Array: List of concatenated and remapped CSS data from $styles,
597 * keyed by media type
598 */
599 protected function readStyleFiles( array $styles, $flip ) {
600 if ( empty( $styles ) ) {
601 return array();
602 }
603 foreach ( $styles as $media => $files ) {
604 $uniqueFiles = array_unique( $files );
605 $styles[$media] = implode(
606 "\n",
607 array_map(
608 array( $this, 'readStyleFile' ),
609 $uniqueFiles,
610 array_fill( 0, count( $uniqueFiles ), $flip )
611 )
612 );
613 }
614 return $styles;
615 }
616
617 /**
618 * Reads a style file.
619 *
620 * This method can be used as a callback for array_map()
621 *
622 * @param string $path File path of style file to read
623 * @param $flip bool
624 *
625 * @return String: CSS data in script file
626 * @throws MWException if the file doesn't exist
627 */
628 protected function readStyleFile( $path, $flip ) {
629 $localPath = $this->getLocalPath( $path );
630 if ( !file_exists( $localPath ) ) {
631 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
632 wfDebugLog( 'resourceloader', $msg );
633 throw new MWException( $msg );
634 }
635 $style = file_get_contents( $localPath );
636 if ( $flip ) {
637 $style = CSSJanus::transform( $style, true, false );
638 }
639 $dirname = dirname( $path );
640 if ( $dirname == '.' ) {
641 // If $path doesn't have a directory component, don't prepend a dot
642 $dirname = '';
643 }
644 $dir = $this->getLocalPath( $dirname );
645 $remoteDir = $this->getRemotePath( $dirname );
646 // Get and register local file references
647 $this->localFileRefs = array_merge(
648 $this->localFileRefs,
649 CSSMin::getLocalFileReferences( $style, $dir )
650 );
651 return CSSMin::remap(
652 $style, $dir, $remoteDir, true
653 );
654 }
655
656 /**
657 * Get whether CSS for this module should be flipped
658 * @param $context ResourceLoaderContext
659 * @return bool
660 */
661 public function getFlip( $context ) {
662 return $context->getDirection() === 'rtl';
663 }
664
665 /**
666 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
667 *
668 * @return array of strings
669 */
670 public function getTargets() {
671 return $this->targets;
672 }
673
674 }