f9d29fc7c67d277726cab37b2f7cd7ddf549b0a8
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
114 * - flip-css \see CSSJanus::transform
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
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', 'flip-css' ) ) )
131 wfProfileOut( __METHOD__
);
136 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
137 $key = wfMemcKey( 'resourceloader', 'filter', $filter, md5( $data ) );
138 $cache = wfGetCache( CACHE_ANYTHING
);
139 $cacheEntry = $cache->get( $key );
140 if ( is_string( $cacheEntry ) ) {
141 wfProfileOut( __METHOD__
);
145 // Run the filter - we've already verified one of these will work
149 $result = JSMin
::minify( $data );
152 $result = CSSMin
::minify( $data );
155 $result = CSSJanus
::transform( $data, true, false );
158 } catch ( Exception
$exception ) {
159 throw new MWException( 'ResourceLoader filter error. ' .
160 'Exception was thrown: ' . $exception->getMessage() );
163 // Save filtered text to Memcached
164 $cache->set( $key, $result );
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 );
213 // Disallow duplicate registrations
214 if ( isset( $this->moduleInfos
[$name] ) ) {
215 // A module has already been registered by this name
216 throw new MWException(
217 'ResourceLoader duplicate registration error. ' .
218 'Another module has already been registered as ' . $name
223 if ( is_object( $info ) ) {
224 // Old calling convention
225 // Validate the input
226 if ( !( $info instanceof ResourceLoaderModule
) ) {
227 throw new MWException( 'ResourceLoader invalid module error. ' .
228 'Instances of ResourceLoaderModule expected.' );
231 $this->moduleInfos
[$name] = array( 'object' => $info );
232 $info->setName( $name );
233 $this->modules
[$name] = $info;
235 // New calling convention
236 $this->moduleInfos
[$name] = $info;
239 wfProfileOut( __METHOD__
);
243 * Get a list of module names
245 * @return Array: List of module names
247 public function getModuleNames() {
248 return array_keys( $this->moduleInfos
);
252 * Get the ResourceLoaderModule object for a given module name.
254 * @param $name String: Module name
255 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
257 public function getModule( $name ) {
258 if ( !isset( $this->modules
[$name] ) ) {
259 if ( !isset( $this->moduleInfos
[$name] ) ) {
263 // Construct the requested object
264 $info = $this->moduleInfos
[$name];
265 if ( isset( $info['object'] ) ) {
266 // Object given in info array
267 $object = $info['object'];
269 if ( !isset( $info['class'] ) ) {
270 $class = 'ResourceLoaderFileModule';
272 $class = $info['class'];
274 $object = new $class( $info );
276 $object->setName( $name );
277 $this->modules
[$name] = $object;
280 return $this->modules
[$name];
284 * Outputs a response to a resource load-request, including a content-type header.
286 * @param $context ResourceLoaderContext: Context in which a response should be formed
288 public function respond( ResourceLoaderContext
$context ) {
289 global $wgResourceLoaderMaxage, $wgCacheEpoch;
291 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
292 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
293 // is used: ob_clean() will clear the GZIP header in that case and it won't come
294 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
295 // the whole thing in our own output buffer to be sure the active buffer
296 // doesn't use ob_gzhandler.
297 // See http://bugs.php.net/bug.php?id=36514
300 wfProfileIn( __METHOD__
);
302 // Split requested modules into two groups, modules and missing
305 foreach ( $context->getModules() as $name ) {
306 if ( isset( $this->moduleInfos
[$name] ) ) {
307 $modules[$name] = $this->getModule( $name );
313 // If a version wasn't specified we need a shorter expiry time for updates
314 // to propagate to clients quickly
315 if ( is_null( $context->getVersion() ) ) {
316 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
317 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
319 // If a version was specified we can use a longer expiry time since changing
320 // version numbers causes cache misses
322 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
323 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
326 // Preload information needed to the mtime calculation below
327 $this->preloadModuleInfo( array_keys( $modules ), $context );
329 wfProfileIn( __METHOD__
.'-getModifiedTime' );
331 // To send Last-Modified and support If-Modified-Since, we need to detect
332 // the last modified time
333 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
334 foreach ( $modules as $module ) {
335 // Bypass squid cache if the request includes any private modules
336 if ( $module->getGroup() === 'private' ) {
339 // Calculate maximum modified time
340 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
343 wfProfileOut( __METHOD__
.'-getModifiedTime' );
345 if ( $context->getOnly() === 'styles' ) {
346 header( 'Content-Type: text/css' );
348 header( 'Content-Type: text/javascript' );
350 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
351 if ( $context->getDebug() ) {
352 header( 'Cache-Control: must-revalidate' );
354 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
355 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
358 // If there's an If-Modified-Since header, respond with a 304 appropriately
359 // Some clients send "timestamp;length=123". Strip the part after the first ';'
360 // so we get a valid timestamp.
361 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
362 if ( $ims !== false ) {
363 $imsTS = strtok( $ims, ';' );
364 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
365 // There's another bug in ob_gzhandler (see also the comment at
366 // the top of this function) that causes it to gzip even empty
367 // responses, meaning it's impossible to produce a truly empty
368 // response (because the gzip header is always there). This is
369 // a problem because 304 responses have to be completely empty
370 // per the HTTP spec, and Firefox behaves buggily when they're not.
371 // See also http://bugs.php.net/bug.php?id=51579
372 // To work around this, we tear down all output buffering before
374 while ( ob_get_level() > 0 ) {
378 header( 'HTTP/1.0 304 Not Modified' );
379 header( 'Status: 304 Not Modified' );
380 wfProfileOut( __METHOD__
);
385 // Generate a response
386 $response = $this->makeModuleResponse( $context, $modules, $missing );
388 // Capture any PHP warnings from the output buffer and append them to the
389 // response in a comment if we're in debug mode.
390 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
391 $response .= "/*\n$warnings\n*/";
394 // Remove the output buffer and output the response
398 wfProfileOut( __METHOD__
);
402 * Generates code for a response
404 * @param $context ResourceLoaderContext: Context in which to generate a response
405 * @param $modules Array: List of module objects keyed by module name
406 * @param $missing Array: List of unavailable modules (optional)
407 * @return String: Response data
409 public function makeModuleResponse( ResourceLoaderContext
$context,
410 array $modules, $missing = array() )
412 if ( $modules === array() && $missing === array() ) {
413 return '/* No modules requested. Max made me put this here */';
417 if ( $context->shouldIncludeMessages() ) {
418 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
425 foreach ( $modules as $name => $module ) {
427 wfProfileIn( __METHOD__
. '-' . $name );
431 if ( $context->shouldIncludeScripts() ) {
432 $scripts .= $module->getScript( $context ) . "\n";
437 if ( $context->shouldIncludeStyles() ) {
438 $styles = $module->getStyles( $context );
439 // Flip CSS on a per-module basis
440 if ( $styles && $module->getFlip( $context ) ) {
441 foreach ( $styles as $media => $style ) {
442 $styles[$media] = $this->filter( 'flip-css', $style );
448 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
451 switch ( $context->getOnly() ) {
456 $out .= self
::makeCombinedStyles( $styles );
459 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
462 // Minify CSS before embedding in mediaWiki.loader.implement call
463 // (unless in debug mode)
464 if ( !$context->getDebug() ) {
465 foreach ( $styles as $media => $style ) {
466 $styles[$media] = $this->filter( 'minify-css', $style );
469 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
470 new XmlJsCode( $messagesBlob ) );
474 wfProfileOut( __METHOD__
. '-' . $name );
477 // Update module states
478 if ( $context->shouldIncludeScripts() ) {
479 // Set the state of modules loaded as only scripts to ready
480 if ( count( $modules ) && $context->getOnly() === 'scripts'
481 && !isset( $modules['startup'] ) )
483 $out .= self
::makeLoaderStateScript(
484 array_fill_keys( array_keys( $modules ), 'ready' ) );
486 // Set the state of modules which were requested but unavailable as missing
487 if ( is_array( $missing ) && count( $missing ) ) {
488 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
492 if ( $context->getDebug() ) {
495 if ( $context->getOnly() === 'styles' ) {
496 return $this->filter( 'minify-css', $out );
498 return $this->filter( 'minify-js', $out );
506 * Returns JS code to call to mediaWiki.loader.implement for a module with
509 * @param $name Module name
510 * @param $scripts Array: List of JavaScript code snippets to be executed after the
512 * @param $styles Array: List of CSS strings keyed by media type
513 * @param $messages Mixed: List of messages associated with this module. May either be an
514 * associative array mapping message key to value, or a JSON-encoded message blob containing
515 * the same data, wrapped in an XmlJsCode object.
517 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
518 if ( is_array( $scripts ) ) {
519 $scripts = implode( $scripts, "\n" );
521 return Xml
::encodeJsCall(
522 'mediaWiki.loader.implement',
525 new XmlJsCode( "function() {{$scripts}}" ),
532 * Returns JS code which, when called, will register a given list of messages.
534 * @param $messages Mixed: Either an associative array mapping message key to value, or a
535 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
537 public static function makeMessageSetScript( $messages ) {
538 return Xml
::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
542 * Combines an associative array mapping media type to CSS into a
543 * single stylesheet with @media blocks.
545 * @param $styles Array: List of CSS strings keyed by media type
547 public static function makeCombinedStyles( array $styles ) {
549 foreach ( $styles as $media => $style ) {
550 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
556 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
557 * module or modules to a given value. Has two calling conventions:
559 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
560 * Set the state of a single module called $name to $state
562 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
563 * Set the state of modules with the given names to the given states
565 public static function makeLoaderStateScript( $name, $state = null ) {
566 if ( is_array( $name ) ) {
567 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
569 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
574 * Returns JS code which calls the script given by $script. The script will
575 * be called with local variables name, version, dependencies and group,
576 * which will have values corresponding to $name, $version, $dependencies
577 * and $group as supplied.
579 * @param $name String: Module name
580 * @param $version Integer: Module version number as a timestamp
581 * @param $dependencies Array: List of module names on which this module depends
582 * @param $group String: Group which the module is in.
583 * @param $script String: JavaScript code
585 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
586 $script = str_replace( "\n", "\n\t", trim( $script ) );
587 return Xml
::encodeJsCall(
588 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
589 array( $name, $version, $dependencies, $group ) );
593 * Returns JS code which calls mediaWiki.loader.register with the given
594 * parameters. Has three calling conventions:
596 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
597 * Register a single module.
599 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
600 * Register modules with the given names.
602 * - ResourceLoader::makeLoaderRegisterScript( array(
603 * array( $name1, $version1, $dependencies1, $group1 ),
604 * array( $name2, $version2, $dependencies1, $group2 ),
607 * Registers modules with the given names and parameters.
609 * @param $name String: Module name
610 * @param $version Integer: Module version number as a timestamp
611 * @param $dependencies Array: List of module names on which this module depends
612 * @param $group String: group which the module is in.
614 public static function makeLoaderRegisterScript( $name, $version = null,
615 $dependencies = null, $group = null )
617 if ( is_array( $name ) ) {
618 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
620 $version = (int) $version > 1 ?
(int) $version : 1;
621 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
622 array( $name, $version, $dependencies, $group ) );
627 * Returns JS code which runs given JS code if the client-side framework is
630 * @param $script String: JavaScript code
632 public static function makeLoaderConditionalScript( $script ) {
633 $script = str_replace( "\n", "\n\t", trim( $script ) );
634 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
638 * Returns JS code which will set the MediaWiki configuration array to
641 * @param $configuration Array: List of configuration values keyed by variable name
643 public static function makeConfigSetScript( array $configuration ) {
644 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
648 * Determine whether debug mode was requested
649 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
652 public static function inDebugMode() {
653 global $wgRequest, $wgResourceLoaderDebug;
654 static $retval = null;
655 if ( !is_null( $retval ) )
657 return $retval = $wgRequest->getFuzzyBool( 'debug',
658 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );