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 $this->modules
[$name] = $info;
234 // New calling convention
235 $this->moduleInfos
[$name] = $info;
238 wfProfileOut( __METHOD__
);
242 * Get a list of module names
244 * @return Array: List of module names
246 public function getModuleNames() {
247 return array_keys( $this->moduleInfos
);
251 * Get the ResourceLoaderModule object for a given module name.
253 * @param $name String: Module name
254 * @return Mixed: ResourceLoaderModule if module has been registered, null otherwise
256 public function getModule( $name ) {
257 if ( !isset( $this->modules
[$name] ) ) {
258 if ( !isset( $this->moduleInfos
[$name] ) ) {
262 // Construct the requested object
263 $info = $this->moduleInfos
[$name];
264 if ( isset( $info['object'] ) ) {
265 // Object given in info array
266 $object = $info['object'];
268 if ( !isset( $info['class'] ) ) {
269 $class = 'ResourceLoaderFileModule';
271 $class = $info['class'];
273 $object = new $class( $info );
275 $object->setName( $name );
276 $this->modules
[$name] = $object;
279 return $this->modules
[$name];
283 * Outputs a response to a resource load-request, including a content-type header.
285 * @param $context ResourceLoaderContext: Context in which a response should be formed
287 public function respond( ResourceLoaderContext
$context ) {
288 global $wgResourceLoaderMaxage, $wgCacheEpoch;
290 wfProfileIn( __METHOD__
);
292 // Split requested modules into two groups, modules and missing
295 foreach ( $context->getModules() as $name ) {
296 if ( isset( $this->moduleInfos
[$name] ) ) {
297 $modules[$name] = $this->getModule( $name );
303 // If a version wasn't specified we need a shorter expiry time for updates
304 // to propagate to clients quickly
305 if ( is_null( $context->getVersion() ) ) {
306 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
307 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
309 // If a version was specified we can use a longer expiry time since changing
310 // version numbers causes cache misses
312 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
313 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
316 // Preload information needed to the mtime calculation below
317 $this->preloadModuleInfo( array_keys( $modules ), $context );
319 wfProfileIn( __METHOD__
.'-getModifiedTime' );
321 // To send Last-Modified and support If-Modified-Since, we need to detect
322 // the last modified time
323 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
324 foreach ( $modules as $module ) {
325 // Bypass squid cache if the request includes any private modules
326 if ( $module->getGroup() === 'private' ) {
329 // Calculate maximum modified time
330 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
333 wfProfileOut( __METHOD__
.'-getModifiedTime' );
335 if ( $context->getOnly() === 'styles' ) {
336 header( 'Content-Type: text/css' );
338 header( 'Content-Type: text/javascript' );
340 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
341 if ( $context->getDebug() ) {
342 header( 'Cache-Control: must-revalidate' );
344 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
345 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, min( $maxage, $smaxage ) +
time() ) );
348 // If there's an If-Modified-Since header, respond with a 304 appropriately
349 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
350 if ( $ims !== false && $mtime <= wfTimestamp( TS_UNIX
, $ims ) ) {
351 header( 'HTTP/1.0 304 Not Modified' );
352 header( 'Status: 304 Not Modified' );
353 wfProfileOut( __METHOD__
);
357 // Generate a response
358 $response = $this->makeModuleResponse( $context, $modules, $missing );
360 // Tack on PHP warnings as a comment in debug mode
361 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
362 $response .= "/*\n$warnings\n*/";
365 // Clear any warnings from the buffer
369 wfProfileOut( __METHOD__
);
373 * Generates code for a response
375 * @param $context ResourceLoaderContext: Context in which to generate a response
376 * @param $modules Array: List of module objects keyed by module name
377 * @param $missing Array: List of unavailable modules (optional)
378 * @return String: Response data
380 public function makeModuleResponse( ResourceLoaderContext
$context,
381 array $modules, $missing = array() )
384 if ( $context->shouldIncludeMessages() ) {
385 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
392 foreach ( $modules as $name => $module ) {
394 wfProfileIn( __METHOD__
. '-' . $name );
398 if ( $context->shouldIncludeScripts() ) {
399 $scripts .= $module->getScript( $context ) . "\n";
404 if ( $context->shouldIncludeStyles() ) {
405 $styles = $module->getStyles( $context );
406 // Flip CSS on a per-module basis
407 if ( $styles && $module->getFlip( $context ) ) {
408 foreach ( $styles as $media => $style ) {
409 $styles[$media] = $this->filter( 'flip-css', $style );
415 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : array();
418 switch ( $context->getOnly() ) {
423 $out .= self
::makeCombinedStyles( $styles );
426 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
429 // Minify CSS before embedding in mediaWiki.loader.implement call
430 // (unless in debug mode)
431 if ( !$context->getDebug() ) {
432 foreach ( $styles as $media => $style ) {
433 $styles[$media] = $this->filter( 'minify-css', $style );
436 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
437 new XmlJsCode( $messagesBlob ) );
441 wfProfileOut( __METHOD__
. '-' . $name );
444 // Update module states
445 if ( $context->shouldIncludeScripts() ) {
446 // Set the state of modules loaded as only scripts to ready
447 if ( count( $modules ) && $context->getOnly() === 'scripts'
448 && !isset( $modules['startup'] ) )
450 $out .= self
::makeLoaderStateScript(
451 array_fill_keys( array_keys( $modules ), 'ready' ) );
453 // Set the state of modules which were requested but unavailable as missing
454 if ( is_array( $missing ) && count( $missing ) ) {
455 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
459 if ( $context->getDebug() ) {
462 if ( $context->getOnly() === 'styles' ) {
463 return $this->filter( 'minify-css', $out );
465 return $this->filter( 'minify-js', $out );
473 * Returns JS code to call to mediaWiki.loader.implement for a module with
476 * @param $name Module name
477 * @param $scripts Array: List of JavaScript code snippets to be executed after the
479 * @param $styles Array: List of CSS strings keyed by media type
480 * @param $messages Mixed: List of messages associated with this module. May either be an
481 * associative array mapping message key to value, or a JSON-encoded message blob containing
482 * the same data, wrapped in an XmlJsCode object.
484 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
485 if ( is_array( $scripts ) ) {
486 $scripts = implode( $scripts, "\n" );
488 return Xml
::encodeJsCall(
489 'mediaWiki.loader.implement',
492 new XmlJsCode( "function() {{$scripts}}" ),
499 * Returns JS code which, when called, will register a given list of messages.
501 * @param $messages Mixed: Either an associative array mapping message key to value, or a
502 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
504 public static function makeMessageSetScript( $messages ) {
505 return Xml
::encodeJsCall( 'mediaWiki.messages.set', array( (object)$messages ) );
509 * Combines an associative array mapping media type to CSS into a
510 * single stylesheet with @media blocks.
512 * @param $styles Array: List of CSS strings keyed by media type
514 public static function makeCombinedStyles( array $styles ) {
516 foreach ( $styles as $media => $style ) {
517 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
523 * Returns a JS call to mediaWiki.loader.state, which sets the state of a
524 * module or modules to a given value. Has two calling conventions:
526 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
527 * Set the state of a single module called $name to $state
529 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
530 * Set the state of modules with the given names to the given states
532 public static function makeLoaderStateScript( $name, $state = null ) {
533 if ( is_array( $name ) ) {
534 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name ) );
536 return Xml
::encodeJsCall( 'mediaWiki.loader.state', array( $name, $state ) );
541 * Returns JS code which calls the script given by $script. The script will
542 * be called with local variables name, version, dependencies and group,
543 * which will have values corresponding to $name, $version, $dependencies
544 * and $group as supplied.
546 * @param $name String: Module name
547 * @param $version Integer: Module version number as a timestamp
548 * @param $dependencies Array: List of module names on which this module depends
549 * @param $group String: Group which the module is in.
550 * @param $script String: JavaScript code
552 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $script ) {
553 $script = str_replace( "\n", "\n\t", trim( $script ) );
554 return Xml
::encodeJsCall(
555 "( function( name, version, dependencies, group ) {\n\t$script\n} )",
556 array( $name, $version, $dependencies, $group ) );
560 * Returns JS code which calls mediaWiki.loader.register with the given
561 * parameters. Has three calling conventions:
563 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group ):
564 * Register a single module.
566 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
567 * Register modules with the given names.
569 * - ResourceLoader::makeLoaderRegisterScript( array(
570 * array( $name1, $version1, $dependencies1, $group1 ),
571 * array( $name2, $version2, $dependencies1, $group2 ),
574 * Registers modules with the given names and parameters.
576 * @param $name String: Module name
577 * @param $version Integer: Module version number as a timestamp
578 * @param $dependencies Array: List of module names on which this module depends
579 * @param $group String: group which the module is in.
581 public static function makeLoaderRegisterScript( $name, $version = null,
582 $dependencies = null, $group = null )
584 if ( is_array( $name ) ) {
585 return Xml
::encodeJsCall( 'mediaWiki.loader.register', array( $name ) );
587 $version = (int) $version > 1 ?
(int) $version : 1;
588 return Xml
::encodeJsCall( 'mediaWiki.loader.register',
589 array( $name, $version, $dependencies, $group ) );
594 * Returns JS code which runs given JS code if the client-side framework is
597 * @param $script String: JavaScript code
599 public static function makeLoaderConditionalScript( $script ) {
600 $script = str_replace( "\n", "\n\t", trim( $script ) );
601 return "if ( window.mediaWiki ) {\n\t$script\n}\n";
605 * Returns JS code which will set the MediaWiki configuration array to
608 * @param $configuration Array: List of configuration values keyed by variable name
610 public static function makeConfigSetScript( array $configuration ) {
611 return Xml
::encodeJsCall( 'mediaWiki.config.set', array( $configuration ) );
615 * Determine whether debug mode was requested
616 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
619 public static function inDebugMode() {
620 global $wgRequest, $wgResourceLoaderDebug;
621 static $retval = null;
622 if ( !is_null( $retval ) )
624 return $retval = $wgRequest->getFuzzyBool( 'debug',
625 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );