3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 use Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\NullLogger
;
30 * Dynamic JavaScript and CSS resource loading system.
32 * Most of the documentation is on the MediaWiki documentation wiki starting at:
33 * https://www.mediawiki.org/wiki/ResourceLoader
35 class ResourceLoader
implements LoggerAwareInterface
{
37 protected static $filterCacheVersion = 7;
40 protected static $debugMode = null;
43 private static $lessVars = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = array();
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = array();
57 /** @var Config $config */
61 * Associative array mapping framework ids to a list of names of test suite modules
62 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
65 protected $testModuleNames = array();
68 * E.g. array( 'source-id' => 'http://.../load.php' )
71 protected $sources = array();
74 * Errors accumulated during current respond() call.
77 protected $errors = array();
80 * @var MessageBlobStore
85 * @var LoggerInterface
90 * Load information stored in the database about modules.
92 * This method grabs modules dependencies from the database and updates modules
95 * This is not inside the module code because it is much faster to
96 * request all of the information at once than it is to have each module
97 * requests its own information. This sacrifice of modularity yields a substantial
98 * performance improvement.
100 * @param array $modules List of module names to preload information for
101 * @param ResourceLoaderContext $context Context to load the information within
103 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
104 if ( !count( $modules ) ) {
105 // Or else Database*::select() will explode, plus it's cheaper!
108 $dbr = wfGetDB( DB_SLAVE
);
109 $skin = $context->getSkin();
110 $lang = $context->getLanguage();
112 // Get file dependency information
113 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
114 'md_module' => $modules,
119 // Set modules' dependencies
120 $modulesWithDeps = array();
121 foreach ( $res as $row ) {
122 $module = $this->getModule( $row->md_module
);
124 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
125 $modulesWithDeps[] = $row->md_module
;
129 // Register the absence of a dependency row too
130 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
131 $module = $this->getModule( $name );
133 $this->getModule( $name )->setFileDependencies( $skin, array() );
137 // Get message blob mtimes. Only do this for modules with messages
138 $modulesWithMessages = array();
139 foreach ( $modules as $name ) {
140 $module = $this->getModule( $name );
141 if ( $module && count( $module->getMessages() ) ) {
142 $modulesWithMessages[] = $name;
145 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
146 if ( count( $modulesWithMessages ) ) {
147 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
148 'mr_resource' => $modulesWithMessages,
152 foreach ( $res as $row ) {
153 $module = $this->getModule( $row->mr_resource
);
155 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
156 unset( $modulesWithoutMessages[$row->mr_resource
] );
160 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
161 $module = $this->getModule( $name );
163 $module->setMsgBlobMtime( $lang, 1 );
169 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
171 * Available filters are:
173 * - minify-js \see JavaScriptMinifier::minify
174 * - minify-css \see CSSMin::minify
176 * If $data is empty, only contains whitespace or the filter was unknown,
177 * $data is returned unmodified.
179 * @param string $filter Name of filter to run
180 * @param string $data Text to filter, such as JavaScript or CSS text
181 * @param array $options For back-compat, can also be the boolean value for "cacheReport". Keys:
182 * - (bool) cache: Whether to allow caching this data. Default: true.
183 * - (bool) cacheReport: Whether to include the "cache key" report comment. Default: true.
184 * @return string Filtered data, or a comment containing an error message
186 public function filter( $filter, $data, $options = array() ) {
188 if ( is_bool( $options ) ) {
189 $options = array( 'cacheReport' => $options );
192 $options +
= array( 'cache' => true, 'cacheReport' => true );
194 // Don't filter empty content
195 if ( trim( $data ) === '' ) {
199 if ( !in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
200 $this->logger
->warning( 'Invalid filter {filter}', array(
206 if ( !$options['cache'] ) {
207 $result = $this->applyFilter( $filter, $data );
209 $key = wfGlobalCacheKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
210 $cache = wfGetCache( wfIsHHVM() ? CACHE_ACCEL
: CACHE_ANYTHING
);
211 $cacheEntry = $cache->get( $key );
212 if ( is_string( $cacheEntry ) ) {
213 wfIncrStats( "resourceloader_cache.$filter.hit" );
218 $stats = RequestContext
::getMain()->getStats();
219 $statStart = microtime( true );
221 $result = $this->applyFilter( $filter, $data );
223 $stats->timing( "resourceloader_cache.$filter.miss", microtime( true ) - $statStart );
224 if ( $options['cacheReport'] ) {
225 $result .= "\n/* cache key: $key */";
227 // Set a TTL since HHVM's APC doesn't have any limitation or eviction logic.
228 $cache->set( $key, $result, 24 * 3600 );
229 } catch ( Exception
$e ) {
230 MWExceptionHandler
::logException( $e );
231 $this->logger
->warning( 'Minification failed: {exception}', array(
234 $this->errors
[] = self
::formatExceptionNoComment( $e );
241 private function applyFilter( $filter, $data ) {
244 return JavaScriptMinifier
::minify( $data,
245 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
246 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
249 return CSSMin
::minify( $data );
258 * Register core modules and runs registration hooks.
259 * @param Config|null $config
261 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
265 $logger = new NullLogger();
267 $this->setLogger( $logger );
270 $this->logger
->debug( __METHOD__
. ' was called without providing a Config instance' );
271 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
273 $this->config
= $config;
275 // Add 'local' source first
276 $this->addSource( 'local', wfScript( 'load' ) );
279 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
281 // Register core modules
282 $this->register( include "$IP/resources/Resources.php" );
283 $this->register( include "$IP/resources/ResourcesOOUI.php" );
284 // Register extension modules
285 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
286 $this->register( $config->get( 'ResourceModules' ) );
288 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
289 $this->registerTestModules();
292 $this->setMessageBlobStore( new MessageBlobStore() );
298 public function getConfig() {
299 return $this->config
;
302 public function setLogger( LoggerInterface
$logger ) {
303 $this->logger
= $logger;
308 * @return MessageBlobStore
310 public function getMessageBlobStore() {
311 return $this->blobStore
;
316 * @param MessageBlobStore $blobStore
318 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
319 $this->blobStore
= $blobStore;
323 * Register a module with the ResourceLoader system.
325 * @param mixed $name Name of module as a string or List of name/object pairs as an array
326 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
327 * this may also be a ResourceLoaderModule object. Optional when using
328 * multiple-registration calling style.
329 * @throws MWException If a duplicate module registration is attempted
330 * @throws MWException If a module name contains illegal characters (pipes or commas)
331 * @throws MWException If something other than a ResourceLoaderModule is being registered
332 * @return bool False if there were any errors, in which case one or more modules were
335 public function register( $name, $info = null ) {
337 // Allow multiple modules to be registered in one call
338 $registrations = is_array( $name ) ?
$name : array( $name => $info );
339 foreach ( $registrations as $name => $info ) {
340 // Disallow duplicate registrations
341 if ( isset( $this->moduleInfos
[$name] ) ) {
342 // A module has already been registered by this name
343 throw new MWException(
344 'ResourceLoader duplicate registration error. ' .
345 'Another module has already been registered as ' . $name
349 // Check $name for validity
350 if ( !self
::isValidModuleName( $name ) ) {
351 throw new MWException( "ResourceLoader module name '$name' is invalid, "
352 . "see ResourceLoader::isValidModuleName()" );
356 if ( $info instanceof ResourceLoaderModule
) {
357 $this->moduleInfos
[$name] = array( 'object' => $info );
358 $info->setName( $name );
359 $this->modules
[$name] = $info;
360 } elseif ( is_array( $info ) ) {
361 // New calling convention
362 $this->moduleInfos
[$name] = $info;
364 throw new MWException(
365 'ResourceLoader module info type error for module \'' . $name .
366 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
370 // Last-minute changes
372 // Apply custom skin-defined styles to existing modules.
373 if ( $this->isFileModule( $name ) ) {
374 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
375 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
376 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
380 // If $name is preceded with a '+', the defined style files will be added to 'default'
381 // skinStyles, otherwise 'default' will be ignored as it normally would be.
382 if ( isset( $skinStyles[$name] ) ) {
383 $paths = (array)$skinStyles[$name];
384 $styleFiles = array();
385 } elseif ( isset( $skinStyles['+' . $name] ) ) {
386 $paths = (array)$skinStyles['+' . $name];
387 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
388 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
394 // Add new file paths, remapping them to refer to our directories and not use settings
395 // from the module we're modifying, which come from the base definition.
396 list( $localBasePath, $remoteBasePath ) =
397 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
399 foreach ( $paths as $path ) {
400 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
403 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
412 public function registerTestModules() {
415 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
416 throw new MWException( 'Attempt to register JavaScript test modules '
417 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
418 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
421 // Get core test suites
422 $testModules = array();
423 $testModules['qunit'] = array();
424 // Get other test suites (e.g. from extensions)
425 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
427 // Add the testrunner (which configures QUnit) to the dependencies.
428 // Since it must be ready before any of the test suites are executed.
429 foreach ( $testModules['qunit'] as &$module ) {
430 // Make sure all test modules are top-loading so that when QUnit starts
431 // on document-ready, it will run once and finish. If some tests arrive
432 // later (possibly after QUnit has already finished) they will be ignored.
433 $module['position'] = 'top';
434 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
437 $testModules['qunit'] =
438 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
440 foreach ( $testModules as $id => $names ) {
441 // Register test modules
442 $this->register( $testModules[$id] );
444 // Keep track of their names so that they can be loaded together
445 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
451 * Add a foreign source of modules.
453 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
454 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
455 * backwards-compatibility.
456 * @throws MWException
458 public function addSource( $id, $loadUrl = null ) {
459 // Allow multiple sources to be registered in one call
460 if ( is_array( $id ) ) {
461 foreach ( $id as $key => $value ) {
462 $this->addSource( $key, $value );
467 // Disallow duplicates
468 if ( isset( $this->sources
[$id] ) ) {
469 throw new MWException(
470 'ResourceLoader duplicate source addition error. ' .
471 'Another source has already been registered as ' . $id
475 // Pre 1.24 backwards-compatibility
476 if ( is_array( $loadUrl ) ) {
477 if ( !isset( $loadUrl['loadScript'] ) ) {
478 throw new MWException(
479 __METHOD__
. ' was passed an array with no "loadScript" key.'
483 $loadUrl = $loadUrl['loadScript'];
486 $this->sources
[$id] = $loadUrl;
490 * Get a list of module names.
492 * @return array List of module names
494 public function getModuleNames() {
495 return array_keys( $this->moduleInfos
);
499 * Get a list of test module names for one (or all) frameworks.
501 * If the given framework id is unknkown, or if the in-object variable is not an array,
502 * then it will return an empty array.
504 * @param string $framework Get only the test module names for one
505 * particular framework (optional)
508 public function getTestModuleNames( $framework = 'all' ) {
509 /** @todo api siteinfo prop testmodulenames modulenames */
510 if ( $framework == 'all' ) {
511 return $this->testModuleNames
;
512 } elseif ( isset( $this->testModuleNames
[$framework] )
513 && is_array( $this->testModuleNames
[$framework] )
515 return $this->testModuleNames
[$framework];
522 * Check whether a ResourceLoader module is registered
525 * @param string $name
528 public function isModuleRegistered( $name ) {
529 return isset( $this->moduleInfos
[$name] );
533 * Get the ResourceLoaderModule object for a given module name.
535 * If an array of module parameters exists but a ResourceLoaderModule object has not
536 * yet been instantiated, this method will instantiate and cache that object such that
537 * subsequent calls simply return the same object.
539 * @param string $name Module name
540 * @return ResourceLoaderModule|null If module has been registered, return a
541 * ResourceLoaderModule instance. Otherwise, return null.
543 public function getModule( $name ) {
544 if ( !isset( $this->modules
[$name] ) ) {
545 if ( !isset( $this->moduleInfos
[$name] ) ) {
549 // Construct the requested object
550 $info = $this->moduleInfos
[$name];
551 /** @var ResourceLoaderModule $object */
552 if ( isset( $info['object'] ) ) {
553 // Object given in info array
554 $object = $info['object'];
556 if ( !isset( $info['class'] ) ) {
557 $class = 'ResourceLoaderFileModule';
559 $class = $info['class'];
561 /** @var ResourceLoaderModule $object */
562 $object = new $class( $info );
563 $object->setConfig( $this->getConfig() );
565 $object->setName( $name );
566 $this->modules
[$name] = $object;
569 return $this->modules
[$name];
573 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
575 * @param string $name Module name
578 protected function isFileModule( $name ) {
579 if ( !isset( $this->moduleInfos
[$name] ) ) {
582 $info = $this->moduleInfos
[$name];
583 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
590 * Get the list of sources.
592 * @return array Like array( id => load.php url, .. )
594 public function getSources() {
595 return $this->sources
;
599 * Get the URL to the load.php endpoint for the given
600 * ResourceLoader source
603 * @param string $source
604 * @throws MWException On an invalid $source name
607 public function getLoadScript( $source ) {
608 if ( !isset( $this->sources
[$source] ) ) {
609 throw new MWException( "The $source source was never registered in ResourceLoader." );
611 return $this->sources
[$source];
616 * @param string $value
617 * @return string Hash
619 public static function makeHash( $value ) {
620 // Use base64 to output more entropy in a more compact string (default hex is only base16).
621 // The first 8 chars of a base64 encoded digest represent the same binary as
622 // the first 12 chars of a hex encoded digest.
623 return substr( base64_encode( sha1( $value, true ) ), 0, 8 );
627 * Helper method to get and combine versions of multiple modules.
630 * @param ResourceLoaderContext $context
631 * @param array $modules List of ResourceLoaderModule objects
632 * @return string Hash
634 public function getCombinedVersion( ResourceLoaderContext
$context, Array $modules ) {
638 // Support: PHP 5.3 ("$this" for anonymous functions was added in PHP 5.4.0)
639 // http://php.net/functions.anonymous
641 $hashes = array_map( function ( $module ) use ( $rl, $context ) {
642 return $rl->getModule( $module )->getVersionHash( $context );
644 return self
::makeHash( implode( $hashes ) );
648 * Output a response to a load request, including the content-type header.
650 * @param ResourceLoaderContext $context Context in which a response should be formed
652 public function respond( ResourceLoaderContext
$context ) {
653 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
654 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
655 // is used: ob_clean() will clear the GZIP header in that case and it won't come
656 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
657 // the whole thing in our own output buffer to be sure the active buffer
658 // doesn't use ob_gzhandler.
659 // See http://bugs.php.net/bug.php?id=36514
662 // Find out which modules are missing and instantiate the others
665 foreach ( $context->getModules() as $name ) {
666 $module = $this->getModule( $name );
668 // Do not allow private modules to be loaded from the web.
669 // This is a security issue, see bug 34907.
670 if ( $module->getGroup() === 'private' ) {
671 $this->logger
->debug( "Request for private module '$name' denied" );
672 $this->errors
[] = "Cannot show private module \"$name\"";
675 $modules[$name] = $module;
682 // Preload for getCombinedVersion()
683 $this->preloadModuleInfo( array_keys( $modules ), $context );
684 } catch ( Exception
$e ) {
685 MWExceptionHandler
::logException( $e );
686 $this->logger
->warning( 'Preloading module info failed: {exception}', array(
689 $this->errors
[] = self
::formatExceptionNoComment( $e );
692 // Combine versions to propagate cache invalidation
695 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
696 } catch ( Exception
$e ) {
697 MWExceptionHandler
::logException( $e );
698 $this->logger
->warning( 'Calculating version hash failed: {exception}', array(
701 $this->errors
[] = self
::formatExceptionNoComment( $e );
704 // See RFC 2616 § 3.11 Entity Tags
705 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
706 $etag = 'W/"' . $versionHash . '"';
708 // Try the client-side cache first
709 if ( $this->tryRespondNotModified( $context, $etag ) ) {
710 return; // output handled (buffers cleared)
713 // Use file cache if enabled and available...
714 if ( $this->config
->get( 'UseFileCache' ) ) {
715 $fileCache = ResourceFileCache
::newFromContext( $context );
716 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
717 return; // output handled
721 // Generate a response
722 $response = $this->makeModuleResponse( $context, $modules, $missing );
724 // Capture any PHP warnings from the output buffer and append them to the
725 // error list if we're in debug mode.
726 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
727 $this->errors
[] = $warnings;
730 // Save response to file cache unless there are errors
731 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
732 // Cache single modules and images...and other requests if there are enough hits
733 if ( ResourceFileCache
::useFileCache( $context ) ) {
734 if ( $fileCache->isCacheWorthy() ) {
735 $fileCache->saveText( $response );
737 $fileCache->incrMissesRecent( $context->getRequest() );
742 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
);
744 // Remove the output buffer and output the response
747 if ( $context->getImageObj() && $this->errors
) {
748 // We can't show both the error messages and the response when it's an image.
750 foreach ( $this->errors
as $error ) {
751 $errorText .= $error . "\n";
753 $response = $errorText;
754 } elseif ( $this->errors
) {
755 // Prepend comments indicating errors
757 foreach ( $this->errors
as $error ) {
758 $errorText .= self
::makeComment( $error );
760 $response = $errorText . $response;
763 $this->errors
= array();
769 * Send main response headers to the client.
771 * Deals with Content-Type, CORS (for stylesheets), and caching.
773 * @param ResourceLoaderContext $context
774 * @param string $etag ETag header value
775 * @param bool $errors Whether there are errors in the response
778 protected function sendResponseHeaders( ResourceLoaderContext
$context, $etag, $errors ) {
779 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
780 // If a version wasn't specified we need a shorter expiry time for updates
781 // to propagate to clients quickly
782 // If there were errors, we also need a shorter expiry time so we can recover quickly
783 if ( is_null( $context->getVersion() ) ||
$errors ) {
784 $maxage = $rlMaxage['unversioned']['client'];
785 $smaxage = $rlMaxage['unversioned']['server'];
786 // If a version was specified we can use a longer expiry time since changing
787 // version numbers causes cache misses
789 $maxage = $rlMaxage['versioned']['client'];
790 $smaxage = $rlMaxage['versioned']['server'];
792 if ( $context->getImageObj() ) {
793 // Output different headers if we're outputting textual errors.
795 header( 'Content-Type: text/plain; charset=utf-8' );
797 $context->getImageObj()->sendResponseHeaders( $context );
799 } elseif ( $context->getOnly() === 'styles' ) {
800 header( 'Content-Type: text/css; charset=utf-8' );
801 header( 'Access-Control-Allow-Origin: *' );
803 header( 'Content-Type: text/javascript; charset=utf-8' );
805 // See RFC 2616 § 14.19 ETag
806 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
807 header( 'ETag: ' . $etag );
808 if ( $context->getDebug() ) {
809 // Do not cache debug responses
810 header( 'Cache-Control: private, no-cache, must-revalidate' );
811 header( 'Pragma: no-cache' );
813 header( "Cache-Control: public, must-revalidate, max-age=$maxage, s-maxage=$smaxage" );
814 $exp = min( $maxage, $smaxage );
815 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
818 // Send the current time expressed as fractional seconds since epoch,
819 // with microsecond precision. This helps distinguish hits from misses
821 header( 'MediaWiki-Timestamp: ' . microtime( true ) );
825 * Respond with HTTP 304 Not Modified if appropiate.
827 * If there's an If-None-Match header, respond with a 304 appropriately
828 * and clear out the output buffer. If the client cache is too old then do nothing.
830 * @param ResourceLoaderContext $context
831 * @param string $etag ETag header value
832 * @return bool True if HTTP 304 was sent and output handled
834 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
835 // See RFC 2616 § 14.26 If-None-Match
836 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
837 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
838 // Never send 304s in debug mode
839 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
840 // There's another bug in ob_gzhandler (see also the comment at
841 // the top of this function) that causes it to gzip even empty
842 // responses, meaning it's impossible to produce a truly empty
843 // response (because the gzip header is always there). This is
844 // a problem because 304 responses have to be completely empty
845 // per the HTTP spec, and Firefox behaves buggily when they're not.
846 // See also http://bugs.php.net/bug.php?id=51579
847 // To work around this, we tear down all output buffering before
849 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
851 HttpStatus
::header( 304 );
853 $this->sendResponseHeaders( $context, $etag, false );
860 * Send out code for a response from file cache if possible.
862 * @param ResourceFileCache $fileCache Cache object for this request URL
863 * @param ResourceLoaderContext $context Context in which to generate a response
864 * @param string $etag ETag header value
865 * @return bool If this found a cache file and handled the response
867 protected function tryRespondFromFileCache(
868 ResourceFileCache
$fileCache,
869 ResourceLoaderContext
$context,
872 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
873 // Buffer output to catch warnings.
875 // Get the maximum age the cache can be
876 $maxage = is_null( $context->getVersion() )
877 ?
$rlMaxage['unversioned']['server']
878 : $rlMaxage['versioned']['server'];
879 // Minimum timestamp the cache file must have
880 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
882 try { // RL always hits the DB on file cache miss...
884 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
885 $good = $fileCache->isCacheGood(); // cache existence check
889 $ts = $fileCache->cacheTimestamp();
890 // Send content type and cache headers
891 $this->sendResponseHeaders( $context, $etag, false );
892 $response = $fileCache->fetchText();
893 // Capture any PHP warnings from the output buffer and append them to the
894 // response in a comment if we're in debug mode.
895 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
896 $response = self
::makeComment( $warnings ) . $response;
898 // Remove the output buffer and output the response
900 echo $response . "\n/* Cached {$ts} */";
901 return true; // cache hit
906 return false; // cache miss
910 * Generate a CSS or JS comment block.
912 * Only use this for public data, not error message details.
914 * @param string $text
917 public static function makeComment( $text ) {
918 $encText = str_replace( '*/', '* /', $text );
919 return "/*\n$encText\n*/\n";
923 * Handle exception display.
925 * @param Exception $e Exception to be shown to the user
926 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
928 public static function formatException( $e ) {
929 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
933 * Handle exception display.
936 * @param Exception $e Exception to be shown to the user
937 * @return string Sanitized text that can be returned to the user
939 protected static function formatExceptionNoComment( $e ) {
940 global $wgShowExceptionDetails;
942 if ( $wgShowExceptionDetails ) {
943 return $e->__toString();
945 return wfMessage( 'internalerror' )->text();
950 * Generate code for a response.
952 * @param ResourceLoaderContext $context Context in which to generate a response
953 * @param array $modules List of module objects keyed by module name
954 * @param array $missing List of requested module names that are unregistered (optional)
955 * @return string Response data
957 public function makeModuleResponse( ResourceLoaderContext
$context,
958 array $modules, array $missing = array()
963 if ( !count( $modules ) && !count( $missing ) ) {
965 /* This file is the Web entry point for MediaWiki's ResourceLoader:
966 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
967 no modules were requested. Max made me put this here. */
971 $image = $context->getImageObj();
973 $data = $image->getImageData( $context );
974 if ( $data === false ) {
976 $this->errors
[] = 'Image generation failed';
982 if ( $context->shouldIncludeMessages() ) {
984 $this->blobStore
->get( $this, $modules, $context->getLanguage() );
985 } catch ( Exception
$e ) {
986 MWExceptionHandler
::logException( $e );
987 $this->logger
->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
990 $this->errors
[] = self
::formatExceptionNoComment( $e );
994 foreach ( $missing as $name ) {
995 $states[$name] = 'missing';
1000 foreach ( $modules as $name => $module ) {
1002 $content = $module->getModuleContent( $context );
1005 switch ( $context->getOnly() ) {
1007 $scripts = $content['scripts'];
1008 if ( is_string( $scripts ) ) {
1009 // Load scripts raw...
1011 } elseif ( is_array( $scripts ) ) {
1012 // ...except when $scripts is an array of URLs
1013 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
1017 $styles = $content['styles'];
1018 // We no longer seperate into media, they are all combined now with
1019 // custom media type groups into @media .. {} sections as part of the css string.
1020 // Module returns either an empty array or a numerical array with css strings.
1021 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1024 $out .= self
::makeLoaderImplementScript(
1026 isset( $content['scripts'] ) ?
$content['scripts'] : '',
1027 isset( $content['styles'] ) ?
$content['styles'] : array(),
1028 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : array(),
1029 isset( $content['templates'] ) ?
$content['templates'] : array()
1033 } catch ( Exception
$e ) {
1034 MWExceptionHandler
::logException( $e );
1035 $this->logger
->warning( 'Generating module package failed: {exception}', array(
1038 $this->errors
[] = self
::formatExceptionNoComment( $e );
1040 // Respond to client with error-state instead of module implementation
1041 $states[$name] = 'error';
1042 unset( $modules[$name] );
1044 $isRaw |
= $module->isRaw();
1047 // Update module states
1048 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1049 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1050 // Set the state of modules loaded as only scripts to ready as
1051 // they don't have an mw.loader.implement wrapper that sets the state
1052 foreach ( $modules as $name => $module ) {
1053 $states[$name] = 'ready';
1057 // Set the state of modules we didn't respond to with mw.loader.implement
1058 if ( count( $states ) ) {
1059 $out .= self
::makeLoaderStateScript( $states );
1062 if ( count( $states ) ) {
1063 $this->errors
[] = 'Problematic modules: ' .
1064 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1068 $enableFilterCache = true;
1069 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule
) {
1070 // If we're building the embedded user.tokens, don't cache (T84960)
1071 $enableFilterCache = false;
1074 if ( !$context->getDebug() ) {
1075 if ( $context->getOnly() === 'styles' ) {
1076 $out = $this->filter( 'minify-css', $out );
1078 $out = $this->filter( 'minify-js', $out, array(
1079 'cache' => $enableFilterCache
1087 /* Static Methods */
1090 * Return JS code that calls mw.loader.implement with given module properties.
1092 * @param string $name Module name
1093 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1094 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1095 * to CSS files keyed by media type
1096 * @param mixed $messages List of messages associated with this module. May either be an
1097 * associative array mapping message key to value, or a JSON-encoded message blob containing
1098 * the same data, wrapped in an XmlJsCode object.
1099 * @param array $templates Keys are name of templates and values are the source of
1101 * @throws MWException
1104 public static function makeLoaderImplementScript(
1105 $name, $scripts, $styles, $messages, $templates
1107 if ( is_string( $scripts ) ) {
1108 // Site and user module are a legacy scripts that run in the global scope (no closure).
1109 // Transportation as string instructs mw.loader.implement to use globalEval.
1110 if ( $name !== 'site' && $name !== 'user' ) {
1111 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1113 } elseif ( !is_array( $scripts ) ) {
1114 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1116 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1117 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1118 // of "{}". Force them to objects.
1126 self
::trimArray( $module );
1128 return Xml
::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader
::inDebugMode() );
1132 * Returns JS code which, when called, will register a given list of messages.
1134 * @param mixed $messages Either an associative array mapping message key to value, or a
1135 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1138 public static function makeMessageSetScript( $messages ) {
1139 return Xml
::encodeJsCall(
1141 array( (object)$messages ),
1142 ResourceLoader
::inDebugMode()
1147 * Combines an associative array mapping media type to CSS into a
1148 * single stylesheet with "@media" blocks.
1150 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1153 public static function makeCombinedStyles( array $stylePairs ) {
1155 foreach ( $stylePairs as $media => $styles ) {
1156 // ResourceLoaderFileModule::getStyle can return the styles
1157 // as a string or an array of strings. This is to allow separation in
1159 $styles = (array)$styles;
1160 foreach ( $styles as $style ) {
1161 $style = trim( $style );
1162 // Don't output an empty "@media print { }" block (bug 40498)
1163 if ( $style !== '' ) {
1164 // Transform the media type based on request params and config
1165 // The way that this relies on $wgRequest to propagate request params is slightly evil
1166 $media = OutputPage
::transformCssMedia( $media );
1168 if ( $media === '' ||
$media == 'all' ) {
1170 } elseif ( is_string( $media ) ) {
1171 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1181 * Returns a JS call to mw.loader.state, which sets the state of a
1182 * module or modules to a given value. Has two calling conventions:
1184 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1185 * Set the state of a single module called $name to $state
1187 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1188 * Set the state of modules with the given names to the given states
1190 * @param string $name
1191 * @param string $state
1194 public static function makeLoaderStateScript( $name, $state = null ) {
1195 if ( is_array( $name ) ) {
1196 return Xml
::encodeJsCall(
1199 ResourceLoader
::inDebugMode()
1202 return Xml
::encodeJsCall(
1204 array( $name, $state ),
1205 ResourceLoader
::inDebugMode()
1211 * Returns JS code which calls the script given by $script. The script will
1212 * be called with local variables name, version, dependencies and group,
1213 * which will have values corresponding to $name, $version, $dependencies
1214 * and $group as supplied.
1216 * @param string $name Module name
1217 * @param string $version Module version hash
1218 * @param array $dependencies List of module names on which this module depends
1219 * @param string $group Group which the module is in.
1220 * @param string $source Source of the module, or 'local' if not foreign.
1221 * @param string $script JavaScript code
1224 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1225 $group, $source, $script
1227 $script = str_replace( "\n", "\n\t", trim( $script ) );
1228 return Xml
::encodeJsCall(
1229 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1230 array( $name, $version, $dependencies, $group, $source ),
1231 ResourceLoader
::inDebugMode()
1235 private static function isEmptyObject( stdClass
$obj ) {
1236 foreach ( $obj as $key => &$value ) {
1243 * Remove empty values from the end of an array.
1245 * Values considered empty:
1249 * - new XmlJsCode( '{}' )
1250 * - new stdClass() // (object) array()
1252 * @param Array $array
1254 private static function trimArray( Array &$array ) {
1255 $i = count( $array );
1257 if ( $array[$i] === null
1258 ||
$array[$i] === array()
1259 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1260 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1262 unset( $array[$i] );
1270 * Returns JS code which calls mw.loader.register with the given
1271 * parameters. Has three calling conventions:
1273 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1274 * $dependencies, $group, $source, $skip
1276 * Register a single module.
1278 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1279 * Register modules with the given names.
1281 * - ResourceLoader::makeLoaderRegisterScript( array(
1282 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1283 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1286 * Registers modules with the given names and parameters.
1288 * @param string $name Module name
1289 * @param string $version Module version hash
1290 * @param array $dependencies List of module names on which this module depends
1291 * @param string $group Group which the module is in
1292 * @param string $source Source of the module, or 'local' if not foreign
1293 * @param string $skip Script body of the skip function
1296 public static function makeLoaderRegisterScript( $name, $version = null,
1297 $dependencies = null, $group = null, $source = null, $skip = null
1299 if ( is_array( $name ) ) {
1300 // Build module name index
1302 foreach ( $name as $i => &$module ) {
1303 $index[$module[0]] = $i;
1306 // Transform dependency names into indexes when possible, they will be resolved by
1307 // mw.loader.register on the other end
1308 foreach ( $name as &$module ) {
1309 if ( isset( $module[2] ) ) {
1310 foreach ( $module[2] as &$dependency ) {
1311 if ( isset( $index[$dependency] ) ) {
1312 $dependency = $index[$dependency];
1318 array_walk( $name, array( 'self', 'trimArray' ) );
1320 return Xml
::encodeJsCall(
1321 'mw.loader.register',
1323 ResourceLoader
::inDebugMode()
1326 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1327 self
::trimArray( $registration );
1328 return Xml
::encodeJsCall(
1329 'mw.loader.register',
1331 ResourceLoader
::inDebugMode()
1337 * Returns JS code which calls mw.loader.addSource() with the given
1338 * parameters. Has two calling conventions:
1340 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1341 * Register a single source
1343 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1344 * Register sources with the given IDs and properties.
1346 * @param string $id Source ID
1347 * @param array $properties Source properties (see addSource())
1350 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1351 if ( is_array( $id ) ) {
1352 return Xml
::encodeJsCall(
1353 'mw.loader.addSource',
1355 ResourceLoader
::inDebugMode()
1358 return Xml
::encodeJsCall(
1359 'mw.loader.addSource',
1360 array( $id, $properties ),
1361 ResourceLoader
::inDebugMode()
1367 * Returns JS code which runs given JS code if the client-side framework is
1370 * @deprecated since 1.25; use makeInlineScript instead
1371 * @param string $script JavaScript code
1374 public static function makeLoaderConditionalScript( $script ) {
1375 return "var RLQ = RLQ || []; RLQ.push( function () {\n" . trim( $script ) . "\n} );";
1379 * Construct an inline script tag with given JS code.
1381 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1382 * only if the client has adequate support for MediaWiki JavaScript code.
1384 * @param string $script JavaScript code
1385 * @return string HTML
1387 public static function makeInlineScript( $script ) {
1388 $js = self
::makeLoaderConditionalScript( $script );
1389 return Html
::inlineScript( $js );
1393 * Returns JS code which will set the MediaWiki configuration array to
1396 * @param array $configuration List of configuration values keyed by variable name
1399 public static function makeConfigSetScript( array $configuration ) {
1400 return Xml
::encodeJsCall(
1402 array( $configuration ),
1403 ResourceLoader
::inDebugMode()
1408 * Convert an array of module names to a packed query string.
1410 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1411 * becomes 'foo.bar,baz|bar.baz,quux'
1412 * @param array $modules List of module names (strings)
1413 * @return string Packed query string
1415 public static function makePackedModulesString( $modules ) {
1416 $groups = array(); // array( prefix => array( suffixes ) )
1417 foreach ( $modules as $module ) {
1418 $pos = strrpos( $module, '.' );
1419 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1420 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1421 $groups[$prefix][] = $suffix;
1425 foreach ( $groups as $prefix => $suffixes ) {
1426 $p = $prefix === '' ?
'' : $prefix . '.';
1427 $arr[] = $p . implode( ',', $suffixes );
1429 $str = implode( '|', $arr );
1434 * Determine whether debug mode was requested
1435 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1438 public static function inDebugMode() {
1439 if ( self
::$debugMode === null ) {
1440 global $wgRequest, $wgResourceLoaderDebug;
1441 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1442 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1445 return self
::$debugMode;
1449 * Reset static members used for caching.
1451 * Global state and $wgRequest are evil, but we're using it right
1452 * now and sometimes we need to be able to force ResourceLoader to
1453 * re-evaluate the context because it has changed (e.g. in the test suite).
1455 public static function clearCache() {
1456 self
::$debugMode = null;
1460 * Build a load.php URL
1463 * @param string $source Name of the ResourceLoader source
1464 * @param ResourceLoaderContext $context
1465 * @param array $extraQuery
1466 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1468 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1469 $extraQuery = array()
1471 $query = self
::createLoaderQuery( $context, $extraQuery );
1472 $script = $this->getLoadScript( $source );
1474 // Prevent the IE6 extension check from being triggered (bug 28840)
1475 // by appending a character that's invalid in Windows extensions ('*')
1476 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1480 * Build a load.php URL
1481 * @deprecated since 1.24 Use createLoaderURL() instead
1482 * @param array $modules Array of module names (strings)
1483 * @param string $lang Language code
1484 * @param string $skin Skin name
1485 * @param string|null $user User name. If null, the &user= parameter is omitted
1486 * @param string|null $version Versioning timestamp
1487 * @param bool $debug Whether the request should be in debug mode
1488 * @param string|null $only &only= parameter
1489 * @param bool $printable Printable mode
1490 * @param bool $handheld Handheld mode
1491 * @param array $extraQuery Extra query parameters to add
1492 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1494 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1495 $version = null, $debug = false, $only = null, $printable = false,
1496 $handheld = false, $extraQuery = array()
1498 global $wgLoadScript;
1500 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1501 $only, $printable, $handheld, $extraQuery
1504 // Prevent the IE6 extension check from being triggered (bug 28840)
1505 // by appending a character that's invalid in Windows extensions ('*')
1506 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1510 * Helper for createLoaderURL()
1513 * @see makeLoaderQuery
1514 * @param ResourceLoaderContext $context
1515 * @param array $extraQuery
1518 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1519 return self
::makeLoaderQuery(
1520 $context->getModules(),
1521 $context->getLanguage(),
1522 $context->getSkin(),
1523 $context->getUser(),
1524 $context->getVersion(),
1525 $context->getDebug(),
1526 $context->getOnly(),
1527 $context->getRequest()->getBool( 'printable' ),
1528 $context->getRequest()->getBool( 'handheld' ),
1534 * Build a query array (array representation of query string) for load.php. Helper
1535 * function for makeLoaderURL().
1537 * @param array $modules
1538 * @param string $lang
1539 * @param string $skin
1540 * @param string $user
1541 * @param string $version
1542 * @param bool $debug
1543 * @param string $only
1544 * @param bool $printable
1545 * @param bool $handheld
1546 * @param array $extraQuery
1550 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1551 $version = null, $debug = false, $only = null, $printable = false,
1552 $handheld = false, $extraQuery = array()
1555 'modules' => self
::makePackedModulesString( $modules ),
1558 'debug' => $debug ?
'true' : 'false',
1560 if ( $user !== null ) {
1561 $query['user'] = $user;
1563 if ( $version !== null ) {
1564 $query['version'] = $version;
1566 if ( $only !== null ) {
1567 $query['only'] = $only;
1570 $query['printable'] = 1;
1573 $query['handheld'] = 1;
1575 $query +
= $extraQuery;
1577 // Make queries uniform in order
1583 * Check a module name for validity.
1585 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1586 * at most 255 bytes.
1588 * @param string $moduleName Module name to check
1589 * @return bool Whether $moduleName is a valid module name
1591 public static function isValidModuleName( $moduleName ) {
1592 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1596 * Returns LESS compiler set up for use with MediaWiki
1598 * @param Config $config
1599 * @throws MWException
1603 public static function getLessCompiler( Config
$config ) {
1604 // When called from the installer, it is possible that a required PHP extension
1605 // is missing (at least for now; see bug 47564). If this is the case, throw an
1606 // exception (caught by the installer) to prevent a fatal error later on.
1607 if ( !class_exists( 'lessc' ) ) {
1608 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1610 if ( !function_exists( 'ctype_digit' ) ) {
1611 throw new MWException( 'lessc requires the Ctype extension' );
1614 $less = new lessc();
1615 $less->setPreserveComments( true );
1616 $less->setVariables( self
::getLessVars( $config ) );
1617 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1618 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1619 $less->registerFunction( $name, $func );
1625 * Get global LESS variables.
1627 * @param Config $config
1629 * @return array Map of variable names to string CSS values.
1631 public static function getLessVars( Config
$config ) {
1632 if ( !self
::$lessVars ) {
1633 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1634 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1635 // Sort by key to ensure consistent hashing for cache lookups.
1637 self
::$lessVars = $lessVars;
1639 return self
::$lessVars;