9973cbc807ba7f46016e8e2b7ecb89807dc88a34
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 = 5;
33 protected static $requiredSourceProperties = array( 'loadScript' );
35 /** Array: List of module name/ResourceLoaderModule object pairs */
36 protected $modules = array();
38 /** Associative array mapping module name to info associative array */
39 protected $moduleInfos = array();
41 /** array( 'source-id' => array( 'loadScript' => 'http://.../load.php' ) ) **/
42 protected $sources = array();
44 /* Protected Methods */
47 * Loads information stored in the database about modules.
49 * This method grabs modules dependencies from the database and updates modules
52 * This is not inside the module code because it is much faster to
53 * request all of the information at once than it is to have each module
54 * requests its own information. This sacrifice of modularity yields a substantial
55 * performance improvement.
57 * @param $modules Array: List of module names to preload information for
58 * @param $context ResourceLoaderContext: Context to load the information within
60 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
61 if ( !count( $modules ) ) {
62 return; // or else Database*::select() will explode, plus it's cheaper!
64 $dbr = wfGetDB( DB_SLAVE
);
65 $skin = $context->getSkin();
66 $lang = $context->getLanguage();
68 // Get file dependency information
69 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
70 'md_module' => $modules,
75 // Set modules' dependencies
76 $modulesWithDeps = array();
77 foreach ( $res as $row ) {
78 $this->getModule( $row->md_module
)->setFileDependencies( $skin,
79 FormatJson
::decode( $row->md_deps
, true )
81 $modulesWithDeps[] = $row->md_module
;
84 // Register the absence of a dependency row too
85 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
86 $this->getModule( $name )->setFileDependencies( $skin, array() );
89 // Get message blob mtimes. Only do this for modules with messages
90 $modulesWithMessages = array();
91 foreach ( $modules as $name ) {
92 if ( count( $this->getModule( $name )->getMessages() ) ) {
93 $modulesWithMessages[] = $name;
96 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
97 if ( count( $modulesWithMessages ) ) {
98 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
99 'mr_resource' => $modulesWithMessages,
103 foreach ( $res as $row ) {
104 $this->getModule( $row->mr_resource
)->setMsgBlobMtime( $lang,
105 wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
106 unset( $modulesWithoutMessages[$row->mr_resource
] );
109 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
110 $this->getModule( $name )->setMsgBlobMtime( $lang, 0 );
115 * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls.
117 * Available filters are:
118 * - minify-js \see JavaScriptMinifier::minify
119 * - minify-css \see CSSMin::minify
121 * If $data is empty, only contains whitespace or the filter was unknown,
122 * $data is returned unmodified.
124 * @param $filter String: Name of filter to run
125 * @param $data String: Text to filter, such as JavaScript or CSS text
126 * @return String: Filtered data, or a comment containing an error message
128 protected function filter( $filter, $data ) {
129 global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength;
130 wfProfileIn( __METHOD__
);
132 // For empty/whitespace-only data or for unknown filters, don't perform
133 // any caching or processing
134 if ( trim( $data ) === ''
135 ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) )
137 wfProfileOut( __METHOD__
);
142 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
143 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
144 $cache = wfGetCache( CACHE_ANYTHING
);
145 $cacheEntry = $cache->get( $key );
146 if ( is_string( $cacheEntry ) ) {
147 wfProfileOut( __METHOD__
);
152 // Run the filter - we've already verified one of these will work
156 $result = JavaScriptMinifier
::minify( $data,
157 $wgResourceLoaderMinifierStatementsOnOwnLine,
158 $wgResourceLoaderMinifierMaxLineLength
160 $result .= "\n\n/* cache key: $key */\n";
163 $result = CSSMin
::minify( $data );
164 $result .= "\n\n/* cache key: $key */\n";
168 // Save filtered text to Memcached
169 $cache->set( $key, $result );
170 } catch ( Exception
$exception ) {
171 // Return exception as a comment
172 $result = "/*\n{$exception->__toString()}\n*/\n";
175 wfProfileOut( __METHOD__
);
183 * Registers core modules and runs registration hooks.
185 public function __construct() {
186 global $IP, $wgResourceModules, $wgResourceLoaderSources, $wgLoadScript;
188 wfProfileIn( __METHOD__
);
190 // Add 'local' source first
191 $this->addSource( 'local', array( 'loadScript' => $wgLoadScript, 'apiScript' => wfScript( 'api' ) ) );
194 $this->addSource( $wgResourceLoaderSources );
196 // Register core modules
197 $this->register( include( "$IP/resources/Resources.php" ) );
198 // Register extension modules
199 wfRunHooks( 'ResourceLoaderRegisterModules', array( &$this ) );
200 $this->register( $wgResourceModules );
202 wfProfileOut( __METHOD__
);
206 * Registers a module with the ResourceLoader system.
208 * @param $name Mixed: Name of module as a string or List of name/object pairs as an array
209 * @param $info Module info array. For backwards compatibility with 1.17alpha,
210 * this may also be a ResourceLoaderModule object. Optional when using
211 * multiple-registration calling style.
212 * @throws MWException: If a duplicate module registration is attempted
213 * @throws MWException: If a module name contains illegal characters (pipes or commas)
214 * @throws MWException: If something other than a ResourceLoaderModule is being registered
215 * @return Boolean: False if there were any errors, in which case one or more modules were not
218 public function register( $name, $info = null ) {
219 wfProfileIn( __METHOD__
);
221 // Allow multiple modules to be registered in one call
222 if ( is_array( $name ) ) {
223 foreach ( $name as $key => $value ) {
224 $this->register( $key, $value );
226 wfProfileOut( __METHOD__
);
230 // Disallow duplicate registrations
231 if ( isset( $this->moduleInfos
[$name] ) ) {
232 // A module has already been registered by this name
233 throw new MWException(
234 'ResourceLoader duplicate registration error. ' .
235 'Another module has already been registered as ' . $name
239 // Check $name for illegal characters
240 if ( preg_match( '/[|,!]/', $name ) ) {
241 throw new MWException( "ResourceLoader module name '$name' is invalid. Names may not contain pipes (|), commas (,) or exclamation marks (!)" );
245 if ( is_object( $info ) ) {
246 // Old calling convention
247 // Validate the input
248 if ( !( $info instanceof ResourceLoaderModule
) ) {
249 throw new MWException( 'ResourceLoader invalid module error. ' .
250 'Instances of ResourceLoaderModule expected.' );
253 $this->moduleInfos
[$name] = array( 'object' => $info );
254 $info->setName( $name );
255 $this->modules
[$name] = $info;
257 // New calling convention
258 $this->moduleInfos
[$name] = $info;
261 wfProfileOut( __METHOD__
);
265 * Add a foreign source of modules.
268 * 'loadScript': URL (either fully-qualified or protocol-relative) of load.php for this source
270 * @param $id Mixed: source ID (string), or array( id1 => props1, id2 => props2, ... )
271 * @param $properties Array: source properties
273 public function addSource( $id, $properties = null) {
274 // Allow multiple sources to be registered in one call
275 if ( is_array( $id ) ) {
276 foreach ( $id as $key => $value ) {
277 $this->addSource( $key, $value );
282 // Disallow duplicates
283 if ( isset( $this->sources
[$id] ) ) {
284 throw new MWException(
285 'ResourceLoader duplicate source addition error. ' .
286 'Another source has already been registered as ' . $id
290 // Validate properties
291 foreach ( self
::$requiredSourceProperties as $prop ) {
292 if ( !isset( $properties[$prop] ) ) {
293 throw new MWException( "Required property $prop missing from source ID $id" );
297 $this->sources
[$id] = $properties;
301 * Get a list of module names
303 * @return Array: List of module names
305 public function getModuleNames() {
306 return array_keys( $this->moduleInfos
);
310 * Get the ResourceLoaderModule object for a given module name.
312 * @param $name String: Module name
313 * @return ResourceLoaderModule if module has been registered, null otherwise
315 public function getModule( $name ) {
316 if ( !isset( $this->modules
[$name] ) ) {
317 if ( !isset( $this->moduleInfos
[$name] ) ) {
321 // Construct the requested object
322 $info = $this->moduleInfos
[$name];
323 if ( isset( $info['object'] ) ) {
324 // Object given in info array
325 $object = $info['object'];
327 if ( !isset( $info['class'] ) ) {
328 $class = 'ResourceLoaderFileModule';
330 $class = $info['class'];
332 $object = new $class( $info );
334 $object->setName( $name );
335 $this->modules
[$name] = $object;
338 return $this->modules
[$name];
342 * Get the list of sources
344 * @return Array: array( id => array of properties, .. )
346 public function getSources() {
347 return $this->sources
;
351 * Outputs a response to a resource load-request, including a content-type header.
353 * @param $context ResourceLoaderContext: Context in which a response should be formed
355 public function respond( ResourceLoaderContext
$context ) {
356 global $wgCacheEpoch, $wgUseFileCache;
358 // Use file cache if enabled and available...
359 if ( $wgUseFileCache ) {
360 $fileCache = ResourceFileCache
::newFromContext( $context );
361 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
362 return; // output handled
366 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
367 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
368 // is used: ob_clean() will clear the GZIP header in that case and it won't come
369 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
370 // the whole thing in our own output buffer to be sure the active buffer
371 // doesn't use ob_gzhandler.
372 // See http://bugs.php.net/bug.php?id=36514
375 wfProfileIn( __METHOD__
);
378 // Split requested modules into two groups, modules and missing
381 foreach ( $context->getModules() as $name ) {
382 if ( isset( $this->moduleInfos
[$name] ) ) {
383 $modules[$name] = $this->getModule( $name );
389 // Preload information needed to the mtime calculation below
391 $this->preloadModuleInfo( array_keys( $modules ), $context );
392 } catch( Exception
$e ) {
393 // Add exception to the output as a comment
394 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
397 wfProfileIn( __METHOD__
.'-getModifiedTime' );
400 // To send Last-Modified and support If-Modified-Since, we need to detect
401 // the last modified time
402 $mtime = wfTimestamp( TS_UNIX
, $wgCacheEpoch );
403 foreach ( $modules as $module ) {
405 * @var $module ResourceLoaderModule
408 // Bypass Squid and other shared caches if the request includes any private modules
409 if ( $module->getGroup() === 'private' ) {
412 // Calculate maximum modified time
413 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
414 } catch ( Exception
$e ) {
415 // Add exception to the output as a comment
416 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
420 wfProfileOut( __METHOD__
.'-getModifiedTime' );
422 // Send content type and cache related headers
423 $this->sendResponseHeaders( $context, $mtime, $private );
425 // If there's an If-Modified-Since header, respond with a 304 appropriately
426 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
427 wfProfileOut( __METHOD__
);
428 return; // output handled (buffers cleared)
431 // Generate a response
432 $response = $this->makeModuleResponse( $context, $modules, $missing );
434 // Prepend comments indicating exceptions
435 $response = $exceptions . $response;
437 // Capture any PHP warnings from the output buffer and append them to the
438 // response in a comment if we're in debug mode.
439 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
440 $response = "/*\n$warnings\n*/\n" . $response;
443 // Remove the output buffer and output the response
447 // Save response to file cache unless there are private modules or errors
448 if ( isset( $fileCache ) && !$private && !$exceptions && !$missing ) {
449 // Cache single modules...and other requests if there are enough hits
450 if ( ResourceFileCache
::useFileCache( $context ) ) {
451 if ( $fileCache->isCacheWorthy() ) {
452 $fileCache->saveText( $response );
454 $fileCache->incrMissesRecent( $context->getRequest() );
459 wfProfileOut( __METHOD__
);
463 * Send content type and last modified headers to the client.
464 * @param $context ResourceLoaderContext
465 * @param $mtime string TS_MW timestamp to use for last-modified
466 * @param $private bool True iff response contains any private modules
469 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $private ) {
470 global $wgResourceLoaderMaxage;
471 // If a version wasn't specified we need a shorter expiry time for updates
472 // to propagate to clients quickly
473 if ( is_null( $context->getVersion() ) ) {
474 $maxage = $wgResourceLoaderMaxage['unversioned']['client'];
475 $smaxage = $wgResourceLoaderMaxage['unversioned']['server'];
476 // If a version was specified we can use a longer expiry time since changing
477 // version numbers causes cache misses
479 $maxage = $wgResourceLoaderMaxage['versioned']['client'];
480 $smaxage = $wgResourceLoaderMaxage['versioned']['server'];
482 if ( $context->getOnly() === 'styles' ) {
483 header( 'Content-Type: text/css; charset=utf-8' );
485 header( 'Content-Type: text/javascript; charset=utf-8' );
487 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
488 if ( $context->getDebug() ) {
489 // Do not cache debug responses
490 header( 'Cache-Control: private, no-cache, must-revalidate' );
491 header( 'Pragma: no-cache' );
494 header( "Cache-Control: private, max-age=$maxage" );
497 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
498 $exp = min( $maxage, $smaxage );
500 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
505 * If there's an If-Modified-Since header, respond with a 304 appropriately
506 * and clear out the output buffer. If the client cache is too old then do nothing.
507 * @param $context ResourceLoaderContext
508 * @param $mtime string The TS_MW timestamp to check the header against
509 * @return bool True iff 304 header sent and output handled
511 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
512 // If there's an If-Modified-Since header, respond with a 304 appropriately
513 // Some clients send "timestamp;length=123". Strip the part after the first ';'
514 // so we get a valid timestamp.
515 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
516 // Never send 304s in debug mode
517 if ( $ims !== false && !$context->getDebug() ) {
518 $imsTS = strtok( $ims, ';' );
519 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
520 // There's another bug in ob_gzhandler (see also the comment at
521 // the top of this function) that causes it to gzip even empty
522 // responses, meaning it's impossible to produce a truly empty
523 // response (because the gzip header is always there). This is
524 // a problem because 304 responses have to be completely empty
525 // per the HTTP spec, and Firefox behaves buggily when they're not.
526 // See also http://bugs.php.net/bug.php?id=51579
527 // To work around this, we tear down all output buffering before
529 // On some setups, ob_get_level() doesn't seem to go down to zero
530 // no matter how often we call ob_get_clean(), so instead of doing
531 // the more intuitive while ( ob_get_level() > 0 ) ob_get_clean();
532 // we have to be safe here and avoid an infinite loop.
533 for ( $i = 0; $i < ob_get_level(); $i++
) {
537 header( 'HTTP/1.0 304 Not Modified' );
538 header( 'Status: 304 Not Modified' );
539 wfProfileOut( __METHOD__
);
547 * Send out code for a response from file cache if possible
549 * @param $fileCache ObjectFileCache: Cache object for this request URL
550 * @param $context ResourceLoaderContext: Context in which to generate a response
551 * @return bool If this found a cache file and handled the response
553 protected function tryRespondFromFileCache(
554 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
556 global $wgResourceLoaderMaxage;
557 // Buffer output to catch warnings.
559 // Get the maximum age the cache can be
560 $maxage = is_null( $context->getVersion() )
561 ?
$wgResourceLoaderMaxage['unversioned']['server']
562 : $wgResourceLoaderMaxage['versioned']['server'];
563 // Minimum timestamp the cache file must have
564 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
566 try { // RL always hits the DB on file cache miss...
568 } catch( DBConnectionError
$e ) { // ...check if we need to fallback to cache
569 $good = $fileCache->isCacheGood(); // cache existence check
573 $ts = $fileCache->cacheTimestamp();
574 // Send content type and cache headers
575 $this->sendResponseHeaders( $context, $ts, false );
576 // If there's an If-Modified-Since header, respond with a 304 appropriately
577 if ( $this->tryRespondLastModified( $context, $ts ) ) {
578 return false; // output handled (buffers cleared)
580 $response = $fileCache->fetchText();
581 // Remove the output buffer and output the response
583 echo $response . "\n/* Cached {$ts} */";
584 return true; // cache hit
589 return false; // cache miss
593 * Generates code for a response
595 * @param $context ResourceLoaderContext: Context in which to generate a response
596 * @param $modules Array: List of module objects keyed by module name
597 * @param $missing Array: List of unavailable modules (optional)
598 * @return String: Response data
600 public function makeModuleResponse( ResourceLoaderContext
$context,
601 array $modules, $missing = array() )
605 if ( $modules === array() && $missing === array() ) {
606 return '/* No modules requested. Max made me put this here */';
609 wfProfileIn( __METHOD__
);
611 if ( $context->shouldIncludeMessages() ) {
613 $blobs = MessageBlobStore
::get( $this, $modules, $context->getLanguage() );
614 } catch ( Exception
$e ) {
615 // Add exception to the output as a comment
616 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
623 foreach ( $modules as $name => $module ) {
625 * @var $module ResourceLoaderModule
628 wfProfileIn( __METHOD__
. '-' . $name );
631 if ( $context->shouldIncludeScripts() ) {
632 // If we are in debug mode, we'll want to return an array of URLs if possible
633 // However, we can't do this if the module doesn't support it
634 // We also can't do this if there is an only= parameter, because we have to give
635 // the module a way to return a load.php URL without causing an infinite loop
636 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
637 $scripts = $module->getScriptURLsForDebug( $context );
639 $scripts = $module->getScript( $context );
640 if ( is_string( $scripts ) ) {
641 // bug 27054: Append semicolon to prevent weird bugs
642 // caused by files not terminating their statements right
649 if ( $context->shouldIncludeStyles() ) {
650 // If we are in debug mode, we'll want to return an array of URLs
651 // See comment near shouldIncludeScripts() for more details
652 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
653 $styles = $module->getStyleURLsForDebug( $context );
655 $styles = $module->getStyles( $context );
660 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
663 switch ( $context->getOnly() ) {
665 if ( is_string( $scripts ) ) {
666 // Load scripts raw...
668 } elseif ( is_array( $scripts ) ) {
669 // ...except when $scripts is an array of URLs
670 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
674 $out .= self
::makeCombinedStyles( $styles );
677 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
680 // Minify CSS before embedding in mw.loader.implement call
681 // (unless in debug mode)
682 if ( !$context->getDebug() ) {
683 foreach ( $styles as $media => $style ) {
684 if ( is_string( $style ) ) {
685 $styles[$media] = $this->filter( 'minify-css', $style );
689 $out .= self
::makeLoaderImplementScript( $name, $scripts, $styles,
690 new XmlJsCode( $messagesBlob ) );
693 } catch ( Exception
$e ) {
694 // Add exception to the output as a comment
695 $exceptions .= "/*\n{$e->__toString()}\n*/\n";
697 // Register module as missing
699 unset( $modules[$name] );
701 wfProfileOut( __METHOD__
. '-' . $name );
704 // Update module states
705 if ( $context->shouldIncludeScripts() ) {
706 // Set the state of modules loaded as only scripts to ready
707 if ( count( $modules ) && $context->getOnly() === 'scripts'
708 && !isset( $modules['startup'] ) )
710 $out .= self
::makeLoaderStateScript(
711 array_fill_keys( array_keys( $modules ), 'ready' ) );
713 // Set the state of modules which were requested but unavailable as missing
714 if ( is_array( $missing ) && count( $missing ) ) {
715 $out .= self
::makeLoaderStateScript( array_fill_keys( $missing, 'missing' ) );
719 if ( !$context->getDebug() ) {
720 if ( $context->getOnly() === 'styles' ) {
721 $out = $this->filter( 'minify-css', $out );
723 $out = $this->filter( 'minify-js', $out );
727 wfProfileOut( __METHOD__
);
728 return $exceptions . $out;
734 * Returns JS code to call to mw.loader.implement for a module with
737 * @param $name Module name
738 * @param $scripts Mixed: List of URLs to JavaScript files or String of JavaScript code
739 * @param $styles Mixed: List of CSS strings keyed by media type, or list of lists of URLs to
740 * CSS files keyed by media type
741 * @param $messages Mixed: List of messages associated with this module. May either be an
742 * associative array mapping message key to value, or a JSON-encoded message blob containing
743 * the same data, wrapped in an XmlJsCode object.
747 public static function makeLoaderImplementScript( $name, $scripts, $styles, $messages ) {
748 if ( is_string( $scripts ) ) {
749 $scripts = new XmlJsCode( "function( $ ) {{$scripts}}" );
750 } elseif ( !is_array( $scripts ) ) {
751 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
753 return Xml
::encodeJsCall(
754 'mw.loader.implement',
764 * Returns JS code which, when called, will register a given list of messages.
766 * @param $messages Mixed: Either an associative array mapping message key to value, or a
767 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
771 public static function makeMessageSetScript( $messages ) {
772 return Xml
::encodeJsCall( 'mw.messages.set', array( (object)$messages ) );
776 * Combines an associative array mapping media type to CSS into a
777 * single stylesheet with @media blocks.
779 * @param $styles Array: List of CSS strings keyed by media type
783 public static function makeCombinedStyles( array $styles ) {
785 foreach ( $styles as $media => $style ) {
786 // Transform the media type based on request params and config
787 // The way that this relies on $wgRequest to propagate request params is slightly evil
788 $media = OutputPage
::transformCssMedia( $media );
790 if ( $media === null ) {
792 } elseif ( $media === '' ||
$media == 'all' ) {
793 // Don't output invalid or frivolous @media statements
796 $out .= "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "\n}\n";
803 * Returns a JS call to mw.loader.state, which sets the state of a
804 * module or modules to a given value. Has two calling conventions:
806 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
807 * Set the state of a single module called $name to $state
809 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
810 * Set the state of modules with the given names to the given states
812 * @param $name string
817 public static function makeLoaderStateScript( $name, $state = null ) {
818 if ( is_array( $name ) ) {
819 return Xml
::encodeJsCall( 'mw.loader.state', array( $name ) );
821 return Xml
::encodeJsCall( 'mw.loader.state', array( $name, $state ) );
826 * Returns JS code which calls the script given by $script. The script will
827 * be called with local variables name, version, dependencies and group,
828 * which will have values corresponding to $name, $version, $dependencies
829 * and $group as supplied.
831 * @param $name String: Module name
832 * @param $version Integer: Module version number as a timestamp
833 * @param $dependencies Array: List of module names on which this module depends
834 * @param $group String: Group which the module is in.
835 * @param $source String: Source of the module, or 'local' if not foreign.
836 * @param $script String: JavaScript code
840 public static function makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script ) {
841 $script = str_replace( "\n", "\n\t", trim( $script ) );
842 return Xml
::encodeJsCall(
843 "( function( name, version, dependencies, group, source ) {\n\t$script\n} )",
844 array( $name, $version, $dependencies, $group, $source ) );
848 * Returns JS code which calls mw.loader.register with the given
849 * parameters. Has three calling conventions:
851 * - ResourceLoader::makeLoaderRegisterScript( $name, $version, $dependencies, $group, $source ):
852 * Register a single module.
854 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
855 * Register modules with the given names.
857 * - ResourceLoader::makeLoaderRegisterScript( array(
858 * array( $name1, $version1, $dependencies1, $group1, $source1 ),
859 * array( $name2, $version2, $dependencies1, $group2, $source2 ),
862 * Registers modules with the given names and parameters.
864 * @param $name String: Module name
865 * @param $version Integer: Module version number as a timestamp
866 * @param $dependencies Array: List of module names on which this module depends
867 * @param $group String: group which the module is in.
868 * @param $source String: source of the module, or 'local' if not foreign
872 public static function makeLoaderRegisterScript( $name, $version = null,
873 $dependencies = null, $group = null, $source = null )
875 if ( is_array( $name ) ) {
876 return Xml
::encodeJsCall( 'mw.loader.register', array( $name ) );
878 $version = (int) $version > 1 ?
(int) $version : 1;
879 return Xml
::encodeJsCall( 'mw.loader.register',
880 array( $name, $version, $dependencies, $group, $source ) );
885 * Returns JS code which calls mw.loader.addSource() with the given
886 * parameters. Has two calling conventions:
888 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
889 * Register a single source
891 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $props1, $id2 => $props2, ... ) );
892 * Register sources with the given IDs and properties.
894 * @param $id String: source ID
895 * @param $properties Array: source properties (see addSource())
899 public static function makeLoaderSourcesScript( $id, $properties = null ) {
900 if ( is_array( $id ) ) {
901 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id ) );
903 return Xml
::encodeJsCall( 'mw.loader.addSource', array( $id, $properties ) );
908 * Returns JS code which runs given JS code if the client-side framework is
911 * @param $script String: JavaScript code
915 public static function makeLoaderConditionalScript( $script ) {
916 $script = str_replace( "\n", "\n\t", trim( $script ) );
917 return "if(window.mw){\n\t$script\n}\n";
921 * Returns JS code which will set the MediaWiki configuration array to
924 * @param $configuration Array: List of configuration values keyed by variable name
928 public static function makeConfigSetScript( array $configuration ) {
929 return Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) );
933 * Convert an array of module names to a packed query string.
935 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
936 * becomes 'foo.bar,baz|bar.baz,quux'
937 * @param $modules array of module names (strings)
938 * @return string Packed query string
940 public static function makePackedModulesString( $modules ) {
941 $groups = array(); // array( prefix => array( suffixes ) )
942 foreach ( $modules as $module ) {
943 $pos = strrpos( $module, '.' );
944 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
945 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
946 $groups[$prefix][] = $suffix;
950 foreach ( $groups as $prefix => $suffixes ) {
951 $p = $prefix === '' ?
'' : $prefix . '.';
952 $arr[] = $p . implode( ',', $suffixes );
954 $str = implode( '|', $arr );
959 * Determine whether debug mode was requested
960 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
963 public static function inDebugMode() {
964 global $wgRequest, $wgResourceLoaderDebug;
965 static $retval = null;
966 if ( !is_null( $retval ) ) {
969 return $retval = $wgRequest->getFuzzyBool( 'debug',
970 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug ) );
974 * Build a load.php URL
975 * @param $modules array of module names (strings)
976 * @param $lang string Language code
977 * @param $skin string Skin name
978 * @param $user string|null User name. If null, the &user= parameter is omitted
979 * @param $version string|null Versioning timestamp
980 * @param $debug bool Whether the request should be in debug mode
981 * @param $only string|null &only= parameter
982 * @param $printable bool Printable mode
983 * @param $handheld bool Handheld mode
984 * @param $extraQuery array Extra query parameters to add
985 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
987 public static function makeLoaderURL( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
988 $printable = false, $handheld = false, $extraQuery = array() ) {
989 global $wgLoadScript;
990 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
991 $only, $printable, $handheld, $extraQuery
994 // Prevent the IE6 extension check from being triggered (bug 28840)
995 // by appending a character that's invalid in Windows extensions ('*')
996 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1000 * Build a query array (array representation of query string) for load.php. Helper
1001 * function for makeLoaderURL().
1004 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null, $version = null, $debug = false, $only = null,
1005 $printable = false, $handheld = false, $extraQuery = array() ) {
1007 'modules' => self
::makePackedModulesString( $modules ),
1010 'debug' => $debug ?
'true' : 'false',
1012 if ( $user !== null ) {
1013 $query['user'] = $user;
1015 if ( $version !== null ) {
1016 $query['version'] = $version;
1018 if ( $only !== null ) {
1019 $query['only'] = $only;
1022 $query['printable'] = 1;
1025 $query['handheld'] = 1;
1027 $query +
= $extraQuery;
1029 // Make queries uniform in order