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
19 * @author Roan Kattouw
20 * @author Trevor Parscal
24 * Dynamic JavaScript and CSS resource loading system.
26 * Most of the documention is on the MediaWiki documentation wiki starting at:
27 * http://www.mediawiki.org/wiki/ResourceLoader
29 class ResourceLoader
{
31 /* Protected Static Members */
33 /** @var {array} List of module name/ResourceLoaderModule object pairs */
34 protected $modules = array();
36 /* Protected Methods */
39 * Loads information stored in the database about modules.
41 * This method grabs modules dependencies from the database and updates modules
44 * This is not inside the module code because it's so much more performant to
45 * request all of the information at once than it is to have each module
46 * requests its own information. This sacrifice of modularity yields a profound
47 * performance improvement.
49 * @param $modules Array: list of module names to preload information for
50 * @param $context ResourceLoaderContext: context to load the information within
52 protected function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
53 if ( !count( $modules ) ) {
54 return; // or else Database*::select() will explode, plus it's cheaper!
56 $dbr = wfGetDb( DB_SLAVE
);
57 $skin = $context->getSkin();
58 $lang = $context->getLanguage();
60 // Get file dependency information
61 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
62 'md_module' => $modules,
63 'md_skin' => $context->getSkin()
67 // Set modules' dependecies
68 $modulesWithDeps = array();
69 foreach ( $res as $row ) {
70 $this->modules
[$row->md_module
]->setFileDependencies( $skin,
71 FormatJson
::decode( $row->md_deps
, true )
73 $modulesWithDeps[] = $row->md_module
;
76 // Register the absence of a dependency row too
77 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
78 $this->modules
[$name]->setFileDependencies( $skin, array() );
81 // Get message blob mtimes. Only do this for modules with messages
82 $modulesWithMessages = array();
83 $modulesWithoutMessages = array();
84 foreach ( $modules as $name ) {
85 if ( count( $this->modules
[$name]->getMessages() ) ) {
86 $modulesWithMessages[] = $name;
88 $modulesWithoutMessages[] = $name;
91 if ( count( $modulesWithMessages ) ) {
92 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
93 'mr_resource' => $modulesWithMessages,
97 foreach ( $res as $row ) {
98 $this->modules
[$row->mr_resource
]->setMsgBlobMtime( $lang, $row->mr_timestamp
);
101 foreach ( $modulesWithoutMessages as $name ) {
102 $this->modules
[$name]->setMsgBlobMtime( $lang, 0 );
107 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
109 * Available filters are:
110 * - minify-js \see JSMin::minify
111 * - minify-css \see CSSMin::minify
112 * - flip-css \see CSSJanus::transform
114 * If $data is empty, only contains whitespace or the filter was unknown,
115 * $data is returned unmodified.
117 * @param $filter String: name of filter to run
118 * @param $data String: text to filter, such as JavaScript or CSS text
119 * @return String: filtered data
121 protected function filter( $filter, $data ) {
124 wfProfileIn( __METHOD__
);
126 // For empty/whitespace-only data or for unknown filters, don't perform
127 // any caching or processing
128 if ( trim( $data ) === ''
129 ||
!in_array( $filter, array( 'minify-js', 'minify-css', 'flip-css' ) ) )
131 wfProfileOut( __METHOD__
);
135 // Try for Memcached hit
136 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
137 $cacheEntry = $wgMemc->get( $key );
138 if ( is_string( $cacheEntry ) ) {
139 wfProfileOut( __METHOD__
);
143 // Run the filter - we've already verified one of these will work
147 $result = JSMin
::minify( $data );
150 $result = CSSMin
::minify( $data );
153 $result = CSSJanus
::transform( $data, true, false );
156 } catch ( Exception
$exception ) {
157 throw new MWException( 'ResourceLoader filter error. ' .
158 'Exception was thrown: ' . $exception->getMessage() );
161 // Save filtered text to Memcached
162 $wgMemc->set( $key, $result );
164 wfProfileOut( __METHOD__
);
172 * Registers core modules and runs registration hooks.
174 public function __construct() {
177 wfProfileIn( __METHOD__
);
179 // Register core modules
180 $this->register( include( "$IP/resources/Resources.php" ) );
181 // Register extension modules
182 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
184 wfProfileOut( __METHOD__
);
188 * Registers a module with the ResourceLoader system.
190 * @param $name Mixed: string of name of module or array of name/object pairs
191 * @param $object ResourceLoaderModule: module object (optional when using
192 * multiple-registration calling style)
193 * @throws MWException If a duplicate module registration is attempted
194 * @throws MWException If something other than a ResourceLoaderModule is being
196 * @return Boolean: false if there were any errors, in which case one or more
197 * modules were not registered
199 public function register( $name, ResourceLoaderModule
$object = null ) {
201 wfProfileIn( __METHOD__
);
203 // Allow multiple modules to be registered in one call
204 if ( is_array( $name ) && !isset( $object ) ) {
205 foreach ( $name as $key => $value ) {
206 $this->register( $key, $value );
209 wfProfileOut( __METHOD__
);
214 // Disallow duplicate registrations
215 if ( isset( $this->modules
[$name] ) ) {
216 // A module has already been registered by this name
217 throw new MWException(
218 'ResourceLoader duplicate registration error. ' .
219 'Another module has already been registered as ' . $name
223 // Validate the input (type hinting lets null through)
224 if ( !( $object instanceof ResourceLoaderModule
) ) {
225 throw new MWException( 'ResourceLoader invalid module error. ' .
226 'Instances of ResourceLoaderModule expected.' );
230 $this->modules
[$name] = $object;
231 $object->setName( $name );
233 wfProfileOut( __METHOD__
);
237 * Gets a map of all modules and their options
239 * @return Array: array( modulename => ResourceLoaderModule )
241 public function getModules() {
242 return $this->modules
;
246 * Get the ResourceLoaderModule object for a given module name.
248 * @param $name String: module name
249 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
251 public function getModule( $name ) {
252 return isset( $this->modules
[$name] ) ?
$this->modules
[$name] : null;
256 * Outputs a response to a resource load-request, including a content-type header.
258 * @param $context ResourceLoaderContext: context in which a response should be formed
260 public function respond( ResourceLoaderContext
$context ) {
261 global $wgResourceLoaderMaxage, $wgCacheEpoch;
263 wfProfileIn( __METHOD__
);
265 // Split requested modules into two groups, modules and missing
268 foreach ( $context->getModules() as $name ) {
269 if ( isset( $this->modules
[$name] ) ) {
270 $modules[$name] = $this->modules
[$name];
276 // If a version wasn't specified we need a shorter expiry time for updates
277 // to propagate to clients quickly
278 if ( is_null( $context->getVersion() ) ) {
279 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
280 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
282 // If a version was specified we can use a longer expiry time since changing
283 // version numbers causes cache misses
285 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
286 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
289 // Preload information needed to the mtime calculation below
290 $this->preloadModuleInfo( array_keys( $modules ), $context );
292 wfProfileIn( __METHOD__
.'-getModifiedTime' );
294 // To send Last-Modified and support If-Modified-Since, we need to detect
295 // the last modified time
296 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
297 foreach ( $modules as $module ) {
298 // Bypass squid cache if the request includes any private modules
299 if ( $module->getGroup() === 'private' ) {
302 // Calculate maximum modified time
303 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
306 wfProfileOut( __METHOD__
.'-getModifiedTime' );
308 if ( $context->getOnly() === 'styles' ) {
309 header( 'Content-Type: text/css' );
311 header( 'Content-Type: text/javascript' );
313 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
314 if ( $context->getDebug() ) {
315 header( 'Cache-Control: must-revalidate' );
317 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
318 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
321 // If there's an If-Modified-Since header, respond with a 304 appropriately
322 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
323 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX
, $ims ) ) {
324 header( 'HTTP/1.0 304 Not Modified' );
325 header( 'Status: 304 Not Modified' );
326 wfProfileOut( __METHOD__
);
330 // Generate a response
331 $response = $this->makeModuleResponse( $context, $modules, $missing );
333 // Tack on PHP warnings as a comment in debug mode
334 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
335 $response .= "/*\n$warnings\n*/";
338 // Clear any warnings from the buffer
342 wfProfileOut( __METHOD__
);
346 * Generates code for a response
348 * @param $context ResourceLoaderContext: context in which to generate a response
349 * @param $modules Array: list of module objects keyed by module name
350 * @param $missing Array: list of unavailable modules (optional)
351 * @return String: response data
353 public function makeModuleResponse( ResourceLoaderContext
$context,
354 array $modules, $missing = array() )
357 if ( $context->shouldIncludeMessages() ) {
358 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
365 foreach ( $modules as $name => $module ) {
367 wfProfileIn( __METHOD__
. '-' . $name );
371 if ( $context->shouldIncludeScripts() ) {
372 $scripts .= $module->getScript( $context ) . "\n";
377 if ( $context->shouldIncludeStyles() ) {
378 $styles = $module->getStyles( $context );
379 // Flip CSS on a per-module basis
380 if ( $styles && $this->modules
[$name]->getFlip( $context ) ) {
381 foreach ( $styles as $media => $style ) {
382 $styles[$media] = $this->filter( 'flip-css', $style );
388 $messages = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
391 switch ( $context->getOnly() ) {
396 $out .= self
::makeCombinedStyles( $styles );
399 $out .= self
::makeMessageSetScript( $messages );
402 // Minify CSS before embedding in mediaWiki.loader.implement call
403 // (unless in debug mode)
404 if ( !$context->getDebug() ) {
405 foreach ( $styles as $media => $style ) {
406 $styles[$media] = $this->filter( 'minify-css', $style );
409 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles, $messages );
413 wfProfileOut( __METHOD__
. '-' . $name );
416 // Update module states
417 if ( $context->shouldIncludeScripts() ) {
418 // Set the state of modules loaded as only scripts to ready
419 if ( count( $modules ) && $context->getOnly() === 'scripts'
420 && !isset( $modules['startup'] ) )
422 $out .= self
::makeLoaderStateScript(
423 array_fill_keys( array_keys( $modules ), 'ready' ) );
425 // Set the state of modules which were requested but unavailable as missing
426 if ( is_array( $missing ) && count( $missing ) ) {
427 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
431 if ( $context->getDebug() ) {
434 if ( $context->getOnly() === 'styles' ) {
435 return $this->filter( 'minify-css', $out );
437 return $this->filter( 'minify-js', $out );
444 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
445 if ( is_array( $scripts ) ) {
446 $scripts = implode( $scripts, "\n" );
448 if ( is_array( $styles ) ) {
449 $styles = count( $styles ) ? FormatJson
::encode( $styles ) : 'null';
451 if ( is_array( $messages ) ) {
452 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
454 return "mediaWiki.loader.implement( '$name', function() {{$scripts}},\n$styles,\n$messages );\n";
457 public static function makeMessageSetScript( $messages ) {
458 if ( is_array( $messages ) ) {
459 $messages = count( $messages ) ? FormatJson
::encode( $messages ) : 'null';
461 return "mediaWiki.msg.set( $messages );\n";
464 public static function makeCombinedStyles( array $styles ) {
466 foreach ( $styles as $media => $style ) {
467 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
472 public static function makeLoaderStateScript( $name, $state = null ) {
473 if ( is_array( $name ) ) {
474 $statuses = FormatJson
::encode( $name );
475 return "mediaWiki.loader.state( $statuses );\n";
477 $name = Xml
::escapeJsString( $name );
478 $state = Xml
::escapeJsString( $state );
479 return "mediaWiki.loader.state( '$name', '$state' );\n";
483 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
484 $name = Xml
::escapeJsString( $name );
485 $version = (int) $version > 1 ?
(int) $version : 1;
486 $dependencies = FormatJson
::encode( $dependencies );
487 $group = FormatJson
::encode( $group );
488 $script = str_replace( "\n", "\n\t", trim( $script ) );
489 return "( function( name, version, dependencies, group ) {\n\t$script\n} )" .
490 "( '$name', $version, $dependencies, $group );\n";
493 public static function makeLoaderRegisterScript( $name, $version = null,
494 $dependencies = null, $group = null )
496 if ( is_array( $name ) ) {
497 $registrations = FormatJson
::encode( $name );
498 return "mediaWiki.loader.register( $registrations );\n";
500 $name = Xml
::escapeJsString( $name );
501 $version = (int) $version > 1 ?
(int) $version : 1;
502 $dependencies = FormatJson
::encode( $dependencies );
503 $group = FormatJson
::encode( $group );
504 return "mediaWiki.loader.register( '$name', $version, $dependencies, $group );\n";
508 public static function makeLoaderConditionalScript( $script ) {
509 $script = str_replace( "\n", "\n\t", trim( $script ) );
510 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
513 public static function makeConfigSetScript( array $configuration ) {
514 $configuration = FormatJson
::encode( $configuration );
515 return "mediaWiki.config.set( $configuration );\n";