8903e5b6a65bf9ce2c4b57f88e55ef811d0ff29e
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 */
32 protected static $filterCacheVersion = 2;
34 /** Array: List of module name/ResourceLoaderModule object pairs */
35 protected $modules = array();
36 /** Associative array mapping module name to info associative array */
37 protected $moduleInfos = array();
39 /* Protected Methods */
42 * Loads information stored in the database about modules.
44 * This method grabs modules dependencies from the database and updates modules
47 * This is not inside the module code because it is much faster to
48 * request all of the information at once than it is to have each module
49 * requests its own information. This sacrifice of modularity yields a substantial
50 * performance improvement.
52 * @param $modules Array: List of module names to preload information for
53 * @param $context ResourceLoaderContext: Context to load the information within
55 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
56 if ( !count( $modules ) ) {
57 return; // or else Database*::select() will explode, plus it's cheaper!
59 $dbr = wfGetDB( DB_SLAVE
);
60 $skin = $context->getSkin();
61 $lang = $context->getLanguage();
63 // Get file dependency information
64 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
65 'md_module' => $modules,
66 'md_skin' => $context->getSkin()
70 // Set modules' dependencies
71 $modulesWithDeps = array();
72 foreach ( $res as $row ) {
73 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
74 FormatJson
::decode( $row->md_deps
, true )
76 $modulesWithDeps[] = $row->md_module
;
79 // Register the absence of a dependency row too
80 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
81 $this->getModule( $name )->setFileDependencies( $skin, array() );
84 // Get message blob mtimes. Only do this for modules with messages
85 $modulesWithMessages = array();
86 foreach ( $modules as $name ) {
87 if ( count( $this->getModule( $name )->getMessages() ) ) {
88 $modulesWithMessages[] = $name;
91 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
92 if ( count( $modulesWithMessages ) ) {
93 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
94 'mr_resource' => $modulesWithMessages,
98 foreach ( $res as $row ) {
99 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
100 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
101 unset( $modulesWithoutMessages[$row->mr_resource
] );
104 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
105 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
110 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
112 * Available filters are:
113 * - minify-js \see JavaScriptMinifier::minify
114 * - minify-css \see CSSMin::minify
116 * If $data is empty, only contains whitespace or the filter was unknown,
117 * $data is returned unmodified.
119 * @param $filter String: Name of filter to run
120 * @param $data String: Text to filter, such as JavaScript or CSS text
121 * @return String: Filtered data, or a comment containing an error message
123 protected function filter( $filter, $data ) {
124 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
125 wfProfileIn( __METHOD__
);
127 // For empty/whitespace-only data or for unknown filters, don't perform
128 // any caching or processing
129 if ( trim( $data ) === ''
130 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
132 wfProfileOut( __METHOD__
);
137 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
138 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
139 $cache = wfGetCache( CACHE_ANYTHING
);
140 $cacheEntry = $cache->get( $key );
141 if ( is_string( $cacheEntry ) ) {
142 wfProfileOut( __METHOD__
);
147 // Run the filter - we've already verified one of these will work
151 $result = JavaScriptMinifier
::minify( $data,
152 $wgResourceLoaderMinifierStatementsOnOwnLine,
153 $wgResourceLoaderMinifierMaxLineLength
155 $result .= "\n\n/* cache key: $key */\n";
158 $result = CSSMin
::minify( $data );
159 $result .= "\n\n/* cache key: $key */\n";
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
165 } catch ( Exception
$exception ) {
166 // Return exception as a comment
167 $result = "/*\n{$exception->__toString()}\n*/\n";
170 wfProfileOut( __METHOD__
);
178 * Registers core modules and runs registration hooks.
180 public function __construct() {
181 global $IP, $wgResourceModules;
183 wfProfileIn( __METHOD__
);
185 // Register core modules
186 $this->register( include( "$IP/resources/Resources.php" ) );
187 // Register extension modules
188 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
189 $this->register( $wgResourceModules );
191 wfProfileOut( __METHOD__
);
195 * Registers a module with the ResourceLoader system.
197 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
198 * @param $info Module info array. For backwards compatibility with 1.17alpha,
199 * this may also be a ResourceLoaderModule object. Optional when using
200 * multiple-registration calling style.
201 * @throws MWException: If a duplicate module registration is attempted
202 * @throws MWException: If something other than a ResourceLoaderModule is being registered
203 * @return Boolean: False if there were any errors, in which case one or more modules were not
206 public function register( $name, $info = null ) {
207 wfProfileIn( __METHOD__
);
209 // Allow multiple modules to be registered in one call
210 if ( is_array( $name ) ) {
211 foreach ( $name as $key => $value ) {
212 $this->register( $key, $value );
214 wfProfileOut( __METHOD__
);
218 // Disallow duplicate registrations
219 if ( isset( $this->moduleInfos
[$name] ) ) {
220 // A module has already been registered by this name
221 throw new MWException(
222 'ResourceLoader duplicate registration error. ' .
223 'Another module has already been registered as ' . $name
228 if ( is_object( $info ) ) {
229 // Old calling convention
230 // Validate the input
231 if ( !( $info instanceof ResourceLoaderModule
) ) {
232 throw new MWException( 'ResourceLoader invalid module error. ' .
233 'Instances of ResourceLoaderModule expected.' );
236 $this->moduleInfos
[$name] = array( 'object' => $info );
237 $info->setName( $name );
238 $this->modules
[$name] = $info;
240 // New calling convention
241 $this->moduleInfos
[$name] = $info;
244 wfProfileOut( __METHOD__
);
248 * Get a list of module names
250 * @return Array: List of module names
252 public function getModuleNames() {
253 return array_keys( $this->moduleInfos
);
257 * Get the ResourceLoaderModule object for a given module name.
259 * @param $name String: Module name
260 * @return ResourceLoaderModule if module has been registered, null otherwise
262 public function getModule( $name ) {
263 if ( !isset( $this->modules
[$name] ) ) {
264 if ( !isset( $this->moduleInfos
[$name] ) ) {
268 // Construct the requested object
269 $info = $this->moduleInfos
[$name];
270 if ( isset( $info['object'] ) ) {
271 // Object given in info array
272 $object = $info['object'];
274 if ( !isset( $info['class'] ) ) {
275 $class = 'ResourceLoaderFileModule';
277 $class = $info['class'];
279 $object = new $class( $info );
281 $object->setName( $name );
282 $this->modules
[$name] = $object;
285 return $this->modules
[$name];
289 * Outputs a response to a resource load-request, including a content-type header.
291 * @param $context ResourceLoaderContext: Context in which a response should be formed
293 public function respond( ResourceLoaderContext
$context ) {
294 global $wgResourceLoaderMaxage, $wgCacheEpoch;
296 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
297 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
298 // is used: ob_clean() will clear the GZIP header in that case and it won't come
299 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
300 // the whole thing in our own output buffer to be sure the active buffer
301 // doesn't use ob_gzhandler.
302 // See http://bugs.php.net/bug.php?id=36514
305 wfProfileIn( __METHOD__
);
308 // Split requested modules into two groups, modules and missing
311 foreach ( $context->getModules() as $name ) {
312 if ( isset( $this->moduleInfos
[$name] ) ) {
313 $modules[$name] = $this->getModule( $name );
319 // If a version wasn't specified we need a shorter expiry time for updates
320 // to propagate to clients quickly
321 if ( is_null( $context->getVersion() ) ) {
322 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
323 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
325 // If a version was specified we can use a longer expiry time since changing
326 // version numbers causes cache misses
328 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
329 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
332 // Preload information needed to the mtime calculation below
334 $this->preloadModuleInfo( array_keys( $modules ), $context );
335 } catch( Exception
$e ) {
336 // Add exception to the output as a comment
337 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
340 wfProfileIn( __METHOD__
.'-getModifiedTime' );
343 // To send Last-Modified and support If-Modified-Since, we need to detect
344 // the last modified time
345 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
346 foreach ( $modules as $module ) {
348 // Bypass Squid and other shared caches if the request includes any private modules
349 if ( $module->getGroup() === 'private' ) {
352 // Calculate maximum modified time
353 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
354 } catch ( Exception
$e ) {
355 // Add exception to the output as a comment
356 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
360 wfProfileOut( __METHOD__
.'-getModifiedTime' );
362 if ( $context->getOnly() === 'styles' ) {
363 header( 'Content-Type: text/css' );
365 header( 'Content-Type: text/javascript' );
367 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
368 if ( $context->getDebug() ) {
369 // Do not cache debug responses
370 header( 'Cache-Control: private, no-cache, must-revalidate' );
371 header( 'Pragma: no-cache' );
374 header( "Cache-Control: private, max-age=$maxage" );
377 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
378 $exp = min( $maxage, $smaxage );
380 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
383 // If there's an If-Modified-Since header, respond with a 304 appropriately
384 // Some clients send "timestamp;length=123". Strip the part after the first ';'
385 // so we get a valid timestamp.
386 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
387 // Never send 304s in debug mode
388 if ( $ims !== false && !$context->getDebug() ) {
389 $imsTS = strtok( $ims, ';' );
390 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
391 // There's another bug in ob_gzhandler (see also the comment at
392 // the top of this function) that causes it to gzip even empty
393 // responses, meaning it's impossible to produce a truly empty
394 // response (because the gzip header is always there). This is
395 // a problem because 304 responses have to be completely empty
396 // per the HTTP spec, and Firefox behaves buggily when they're not.
397 // See also http://bugs.php.net/bug.php?id=51579
398 // To work around this, we tear down all output buffering before
400 // On some setups, ob_get_level() doesn't seem to go down to zero
401 // no matter how often we call ob_get_clean(), so instead of doing
402 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
403 // we have to be safe here and avoid an infinite loop.
404 for ( $i = 0; $i < ob_get_level(); $i++
) {
408 header( 'HTTP/1.0 304 Not Modified' );
409 header( 'Status: 304 Not Modified' );
410 wfProfileOut( __METHOD__
);
415 // Generate a response
416 $response = $this->makeModuleResponse( $context, $modules, $missing );
418 // Prepend comments indicating exceptions
419 $response = $exceptions . $response;
421 // Capture any PHP warnings from the output buffer and append them to the
422 // response in a comment if we're in debug mode.
423 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
424 $response = "/*\n$warnings\n*/\n" . $response;
427 // Remove the output buffer and output the response
431 wfProfileOut( __METHOD__
);
435 * Generates code for a response
437 * @param $context ResourceLoaderContext: Context in which to generate a response
438 * @param $modules Array: List of module objects keyed by module name
439 * @param $missing Array: List of unavailable modules (optional)
440 * @return String: Response data
442 public function makeModuleResponse( ResourceLoaderContext
$context,
443 array $modules, $missing = array() )
447 if ( $modules === array() && $missing === array() ) {
448 return '/* No modules requested. Max made me put this here */';
451 wfProfileIn( __METHOD__
);
453 if ( $context->shouldIncludeMessages() ) {
455 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
456 } catch ( Exception
$e ) {
457 // Add exception to the output as a comment
458 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
465 foreach ( $modules as $name => $module ) {
466 wfProfileIn( __METHOD__
. '-' . $name );
470 if ( $context->shouldIncludeScripts() ) {
471 $scripts .= $module->getScript( $context ) . "\n";
476 if ( $context->shouldIncludeStyles() ) {
477 $styles = $module->getStyles( $context );
481 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
484 switch ( $context->getOnly() ) {
489 $out .= self
::makeCombinedStyles( $styles );
492 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
495 // Minify CSS before embedding in mw.loader.implement call
496 // (unless in debug mode)
497 if ( !$context->getDebug() ) {
498 foreach ( $styles as $media => $style ) {
499 $styles[$media] = $this->filter( 'minify-css', $style );
502 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
503 new XmlJsCode( $messagesBlob ) );
506 } catch ( Exception
$e ) {
507 // Add exception to the output as a comment
508 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
510 // Register module as missing
512 unset( $modules[$name] );
514 wfProfileOut( __METHOD__
. '-' . $name );
517 // Update module states
518 if ( $context->shouldIncludeScripts() ) {
519 // Set the state of modules loaded as only scripts to ready
520 if ( count( $modules ) && $context->getOnly() === 'scripts'
521 && !isset( $modules['startup'] ) )
523 $out .= self
::makeLoaderStateScript(
524 array_fill_keys( array_keys( $modules ), 'ready' ) );
526 // Set the state of modules which were requested but unavailable as missing
527 if ( is_array( $missing ) && count( $missing ) ) {
528 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
532 if ( !$context->getDebug() ) {
533 if ( $context->getOnly() === 'styles' ) {
534 $out = $this->filter( 'minify-css', $out );
536 $out = $this->filter( 'minify-js', $out );
540 wfProfileOut( __METHOD__
);
541 return $exceptions . $out;
547 * Returns JS code to call to mw.loader.implement for a module with
550 * @param $name Module name
551 * @param $scripts Array: List of JavaScript code snippets to be executed after the
553 * @param $styles Array: List of CSS strings keyed by media type
554 * @param $messages Mixed: List of messages associated with this module. May either be an
555 * associative array mapping message key to value, or a JSON-encoded message blob containing
556 * the same data, wrapped in an XmlJsCode object.
558 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
559 if ( is_array( $scripts ) ) {
560 $scripts = implode( $scripts, "\n" );
562 return Xml
::encodeJsCall(
563 'mw.loader.implement',
566 new XmlJsCode( "function( $ ) {{$scripts}}" ),
573 * Returns JS code which, when called, will register a given list of messages.
575 * @param $messages Mixed: Either an associative array mapping message key to value, or a
576 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
578 public static function makeMessageSetScript( $messages ) {
579 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
583 * Combines an associative array mapping media type to CSS into a
584 * single stylesheet with @media blocks.
586 * @param $styles Array: List of CSS strings keyed by media type
588 public static function makeCombinedStyles( array $styles ) {
590 foreach ( $styles as $media => $style ) {
591 // Transform the media type based on request params and config
592 // The way that this relies on $wgRequest to propagate request params is slightly evil
593 $media = OutputPage
::transformCssMedia( $media );
595 if ( $media === null ) {
597 } else if ( $media === '' ||
$media == 'all' ) {
598 // Don't output invalid or frivolous @media statements
601 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
608 * Returns a JS call to mw.loader.state, which sets the state of a
609 * module or modules to a given value. Has two calling conventions:
611 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
612 * Set the state of a single module called $name to $state
614 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
615 * Set the state of modules with the given names to the given states
617 public static function makeLoaderStateScript( $name, $state = null ) {
618 if ( is_array( $name ) ) {
619 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
621 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
626 * Returns JS code which calls the script given by $script. The script will
627 * be called with local variables name, version, dependencies and group,
628 * which will have values corresponding to $name, $version, $dependencies
629 * and $group as supplied.
631 * @param $name String: Module name
632 * @param $version Integer: Module version number as a timestamp
633 * @param $dependencies Array: List of module names on which this module depends
634 * @param $group String: Group which the module is in.
635 * @param $script String: JavaScript code
637 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
638 $script = str_replace( "\n", "\n\t", trim( $script ) );
639 return Xml
::encodeJsCall(
640 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
641 array( $name, $version, $dependencies, $group ) );
645 * Returns JS code which calls mw.loader.register with the given
646 * parameters. Has three calling conventions:
648 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
649 * Register a single module.
651 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
652 * Register modules with the given names.
654 * - ResourceLoader::makeLoaderRegisterScript( array(
655 * array( $name1, $version1, $dependencies1, $group1 ),
656 * array( $name2, $version2, $dependencies1, $group2 ),
659 * Registers modules with the given names and parameters.
661 * @param $name String: Module name
662 * @param $version Integer: Module version number as a timestamp
663 * @param $dependencies Array: List of module names on which this module depends
664 * @param $group String: group which the module is in.
666 public static function makeLoaderRegisterScript( $name, $version = null,
667 $dependencies = null, $group = null )
669 if ( is_array( $name ) ) {
670 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
672 $version = (int) $version > 1 ?
(int) $version : 1;
673 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
674 array( $name, $version, $dependencies, $group ) );
679 * Returns JS code which runs given JS code if the client-side framework is
682 * @param $script String: JavaScript code
684 public static function makeLoaderConditionalScript( $script ) {
685 $script = str_replace( "\n", "\n\t", trim( $script ) );
686 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
690 * Returns JS code which will set the MediaWiki configuration array to
693 * @param $configuration Array: List of configuration values keyed by variable name
695 public static function makeConfigSetScript( array $configuration ) {
696 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
700 * Determine whether debug mode was requested
701 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
704 public static function inDebugMode() {
705 global $wgRequest, $wgResourceLoaderDebug;
706 static $retval = null;
707 if ( !is_null( $retval ) )
709 return $retval = $wgRequest->getFuzzyBool( 'debug',
710 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );