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