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.
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.
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
18 * @author Trevor Parscal
19 * @author Roan Kattouw
23 * Interface for resource loader modules, with name registration and maxage functionality.
25 abstract class ResourceLoaderModule
{
27 /* Protected Members */
29 protected $name = null;
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
38 public function getName() {
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
47 public function setName( $name ) {
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
57 public function getClientMaxage() {
58 global $wgResourceLoaderClientMaxage;
59 return $wgResourceLoaderClientMaxage;
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
68 public function getServerMaxage() {
69 global $wgResourceLoaderServerMaxage;
70 return $wgResourceLoaderServerMaxage;
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
81 public abstract function getScript( ResourceLoaderContext
$context );
84 * Get all CSS for this module for a given skin.
85 * @param $skin string Skin name
88 public abstract function getStyle( ResourceLoaderContext
$context );
91 * Get the messages needed for this module.
93 * To get a JSON blob with messages, use MessageBlobStore::get()
94 * @return array of message keys. Keys may occur more than once
96 public abstract function getMessages();
99 * Get the loader JS for this module, if set.
100 * @return mixed Loader JS (string) or false if no custom loader set
102 public abstract function getLoaderScript();
105 * Get a list of modules this module depends on.
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.
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)
119 public abstract function getDependencies();
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
132 public abstract function getModifiedTime( ResourceLoaderContext
$context );
136 * Module based on local JS/CSS files. This is the most common type of module.
138 class ResourceLoaderFileModule
extends ResourceLoaderModule
{
140 /* Protected Members */
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();
153 // In-object cache for file dependencies
154 protected $fileDeps = array();
155 // In-object cache for mtime
156 protected $modifiedTime = array();
161 * Construct a new module from an options array.
163 * @param $options array Options array. If empty, an empty module will be constructed
167 * // Required module options (mutually exclusive)
168 * 'scripts' => 'dir/script.js' | array( 'dir/script1.js', 'dir/script2.js' ... ),
170 * // Optional module options
171 * 'languageScripts' => array(
172 * '[lang name]' => 'dir/lang.js' | '[lang name]' => array( 'dir/lang1.js', 'dir/lang2.js' ... )
175 * 'skinScripts' => 'dir/skin.js' | array( 'dir/skin1.js', 'dir/skin2.js' ... ),
176 * 'debugScripts' => 'dir/debug.js' | array( 'dir/debug1.js', 'dir/debug2.js' ... ),
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' ... )
186 * 'messages' => array( 'message1', 'message2' ... ),
189 public function __construct( $options = array() ) {
190 foreach ( $options as $option => $value ) {
193 $this->scripts
= (array)$value;
196 $this->styles
= (array)$value;
199 $this->messages
= (array)$value;
202 $this->dependencies
= (array)$value;
205 $this->debugScripts
= (array)$value;
207 case 'languageScripts':
208 $this->languageScripts
= (array)$value;
211 $this->skinScripts
= (array)$value;
214 $this->skinStyles
= (array)$value;
217 $this->loaders
= (array)$value;
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
228 public function addScripts( $scripts ) {
229 $this->scripts
= array_merge( $this->scripts
, (array)$scripts );
233 * Add style (CSS) files to this module.
234 * @param $styles mixed Path to CSS file (string) or array of paths
236 public function addStyles( $styles ) {
237 $this->styles
= array_merge( $this->styles
, (array)$styles );
241 * Add messages to this module.
242 * @param $messages mixed Message key (string) or array of message keys
244 public function addMessages( $messages ) {
245 $this->messages
= array_merge( $this->messages
, (array)$messages );
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.
257 * To add dependencies dynamically on the client side, use a custom
258 * loader (see addLoaders())
260 * @param $dependencies mixed Module name (string) or array of module names
262 public function addDependencies( $dependencies ) {
263 $this->dependencies
= array_merge( $this->dependencies
, (array)$dependencies );
267 * Add debug scripts to the module. These scripts are only included
269 * @param $scripts mixed Path to script file (string) or array of paths
271 public function addDebugScripts( $scripts ) {
272 $this->debugScripts
= array_merge( $this->debugScripts
, (array)$scripts );
276 * Add language-specific scripts. These scripts are only included for
278 * @param $lang string Language code
279 * @param $scripts mixed Path to script file (string) or array of paths
281 public function addLanguageScripts( $lang, $scripts ) {
282 $this->languageScripts
= array_merge_recursive(
283 $this->languageScripts
,
284 array( $lang => $scripts )
289 * Add skin-specific scripts. These scripts are only included for
291 * @param $skin string Skin name, or 'default'
292 * @param $scripts mixed Path to script file (string) or array of paths
294 public function addSkinScripts( $skin, $scripts ) {
295 $this->skinScripts
= array_merge_recursive(
297 array( $skin => $scripts )
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
308 public function addSkinStyles( $skin, $scripts ) {
309 $this->skinStyles
= array_merge_recursive(
311 array( $skin => $scripts )
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.
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
328 public function addLoaders( $scripts ) {
329 $this->loaders
= array_merge( $this->loaders
, (array)$scripts );
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();
342 public function getStyle( ResourceLoaderContext
$context ) {
343 $style = $this->getPrimaryStyle() . "\n" . $this->getSkinStyle( $context->getSkin() );
345 // Extract and store the list of referenced files
346 $files = CSSMin
::getLocalFileReferences( $style );
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,
360 // Save into memcached
362 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $context->getSkin() );
363 $wgMemc->set( $key, $encFiles );
368 public function getMessages() {
369 return $this->messages
;
372 public function getDependencies() {
373 return $this->dependencies
;
376 public function getLoaderScript() {
377 if ( count( $this->loaders
) == 0 ) {
380 return self
::concatScripts( $this->loaders
);
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
390 * @param $lang string Language code
391 * @param $skin string Skin name
392 * @param $debug bool Debug mode flag
393 * @return int UNIX timestamp
395 public function getModifiedTime( ResourceLoaderContext
$context ) {
396 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
397 return $this->modifiedTime
[$context->getHash()];
400 $files = array_merge(
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
),
409 $this->getFileDependencies( $context->getSkin() )
411 $filesMtime = max( array_map( 'filemtime', array_map( array( __CLASS__
, 'remapFilename' ), $files ) ) );
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()
421 $msgBlobMtime = $msgBlobMtime ?
wfTimestamp( TS_UNIX
, $msgBlobMtime ) : 0;
423 $this->modifiedTime
[$context->getHash()] = max( $filesMtime, $msgBlobMtime );
424 return $this->modifiedTime
[$context->getHash()];
427 /* Protected Members */
430 * Get the primary JS for this module. This is pulled from the
431 * script files added through addScripts()
434 protected function getPrimaryScript() {
435 return self
::concatScripts( $this->scripts
);
439 * Get the primary CSS for this module. This is pulled from the CSS
440 * files added through addStyles()
443 protected function getPrimaryStyle() {
444 return self
::concatStyles( $this->styles
);
448 * Get the debug JS for this module. This is pulled from the script
449 * files added through addDebugScripts()
452 protected function getDebugScript() {
453 return self
::concatScripts( $this->debugScripts
);
457 * Get the language-specific JS for a given language. This is pulled
458 * from the language-specific script files added through addLanguageScripts()
461 protected function getLanguageScript( $lang ) {
462 if ( !isset( $this->languageScripts
[$lang] ) ) {
465 return self
::concatScripts( $this->languageScripts
[$lang] );
469 * Get the skin-specific JS for a given skin. This is pulled from the
470 * skin-specific JS files added through addSkinScripts()
473 protected function getSkinScript( $skin ) {
474 return self
::concatScripts( self
::getSkinFiles( $skin, $this->skinScripts
) );
478 * Get the skin-specific CSS for a given skin. This is pulled from the
479 * skin-specific CSS files added through addSkinStyles()
482 protected function getSkinStyle( $skin ) {
483 return self
::concatStyles( self
::getSkinFiles( $skin, $this->skinStyles
) );
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
492 protected static function getSkinFiles( $skin, $map ) {
494 if ( isset( $map[$skin] ) && $map[$skin] ) {
495 $retval = $map[$skin];
496 } else if ( isset( $map['default'] ) ) {
497 $retval = $map['default'];
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
508 protected function getFileDependencies( $skin ) {
509 // Try in-object cache first
510 if ( isset( $this->fileDeps
[$skin] ) ) {
511 return $this->fileDeps
[$skin];
516 $key = wfMemcKey( 'resourceloader', 'module_deps', $this->getName(), $skin );
517 $deps = $wgMemc->get( $key );
520 $dbr = wfGetDb( DB_SLAVE
);
521 $deps = $dbr->selectField( 'module_deps', 'md_deps', array(
522 'md_module' => $this->getName(),
527 $deps = '[]'; // Empty array so we can do negative caching
529 $wgMemc->set( $key, $deps );
531 $this->fileDeps
= FormatJson
::decode( $deps, true );
532 return $this->fileDeps
;
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
541 protected static function concatScripts( $files ) {
542 return implode( "\n", array_map( 'file_get_contents', array_map( array( __CLASS__
, 'remapFilename' ), array_unique( (array) $files ) ) ) );
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
551 protected static function concatStyles( $files ) {
552 return implode( "\n", array_map( array( __CLASS__
, 'remapStyle' ), array_unique( (array) $files ) ) );
556 * Remap a relative to $IP. Used as a callback for array_map()
557 * @param $file string File name
558 * @return string $IP/$file
560 protected static function remapFilename( $file ) {
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
571 protected static function remapStyle( $file ) {
572 return CSSMin
::remap( file_get_contents( self
::remapFilename( $file ) ), dirname( $file ) );
577 * Custom module for MediaWiki:Common.js and MediaWiki:Skinname.js
578 * TODO: Add Site CSS functionality too
580 class ResourceLoaderSiteModule
extends ResourceLoaderModule
{
582 /* Protected Members */
584 // In-object cache for modified time
585 protected $modifiedTime = null;
589 public function getScript( ResourceLoaderContext
$context ) {
590 return Skin
::newFromKey( $context->getSkin() )->generateUserJs();
593 public function getModifiedTime( ResourceLoaderContext
$context ) {
594 if ( isset( $this->modifiedTime
[$context->getHash()] ) ) {
595 return $this->modifiedTime
[$context->getHash()];
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' )
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 );
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() ) );
616 return $this->modifiedTime
;
619 public function getStyle( ResourceLoaderContext
$context ) { return ''; }
620 public function getMessages() { return array(); }
621 public function getLoaderScript() { return ''; }
622 public function getDependencies() { return array(); }
626 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
628 /* Protected Members */
630 protected $modifiedTime = null;
634 public function getScript( ResourceLoaderContext
$context ) {
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() )
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(
650 'modules' => implode( '|', array( 'jquery', 'mediawiki' ) ),
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 )
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'];";
672 public function getModifiedTime( ResourceLoaderContext
$context ) {
674 if ( !is_null( $this->modifiedTime
) ) {
675 return $this->modifiedTime
;
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
;
683 public function getClientMaxage() {
684 return 300; // 5 minutes
687 public function getServerMaxage() {
688 return 300; // 5 minutes
691 public function getStyle( ResourceLoaderContext
$context ) { return ''; }
692 public function getMessages() { return array(); }
693 public function getLoaderScript() { return ''; }
694 public function getDependencies() { return array(); }