5eab3cb66bebaf94692a27a6220e1931c1764b9c
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
26 * Dynamic JavaScript and CSS resource loading system.
28 * Most of the documentation is on the MediaWiki documentation wiki starting at:
29 * https://www.mediawiki.org/wiki/ResourceLoader
31 class ResourceLoader
{
33 protected static $filterCacheVersion = 7;
36 protected static $debugMode = null;
39 private static $lessVars = null;
42 * Module name/ResourceLoaderModule object pairs
45 protected $modules = array();
48 * Associative array mapping module name to info associative array
51 protected $moduleInfos = array();
53 /** @var Config $config */
57 * Associative array mapping framework ids to a list of names of test suite modules
58 * like array( 'qunit' => array( 'mediawiki.tests.qunit.suites', 'ext.foo.tests', .. ), .. )
61 protected $testModuleNames = array();
64 * E.g. array( 'source-id' => 'http://.../load.php' )
67 protected $sources = array();
70 * Errors accumulated during current respond() call.
73 protected $errors = array();
76 * Load information stored in the database about modules.
78 * This method grabs modules dependencies from the database and updates modules
81 * This is not inside the module code because it is much faster to
82 * request all of the information at once than it is to have each module
83 * requests its own information. This sacrifice of modularity yields a substantial
84 * performance improvement.
86 * @param array $modules List of module names to preload information for
87 * @param ResourceLoaderContext $context Context to load the information within
89 public function preloadModuleInfo( array $modules, ResourceLoaderContext
$context ) {
90 if ( !count( $modules ) ) {
91 // Or else Database*::select() will explode, plus it's cheaper!
94 $dbr = wfGetDB( DB_SLAVE
);
95 $skin = $context->getSkin();
96 $lang = $context->getLanguage();
98 // Get file dependency information
99 $res = $dbr->select( 'module_deps', array( 'md_module', 'md_deps' ), array(
100 'md_module' => $modules,
105 // Set modules' dependencies
106 $modulesWithDeps = array();
107 foreach ( $res as $row ) {
108 $module = $this->getModule( $row->md_module
);
110 $module->setFileDependencies( $skin, FormatJson
::decode( $row->md_deps
, true ) );
111 $modulesWithDeps[] = $row->md_module
;
115 // Register the absence of a dependency row too
116 foreach ( array_diff( $modules, $modulesWithDeps ) as $name ) {
117 $module = $this->getModule( $name );
119 $this->getModule( $name )->setFileDependencies( $skin, array() );
123 // Get message blob mtimes. Only do this for modules with messages
124 $modulesWithMessages = array();
125 foreach ( $modules as $name ) {
126 $module = $this->getModule( $name );
127 if ( $module && count( $module->getMessages() ) ) {
128 $modulesWithMessages[] = $name;
131 $modulesWithoutMessages = array_flip( $modules ); // Will be trimmed down by the loop below
132 if ( count( $modulesWithMessages ) ) {
133 $res = $dbr->select( 'msg_resource', array( 'mr_resource', 'mr_timestamp' ), array(
134 'mr_resource' => $modulesWithMessages,
138 foreach ( $res as $row ) {
139 $module = $this->getModule( $row->mr_resource
);
141 $module->setMsgBlobMtime( $lang, wfTimestamp( TS_UNIX
, $row->mr_timestamp
) );
142 unset( $modulesWithoutMessages[$row->mr_resource
] );
146 foreach ( array_keys( $modulesWithoutMessages ) as $name ) {
147 $module = $this->getModule( $name );
149 $module->setMsgBlobMtime( $lang, 1 );
155 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
157 * Available filters are:
159 * - minify-js \see JavaScriptMinifier::minify
160 * - minify-css \see CSSMin::minify
162 * If $data is empty, only contains whitespace or the filter was unknown,
163 * $data is returned unmodified.
165 * @param string $filter Name of filter to run
166 * @param string $data Text to filter, such as JavaScript or CSS text
167 * @param string $cacheReport Whether to include the cache key report
168 * @return string Filtered data, or a comment containing an error message
170 public function filter( $filter, $data, $cacheReport = true ) {
172 // For empty/whitespace-only data or for unknown filters, don't perform
173 // any caching or processing
174 if ( trim( $data ) === '' ||
!in_array( $filter, array( 'minify-js', 'minify-css' ) ) ) {
179 // Use CACHE_ANYTHING since filtering is very slow compared to DB queries
180 $key = wfMemcKey( 'resourceloader', 'filter', $filter, self
::$filterCacheVersion, md5( $data ) );
181 $cache = wfGetCache( CACHE_ANYTHING
);
182 $cacheEntry = $cache->get( $key );
183 if ( is_string( $cacheEntry ) ) {
184 wfIncrStats( "rl-$filter-cache-hits" );
189 // Run the filter - we've already verified one of these will work
191 wfIncrStats( "rl-$filter-cache-misses" );
194 $result = JavaScriptMinifier
::minify( $data,
195 $this->config
->get( 'ResourceLoaderMinifierStatementsOnOwnLine' ),
196 $this->config
->get( 'ResourceLoaderMinifierMaxLineLength' )
198 if ( $cacheReport ) {
199 $result .= "\n/* cache key: $key */";
203 $result = CSSMin
::minify( $data );
204 if ( $cacheReport ) {
205 $result .= "\n/* cache key: $key */";
210 // Save filtered text to Memcached
211 $cache->set( $key, $result );
212 } catch ( Exception
$e ) {
213 MWExceptionHandler
::logException( $e );
214 wfDebugLog( 'resourceloader', __METHOD__
. ": minification failed: $e" );
215 $this->errors
[] = self
::formatExceptionNoComment( $e );
224 * Register core modules and runs registration hooks.
225 * @param Config|null $config
227 public function __construct( Config
$config = null ) {
230 if ( $config === null ) {
231 wfDebug( __METHOD__
. ' was called without providing a Config instance' );
232 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
235 $this->config
= $config;
237 // Add 'local' source first
238 $this->addSource( 'local', wfScript( 'load' ) );
241 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
243 // Register core modules
244 $this->register( include "$IP/resources/Resources.php" );
245 // Register extension modules
246 Hooks
::run( 'ResourceLoaderRegisterModules', array( &$this ) );
247 $this->register( $config->get( 'ResourceModules' ) );
249 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
250 $this->registerTestModules();
258 public function getConfig() {
259 return $this->config
;
263 * Register a module with the ResourceLoader system.
265 * @param mixed $name Name of module as a string or List of name/object pairs as an array
266 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
267 * this may also be a ResourceLoaderModule object. Optional when using
268 * multiple-registration calling style.
269 * @throws MWException If a duplicate module registration is attempted
270 * @throws MWException If a module name contains illegal characters (pipes or commas)
271 * @throws MWException If something other than a ResourceLoaderModule is being registered
272 * @return bool False if there were any errors, in which case one or more modules were
275 public function register( $name, $info = null ) {
277 // Allow multiple modules to be registered in one call
278 $registrations = is_array( $name ) ?
$name : array( $name => $info );
279 foreach ( $registrations as $name => $info ) {
280 // Disallow duplicate registrations
281 if ( isset( $this->moduleInfos
[$name] ) ) {
282 // A module has already been registered by this name
283 throw new MWException(
284 'ResourceLoader duplicate registration error. ' .
285 'Another module has already been registered as ' . $name
289 // Check $name for validity
290 if ( !self
::isValidModuleName( $name ) ) {
291 throw new MWException( "ResourceLoader module name '$name' is invalid, "
292 . "see ResourceLoader::isValidModuleName()" );
296 if ( $info instanceof ResourceLoaderModule
) {
297 $this->moduleInfos
[$name] = array( 'object' => $info );
298 $info->setName( $name );
299 $this->modules
[$name] = $info;
300 } elseif ( is_array( $info ) ) {
301 // New calling convention
302 $this->moduleInfos
[$name] = $info;
304 throw new MWException(
305 'ResourceLoader module info type error for module \'' . $name .
306 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
310 // Last-minute changes
312 // Apply custom skin-defined styles to existing modules.
313 if ( $this->isFileModule( $name ) ) {
314 foreach ( $this->config
->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
315 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
316 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
320 // If $name is preceded with a '+', the defined style files will be added to 'default'
321 // skinStyles, otherwise 'default' will be ignored as it normally would be.
322 if ( isset( $skinStyles[$name] ) ) {
323 $paths = (array)$skinStyles[$name];
324 $styleFiles = array();
325 } elseif ( isset( $skinStyles['+' . $name] ) ) {
326 $paths = (array)$skinStyles['+' . $name];
327 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
328 $this->moduleInfos
[$name]['skinStyles']['default'] :
334 // Add new file paths, remapping them to refer to our directories and not use settings
335 // from the module we're modifying. These can come from the base definition or be defined
337 list( $localBasePath, $remoteBasePath ) =
338 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
339 list( $localBasePath, $remoteBasePath ) =
340 ResourceLoaderFileModule
::extractBasePaths( $paths, $localBasePath, $remoteBasePath );
342 foreach ( $paths as $path ) {
343 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
346 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
355 public function registerTestModules() {
358 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
359 throw new MWException( 'Attempt to register JavaScript test modules '
360 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
361 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
364 // Get core test suites
365 $testModules = array();
366 $testModules['qunit'] = array();
367 // Get other test suites (e.g. from extensions)
368 Hooks
::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
370 // Add the testrunner (which configures QUnit) to the dependencies.
371 // Since it must be ready before any of the test suites are executed.
372 foreach ( $testModules['qunit'] as &$module ) {
373 // Make sure all test modules are top-loading so that when QUnit starts
374 // on document-ready, it will run once and finish. If some tests arrive
375 // later (possibly after QUnit has already finished) they will be ignored.
376 $module['position'] = 'top';
377 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
380 $testModules['qunit'] =
381 ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules['qunit'];
383 foreach ( $testModules as $id => $names ) {
384 // Register test modules
385 $this->register( $testModules[$id] );
387 // Keep track of their names so that they can be loaded together
388 $this->testModuleNames
[$id] = array_keys( $testModules[$id] );
394 * Add a foreign source of modules.
396 * @param array|string $id Source ID (string), or array( id1 => loadUrl, id2 => loadUrl, ... )
397 * @param string|array $loadUrl load.php url (string), or array with loadUrl key for
398 * backwards-compatibility.
399 * @throws MWException
401 public function addSource( $id, $loadUrl = null ) {
402 // Allow multiple sources to be registered in one call
403 if ( is_array( $id ) ) {
404 foreach ( $id as $key => $value ) {
405 $this->addSource( $key, $value );
410 // Disallow duplicates
411 if ( isset( $this->sources
[$id] ) ) {
412 throw new MWException(
413 'ResourceLoader duplicate source addition error. ' .
414 'Another source has already been registered as ' . $id
418 // Pre 1.24 backwards-compatibility
419 if ( is_array( $loadUrl ) ) {
420 if ( !isset( $loadUrl['loadScript'] ) ) {
421 throw new MWException(
422 __METHOD__
. ' was passed an array with no "loadScript" key.'
426 $loadUrl = $loadUrl['loadScript'];
429 $this->sources
[$id] = $loadUrl;
433 * Get a list of module names.
435 * @return array List of module names
437 public function getModuleNames() {
438 return array_keys( $this->moduleInfos
);
442 * Get a list of test module names for one (or all) frameworks.
444 * If the given framework id is unknkown, or if the in-object variable is not an array,
445 * then it will return an empty array.
447 * @param string $framework Get only the test module names for one
448 * particular framework (optional)
451 public function getTestModuleNames( $framework = 'all' ) {
452 /** @todo api siteinfo prop testmodulenames modulenames */
453 if ( $framework == 'all' ) {
454 return $this->testModuleNames
;
455 } elseif ( isset( $this->testModuleNames
[$framework] )
456 && is_array( $this->testModuleNames
[$framework] )
458 return $this->testModuleNames
[$framework];
465 * Check whether a ResourceLoader module is registered
468 * @param string $name
471 public function isModuleRegistered( $name ) {
472 return isset( $this->moduleInfos
[$name] );
476 * Get the ResourceLoaderModule object for a given module name.
478 * If an array of module parameters exists but a ResourceLoaderModule object has not
479 * yet been instantiated, this method will instantiate and cache that object such that
480 * subsequent calls simply return the same object.
482 * @param string $name Module name
483 * @return ResourceLoaderModule|null If module has been registered, return a
484 * ResourceLoaderModule instance. Otherwise, return null.
486 public function getModule( $name ) {
487 if ( !isset( $this->modules
[$name] ) ) {
488 if ( !isset( $this->moduleInfos
[$name] ) ) {
492 // Construct the requested object
493 $info = $this->moduleInfos
[$name];
494 /** @var ResourceLoaderModule $object */
495 if ( isset( $info['object'] ) ) {
496 // Object given in info array
497 $object = $info['object'];
499 if ( !isset( $info['class'] ) ) {
500 $class = 'ResourceLoaderFileModule';
502 $class = $info['class'];
504 /** @var ResourceLoaderModule $object */
505 $object = new $class( $info );
506 $object->setConfig( $this->getConfig() );
508 $object->setName( $name );
509 $this->modules
[$name] = $object;
512 return $this->modules
[$name];
516 * Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
518 * @param string $name Module name
521 protected function isFileModule( $name ) {
522 if ( !isset( $this->moduleInfos
[$name] ) ) {
525 $info = $this->moduleInfos
[$name];
526 if ( isset( $info['object'] ) ||
isset( $info['class'] ) ) {
533 * Get the list of sources.
535 * @return array Like array( id => load.php url, .. )
537 public function getSources() {
538 return $this->sources
;
542 * Get the URL to the load.php endpoint for the given
543 * ResourceLoader source
546 * @param string $source
547 * @throws MWException On an invalid $source name
550 public function getLoadScript( $source ) {
551 if ( !isset( $this->sources
[$source] ) ) {
552 throw new MWException( "The $source source was never registered in ResourceLoader." );
554 return $this->sources
[$source];
558 * Output a response to a load request, including the content-type header.
560 * @param ResourceLoaderContext $context Context in which a response should be formed
562 public function respond( ResourceLoaderContext
$context ) {
563 // Use file cache if enabled and available...
564 if ( $this->config
->get( 'UseFileCache' ) ) {
565 $fileCache = ResourceFileCache
::newFromContext( $context );
566 if ( $this->tryRespondFromFileCache( $fileCache, $context ) ) {
567 return; // output handled
571 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
572 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
573 // is used: ob_clean() will clear the GZIP header in that case and it won't come
574 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
575 // the whole thing in our own output buffer to be sure the active buffer
576 // doesn't use ob_gzhandler.
577 // See http://bugs.php.net/bug.php?id=36514
580 // Find out which modules are missing and instantiate the others
583 foreach ( $context->getModules() as $name ) {
584 $module = $this->getModule( $name );
586 // Do not allow private modules to be loaded from the web.
587 // This is a security issue, see bug 34907.
588 if ( $module->getGroup() === 'private' ) {
589 wfDebugLog( 'resourceloader', __METHOD__
. ": request for private module '$name' denied" );
590 $this->errors
[] = "Cannot show private module \"$name\"";
593 $modules[$name] = $module;
599 // Preload information needed to the mtime calculation below
601 $this->preloadModuleInfo( array_keys( $modules ), $context );
602 } catch ( Exception
$e ) {
603 MWExceptionHandler
::logException( $e );
604 wfDebugLog( 'resourceloader', __METHOD__
. ": preloading module info failed: $e" );
605 $this->errors
[] = self
::formatExceptionNoComment( $e );
608 // To send Last-Modified and support If-Modified-Since, we need to detect
609 // the last modified time
610 $mtime = wfTimestamp( TS_UNIX
, $this->config
->get( 'CacheEpoch' ) );
611 foreach ( $modules as $module ) {
613 * @var $module ResourceLoaderModule
616 // Calculate maximum modified time
617 $mtime = max( $mtime, $module->getModifiedTime( $context ) );
618 } catch ( Exception
$e ) {
619 MWExceptionHandler
::logException( $e );
620 wfDebugLog( 'resourceloader', __METHOD__
. ": calculating maximum modified time failed: $e" );
621 $this->errors
[] = self
::formatExceptionNoComment( $e );
625 // If there's an If-Modified-Since header, respond with a 304 appropriately
626 if ( $this->tryRespondLastModified( $context, $mtime ) ) {
627 return; // output handled (buffers cleared)
630 // Generate a response
631 $response = $this->makeModuleResponse( $context, $modules, $missing );
633 // Capture any PHP warnings from the output buffer and append them to the
634 // error list if we're in debug mode.
635 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
636 $this->errors
[] = $warnings;
639 // Save response to file cache unless there are errors
640 if ( isset( $fileCache ) && !$this->errors
&& !count( $missing ) ) {
641 // Cache single modules and images...and other requests if there are enough hits
642 if ( ResourceFileCache
::useFileCache( $context ) ) {
643 if ( $fileCache->isCacheWorthy() ) {
644 $fileCache->saveText( $response );
646 $fileCache->incrMissesRecent( $context->getRequest() );
651 // Send content type and cache related headers
652 $this->sendResponseHeaders( $context, $mtime, (bool)$this->errors
);
654 // Remove the output buffer and output the response
657 if ( $context->getImageObj() && $this->errors
) {
658 // We can't show both the error messages and the response when it's an image.
660 foreach ( $this->errors
as $error ) {
661 $errorText .= $error . "\n";
663 $response = $errorText;
664 } elseif ( $this->errors
) {
665 // Prepend comments indicating errors
667 foreach ( $this->errors
as $error ) {
668 $errorText .= self
::makeComment( $error );
670 $response = $errorText . $response;
673 $this->errors
= array();
679 * Send content type and last modified headers to the client.
680 * @param ResourceLoaderContext $context
681 * @param string $mtime TS_MW timestamp to use for last-modified
682 * @param bool $errors Whether there are errors in the response
685 protected function sendResponseHeaders( ResourceLoaderContext
$context, $mtime, $errors ) {
686 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
687 // If a version wasn't specified we need a shorter expiry time for updates
688 // to propagate to clients quickly
689 // If there were errors, we also need a shorter expiry time so we can recover quickly
690 if ( is_null( $context->getVersion() ) ||
$errors ) {
691 $maxage = $rlMaxage['unversioned']['client'];
692 $smaxage = $rlMaxage['unversioned']['server'];
693 // If a version was specified we can use a longer expiry time since changing
694 // version numbers causes cache misses
696 $maxage = $rlMaxage['versioned']['client'];
697 $smaxage = $rlMaxage['versioned']['server'];
699 if ( $context->getImageObj() ) {
700 // Output different headers if we're outputting textual errors.
702 header( 'Content-Type: text/plain; charset=utf-8' );
704 $context->getImageObj()->sendResponseHeaders( $context );
706 } elseif ( $context->getOnly() === 'styles' ) {
707 header( 'Content-Type: text/css; charset=utf-8' );
708 header( 'Access-Control-Allow-Origin: *' );
710 header( 'Content-Type: text/javascript; charset=utf-8' );
712 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $mtime ) );
713 if ( $context->getDebug() ) {
714 // Do not cache debug responses
715 header( 'Cache-Control: private, no-cache, must-revalidate' );
716 header( 'Pragma: no-cache' );
718 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
719 $exp = min( $maxage, $smaxage );
720 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
725 * Respond with 304 Last Modified if appropiate.
727 * If there's an If-Modified-Since header, respond with a 304 appropriately
728 * and clear out the output buffer. If the client cache is too old then do nothing.
730 * @param ResourceLoaderContext $context
731 * @param string $mtime The TS_MW timestamp to check the header against
732 * @return bool True if 304 header sent and output handled
734 protected function tryRespondLastModified( ResourceLoaderContext
$context, $mtime ) {
735 // If there's an If-Modified-Since header, respond with a 304 appropriately
736 // Some clients send "timestamp;length=123". Strip the part after the first ';'
737 // so we get a valid timestamp.
738 $ims = $context->getRequest()->getHeader( 'If-Modified-Since' );
739 // Never send 304s in debug mode
740 if ( $ims !== false && !$context->getDebug() ) {
741 $imsTS = strtok( $ims, ';' );
742 if ( $mtime <= wfTimestamp( TS_UNIX
, $imsTS ) ) {
743 // There's another bug in ob_gzhandler (see also the comment at
744 // the top of this function) that causes it to gzip even empty
745 // responses, meaning it's impossible to produce a truly empty
746 // response (because the gzip header is always there). This is
747 // a problem because 304 responses have to be completely empty
748 // per the HTTP spec, and Firefox behaves buggily when they're not.
749 // See also http://bugs.php.net/bug.php?id=51579
750 // To work around this, we tear down all output buffering before
752 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
754 header( 'HTTP/1.0 304 Not Modified' );
755 header( 'Status: 304 Not Modified' );
763 * Send out code for a response from file cache if possible.
765 * @param ResourceFileCache $fileCache Cache object for this request URL
766 * @param ResourceLoaderContext $context Context in which to generate a response
767 * @return bool If this found a cache file and handled the response
769 protected function tryRespondFromFileCache(
770 ResourceFileCache
$fileCache, ResourceLoaderContext
$context
772 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
773 // Buffer output to catch warnings.
775 // Get the maximum age the cache can be
776 $maxage = is_null( $context->getVersion() )
777 ?
$rlMaxage['unversioned']['server']
778 : $rlMaxage['versioned']['server'];
779 // Minimum timestamp the cache file must have
780 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
782 try { // RL always hits the DB on file cache miss...
784 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
785 $good = $fileCache->isCacheGood(); // cache existence check
789 $ts = $fileCache->cacheTimestamp();
790 // Send content type and cache headers
791 $this->sendResponseHeaders( $context, $ts, false );
792 // If there's an If-Modified-Since header, respond with a 304 appropriately
793 if ( $this->tryRespondLastModified( $context, $ts ) ) {
794 return false; // output handled (buffers cleared)
796 $response = $fileCache->fetchText();
797 // Capture any PHP warnings from the output buffer and append them to the
798 // response in a comment if we're in debug mode.
799 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
800 $response = "/*\n$warnings\n*/\n" . $response;
802 // Remove the output buffer and output the response
804 echo $response . "\n/* Cached {$ts} */";
805 return true; // cache hit
810 return false; // cache miss
814 * Generate a CSS or JS comment block.
816 * Only use this for public data, not error message details.
818 * @param string $text
821 public static function makeComment( $text ) {
822 $encText = str_replace( '*/', '* /', $text );
823 return "/*\n$encText\n*/\n";
827 * Handle exception display.
829 * @param Exception $e Exception to be shown to the user
830 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
832 public static function formatException( $e ) {
833 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
837 * Handle exception display.
840 * @param Exception $e Exception to be shown to the user
841 * @return string Sanitized text that can be returned to the user
843 protected static function formatExceptionNoComment( $e ) {
844 global $wgShowExceptionDetails;
846 if ( $wgShowExceptionDetails ) {
847 return $e->__toString();
849 return wfMessage( 'internalerror' )->text();
854 * Generate code for a response.
856 * @param ResourceLoaderContext $context Context in which to generate a response
857 * @param array $modules List of module objects keyed by module name
858 * @param array $missing List of requested module names that are unregistered (optional)
859 * @return string Response data
861 public function makeModuleResponse( ResourceLoaderContext
$context,
862 array $modules, array $missing = array()
867 if ( !count( $modules ) && !count( $missing ) ) {
869 /* This file is the Web entry point for MediaWiki's ResourceLoader:
870 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
871 no modules were requested. Max made me put this here. */
875 $image = $context->getImageObj();
877 $data = $image->getImageData( $context );
878 if ( $data === false ) {
880 $this->errors
[] = 'Image generation failed';
886 if ( $context->shouldIncludeMessages() ) {
888 $blobs = MessageBlobStore
::getInstance()->get( $this, $modules, $context->getLanguage() );
889 } catch ( Exception
$e ) {
890 MWExceptionHandler
::logException( $e );
893 __METHOD__
. ": pre-fetching blobs from MessageBlobStore failed: $e"
895 $this->errors
[] = self
::formatExceptionNoComment( $e );
901 foreach ( $missing as $name ) {
902 $states[$name] = 'missing';
907 foreach ( $modules as $name => $module ) {
909 * @var $module ResourceLoaderModule
914 if ( $context->shouldIncludeScripts() ) {
915 // If we are in debug mode, we'll want to return an array of URLs if possible
916 // However, we can't do this if the module doesn't support it
917 // We also can't do this if there is an only= parameter, because we have to give
918 // the module a way to return a load.php URL without causing an infinite loop
919 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
920 $scripts = $module->getScriptURLsForDebug( $context );
922 $scripts = $module->getScript( $context );
923 // rtrim() because there are usually a few line breaks
924 // after the last ';'. A new line at EOF, a new line
925 // added by ResourceLoaderFileModule::readScriptFiles, etc.
926 if ( is_string( $scripts )
927 && strlen( $scripts )
928 && substr( rtrim( $scripts ), -1 ) !== ';'
930 // Append semicolon to prevent weird bugs caused by files not
931 // terminating their statements right (bug 27054)
938 if ( $context->shouldIncludeStyles() ) {
939 // Don't create empty stylesheets like array( '' => '' ) for modules
940 // that don't *have* any stylesheets (bug 38024).
941 $stylePairs = $module->getStyles( $context );
942 if ( count( $stylePairs ) ) {
943 // If we are in debug mode without &only= set, we'll want to return an array of URLs
944 // See comment near shouldIncludeScripts() for more details
945 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
947 'url' => $module->getStyleURLsForDebug( $context )
950 // Minify CSS before embedding in mw.loader.implement call
951 // (unless in debug mode)
952 if ( !$context->getDebug() ) {
953 foreach ( $stylePairs as $media => $style ) {
954 // Can be either a string or an array of strings.
955 if ( is_array( $style ) ) {
956 $stylePairs[$media] = array();
957 foreach ( $style as $cssText ) {
958 if ( is_string( $cssText ) ) {
959 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
962 } elseif ( is_string( $style ) ) {
963 $stylePairs[$media] = $this->filter( 'minify-css', $style );
967 // Wrap styles into @media groups as needed and flatten into a numerical array
969 'css' => self
::makeCombinedStyles( $stylePairs )
976 $messagesBlob = isset( $blobs[$name] ) ?
$blobs[$name] : '{}';
979 switch ( $context->getOnly() ) {
981 if ( is_string( $scripts ) ) {
982 // Load scripts raw...
984 } elseif ( is_array( $scripts ) ) {
985 // ...except when $scripts is an array of URLs
986 $out .= self
::makeLoaderImplementScript( $name, $scripts, array(), array() );
990 // We no longer seperate into media, they are all combined now with
991 // custom media type groups into @media .. {} sections as part of the css string.
992 // Module returns either an empty array or a numerical array with css strings.
993 $out .= isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
996 $out .= self
::makeMessageSetScript( new XmlJsCode( $messagesBlob ) );
999 $out .= Xml
::encodeJsCall(
1001 array( $name, (object)$module->getTemplates() ),
1002 ResourceLoader
::inDebugMode()
1006 $out .= self
::makeLoaderImplementScript(
1010 new XmlJsCode( $messagesBlob ),
1011 $module->getTemplates()
1015 } catch ( Exception
$e ) {
1016 MWExceptionHandler
::logException( $e );
1017 wfDebugLog( 'resourceloader', __METHOD__
. ": generating module package failed: $e" );
1018 $this->errors
[] = self
::formatExceptionNoComment( $e );
1020 // Respond to client with error-state instead of module implementation
1021 $states[$name] = 'error';
1022 unset( $modules[$name] );
1024 $isRaw |
= $module->isRaw();
1027 // Update module states
1028 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1029 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1030 // Set the state of modules loaded as only scripts to ready as
1031 // they don't have an mw.loader.implement wrapper that sets the state
1032 foreach ( $modules as $name => $module ) {
1033 $states[$name] = 'ready';
1037 // Set the state of modules we didn't respond to with mw.loader.implement
1038 if ( count( $states ) ) {
1039 $out .= self
::makeLoaderStateScript( $states );
1042 if ( count( $states ) ) {
1043 $this->errors
[] = 'Problematic modules: ' .
1044 FormatJson
::encode( $states, ResourceLoader
::inDebugMode() );
1048 if ( !$context->getDebug() ) {
1049 if ( $context->getOnly() === 'styles' ) {
1050 $out = $this->filter( 'minify-css', $out );
1052 $out = $this->filter( 'minify-js', $out );
1059 /* Static Methods */
1062 * Return JS code that calls mw.loader.implement with given module properties.
1064 * @param string $name Module name
1065 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1066 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1067 * to CSS files keyed by media type
1068 * @param mixed $messages List of messages associated with this module. May either be an
1069 * associative array mapping message key to value, or a JSON-encoded message blob containing
1070 * the same data, wrapped in an XmlJsCode object.
1071 * @param array $templates Keys are name of templates and values are the source of
1073 * @throws MWException
1076 public static function makeLoaderImplementScript( $name, $scripts, $styles,
1077 $messages, $templates
1079 if ( is_string( $scripts ) ) {
1080 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1081 } elseif ( !is_array( $scripts ) ) {
1082 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1085 return Xml
::encodeJsCall(
1086 'mw.loader.implement',
1090 // Force objects. mw.loader.implement requires them to be javascript objects.
1091 // Although these variables are associative arrays, which become javascript
1092 // objects through json_encode. In many cases they will be empty arrays, and
1093 // PHP/json_encode() consider empty arrays to be numerical arrays and
1094 // output javascript "[]" instead of "{}". This fixes that.
1099 ResourceLoader
::inDebugMode()
1104 * Returns JS code which, when called, will register a given list of messages.
1106 * @param mixed $messages Either an associative array mapping message key to value, or a
1107 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1110 public static function makeMessageSetScript( $messages ) {
1111 return Xml
::encodeJsCall(
1113 array( (object)$messages ),
1114 ResourceLoader
::inDebugMode()
1119 * Combines an associative array mapping media type to CSS into a
1120 * single stylesheet with "@media" blocks.
1122 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1125 public static function makeCombinedStyles( array $stylePairs ) {
1127 foreach ( $stylePairs as $media => $styles ) {
1128 // ResourceLoaderFileModule::getStyle can return the styles
1129 // as a string or an array of strings. This is to allow separation in
1131 $styles = (array)$styles;
1132 foreach ( $styles as $style ) {
1133 $style = trim( $style );
1134 // Don't output an empty "@media print { }" block (bug 40498)
1135 if ( $style !== '' ) {
1136 // Transform the media type based on request params and config
1137 // The way that this relies on $wgRequest to propagate request params is slightly evil
1138 $media = OutputPage
::transformCssMedia( $media );
1140 if ( $media === '' ||
$media == 'all' ) {
1142 } elseif ( is_string( $media ) ) {
1143 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1153 * Returns a JS call to mw.loader.state, which sets the state of a
1154 * module or modules to a given value. Has two calling conventions:
1156 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1157 * Set the state of a single module called $name to $state
1159 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1160 * Set the state of modules with the given names to the given states
1162 * @param string $name
1163 * @param string $state
1166 public static function makeLoaderStateScript( $name, $state = null ) {
1167 if ( is_array( $name ) ) {
1168 return Xml
::encodeJsCall(
1171 ResourceLoader
::inDebugMode()
1174 return Xml
::encodeJsCall(
1176 array( $name, $state ),
1177 ResourceLoader
::inDebugMode()
1183 * Returns JS code which calls the script given by $script. The script will
1184 * be called with local variables name, version, dependencies and group,
1185 * which will have values corresponding to $name, $version, $dependencies
1186 * and $group as supplied.
1188 * @param string $name Module name
1189 * @param int $version Module version number as a timestamp
1190 * @param array $dependencies List of module names on which this module depends
1191 * @param string $group Group which the module is in.
1192 * @param string $source Source of the module, or 'local' if not foreign.
1193 * @param string $script JavaScript code
1196 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1197 $group, $source, $script
1199 $script = str_replace( "\n", "\n\t", trim( $script ) );
1200 return Xml
::encodeJsCall(
1201 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1202 array( $name, $version, $dependencies, $group, $source ),
1203 ResourceLoader
::inDebugMode()
1208 * Remove empty values from the end of an array.
1210 * Values considered empty:
1215 * @param Array $array
1217 private static function trimArray( Array &$array ) {
1218 $i = count( $array );
1220 if ( $array[$i] === null ||
$array[$i] === array() ) {
1221 unset( $array[$i] );
1229 * Returns JS code which calls mw.loader.register with the given
1230 * parameters. Has three calling conventions:
1232 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1233 * $dependencies, $group, $source, $skip
1235 * Register a single module.
1237 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1238 * Register modules with the given names.
1240 * - ResourceLoader::makeLoaderRegisterScript( array(
1241 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1242 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1245 * Registers modules with the given names and parameters.
1247 * @param string $name Module name
1248 * @param int $version Module version number as a timestamp
1249 * @param array $dependencies List of module names on which this module depends
1250 * @param string $group Group which the module is in
1251 * @param string $source Source of the module, or 'local' if not foreign
1252 * @param string $skip Script body of the skip function
1255 public static function makeLoaderRegisterScript( $name, $version = null,
1256 $dependencies = null, $group = null, $source = null, $skip = null
1258 if ( is_array( $name ) ) {
1259 // Build module name index
1261 foreach ( $name as $i => &$module ) {
1262 $index[$module[0]] = $i;
1265 // Transform dependency names into indexes when possible, they will be resolved by
1266 // mw.loader.register on the other end
1267 foreach ( $name as &$module ) {
1268 if ( isset( $module[2] ) ) {
1269 foreach ( $module[2] as &$dependency ) {
1270 if ( isset( $index[$dependency] ) ) {
1271 $dependency = $index[$dependency];
1277 array_walk( $name, array( 'self', 'trimArray' ) );
1279 return Xml
::encodeJsCall(
1280 'mw.loader.register',
1282 ResourceLoader
::inDebugMode()
1285 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1286 self
::trimArray( $registration );
1287 return Xml
::encodeJsCall(
1288 'mw.loader.register',
1290 ResourceLoader
::inDebugMode()
1296 * Returns JS code which calls mw.loader.addSource() with the given
1297 * parameters. Has two calling conventions:
1299 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1300 * Register a single source
1302 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1303 * Register sources with the given IDs and properties.
1305 * @param string $id Source ID
1306 * @param array $properties Source properties (see addSource())
1309 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1310 if ( is_array( $id ) ) {
1311 return Xml
::encodeJsCall(
1312 'mw.loader.addSource',
1314 ResourceLoader
::inDebugMode()
1317 return Xml
::encodeJsCall(
1318 'mw.loader.addSource',
1319 array( $id, $properties ),
1320 ResourceLoader
::inDebugMode()
1326 * Returns JS code which runs given JS code if the client-side framework is
1329 * @param string $script JavaScript code
1332 public static function makeLoaderConditionalScript( $script ) {
1333 return "if(window.mw){\n" . trim( $script ) . "\n}";
1337 * Returns JS code which will set the MediaWiki configuration array to
1340 * @param array $configuration List of configuration values keyed by variable name
1343 public static function makeConfigSetScript( array $configuration ) {
1344 return Xml
::encodeJsCall(
1346 array( $configuration ),
1347 ResourceLoader
::inDebugMode()
1352 * Convert an array of module names to a packed query string.
1354 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1355 * becomes 'foo.bar,baz|bar.baz,quux'
1356 * @param array $modules List of module names (strings)
1357 * @return string Packed query string
1359 public static function makePackedModulesString( $modules ) {
1360 $groups = array(); // array( prefix => array( suffixes ) )
1361 foreach ( $modules as $module ) {
1362 $pos = strrpos( $module, '.' );
1363 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1364 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1365 $groups[$prefix][] = $suffix;
1369 foreach ( $groups as $prefix => $suffixes ) {
1370 $p = $prefix === '' ?
'' : $prefix . '.';
1371 $arr[] = $p . implode( ',', $suffixes );
1373 $str = implode( '|', $arr );
1378 * Determine whether debug mode was requested
1379 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1382 public static function inDebugMode() {
1383 if ( self
::$debugMode === null ) {
1384 global $wgRequest, $wgResourceLoaderDebug;
1385 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1386 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1389 return self
::$debugMode;
1393 * Reset static members used for caching.
1395 * Global state and $wgRequest are evil, but we're using it right
1396 * now and sometimes we need to be able to force ResourceLoader to
1397 * re-evaluate the context because it has changed (e.g. in the test suite).
1399 public static function clearCache() {
1400 self
::$debugMode = null;
1404 * Build a load.php URL
1407 * @param string $source Name of the ResourceLoader source
1408 * @param ResourceLoaderContext $context
1409 * @param array $extraQuery
1410 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1412 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1413 $extraQuery = array()
1415 $query = self
::createLoaderQuery( $context, $extraQuery );
1416 $script = $this->getLoadScript( $source );
1418 // Prevent the IE6 extension check from being triggered (bug 28840)
1419 // by appending a character that's invalid in Windows extensions ('*')
1420 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE
);
1424 * Build a load.php URL
1425 * @deprecated since 1.24, use createLoaderURL instead
1426 * @param array $modules Array of module names (strings)
1427 * @param string $lang Language code
1428 * @param string $skin Skin name
1429 * @param string|null $user User name. If null, the &user= parameter is omitted
1430 * @param string|null $version Versioning timestamp
1431 * @param bool $debug Whether the request should be in debug mode
1432 * @param string|null $only &only= parameter
1433 * @param bool $printable Printable mode
1434 * @param bool $handheld Handheld mode
1435 * @param array $extraQuery Extra query parameters to add
1436 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1438 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1439 $version = null, $debug = false, $only = null, $printable = false,
1440 $handheld = false, $extraQuery = array()
1442 global $wgLoadScript;
1444 $query = self
::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1445 $only, $printable, $handheld, $extraQuery
1448 // Prevent the IE6 extension check from being triggered (bug 28840)
1449 // by appending a character that's invalid in Windows extensions ('*')
1450 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE
);
1454 * Helper for createLoaderURL()
1457 * @see makeLoaderQuery
1458 * @param ResourceLoaderContext $context
1459 * @param array $extraQuery
1462 public static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = array() ) {
1463 return self
::makeLoaderQuery(
1464 $context->getModules(),
1465 $context->getLanguage(),
1466 $context->getSkin(),
1467 $context->getUser(),
1468 $context->getVersion(),
1469 $context->getDebug(),
1470 $context->getOnly(),
1471 $context->getRequest()->getBool( 'printable' ),
1472 $context->getRequest()->getBool( 'handheld' ),
1478 * Build a query array (array representation of query string) for load.php. Helper
1479 * function for makeLoaderURL().
1481 * @param array $modules
1482 * @param string $lang
1483 * @param string $skin
1484 * @param string $user
1485 * @param string $version
1486 * @param bool $debug
1487 * @param string $only
1488 * @param bool $printable
1489 * @param bool $handheld
1490 * @param array $extraQuery
1494 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1495 $version = null, $debug = false, $only = null, $printable = false,
1496 $handheld = false, $extraQuery = array()
1499 'modules' => self
::makePackedModulesString( $modules ),
1502 'debug' => $debug ?
'true' : 'false',
1504 if ( $user !== null ) {
1505 $query['user'] = $user;
1507 if ( $version !== null ) {
1508 $query['version'] = $version;
1510 if ( $only !== null ) {
1511 $query['only'] = $only;
1514 $query['printable'] = 1;
1517 $query['handheld'] = 1;
1519 $query +
= $extraQuery;
1521 // Make queries uniform in order
1527 * Check a module name for validity.
1529 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1530 * at most 255 bytes.
1532 * @param string $moduleName Module name to check
1533 * @return bool Whether $moduleName is a valid module name
1535 public static function isValidModuleName( $moduleName ) {
1536 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1540 * Returns LESS compiler set up for use with MediaWiki
1542 * @param Config $config
1543 * @throws MWException
1547 public static function getLessCompiler( Config
$config ) {
1548 // When called from the installer, it is possible that a required PHP extension
1549 // is missing (at least for now; see bug 47564). If this is the case, throw an
1550 // exception (caught by the installer) to prevent a fatal error later on.
1551 if ( !class_exists( 'lessc' ) ) {
1552 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1554 if ( !function_exists( 'ctype_digit' ) ) {
1555 throw new MWException( 'lessc requires the Ctype extension' );
1558 $less = new lessc();
1559 $less->setPreserveComments( true );
1560 $less->setVariables( self
::getLessVars( $config ) );
1561 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1562 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1563 $less->registerFunction( $name, $func );
1569 * Get global LESS variables.
1571 * @param Config $config
1573 * @return array Map of variable names to string CSS values.
1575 public static function getLessVars( Config
$config ) {
1576 if ( !self
::$lessVars ) {
1577 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1578 Hooks
::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1579 // Sort by key to ensure consistent hashing for cache lookups.
1581 self
::$lessVars = $lessVars;
1583 return self
::$lessVars;