e376b6a4e1b08703373a7011e3985e33e52878bb
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 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' ) ) )
131 wfProfileOut( __METHOD__
);
136 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
137 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
138 $cache = wfGetCache( CACHE_ANYTHING
);
139 $cacheEntry = $cache->get( $key );
140 if ( is_string( $cacheEntry ) ) {
141 wfProfileOut( __METHOD__
);
146 // Run the filter - we've already verified one of these will work
150 $result = JavaScriptMinifier
::minify( $data );
151 $result .= "\n\n/* cache key: $key */\n";
154 $result = CSSMin
::minify( $data );
155 $result .= "\n\n/* cache key: $key */\n";
159 // Save filtered text to Memcached
160 $cache->set( $key, $result );
161 } catch ( Exception
$exception ) {
162 // Return exception as a comment
163 $result = "/*\n{$exception->__toString()}\n*/\n";
166 wfProfileOut( __METHOD__
);
174 * Registers core modules and runs registration hooks.
176 public function __construct() {
177 global $IP, $wgResourceModules;
179 wfProfileIn( __METHOD__
);
181 // Register core modules
182 $this->register( include( "$IP/resources/Resources.php" ) );
183 // Register extension modules
184 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
185 $this->register( $wgResourceModules );
187 wfProfileOut( __METHOD__
);
191 * Registers a module with the ResourceLoader system.
193 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
194 * @param $info Module info array. For backwards compatibility with 1.17alpha,
195 * this may also be a ResourceLoaderModule object. Optional when using
196 * multiple-registration calling style.
197 * @throws MWException: If a duplicate module registration is attempted
198 * @throws MWException: If something other than a ResourceLoaderModule is being registered
199 * @return Boolean: False if there were any errors, in which case one or more modules were not
202 public function register( $name, $info = null ) {
203 wfProfileIn( __METHOD__
);
205 // Allow multiple modules to be registered in one call
206 if ( is_array( $name ) ) {
207 foreach ( $name as $key => $value ) {
208 $this->register( $key, $value );
210 wfProfileOut( __METHOD__
);
214 // Disallow duplicate registrations
215 if ( isset( $this->moduleInfos
[$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
224 if ( is_object( $info ) ) {
225 // Old calling convention
226 // Validate the input
227 if ( !( $info instanceof ResourceLoaderModule
) ) {
228 throw new MWException( 'ResourceLoader invalid module error. ' .
229 'Instances of ResourceLoaderModule expected.' );
232 $this->moduleInfos
[$name] = array( 'object' => $info );
233 $info->setName( $name );
234 $this->modules
[$name] = $info;
236 // New calling convention
237 $this->moduleInfos
[$name] = $info;
240 wfProfileOut( __METHOD__
);
244 * Get a list of module names
246 * @return Array: List of module names
248 public function getModuleNames() {
249 return array_keys( $this->moduleInfos
);
253 * Get the ResourceLoaderModule object for a given module name.
255 * @param $name String: Module name
256 * @return ResourceLoaderModule if module has been registered, null otherwise
258 public function getModule( $name ) {
259 if ( !isset( $this->modules
[$name] ) ) {
260 if ( !isset( $this->moduleInfos
[$name] ) ) {
264 // Construct the requested object
265 $info = $this->moduleInfos
[$name];
266 if ( isset( $info['object'] ) ) {
267 // Object given in info array
268 $object = $info['object'];
270 if ( !isset( $info['class'] ) ) {
271 $class = 'ResourceLoaderFileModule';
273 $class = $info['class'];
275 $object = new $class( $info );
277 $object->setName( $name );
278 $this->modules
[$name] = $object;
281 return $this->modules
[$name];
285 * Outputs a response to a resource load-request, including a content-type header.
287 * @param $context ResourceLoaderContext: Context in which a response should be formed
289 public function respond( ResourceLoaderContext
$context ) {
290 global $wgResourceLoaderMaxage, $wgCacheEpoch;
292 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
293 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
294 // is used: ob_clean() will clear the GZIP header in that case and it won't come
295 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
296 // the whole thing in our own output buffer to be sure the active buffer
297 // doesn't use ob_gzhandler.
298 // See http://bugs.php.net/bug.php?id=36514
301 wfProfileIn( __METHOD__
);
304 // Split requested modules into two groups, modules and missing
307 foreach ( $context->getModules() as $name ) {
308 if ( isset( $this->moduleInfos
[$name] ) ) {
309 $modules[$name] = $this->getModule( $name );
315 // If a version wasn't specified we need a shorter expiry time for updates
316 // to propagate to clients quickly
317 if ( is_null( $context->getVersion() ) ) {
318 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
319 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
321 // If a version was specified we can use a longer expiry time since changing
322 // version numbers causes cache misses
324 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
325 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
328 // Preload information needed to the mtime calculation below
330 $this->preloadModuleInfo( array_keys( $modules ), $context );
331 } catch( Exception
$e ) {
332 // Add exception to the output as a comment
333 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
336 wfProfileIn( __METHOD__
.'-getModifiedTime' );
339 // To send Last-Modified and support If-Modified-Since, we need to detect
340 // the last modified time
341 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
342 foreach ( $modules as $module ) {
344 // Bypass Squid and other shared caches if the request includes any private modules
345 if ( $module->getGroup() === 'private' ) {
348 // Calculate maximum modified time
349 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
350 } catch ( Exception
$e ) {
351 // Add exception to the output as a comment
352 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
356 wfProfileOut( __METHOD__
.'-getModifiedTime' );
358 if ( $context->getOnly() === 'styles' ) {
359 header( 'Content-Type: text/css' );
361 header( 'Content-Type: text/javascript' );
363 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
364 if ( $context->getDebug() ) {
365 // Do not cache debug responses
366 header( 'Cache-Control: private, no-cache, must-revalidate' );
367 header( 'Pragma: no-cache' );
370 header( "Cache-Control: private, max-age=$maxage" );
373 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
374 $exp = min( $maxage, $smaxage );
376 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
379 // If there's an If-Modified-Since header, respond with a 304 appropriately
380 // Some clients send "timestamp;length=123". Strip the part after the first ';'
381 // so we get a valid timestamp.
382 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
383 // Never send 304s in debug mode
384 if ( $ims !== false && !$context->getDebug() ) {
385 $imsTS = strtok( $ims, ';' );
386 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
387 // There's another bug in ob_gzhandler (see also the comment at
388 // the top of this function) that causes it to gzip even empty
389 // responses, meaning it's impossible to produce a truly empty
390 // response (because the gzip header is always there). This is
391 // a problem because 304 responses have to be completely empty
392 // per the HTTP spec, and Firefox behaves buggily when they're not.
393 // See also http://bugs.php.net/bug.php?id=51579
394 // To work around this, we tear down all output buffering before
396 // On some setups, ob_get_level() doesn't seem to go down to zero
397 // no matter how often we call ob_get_clean(), so instead of doing
398 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
399 // we have to be safe here and avoid an infinite loop.
400 for ( $i = 0; $i < ob_get_level(); $i++
) {
404 header( 'HTTP/1.0 304 Not Modified' );
405 header( 'Status: 304 Not Modified' );
406 wfProfileOut( __METHOD__
);
411 // Generate a response
412 $response = $this->makeModuleResponse( $context, $modules, $missing );
414 // Prepend comments indicating exceptions
415 $response = $exceptions . $response;
417 // Capture any PHP warnings from the output buffer and append them to the
418 // response in a comment if we're in debug mode.
419 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
420 $response = "/*\n$warnings\n*/\n" . $response;
423 // Remove the output buffer and output the response
427 wfProfileOut( __METHOD__
);
431 * Generates code for a response
433 * @param $context ResourceLoaderContext: Context in which to generate a response
434 * @param $modules Array: List of module objects keyed by module name
435 * @param $missing Array: List of unavailable modules (optional)
436 * @return String: Response data
438 public function makeModuleResponse( ResourceLoaderContext
$context,
439 array $modules, $missing = array() )
443 if ( $modules === array() && $missing === array() ) {
444 return '/* No modules requested. Max made me put this here */';
447 wfProfileIn( __METHOD__
);
449 if ( $context->shouldIncludeMessages() ) {
451 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
452 } catch ( Exception
$e ) {
453 // Add exception to the output as a comment
454 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
461 foreach ( $modules as $name => $module ) {
462 wfProfileIn( __METHOD__
. '-' . $name );
466 if ( $context->shouldIncludeScripts() ) {
467 $scripts .= $module->getScript( $context ) . "\n";
472 if ( $context->shouldIncludeStyles() ) {
473 $styles = $module->getStyles( $context );
477 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
480 switch ( $context->getOnly() ) {
485 $out .= self
::makeCombinedStyles( $styles );
488 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
491 // Minify CSS before embedding in mw.loader.implement call
492 // (unless in debug mode)
493 if ( !$context->getDebug() ) {
494 foreach ( $styles as $media => $style ) {
495 $styles[$media] = $this->filter( 'minify-css', $style );
498 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
499 new XmlJsCode( $messagesBlob ) );
502 } catch ( Exception
$e ) {
503 // Add exception to the output as a comment
504 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
506 // Register module as missing
508 unset( $modules[$name] );
510 wfProfileOut( __METHOD__
. '-' . $name );
513 // Update module states
514 if ( $context->shouldIncludeScripts() ) {
515 // Set the state of modules loaded as only scripts to ready
516 if ( count( $modules ) && $context->getOnly() === 'scripts'
517 && !isset( $modules['startup'] ) )
519 $out .= self
::makeLoaderStateScript(
520 array_fill_keys( array_keys( $modules ), 'ready' ) );
522 // Set the state of modules which were requested but unavailable as missing
523 if ( is_array( $missing ) && count( $missing ) ) {
524 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
528 if ( !$context->getDebug() ) {
529 if ( $context->getOnly() === 'styles' ) {
530 $out = $this->filter( 'minify-css', $out );
532 $out = $this->filter( 'minify-js', $out );
536 wfProfileOut( __METHOD__
);
537 return $exceptions . $out;
543 * Returns JS code to call to mw.loader.implement for a module with
546 * @param $name Module name
547 * @param $scripts Array: List of JavaScript code snippets to be executed after the
549 * @param $styles Array: List of CSS strings keyed by media type
550 * @param $messages Mixed: List of messages associated with this module. May either be an
551 * associative array mapping message key to value, or a JSON-encoded message blob containing
552 * the same data, wrapped in an XmlJsCode object.
554 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
555 if ( is_array( $scripts ) ) {
556 $scripts = implode( $scripts, "\n" );
558 return Xml
::encodeJsCall(
559 'mw.loader.implement',
562 new XmlJsCode( "function( $ ) {{$scripts}}" ),
569 * Returns JS code which, when called, will register a given list of messages.
571 * @param $messages Mixed: Either an associative array mapping message key to value, or a
572 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
574 public static function makeMessageSetScript( $messages ) {
575 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
579 * Combines an associative array mapping media type to CSS into a
580 * single stylesheet with @media blocks.
582 * @param $styles Array: List of CSS strings keyed by media type
584 public static function makeCombinedStyles( array $styles ) {
586 foreach ( $styles as $media => $style ) {
587 // Transform the media type based on request params and config
588 // The way that this relies on $wgRequest to propagate request params is slightly evil
589 $media = OutputPage
::transformCssMedia( $media );
591 if ( $media === null ) {
593 } else if ( $media === '' ||
$media == 'all' ) {
594 // Don't output invalid or frivolous @media statements
597 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
604 * Returns a JS call to mw.loader.state, which sets the state of a
605 * module or modules to a given value. Has two calling conventions:
607 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
608 * Set the state of a single module called $name to $state
610 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
611 * Set the state of modules with the given names to the given states
613 public static function makeLoaderStateScript( $name, $state = null ) {
614 if ( is_array( $name ) ) {
615 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
617 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
622 * Returns JS code which calls the script given by $script. The script will
623 * be called with local variables name, version, dependencies and group,
624 * which will have values corresponding to $name, $version, $dependencies
625 * and $group as supplied.
627 * @param $name String: Module name
628 * @param $version Integer: Module version number as a timestamp
629 * @param $dependencies Array: List of module names on which this module depends
630 * @param $group String: Group which the module is in.
631 * @param $script String: JavaScript code
633 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
634 $script = str_replace( "\n", "\n\t", trim( $script ) );
635 return Xml
::encodeJsCall(
636 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
637 array( $name, $version, $dependencies, $group ) );
641 * Returns JS code which calls mw.loader.register with the given
642 * parameters. Has three calling conventions:
644 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
645 * Register a single module.
647 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
648 * Register modules with the given names.
650 * - ResourceLoader::makeLoaderRegisterScript( array(
651 * array( $name1, $version1, $dependencies1, $group1 ),
652 * array( $name2, $version2, $dependencies1, $group2 ),
655 * Registers modules with the given names and parameters.
657 * @param $name String: Module name
658 * @param $version Integer: Module version number as a timestamp
659 * @param $dependencies Array: List of module names on which this module depends
660 * @param $group String: group which the module is in.
662 public static function makeLoaderRegisterScript( $name, $version = null,
663 $dependencies = null, $group = null )
665 if ( is_array( $name ) ) {
666 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
668 $version = (int) $version > 1 ?
(int) $version : 1;
669 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
670 array( $name, $version, $dependencies, $group ) );
675 * Returns JS code which runs given JS code if the client-side framework is
678 * @param $script String: JavaScript code
680 public static function makeLoaderConditionalScript( $script ) {
681 $script = str_replace( "\n", "\n\t", trim( $script ) );
682 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
686 * Returns JS code which will set the MediaWiki configuration array to
689 * @param $configuration Array: List of configuration values keyed by variable name
691 public static function makeConfigSetScript( array $configuration ) {
692 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
696 * Determine whether debug mode was requested
697 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
700 public static function inDebugMode() {
701 global $wgRequest, $wgResourceLoaderDebug;
702 static $retval = null;
703 if ( !is_null( $retval ) )
705 return $retval = $wgRequest->getFuzzyBool( 'debug',
706 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );