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 /** Array: List of module name/ResourceLoaderModule object pairs */
34 protected $modules = array();
35 /** Associative array mapping module name to info associative array */
36 protected $moduleInfos = array();
38 /* Protected Methods */
41 * Loads information stored in the database about modules.
43 * This method grabs modules dependencies from the database and updates modules
46 * This is not inside the module code because it is much faster to
47 * request all of the information at once than it is to have each module
48 * requests its own information. This sacrifice of modularity yields a substantial
49 * performance improvement.
51 * @param $modules Array: List of module names to preload information for
52 * @param $context ResourceLoaderContext: Context to load the information within
54 protected function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
55 if ( !count( $modules ) ) {
56 return; // or else Database*::select() will explode, plus it's cheaper!
58 $dbr = wfGetDB( DB_SLAVE
);
59 $skin = $context->getSkin();
60 $lang = $context->getLanguage();
62 // Get file dependency information
63 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
64 'md_module' => $modules,
65 'md_skin' => $context->getSkin()
69 // Set modules' dependecies
70 $modulesWithDeps = array();
71 foreach ( $res as $row ) {
72 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
73 FormatJson
::decode( $row->md_deps
, true )
75 $modulesWithDeps[] = $row->md_module
;
78 // Register the absence of a dependency row too
79 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
80 $this->getModule( $name )->setFileDependencies( $skin, array() );
83 // Get message blob mtimes. Only do this for modules with messages
84 $modulesWithMessages = array();
85 $modulesWithoutMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
90 $modulesWithoutMessages[] = $name;
93 if ( count( $modulesWithMessages ) ) {
94 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
95 'mr_resource' => $modulesWithMessages,
99 foreach ( $res as $row ) {
100 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang, $row->mr_timestamp
);
103 foreach ( $modulesWithoutMessages as $name ) {
104 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
109 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
111 * Available filters are:
112 * - minify-js \see JSMin::minify
113 * - minify-css \see CSSMin::minify
115 * If $data is empty, only contains whitespace or the filter was unknown,
116 * $data is returned unmodified.
118 * @param $filter String: Name of filter to run
119 * @param $data String: Text to filter, such as JavaScript or CSS text
120 * @return String: Filtered data
122 protected function filter( $filter, $data ) {
123 wfProfileIn( __METHOD__
);
125 // For empty/whitespace-only data or for unknown filters, don't perform
126 // any caching or processing
127 if ( trim( $data ) === ''
128 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
130 wfProfileOut( __METHOD__
);
135 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
136 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
137 $cache = wfGetCache( CACHE_ANYTHING
);
138 $cacheEntry = $cache->get( $key );
139 if ( is_string( $cacheEntry ) ) {
140 wfProfileOut( __METHOD__
);
144 // Run the filter - we've already verified one of these will work
148 $result = JSMin
::minify( $data );
151 $result = CSSMin
::minify( $data );
154 } catch ( Exception
$exception ) {
155 throw new MWException( 'ResourceLoader filter error. ' .
156 'Exception was thrown: ' . $exception->getMessage() );
159 // Save filtered text to Memcached
160 $cache->set( $key, $result );
162 wfProfileOut( __METHOD__
);
170 * Registers core modules and runs registration hooks.
172 public function __construct() {
173 global $IP, $wgResourceModules;
175 wfProfileIn( __METHOD__
);
177 // Register core modules
178 $this->register( include( "$IP/resources/Resources.php" ) );
179 // Register extension modules
180 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
181 $this->register( $wgResourceModules );
183 wfProfileOut( __METHOD__
);
187 * Registers a module with the ResourceLoader system.
189 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
190 * @param $info Module info array. For backwards compatibility with 1.17alpha,
191 * this may also be a ResourceLoaderModule 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 registered
195 * @return Boolean: False if there were any errors, in which case one or more modules were not
198 public function register( $name, $info = null ) {
199 wfProfileIn( __METHOD__
);
201 // Allow multiple modules to be registered in one call
202 if ( is_array( $name ) ) {
203 foreach ( $name as $key => $value ) {
204 $this->register( $key, $value );
209 // Disallow duplicate registrations
210 if ( isset( $this->moduleInfos
[$name] ) ) {
211 // A module has already been registered by this name
212 throw new MWException(
213 'ResourceLoader duplicate registration error. ' .
214 'Another module has already been registered as ' . $name
219 if ( is_object( $info ) ) {
220 // Old calling convention
221 // Validate the input
222 if ( !( $info instanceof ResourceLoaderModule
) ) {
223 throw new MWException( 'ResourceLoader invalid module error. ' .
224 'Instances of ResourceLoaderModule expected.' );
227 $this->moduleInfos
[$name] = array( 'object' => $info );
228 $info->setName( $name );
229 $this->modules
[$name] = $info;
231 // New calling convention
232 $this->moduleInfos
[$name] = $info;
235 wfProfileOut( __METHOD__
);
239 * Get a list of module names
241 * @return Array: List of module names
243 public function getModuleNames() {
244 return array_keys( $this->moduleInfos
);
248 * Get the ResourceLoaderModule object for a given module name.
250 * @param $name String: Module name
251 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
253 public function getModule( $name ) {
254 if ( !isset( $this->modules
[$name] ) ) {
255 if ( !isset( $this->moduleInfos
[$name] ) ) {
259 // Construct the requested object
260 $info = $this->moduleInfos
[$name];
261 if ( isset( $info['object'] ) ) {
262 // Object given in info array
263 $object = $info['object'];
265 if ( !isset( $info['class'] ) ) {
266 $class = 'ResourceLoaderFileModule';
268 $class = $info['class'];
270 $object = new $class( $info );
272 $object->setName( $name );
273 $this->modules
[$name] = $object;
276 return $this->modules
[$name];
280 * Outputs a response to a resource load-request, including a content-type header.
282 * @param $context ResourceLoaderContext: Context in which a response should be formed
284 public function respond( ResourceLoaderContext
$context ) {
285 global $wgResourceLoaderMaxage, $wgCacheEpoch;
287 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
288 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
289 // is used: ob_clean() will clear the GZIP header in that case and it won't come
290 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
291 // the whole thing in our own output buffer to be sure the active buffer
292 // doesn't use ob_gzhandler.
293 // See http://bugs.php.net/bug.php?id=36514
296 wfProfileIn( __METHOD__
);
298 // Split requested modules into two groups, modules and missing
301 foreach ( $context->getModules() as $name ) {
302 if ( isset( $this->moduleInfos
[$name] ) ) {
303 $modules[$name] = $this->getModule( $name );
309 // If a version wasn't specified we need a shorter expiry time for updates
310 // to propagate to clients quickly
311 if ( is_null( $context->getVersion() ) ) {
312 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
313 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
315 // If a version was specified we can use a longer expiry time since changing
316 // version numbers causes cache misses
318 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
319 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
322 // Preload information needed to the mtime calculation below
323 $this->preloadModuleInfo( array_keys( $modules ), $context );
325 wfProfileIn( __METHOD__
.'-getModifiedTime' );
327 // To send Last-Modified and support If-Modified-Since, we need to detect
328 // the last modified time
329 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
330 foreach ( $modules as $module ) {
331 // Bypass squid cache if the request includes any private modules
332 if ( $module->getGroup() === 'private' ) {
335 // Calculate maximum modified time
336 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
339 wfProfileOut( __METHOD__
.'-getModifiedTime' );
341 if ( $context->getOnly() === 'styles' ) {
342 header( 'Content-Type: text/css' );
344 header( 'Content-Type: text/javascript' );
346 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
347 if ( $context->getDebug() ) {
348 header( 'Cache-Control: must-revalidate' );
350 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
351 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
354 // If there's an If-Modified-Since header, respond with a 304 appropriately
355 // Some clients send "timestamp;length=123". Strip the part after the first ';'
356 // so we get a valid timestamp.
357 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
358 if ( $ims !== false ) {
359 $imsTS = strtok( $ims, ';' );
360 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
361 // There's another bug in ob_gzhandler (see also the comment at
362 // the top of this function) that causes it to gzip even empty
363 // responses, meaning it's impossible to produce a truly empty
364 // response (because the gzip header is always there). This is
365 // a problem because 304 responses have to be completely empty
366 // per the HTTP spec, and Firefox behaves buggily when they're not.
367 // See also http://bugs.php.net/bug.php?id=51579
368 // To work around this, we tear down all output buffering before
370 while ( ob_get_level() > 0 ) {
374 header( 'HTTP/1.0 304 Not Modified' );
375 header( 'Status: 304 Not Modified' );
376 wfProfileOut( __METHOD__
);
381 // Generate a response
382 $response = $this->makeModuleResponse( $context, $modules, $missing );
384 // Capture any PHP warnings from the output buffer and append them to the
385 // response in a comment if we're in debug mode.
386 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
387 $response .= "/*\n$warnings\n*/";
390 // Remove the output buffer and output the response
394 wfProfileOut( __METHOD__
);
398 * Generates code for a response
400 * @param $context ResourceLoaderContext: Context in which to generate a response
401 * @param $modules Array: List of module objects keyed by module name
402 * @param $missing Array: List of unavailable modules (optional)
403 * @return String: Response data
405 public function makeModuleResponse( ResourceLoaderContext
$context,
406 array $modules, $missing = array() )
408 if ( $modules === array() && $missing === array() ) {
409 return '/* No modules requested. Max made me put this here */';
413 if ( $context->shouldIncludeMessages() ) {
414 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
421 foreach ( $modules as $name => $module ) {
423 wfProfileIn( __METHOD__
. '-' . $name );
427 if ( $context->shouldIncludeScripts() ) {
428 $scripts .= $module->getScript( $context ) . "\n";
433 if ( $context->shouldIncludeStyles() ) {
434 $styles = $module->getStyles( $context );
438 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
441 switch ( $context->getOnly() ) {
446 $out .= self
::makeCombinedStyles( $styles );
449 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
452 // Minify CSS before embedding in mediaWiki.loader.implement call
453 // (unless in debug mode)
454 if ( !$context->getDebug() ) {
455 foreach ( $styles as $media => $style ) {
456 $styles[$media] = $this->filter( 'minify-css', $style );
459 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
460 new XmlJsCode( $messagesBlob ) );
464 wfProfileOut( __METHOD__
. '-' . $name );
467 // Update module states
468 if ( $context->shouldIncludeScripts() ) {
469 // Set the state of modules loaded as only scripts to ready
470 if ( count( $modules ) && $context->getOnly() === 'scripts'
471 && !isset( $modules['startup'] ) )
473 $out .= self
::makeLoaderStateScript(
474 array_fill_keys( array_keys( $modules ), 'ready' ) );
476 // Set the state of modules which were requested but unavailable as missing
477 if ( is_array( $missing ) && count( $missing ) ) {
478 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
482 if ( $context->getDebug() ) {
485 if ( $context->getOnly() === 'styles' ) {
486 return $this->filter( 'minify-css', $out );
488 return $this->filter( 'minify-js', $out );
496 * Returns JS code to call to mediaWiki.loader.implement for a module with
499 * @param $name Module name
500 * @param $scripts Array: List of JavaScript code snippets to be executed after the
502 * @param $styles Array: List of CSS strings keyed by media type
503 * @param $messages Mixed: List of messages associated with this module. May either be an
504 * associative array mapping message key to value, or a JSON-encoded message blob containing
505 * the same data, wrapped in an XmlJsCode object.
507 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
508 if ( is_array( $scripts ) ) {
509 $scripts = implode( $scripts, "\n" );
511 return Xml
::encodeJsCall(
512 'mediaWiki.loader.implement',
515 new XmlJsCode( "function() {{$scripts}}" ),
522 * Returns JS code which, when called, will register a given list of messages.
524 * @param $messages Mixed: Either an associative array mapping message key to value, or a
525 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
527 public static function makeMessageSetScript( $messages ) {
528 return Xml
::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
532 * Combines an associative array mapping media type to CSS into a
533 * single stylesheet with @media blocks.
535 * @param $styles Array: List of CSS strings keyed by media type
537 public static function makeCombinedStyles( array $styles ) {
539 foreach ( $styles as $media => $style ) {
540 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
546 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
547 * module or modules to a given value. Has two calling conventions:
549 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
550 * Set the state of a single module called $name to $state
552 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
553 * Set the state of modules with the given names to the given states
555 public static function makeLoaderStateScript( $name, $state = null ) {
556 if ( is_array( $name ) ) {
557 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
559 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
564 * Returns JS code which calls the script given by $script. The script will
565 * be called with local variables name, version, dependencies and group,
566 * which will have values corresponding to $name, $version, $dependencies
567 * and $group as supplied.
569 * @param $name String: Module name
570 * @param $version Integer: Module version number as a timestamp
571 * @param $dependencies Array: List of module names on which this module depends
572 * @param $group String: Group which the module is in.
573 * @param $script String: JavaScript code
575 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
576 $script = str_replace( "\n", "\n\t", trim( $script ) );
577 return Xml
::encodeJsCall(
578 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
579 array( $name, $version, $dependencies, $group ) );
583 * Returns JS code which calls mediaWiki.loader.register with the given
584 * parameters. Has three calling conventions:
586 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
587 * Register a single module.
589 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
590 * Register modules with the given names.
592 * - ResourceLoader::makeLoaderRegisterScript( array(
593 * array( $name1, $version1, $dependencies1, $group1 ),
594 * array( $name2, $version2, $dependencies1, $group2 ),
597 * Registers modules with the given names and parameters.
599 * @param $name String: Module name
600 * @param $version Integer: Module version number as a timestamp
601 * @param $dependencies Array: List of module names on which this module depends
602 * @param $group String: group which the module is in.
604 public static function makeLoaderRegisterScript( $name, $version = null,
605 $dependencies = null, $group = null )
607 if ( is_array( $name ) ) {
608 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
610 $version = (int) $version > 1 ?
(int) $version : 1;
611 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
612 array( $name, $version, $dependencies, $group ) );
617 * Returns JS code which runs given JS code if the client-side framework is
620 * @param $script String: JavaScript code
622 public static function makeLoaderConditionalScript( $script ) {
623 $script = str_replace( "\n", "\n\t", trim( $script ) );
624 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
628 * Returns JS code which will set the MediaWiki configuration array to
631 * @param $configuration Array: List of configuration values keyed by variable name
633 public static function makeConfigSetScript( array $configuration ) {
634 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
638 * Determine whether debug mode was requested
639 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
642 public static function inDebugMode() {
643 global $wgRequest, $wgResourceLoaderDebug;
644 static $retval = null;
645 if ( !is_null( $retval ) )
647 return $retval = $wgRequest->getFuzzyBool( 'debug',
648 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );