874c01773d65bce2c999e05870bdcb7ce5f3be20
[lhc/web/wiklou.git] / includes / ResourceLoaderModule.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 * @author Trevor Parscal
19 * @author Roan Kattouw
20 */
21
22 /**
23 * Interface for resource loader modules, with name registration and maxage functionality.
24 */
25 abstract class ResourceLoaderModule {
26
27 /* Protected Members */
28
29 protected $name = null;
30
31 /* Methods */
32
33 /**
34 * Get this module's name. This is set when the module is registered
35 * with ResourceLoader::register()
36 * @return mixed Name (string) or null if no name was set
37 */
38 public function getName() {
39 return $this->name;
40 }
41
42 /**
43 * Set this module's name. This is called by ResourceLodaer::register()
44 * when registering the module. Other code should not call this.
45 * @param $name string Name
46 */
47 public function setName( $name ) {
48 $this->name = $name;
49 }
50
51 /**
52 * The maximum number of seconds to cache this module for in the
53 * client-side (browser) cache. Override this only if you have a good
54 * reason not to use $wgResourceLoaderClientMaxage.
55 * @return int Cache maxage in seconds
56 */
57 public function getClientMaxage() {
58 global $wgResourceLoaderClientMaxage;
59 return $wgResourceLoaderClientMaxage;
60 }
61
62 /**
63 * The maximum number of seconds to cache this module for in the
64 * server-side (Squid / proxy) cache. Override this only if you have a
65 * good reason not to use $wgResourceLoaderServerMaxage.
66 * @return int Cache maxage in seconds
67 */
68 public function getServerMaxage() {
69 global $wgResourceLoaderServerMaxage;
70 return $wgResourceLoaderServerMaxage;
71 }
72
73 /**
74 * Get all JS for this module for a given language and skin.
75 * Includes all relevant JS except loader scripts.
76 * @param $lang string Language code
77 * @param $skin string Skin name
78 * @param $debug bool Whether to include debug scripts
79 * @return string JS
80 */
81 public abstract function getScript( ResourceLoaderContext $context );
82
83 /**
84 * Get all CSS for this module for a given skin.
85 * @param $skin string Skin name
86 * @return string CSS
87 */
88 public abstract function getStyle( ResourceLoaderContext $context );
89
90 /**
91 * Get the messages needed for this module.
92 *
93 * To get a JSON blob with messages, use MessageBlobStore::get()
94 * @return array of message keys. Keys may occur more than once
95 */
96 public abstract function getMessages();
97
98 /**
99 * Get the loader JS for this module, if set.
100 * @return mixed Loader JS (string) or false if no custom loader set
101 */
102 public abstract function getLoaderScript();
103
104 /**
105 * Get a list of modules this module depends on.
106 *
107 * Dependency information is taken into account when loading a module
108 * on the client side. When adding a module on the server side,
109 * dependency information is NOT taken into account and YOU are
110 * responsible for adding dependent modules as well. If you don't do
111 * this, the client side loader will send a second request back to the
112 * server to fetch the missing modules, which kind of defeats the
113 * purpose of the resource loader.
114 *
115 * To add dependencies dynamically on the client side, use a custom
116 * loader script, see getLoaderScript()
117 * @return array Array of module names (strings)
118 */
119 public abstract function getDependencies();
120
121 /**
122 * Get this module's last modification timestamp for a given
123 * combination of language, skin and debug mode flag. This is typically
124 * the highest of each of the relevant components' modification
125 * timestamps. Whenever anything happens that changes the module's
126 * contents for these parameters, the mtime should increase.
127 * @param $lang string Language code
128 * @param $skin string Skin name
129 * @param $debug bool Debug mode flag
130 * @return int UNIX timestamp
131 */
132 public abstract function getModifiedTime( ResourceLoaderContext $context );
133 }
134
135 /**
136 * Module based on local JS/CSS files. This is the most common type of module.
137 */
138 class ResourceLoaderFileModule extends ResourceLoaderModule {
139
140 /* Protected Members */
141
142 protected $scripts = array();
143 protected $styles = array();
144 protected $messages = array();
145 protected $dependencies = array();
146 protected $debugScripts = array();
147 protected $languageScripts = array();
148 protected $skinScripts = array();
149 protected $skinStyles = array();
150 protected $loaders = array();
151 protected $parameters = array();
152
153 // In-object cache for file dependencies
154 protected $fileDeps = array();
155 // In-object cache for mtime
156 protected $modifiedTime = array();
157
158 /* Methods */
159
160 /**
161 * Construct a new module from an options array.
162 *
163 * @param $options array Options array. If empty, an empty module will be constructed
164 *
165 * $options format:
166 * array(
167 * // Required module options (mutually exclusive)
168 * 'scripts' => 'dir/script.js' | array( 'dir/script1.js', 'dir/script2.js' ... ),
169 *
170 * // Optional module options
171 * 'languageScripts' => array(
172 * '[lang name]' => 'dir/lang.js' | '[lang name]' => array( 'dir/lang1.js', 'dir/lang2.js' ... )
173 * ...
174 * ),
175 * 'skinScripts' => 'dir/skin.js' | array( 'dir/skin1.js', 'dir/skin2.js' ... ),
176 * 'debugScripts' => 'dir/debug.js' | array( 'dir/debug1.js', 'dir/debug2.js' ... ),
177 *
178 * // Non-raw module options
179 * 'dependencies' => 'module' | array( 'module1', 'module2' ... )
180 * 'loaderScripts' => 'dir/loader.js' | array( 'dir/loader1.js', 'dir/loader2.js' ... ),
181 * 'styles' => 'dir/file.css' | array( 'dir/file1.css', 'dir/file2.css' ... ),
182 * 'skinStyles' => array(
183 * '[skin name]' => 'dir/skin.css' | '[skin name]' => array( 'dir/skin1.css', 'dir/skin2.css' ... )
184 * ...
185 * ),
186 * 'messages' => array( 'message1', 'message2' ... ),
187 * )
188 */
189 public function __construct( $options = array() ) {
190 foreach ( $options as $option => $value ) {
191 switch ( $option ) {
192 case 'scripts':
193 $this->scripts = (array)$value;
194 break;
195 case 'styles':
196 $this->styles = (array)$value;
197 break;
198 case 'messages':
199 $this->messages = (array)$value;
200 break;
201 case 'dependencies':
202 $this->dependencies = (array)$value;
203 break;
204 case 'debugScripts':
205 $this->debugScripts = (array)$value;
206 break;
207 case 'languageScripts':
208 $this->languageScripts = (array)$value;
209 break;
210 case 'skinScripts':
211 $this->skinScripts = (array)$value;
212 break;
213 case 'skinStyles':
214 $this->skinStyles = (array)$value;
215 break;
216 case 'loaders':
217 $this->loaders = (array)$value;
218 break;
219 }
220 }
221 }
222
223 /**
224 * Add script files to this module. In order to be valid, a module
225 * must contain at least one script file.
226 * @param $scripts mixed Path to script file (string) or array of paths
227 */
228 public function addScripts( $scripts ) {
229 $this->scripts = array_merge( $this->scripts, (array)$scripts );
230 }
231
232 /**
233 * Add style (CSS) files to this module.
234 * @param $styles mixed Path to CSS file (string) or array of paths
235 */
236 public function addStyles( $styles ) {
237 $this->styles = array_merge( $this->styles, (array)$styles );
238 }
239
240 /**
241 * Add messages to this module.
242 * @param $messages mixed Message key (string) or array of message keys
243 */
244 public function addMessages( $messages ) {
245 $this->messages = array_merge( $this->messages, (array)$messages );
246 }
247
248 /**
249 * Add dependencies. Dependency information is taken into account when
250 * loading a module on the client side. When adding a module on the
251 * server side, dependency information is NOT taken into account and
252 * YOU are responsible for adding dependent modules as well. If you
253 * don't do this, the client side loader will send a second request
254 * back to the server to fetch the missing modules, which kind of
255 * defeats the point of using the resource loader in the first place.
256 *
257 * To add dependencies dynamically on the client side, use a custom
258 * loader (see addLoaders())
259 *
260 * @param $dependencies mixed Module name (string) or array of module names
261 */
262 public function addDependencies( $dependencies ) {
263 $this->dependencies = array_merge( $this->dependencies, (array)$dependencies );
264 }
265
266 /**
267 * Add debug scripts to the module. These scripts are only included
268 * in debug mode.
269 * @param $scripts mixed Path to script file (string) or array of paths
270 */
271 public function addDebugScripts( $scripts ) {
272 $this->debugScripts = array_merge( $this->debugScripts, (array)$scripts );
273 }
274
275 /**
276 * Add language-specific scripts. These scripts are only included for
277 * a given language.
278 * @param $lang string Language code
279 * @param $scripts mixed Path to script file (string) or array of paths
280 */
281 public function addLanguageScripts( $lang, $scripts ) {
282 $this->languageScripts = array_merge_recursive(
283 $this->languageScripts,
284 array( $lang => $scripts )
285 );
286 }
287
288 /**
289 * Add skin-specific scripts. These scripts are only included for
290 * a given skin.
291 * @param $skin string Skin name, or 'default'
292 * @param $scripts mixed Path to script file (string) or array of paths
293 */
294 public function addSkinScripts( $skin, $scripts ) {
295 $this->skinScripts = array_merge_recursive(
296 $this->skinScripts,
297 array( $skin => $scripts )
298 );
299 }
300
301 /**
302 * Add skin-specific CSS. These CSS files are only included for a
303 * given skin. If there are no skin-specific CSS files for a skin,
304 * the files defined for 'default' will be used, if any.
305 * @param $skin string Skin name, or 'default'
306 * @param $scripts mixed Path to CSS file (string) or array of paths
307 */
308 public function addSkinStyles( $skin, $scripts ) {
309 $this->skinStyles = array_merge_recursive(
310 $this->skinStyles,
311 array( $skin => $scripts )
312 );
313 }
314
315 /**
316 * Add loader scripts. These scripts are loaded on every page and are
317 * responsible for registering this module using
318 * mediaWiki.loader.register(). If there are no loader scripts defined,
319 * the resource loader will register the module itself.
320 *
321 * Loader scripts are used to determine a module's dependencies
322 * dynamically on the client side (e.g. based on browser type/version).
323 * Note that loader scripts are included on every page, so they should
324 * be lightweight and use mediaWiki.loader.register()'s callback
325 * feature to defer dependency calculation.
326 * @param $scripts mixed Path to script file (string) or array of paths
327 */
328 public function addLoaders( $scripts ) {
329 $this->loaders = array_merge( $this->loaders, (array)$scripts );
330 }
331
332 public function getScript( ResourceLoaderContext $context ) {
333 $retval = $this->getPrimaryScript() . "\n" .
334 $this->getLanguageScript( $context->getLanguage() ) . "\n" .
335 $this->getSkinScript( $context->getSkin() );
336 if ( $context->getDebug() ) {
337 $retval .= $this->getDebugScript();
338 }
339 return $retval;
340 }
341
342 public function getStyle( ResourceLoaderContext $context ) {
343 $style = $this->getPrimaryStyle() . "\n" . $this->getSkinStyle( $context->getSkin() );
344
345 // Extract and store the list of referenced files
346 $files = CSSMin::getLocalFileReferences( $style );
347
348 // Only store if modified
349 if ( $files !== $this->getFileDependencies( $context->getSkin() ) ) {
350 $encFiles = FormatJson::encode( $files );
351 $dbw = wfGetDb( DB_MASTER );
352 $dbw->replace( 'module_deps',
353 array( array( 'md_module', 'md_skin' ) ), array(
354 'md_module' => $this->getName(),
355 'md_skin' => $context->getSkin(),
356 'md_deps' => $encFiles,
357 )
358 );
359
360 // Save into memcached
361 global $wgMemc;
362 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $context->getSkin() );
363 $wgMemc->set( $key, $encFiles );
364 }
365 return $style;
366 }
367
368 public function getMessages() {
369 return $this->messages;
370 }
371
372 public function getDependencies() {
373 return $this->dependencies;
374 }
375
376 public function getLoaderScript() {
377 if ( count( $this->loaders ) == 0 ) {
378 return false;
379 }
380 return self::concatScripts( $this->loaders );
381 }
382
383 /**
384 * Get the last modified timestamp of this module, which is calculated
385 * as the highest last modified timestamp of its constituent files and
386 * the files it depends on (see getFileDependencies()). Only files
387 * relevant to the given language and skin are taken into account, and
388 * files only relevant in debug mode are not taken into account when
389 * debug mode is off.
390 * @param $lang string Language code
391 * @param $skin string Skin name
392 * @param $debug bool Debug mode flag
393 * @return int UNIX timestamp
394 */
395 public function getModifiedTime( ResourceLoaderContext $context ) {
396 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
397 return $this->modifiedTime[$context->getHash()];
398 }
399
400 $files = array_merge(
401 $this->scripts,
402 $this->styles,
403 $context->getDebug() ? $this->debugScripts : array(),
404 isset( $this->languageScripts[$context->getLanguage()] ) ?
405 (array) $this->languageScripts[$context->getLanguage()] : array(),
406 (array) self::getSkinFiles( $context->getSkin(), $this->skinScripts ),
407 (array) self::getSkinFiles( $context->getSkin(), $this->skinStyles ),
408 $this->loaders,
409 $this->getFileDependencies( $context->getSkin() )
410 );
411 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__, 'remapFilename' ), $files ) ) );
412
413 // Get the mtime of the message blob
414 // TODO: This timestamp is queried a lot and queried separately for each module. Maybe it should be put in memcached?
415 $dbr = wfGetDb( DB_SLAVE );
416 $msgBlobMtime = $dbr->selectField( 'msg_resource', 'mr_timestamp', array(
417 'mr_resource' => $this->getName(),
418 'mr_lang' => $context->getLanguage()
419 ), __METHOD__
420 );
421 $msgBlobMtime = $msgBlobMtime ? wfTimestamp( TS_UNIX, $msgBlobMtime ) : 0;
422
423 $this->modifiedTime[$context->getHash()] = max( $filesMtime, $msgBlobMtime );
424 return $this->modifiedTime[$context->getHash()];
425 }
426
427 /* Protected Members */
428
429 /**
430 * Get the primary JS for this module. This is pulled from the
431 * script files added through addScripts()
432 * @return string JS
433 */
434 protected function getPrimaryScript() {
435 return self::concatScripts( $this->scripts );
436 }
437
438 /**
439 * Get the primary CSS for this module. This is pulled from the CSS
440 * files added through addStyles()
441 * @return string JS
442 */
443 protected function getPrimaryStyle() {
444 return self::concatStyles( $this->styles );
445 }
446
447 /**
448 * Get the debug JS for this module. This is pulled from the script
449 * files added through addDebugScripts()
450 * @return string JS
451 */
452 protected function getDebugScript() {
453 return self::concatScripts( $this->debugScripts );
454 }
455
456 /**
457 * Get the language-specific JS for a given language. This is pulled
458 * from the language-specific script files added through addLanguageScripts()
459 * @return string JS
460 */
461 protected function getLanguageScript( $lang ) {
462 if ( !isset( $this->languageScripts[$lang] ) ) {
463 return '';
464 }
465 return self::concatScripts( $this->languageScripts[$lang] );
466 }
467
468 /**
469 * Get the skin-specific JS for a given skin. This is pulled from the
470 * skin-specific JS files added through addSkinScripts()
471 * @return string JS
472 */
473 protected function getSkinScript( $skin ) {
474 return self::concatScripts( self::getSkinFiles( $skin, $this->skinScripts ) );
475 }
476
477 /**
478 * Get the skin-specific CSS for a given skin. This is pulled from the
479 * skin-specific CSS files added through addSkinStyles()
480 * @return string CSS
481 */
482 protected function getSkinStyle( $skin ) {
483 return self::concatStyles( self::getSkinFiles( $skin, $this->skinStyles ) );
484 }
485
486 /**
487 * Helper function to get skin-specific data from an array.
488 * @param $skin string Skin name
489 * @param $map array Map of skin names to arrays
490 * @return $map[$skin] if set and non-empty, or $map['default'] if set, or an empty array
491 */
492 protected static function getSkinFiles( $skin, $map ) {
493 $retval = array();
494 if ( isset( $map[$skin] ) && $map[$skin] ) {
495 $retval = $map[$skin];
496 } else if ( isset( $map['default'] ) ) {
497 $retval = $map['default'];
498 }
499 return $retval;
500 }
501
502 /**
503 * Get the files this module depends on indirectly for a given skin.
504 * Currently these are only image files referenced by the module's CSS.
505 * @param $skin string Skin name
506 * @return array of files
507 */
508 protected function getFileDependencies( $skin ) {
509 // Try in-object cache first
510 if ( isset( $this->fileDeps[$skin] ) ) {
511 return $this->fileDeps[$skin];
512 }
513
514 // Now try memcached
515 global $wgMemc;
516 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $skin );
517 $deps = $wgMemc->get( $key );
518
519 if ( !$deps ) {
520 $dbr = wfGetDb( DB_SLAVE );
521 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
522 'md_module' => $this->getName(),
523 'md_skin' => $skin,
524 ), __METHOD__
525 );
526 if ( !$deps ) {
527 $deps = '[]'; // Empty array so we can do negative caching
528 }
529 $wgMemc->set( $key, $deps );
530 }
531 $this->fileDeps = FormatJson::decode( $deps, true );
532 return $this->fileDeps;
533 }
534
535 /**
536 * Get the contents of a set of files and concatenate them, with
537 * newlines in between. Each file is used only once.
538 * @param $files array Array of file names
539 * @return string Concatenated contents of $files
540 */
541 protected static function concatScripts( $files ) {
542 return implode( "\n", array_map( 'file_get_contents', array_map( array( __CLASS__, 'remapFilename' ), array_unique( (array) $files ) ) ) );
543 }
544
545 /**
546 * Get the contents of a set of CSS files, remap then and concatenate
547 * them, with newlines in between. Each file is used only once.
548 * @param $files array Array of file names
549 * @return string Concatenated and remapped contents of $files
550 */
551 protected static function concatStyles( $files ) {
552 return implode( "\n", array_map( array( __CLASS__, 'remapStyle' ), array_unique( (array) $files ) ) );
553 }
554
555 /**
556 * Remap a relative to $IP. Used as a callback for array_map()
557 * @param $file string File name
558 * @return string $IP/$file
559 */
560 protected static function remapFilename( $file ) {
561 global $IP;
562 return "$IP/$file";
563 }
564
565 /**
566 * Get the contents of a CSS file and run it through CSSMin::remap().
567 * This wrapper is needed so we can use array_map() in concatStyles()
568 * @param $file string File name
569 * @return string Remapped CSS
570 */
571 protected static function remapStyle( $file ) {
572 return CSSMin::remap( file_get_contents( self::remapFilename( $file ) ), dirname( $file ) );
573 }
574 }
575
576 /**
577 * Custom module for MediaWiki:Common.js and MediaWiki:Skinname.js
578 * TODO: Add Site CSS functionality too
579 */
580 class ResourceLoaderSiteModule extends ResourceLoaderModule {
581
582 /* Protected Members */
583
584 // In-object cache for modified time
585 protected $modifiedTime = null;
586
587 /* Methods */
588
589 public function getScript( ResourceLoaderContext $context ) {
590 return Skin::newFromKey( $context->getSkin() )->generateUserJs();
591 }
592
593 public function getModifiedTime( ResourceLoaderContext $context ) {
594 if ( isset( $this->modifiedTime[$context->getHash()] ) ) {
595 return $this->modifiedTime[$context->getHash()];
596 }
597
598 // HACK: We duplicate the message names from generateUserJs()
599 // here and weird things (i.e. mtime moving backwards) can happen
600 // when a MediaWiki:Something.js page is deleted
601 $jsPages = array( Title::makeTitle( NS_MEDIAWIKI, 'Common.js' ),
602 Title::makeTitle( NS_MEDIAWIKI, ucfirst( $context->getSkin() ) . '.js' )
603 );
604
605 // Do batch existence check
606 // TODO: This would work better if page_touched were loaded by this as well
607 $lb = new LinkBatch( $jsPages );
608 $lb->execute();
609
610 $this->modifiedTime = 1; // wfTimestamp() interprets 0 as "now"
611 foreach ( $jsPages as $jsPage ) {
612 if ( $jsPage->exists() ) {
613 $this->modifiedTime = max( $this->modifiedTime, wfTimestamp( TS_UNIX, $jsPage->getTouched() ) );
614 }
615 }
616 return $this->modifiedTime;
617 }
618
619 public function getStyle( ResourceLoaderContext $context ) { return ''; }
620 public function getMessages() { return array(); }
621 public function getLoaderScript() { return ''; }
622 public function getDependencies() { return array(); }
623 }
624
625
626 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
627
628 /* Protected Members */
629
630 protected $modifiedTime = null;
631
632 /* Methods */
633
634 public function getScript( ResourceLoaderContext $context ) {
635 global $IP;
636
637 $scripts = file_get_contents( "$IP/resources/startup.js" );
638 if ( $context->getOnly() === 'scripts' ) {
639 // Get all module registrations
640 $registration = ResourceLoader::getModuleRegistrations( $context );
641 // Build configuration
642 $config = FormatJson::encode(
643 array( 'server' => $context->getServer(), 'debug' => $context->getDebug() )
644 );
645 // Add a well-known start-up function
646 $scripts .= "window.startUp = function() { $registration mediaWiki.config.set( $config ); };";
647 // Build load query for jquery and mediawiki modules
648 $query = wfArrayToCGI(
649 array(
650 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
651 'only' => 'scripts',
652 'lang' => $context->getLanguage(),
653 'dir' => $context->getDirection(),
654 'skin' => $context->getSkin(),
655 'debug' => $context->getDebug(),
656 'version' => wfTimestamp( TS_ISO_8601, round( max(
657 ResourceLoader::getModule( 'jquery' )->getModifiedTime( $context ),
658 ResourceLoader::getModule( 'mediawiki' )->getModifiedTime( $context )
659 ), -2 ) )
660 )
661 );
662 // Build HTML code for loading jquery and mediawiki modules
663 $loadScript = Html::linkedScript( $context->getServer() . "?$query" );
664 // Add code to add jquery and mediawiki loading code; only if the current client is compatible
665 $scripts .= "if ( isCompatible() ) { document.write( '$loadScript' ); }";
666 // Delete the compatible function - it's not needed anymore
667 $scripts .= "delete window['isCompatible'];";
668 }
669 return $scripts;
670 }
671
672 public function getModifiedTime( ResourceLoaderContext $context ) {
673 global $IP;
674 if ( !is_null( $this->modifiedTime ) ) {
675 return $this->modifiedTime;
676 }
677 // HACK getHighestModifiedTime() calls this function, so protect against infinite recursion
678 $this->modifiedTime = filemtime( "$IP/resources/startup.js" );
679 $this->modifiedTime = ResourceLoader::getHighestModifiedTime( $context );
680 return $this->modifiedTime;
681 }
682
683 public function getClientMaxage() {
684 return 300; // 5 minutes
685 }
686
687 public function getServerMaxage() {
688 return 300; // 5 minutes
689 }
690
691 public function getStyle( ResourceLoaderContext $context ) { return ''; }
692 public function getMessages() { return array(); }
693 public function getLoaderScript() { return ''; }
694 public function getDependencies() { return array(); }
695 }