Merge "resourceloader: Add $context to static functions in ResourceLoader"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoader.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Roan Kattouw
20 * @author Trevor Parscal
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use Wikimedia\Rdbms\DBConnectionError;
28 use Wikimedia\WrappedString;
29
30 /**
31 * @defgroup ResourceLoader ResourceLoader
32 *
33 * For higher level documentation, see <https://www.mediawiki.org/wiki/ResourceLoader/Architecture>.
34 */
35
36 /**
37 * ResourceLoader is a loading system for JavaScript and CSS resources.
38 *
39 * For higher level documentation, see <https://www.mediawiki.org/wiki/ResourceLoader/Architecture>.
40 *
41 * @ingroup ResourceLoader
42 * @since 1.17
43 */
44 class ResourceLoader implements LoggerAwareInterface {
45 /** @var Config */
46 protected $config;
47 /** @var MessageBlobStore */
48 protected $blobStore;
49
50 /** @var LoggerInterface */
51 private $logger;
52
53 /** @var ResourceLoaderModule[] Map of (module name => ResourceLoaderModule) */
54 protected $modules = [];
55 /** @var array[] Map of (module name => associative info array) */
56 protected $moduleInfos = [];
57 /**
58 * Associative array mapping framework ids to a list of names of test suite modules
59 * like [ 'qunit' => [ 'mediawiki.tests.qunit.suites', 'ext.foo.tests', ... ], ... ]
60 * @var array
61 */
62 protected $testModuleNames = [];
63 /** @var string[] List of module names that contain QUnit test suites */
64 protected $testSuiteModuleNames = [];
65
66 /** @var array Map of (source => path); E.g. [ 'source-id' => 'http://.../load.php' ] */
67 protected $sources = [];
68 /** @var array Errors accumulated during current respond() call */
69 protected $errors = [];
70 /** @var string[] Extra HTTP response headers from modules loaded in makeModuleResponse() */
71 protected $extraHeaders = [];
72
73 /** @var bool */
74 protected static $debugMode = null;
75
76 /** @var int */
77 const CACHE_VERSION = 8;
78
79 /** @var string JavaScript / CSS pragma to disable minification. * */
80 const FILTER_NOMIN = '/*@nomin*/';
81
82 /**
83 * Load information stored in the database about modules.
84 *
85 * This method grabs modules dependencies from the database and updates modules
86 * objects.
87 *
88 * This is not inside the module code because it is much faster to
89 * request all of the information at once than it is to have each module
90 * requests its own information. This sacrifice of modularity yields a substantial
91 * performance improvement.
92 *
93 * @param array $moduleNames List of module names to preload information for
94 * @param ResourceLoaderContext $context Context to load the information within
95 */
96 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext $context ) {
97 if ( !$moduleNames ) {
98 // Or else Database*::select() will explode, plus it's cheaper!
99 return;
100 }
101 $dbr = wfGetDB( DB_REPLICA );
102 $lang = $context->getLanguage();
103
104 // Batched version of ResourceLoaderModule::getFileDependencies
105 $vary = ResourceLoaderModule::getVary( $context );
106 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
107 'md_module' => $moduleNames,
108 'md_skin' => $vary,
109 ], __METHOD__
110 );
111
112 // Prime in-object cache for file dependencies
113 $modulesWithDeps = [];
114 foreach ( $res as $row ) {
115 $module = $this->getModule( $row->md_module );
116 if ( $module ) {
117 $module->setFileDependencies( $context, ResourceLoaderModule::expandRelativePaths(
118 json_decode( $row->md_deps, true )
119 ) );
120 $modulesWithDeps[] = $row->md_module;
121 }
122 }
123 // Register the absence of a dependency row too
124 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
125 $module = $this->getModule( $name );
126 if ( $module ) {
127 $this->getModule( $name )->setFileDependencies( $context, [] );
128 }
129 }
130
131 // Batched version of ResourceLoaderWikiModule::getTitleInfo
132 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $moduleNames );
133
134 // Prime in-object cache for message blobs for modules with messages
135 $modules = [];
136 foreach ( $moduleNames as $name ) {
137 $module = $this->getModule( $name );
138 if ( $module && $module->getMessages() ) {
139 $modules[$name] = $module;
140 }
141 }
142 $store = $this->getMessageBlobStore();
143 $blobs = $store->getBlobs( $modules, $lang );
144 foreach ( $blobs as $name => $blob ) {
145 $modules[$name]->setMessageBlob( $blob, $lang );
146 }
147 }
148
149 /**
150 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
151 *
152 * Available filters are:
153 *
154 * - minify-js \see JavaScriptMinifier::minify
155 * - minify-css \see CSSMin::minify
156 *
157 * If $data is empty, only contains whitespace or the filter was unknown,
158 * $data is returned unmodified.
159 *
160 * @param string $filter Name of filter to run
161 * @param string $data Text to filter, such as JavaScript or CSS text
162 * @param array $options Keys:
163 * - (bool) cache: Whether to allow caching this data. Default: true.
164 * @return string Filtered data, or a comment containing an error message
165 */
166 public static function filter( $filter, $data, array $options = [] ) {
167 if ( strpos( $data, self::FILTER_NOMIN ) !== false ) {
168 return $data;
169 }
170
171 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
172 return self::applyFilter( $filter, $data );
173 }
174
175 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
176 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
177
178 $key = $cache->makeGlobalKey(
179 'resourceloader-filter',
180 $filter,
181 self::CACHE_VERSION,
182 md5( $data )
183 );
184
185 $result = $cache->get( $key );
186 if ( $result === false ) {
187 $stats->increment( "resourceloader_cache.$filter.miss" );
188 $result = self::applyFilter( $filter, $data );
189 $cache->set( $key, $result, 24 * 3600 );
190 } else {
191 $stats->increment( "resourceloader_cache.$filter.hit" );
192 }
193 if ( $result === null ) {
194 // Cached failure
195 $result = $data;
196 }
197
198 return $result;
199 }
200
201 private static function applyFilter( $filter, $data ) {
202 $data = trim( $data );
203 if ( $data ) {
204 try {
205 $data = ( $filter === 'minify-css' )
206 ? CSSMin::minify( $data )
207 : JavaScriptMinifier::minify( $data );
208 } catch ( Exception $e ) {
209 MWExceptionHandler::logException( $e );
210 return null;
211 }
212 }
213 return $data;
214 }
215
216 /**
217 * Register core modules and runs registration hooks.
218 * @param Config|null $config
219 * @param LoggerInterface|null $logger [optional]
220 */
221 public function __construct( Config $config = null, LoggerInterface $logger = null ) {
222 $this->logger = $logger ?: new NullLogger();
223
224 if ( !$config ) {
225 wfDeprecated( __METHOD__ . ' without a Config instance', '1.34' );
226 $config = MediaWikiServices::getInstance()->getMainConfig();
227 }
228 $this->config = $config;
229
230 // Add 'local' source first
231 $this->addSource( 'local', $config->get( 'LoadScript' ) );
232
233 // Special module that always exists
234 $this->register( 'startup', [ 'class' => ResourceLoaderStartUpModule::class ] );
235
236 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger ) );
237 }
238
239 /**
240 * @return Config
241 */
242 public function getConfig() {
243 return $this->config;
244 }
245
246 /**
247 * @since 1.26
248 * @param LoggerInterface $logger
249 */
250 public function setLogger( LoggerInterface $logger ) {
251 $this->logger = $logger;
252 }
253
254 /**
255 * @since 1.27
256 * @return LoggerInterface
257 */
258 public function getLogger() {
259 return $this->logger;
260 }
261
262 /**
263 * @since 1.26
264 * @return MessageBlobStore
265 */
266 public function getMessageBlobStore() {
267 return $this->blobStore;
268 }
269
270 /**
271 * @since 1.25
272 * @param MessageBlobStore $blobStore
273 */
274 public function setMessageBlobStore( MessageBlobStore $blobStore ) {
275 $this->blobStore = $blobStore;
276 }
277
278 /**
279 * Register a module with the ResourceLoader system.
280 *
281 * @param string|array[] $name Module name as a string or, array of module info arrays
282 * keyed by name.
283 * @param array|null $info Module info array. When using the first parameter to register
284 * multiple modules at once, this parameter is optional.
285 * @throws MWException If a duplicate module registration is attempted
286 * @throws MWException If a module name contains illegal characters (pipes or commas)
287 * @throws InvalidArgumentException If the module info is not an array
288 */
289 public function register( $name, $info = null ) {
290 $moduleSkinStyles = $this->config->get( 'ResourceModuleSkinStyles' );
291
292 // Allow multiple modules to be registered in one call
293 $registrations = is_array( $name ) ? $name : [ $name => $info ];
294 foreach ( $registrations as $name => $info ) {
295 // Warn on duplicate registrations
296 if ( isset( $this->moduleInfos[$name] ) ) {
297 // A module has already been registered by this name
298 $this->logger->warning(
299 'ResourceLoader duplicate registration warning. ' .
300 'Another module has already been registered as ' . $name
301 );
302 }
303
304 // Check validity
305 if ( !self::isValidModuleName( $name ) ) {
306 throw new MWException( "ResourceLoader module name '$name' is invalid, "
307 . "see ResourceLoader::isValidModuleName()" );
308 }
309 if ( !is_array( $info ) ) {
310 throw new InvalidArgumentException(
311 'Invalid module info for "' . $name . '": expected array, got ' . gettype( $info )
312 );
313 }
314
315 // Attach module
316 $this->moduleInfos[$name] = $info;
317
318 // Last-minute changes
319 // Apply custom skin-defined styles to existing modules.
320 if ( $this->isFileModule( $name ) ) {
321 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
322 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
323 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
324 continue;
325 }
326
327 // If $name is preceded with a '+', the defined style files will be added to 'default'
328 // skinStyles, otherwise 'default' will be ignored as it normally would be.
329 if ( isset( $skinStyles[$name] ) ) {
330 $paths = (array)$skinStyles[$name];
331 $styleFiles = [];
332 } elseif ( isset( $skinStyles['+' . $name] ) ) {
333 $paths = (array)$skinStyles['+' . $name];
334 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
335 (array)$this->moduleInfos[$name]['skinStyles']['default'] :
336 [];
337 } else {
338 continue;
339 }
340
341 // Add new file paths, remapping them to refer to our directories and not use settings
342 // from the module we're modifying, which come from the base definition.
343 list( $localBasePath, $remoteBasePath ) =
344 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
345
346 foreach ( $paths as $path ) {
347 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
348 }
349
350 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
351 }
352 }
353 }
354 }
355
356 /**
357 * @internal For use by ServiceWiring only
358 * @codeCoverageIgnore
359 */
360 public function registerTestModules() {
361 global $IP;
362
363 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
364 throw new MWException( 'Attempt to register JavaScript test modules '
365 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
366 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
367 }
368
369 // This has a 'qunit' key for compat with the below hook.
370 $testModulesMeta = [ 'qunit' => [] ];
371
372 // Get test suites from extensions
373 // Avoid PHP 7.1 warning from passing $this by reference
374 $rl = $this;
375 Hooks::run( 'ResourceLoaderTestModules', [ &$testModulesMeta, &$rl ] );
376 $extRegistry = ExtensionRegistry::getInstance();
377 // In case of conflict, the deprecated hook has precedence.
378 $testModules = $testModulesMeta['qunit'] + $extRegistry->getAttribute( 'QUnitTestModules' );
379
380 $testSuiteModuleNames = [];
381 foreach ( $testModules as $name => &$module ) {
382 // Turn any single-module dependency into an array
383 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
384 $module['dependencies'] = [ $module['dependencies'] ];
385 }
386
387 // Ensure the testrunner loads before any test suites
388 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
389
390 // Keep track of the test suites to load on SpecialJavaScriptTest
391 $testSuiteModuleNames[] = $name;
392 }
393
394 // Core test suites (their names have further precedence).
395 $testModules = ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules;
396 $testSuiteModuleNames[] = 'test.mediawiki.qunit.suites';
397
398 $this->register( $testModules );
399 $this->testSuiteModuleNames = $testSuiteModuleNames;
400 }
401
402 /**
403 * Add a foreign source of modules.
404 *
405 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
406 *
407 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
408 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
409 * backwards-compatibility.
410 * @throws MWException
411 */
412 public function addSource( $id, $loadUrl = null ) {
413 // Allow multiple sources to be registered in one call
414 if ( is_array( $id ) ) {
415 foreach ( $id as $key => $value ) {
416 $this->addSource( $key, $value );
417 }
418 return;
419 }
420
421 // Disallow duplicates
422 if ( isset( $this->sources[$id] ) ) {
423 throw new MWException(
424 'ResourceLoader duplicate source addition error. ' .
425 'Another source has already been registered as ' . $id
426 );
427 }
428
429 // Pre 1.24 backwards-compatibility
430 if ( is_array( $loadUrl ) ) {
431 if ( !isset( $loadUrl['loadScript'] ) ) {
432 throw new MWException(
433 __METHOD__ . ' was passed an array with no "loadScript" key.'
434 );
435 }
436
437 $loadUrl = $loadUrl['loadScript'];
438 }
439
440 $this->sources[$id] = $loadUrl;
441 }
442
443 /**
444 * Get a list of module names.
445 *
446 * @return array List of module names
447 */
448 public function getModuleNames() {
449 return array_keys( $this->moduleInfos );
450 }
451
452 /**
453 * Get a list of module names with QUnit test suites.
454 *
455 * @internal For use by SpecialJavaScriptTest only
456 * @return array
457 * @codeCoverageIgnore
458 */
459 public function getTestSuiteModuleNames() {
460 return $this->testSuiteModuleNames;
461 }
462
463 /**
464 * Check whether a ResourceLoader module is registered
465 *
466 * @since 1.25
467 * @param string $name
468 * @return bool
469 */
470 public function isModuleRegistered( $name ) {
471 return isset( $this->moduleInfos[$name] );
472 }
473
474 /**
475 * Get the ResourceLoaderModule object for a given module name.
476 *
477 * If an array of module parameters exists but a ResourceLoaderModule object has not
478 * yet been instantiated, this method will instantiate and cache that object such that
479 * subsequent calls simply return the same object.
480 *
481 * @param string $name Module name
482 * @return ResourceLoaderModule|null If module has been registered, return a
483 * ResourceLoaderModule instance. Otherwise, return null.
484 */
485 public function getModule( $name ) {
486 if ( !isset( $this->modules[$name] ) ) {
487 if ( !isset( $this->moduleInfos[$name] ) ) {
488 // No such module
489 return null;
490 }
491 // Construct the requested module object
492 $info = $this->moduleInfos[$name];
493 if ( isset( $info['factory'] ) ) {
494 /** @var ResourceLoaderModule $object */
495 $object = call_user_func( $info['factory'], $info );
496 } else {
497 $class = $info['class'] ?? ResourceLoaderFileModule::class;
498 /** @var ResourceLoaderModule $object */
499 $object = new $class( $info );
500 }
501 $object->setConfig( $this->getConfig() );
502 $object->setLogger( $this->logger );
503 $object->setName( $name );
504 $this->modules[$name] = $object;
505 }
506
507 return $this->modules[$name];
508 }
509
510 /**
511 * Whether the module is a ResourceLoaderFileModule (including subclasses).
512 *
513 * @param string $name Module name
514 * @return bool
515 */
516 protected function isFileModule( $name ) {
517 if ( !isset( $this->moduleInfos[$name] ) ) {
518 return false;
519 }
520 $info = $this->moduleInfos[$name];
521 return !isset( $info['factory'] ) && (
522 // The implied default for 'class' is ResourceLoaderFileModule
523 !isset( $info['class'] ) ||
524 // Explicit default
525 $info['class'] === ResourceLoaderFileModule::class ||
526 is_subclass_of( $info['class'], ResourceLoaderFileModule::class )
527 );
528 }
529
530 /**
531 * Get the list of sources.
532 *
533 * @return array Like [ id => load.php url, ... ]
534 */
535 public function getSources() {
536 return $this->sources;
537 }
538
539 /**
540 * Get the URL to the load.php endpoint for the given
541 * ResourceLoader source
542 *
543 * @since 1.24
544 * @param string $source
545 * @throws MWException On an invalid $source name
546 * @return string
547 */
548 public function getLoadScript( $source ) {
549 if ( !isset( $this->sources[$source] ) ) {
550 throw new MWException( "The $source source was never registered in ResourceLoader." );
551 }
552 return $this->sources[$source];
553 }
554
555 /**
556 * @internal For use by ResourceLoaderStartUpModule only.
557 */
558 const HASH_LENGTH = 5;
559
560 /**
561 * Create a hash for module versioning purposes.
562 *
563 * This hash is used in three ways:
564 *
565 * - To differentiate between the current version and a past version
566 * of a module by the same name.
567 *
568 * In the cache key of localStorage in the browser (mw.loader.store).
569 * This store keeps only one version of any given module. As long as the
570 * next version the client encounters has a different hash from the last
571 * version it saw, it will correctly discard it in favour of a network fetch.
572 *
573 * A browser may evict a site's storage container for any reason (e.g. when
574 * the user hasn't visited a site for some time, and/or when the device is
575 * low on storage space). Anecdotally it seems devices rarely keep unused
576 * storage beyond 2 weeks on mobile devices and 4 weeks on desktop.
577 * But, there is no hard limit or expiration on localStorage.
578 * ResourceLoader's Client also clears localStorage when the user changes
579 * their language preference or when they (temporarily) use Debug Mode.
580 *
581 * The only hard factors that reduce the range of possible versions are
582 * 1) the name and existence of a given module, and
583 * 2) the TTL for mw.loader.store, and
584 * 3) the `$wgResourceLoaderStorageVersion` configuration variable.
585 *
586 * - To identify a batch response of modules from load.php in an HTTP cache.
587 *
588 * When fetching modules in a batch from load.php, a combined hash
589 * is created by the JS code, and appended as query parameter.
590 *
591 * In cache proxies (e.g. Varnish, Nginx) and in the browser's HTTP cache,
592 * these urls are used to identify other previously cached responses.
593 * The range of possible versions a given version has to be unique amongst
594 * is determined by the maximum duration each response is stored for, which
595 * is controlled by `$wgResourceLoaderMaxage['versioned']`.
596 *
597 * - To detect race conditions between multiple web servers in a MediaWiki
598 * deployment of which some have the newer version and some still the older
599 * version.
600 *
601 * An HTTP request from a browser for the Startup manifest may be responded
602 * to by a server with the newer version. The browser may then use that to
603 * request a given module, which may then be responded to by a server with
604 * the older version. To avoid caching this for too long (which would pollute
605 * all other users without repairing itself), the combined hash that the JS
606 * client adds to the url is verified by the server (in ::sendResponseHeaders).
607 * If they don't match, we instruct cache proxies and clients to not cache
608 * this response as long as they normally would. This is also the reason
609 * that the algorithm used here in PHP must match the one used in JS.
610 *
611 * The fnv132 digest creates a 32-bit integer, which goes upto 4 Giga and
612 * needs up to 7 chars in base 36.
613 * Within 7 characters, base 36 can count up to 78,364,164,096 (78 Giga),
614 * (but with fnv132 we'd use very little of this range, mostly padding).
615 * Within 6 characters, base 36 can count up to 2,176,782,336 (2 Giga).
616 * Within 5 characters, base 36 can count up to 60,466,176 (60 Mega).
617 *
618 * @since 1.26
619 * @param string $value
620 * @return string Hash
621 */
622 public static function makeHash( $value ) {
623 $hash = hash( 'fnv132', $value );
624 // The base_convert will pad it (if too short),
625 // then substr() will trim it (if too long).
626 return substr(
627 Wikimedia\base_convert( $hash, 16, 36, self::HASH_LENGTH ),
628 0,
629 self::HASH_LENGTH
630 );
631 }
632
633 /**
634 * Add an error to the 'errors' array and log it.
635 *
636 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
637 * @since 1.29
638 * @param Exception $e
639 * @param string $msg
640 * @param array $context
641 */
642 public function outputErrorAndLog( Exception $e, $msg, array $context = [] ) {
643 MWExceptionHandler::logException( $e );
644 $this->logger->warning(
645 $msg,
646 $context + [ 'exception' => $e ]
647 );
648 $this->errors[] = self::formatExceptionNoComment( $e );
649 }
650
651 /**
652 * Helper method to get and combine versions of multiple modules.
653 *
654 * @since 1.26
655 * @param ResourceLoaderContext $context
656 * @param string[] $moduleNames List of known module names
657 * @return string Hash
658 */
659 public function getCombinedVersion( ResourceLoaderContext $context, array $moduleNames ) {
660 if ( !$moduleNames ) {
661 return '';
662 }
663 $hashes = array_map( function ( $module ) use ( $context ) {
664 try {
665 return $this->getModule( $module )->getVersionHash( $context );
666 } catch ( Exception $e ) {
667 // If modules fail to compute a version, don't fail the request (T152266)
668 // and still compute versions of other modules.
669 $this->outputErrorAndLog( $e,
670 'Calculating version for "{module}" failed: {exception}',
671 [
672 'module' => $module,
673 ]
674 );
675 return '';
676 }
677 }, $moduleNames );
678 return self::makeHash( implode( '', $hashes ) );
679 }
680
681 /**
682 * Get the expected value of the 'version' query parameter.
683 *
684 * This is used by respond() to set a short Cache-Control header for requests with
685 * information newer than the current server has. This avoids pollution of edge caches.
686 * Typically during deployment. (T117587)
687 *
688 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
689 *
690 * @since 1.28
691 * @param ResourceLoaderContext $context
692 * @return string Hash
693 */
694 public function makeVersionQuery( ResourceLoaderContext $context ) {
695 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
696 // version hashes. There is no technical reason for this to be same, and for years the
697 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
698 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
699 // query parameter), then this method must continue to match the JS one.
700 $moduleNames = [];
701 foreach ( $context->getModules() as $name ) {
702 if ( !$this->getModule( $name ) ) {
703 // If a versioned request contains a missing module, the version is a mismatch
704 // as the client considered a module (and version) we don't have.
705 return '';
706 }
707 $moduleNames[] = $name;
708 }
709 return $this->getCombinedVersion( $context, $moduleNames );
710 }
711
712 /**
713 * Output a response to a load request, including the content-type header.
714 *
715 * @param ResourceLoaderContext $context Context in which a response should be formed
716 */
717 public function respond( ResourceLoaderContext $context ) {
718 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
719 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
720 // is used: ob_clean() will clear the GZIP header in that case and it won't come
721 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
722 // the whole thing in our own output buffer to be sure the active buffer
723 // doesn't use ob_gzhandler.
724 // See https://bugs.php.net/bug.php?id=36514
725 ob_start();
726
727 $this->measureResponseTime( RequestContext::getMain()->getTiming() );
728
729 // Find out which modules are missing and instantiate the others
730 $modules = [];
731 $missing = [];
732 foreach ( $context->getModules() as $name ) {
733 $module = $this->getModule( $name );
734 if ( $module ) {
735 // Do not allow private modules to be loaded from the web.
736 // This is a security issue, see T36907.
737 if ( $module->getGroup() === 'private' ) {
738 // Not a serious error, just means something is trying to access it (T101806)
739 $this->logger->debug( "Request for private module '$name' denied" );
740 $this->errors[] = "Cannot build private module \"$name\"";
741 continue;
742 }
743 $modules[$name] = $module;
744 } else {
745 $missing[] = $name;
746 }
747 }
748
749 try {
750 // Preload for getCombinedVersion() and for batch makeModuleResponse()
751 $this->preloadModuleInfo( array_keys( $modules ), $context );
752 } catch ( Exception $e ) {
753 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
754 }
755
756 // Combine versions to propagate cache invalidation
757 $versionHash = '';
758 try {
759 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
760 } catch ( Exception $e ) {
761 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
762 }
763
764 // See RFC 2616 § 3.11 Entity Tags
765 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
766 $etag = 'W/"' . $versionHash . '"';
767
768 // Try the client-side cache first
769 if ( $this->tryRespondNotModified( $context, $etag ) ) {
770 return; // output handled (buffers cleared)
771 }
772
773 // Use file cache if enabled and available...
774 if ( $this->config->get( 'UseFileCache' ) ) {
775 $fileCache = ResourceFileCache::newFromContext( $context );
776 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
777 return; // output handled
778 }
779 } else {
780 $fileCache = null;
781 }
782
783 // Generate a response
784 $response = $this->makeModuleResponse( $context, $modules, $missing );
785
786 // Capture any PHP warnings from the output buffer and append them to the
787 // error list if we're in debug mode.
788 if ( $context->getDebug() ) {
789 $warnings = ob_get_contents();
790 if ( strlen( $warnings ) ) {
791 $this->errors[] = $warnings;
792 }
793 }
794
795 // Consider saving the response to file cache (unless there are errors).
796 if ( $fileCache &&
797 !$this->errors &&
798 $missing === [] &&
799 ResourceFileCache::useFileCache( $context )
800 ) {
801 if ( $fileCache->isCacheWorthy() ) {
802 // There were enough hits, save the response to the cache
803 $fileCache->saveText( $response );
804 } else {
805 $fileCache->incrMissesRecent( $context->getRequest() );
806 }
807 }
808
809 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors, $this->extraHeaders );
810
811 // Remove the output buffer and output the response
812 ob_end_clean();
813
814 if ( $context->getImageObj() && $this->errors ) {
815 // We can't show both the error messages and the response when it's an image.
816 $response = implode( "\n\n", $this->errors );
817 } elseif ( $this->errors ) {
818 $errorText = implode( "\n\n", $this->errors );
819 $errorResponse = self::makeComment( $errorText );
820 if ( $context->shouldIncludeScripts() ) {
821 $errorResponse .= 'if (window.console && console.error) { console.error('
822 . $context->encodeJson( $errorText )
823 . "); }\n";
824 }
825
826 // Prepend error info to the response
827 $response = $errorResponse . $response;
828 }
829
830 $this->errors = [];
831 echo $response;
832 }
833
834 protected function measureResponseTime( Timing $timing ) {
835 DeferredUpdates::addCallableUpdate( function () use ( $timing ) {
836 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
837 if ( $measure !== false ) {
838 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
839 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
840 }
841 } );
842 }
843
844 /**
845 * Send main response headers to the client.
846 *
847 * Deals with Content-Type, CORS (for stylesheets), and caching.
848 *
849 * @param ResourceLoaderContext $context
850 * @param string $etag ETag header value
851 * @param bool $errors Whether there are errors in the response
852 * @param string[] $extra Array of extra HTTP response headers
853 * @return void
854 */
855 protected function sendResponseHeaders(
856 ResourceLoaderContext $context, $etag, $errors, array $extra = []
857 ) {
858 \MediaWiki\HeaderCallback::warnIfHeadersSent();
859 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
860 // Use a short cache expiry so that updates propagate to clients quickly, if:
861 // - No version specified (shared resources, e.g. stylesheets)
862 // - There were errors (recover quickly)
863 // - Version mismatch (T117587, T47877)
864 if ( is_null( $context->getVersion() )
865 || $errors
866 || $context->getVersion() !== $this->makeVersionQuery( $context )
867 ) {
868 $maxage = $rlMaxage['unversioned']['client'];
869 $smaxage = $rlMaxage['unversioned']['server'];
870 // If a version was specified we can use a longer expiry time since changing
871 // version numbers causes cache misses
872 } else {
873 $maxage = $rlMaxage['versioned']['client'];
874 $smaxage = $rlMaxage['versioned']['server'];
875 }
876 if ( $context->getImageObj() ) {
877 // Output different headers if we're outputting textual errors.
878 if ( $errors ) {
879 header( 'Content-Type: text/plain; charset=utf-8' );
880 } else {
881 $context->getImageObj()->sendResponseHeaders( $context );
882 }
883 } elseif ( $context->getOnly() === 'styles' ) {
884 header( 'Content-Type: text/css; charset=utf-8' );
885 header( 'Access-Control-Allow-Origin: *' );
886 } else {
887 header( 'Content-Type: text/javascript; charset=utf-8' );
888 }
889 // See RFC 2616 § 14.19 ETag
890 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
891 header( 'ETag: ' . $etag );
892 if ( $context->getDebug() ) {
893 // Do not cache debug responses
894 header( 'Cache-Control: private, no-cache, must-revalidate' );
895 header( 'Pragma: no-cache' );
896 } else {
897 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
898 $exp = min( $maxage, $smaxage );
899 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
900 }
901 foreach ( $extra as $header ) {
902 header( $header );
903 }
904 }
905
906 /**
907 * Respond with HTTP 304 Not Modified if appropiate.
908 *
909 * If there's an If-None-Match header, respond with a 304 appropriately
910 * and clear out the output buffer. If the client cache is too old then do nothing.
911 *
912 * @param ResourceLoaderContext $context
913 * @param string $etag ETag header value
914 * @return bool True if HTTP 304 was sent and output handled
915 */
916 protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
917 // See RFC 2616 § 14.26 If-None-Match
918 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
919 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
920 // Never send 304s in debug mode
921 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
922 // There's another bug in ob_gzhandler (see also the comment at
923 // the top of this function) that causes it to gzip even empty
924 // responses, meaning it's impossible to produce a truly empty
925 // response (because the gzip header is always there). This is
926 // a problem because 304 responses have to be completely empty
927 // per the HTTP spec, and Firefox behaves buggily when they're not.
928 // See also https://bugs.php.net/bug.php?id=51579
929 // To work around this, we tear down all output buffering before
930 // sending the 304.
931 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
932
933 HttpStatus::header( 304 );
934
935 $this->sendResponseHeaders( $context, $etag, false );
936 return true;
937 }
938 return false;
939 }
940
941 /**
942 * Send out code for a response from file cache if possible.
943 *
944 * @param ResourceFileCache $fileCache Cache object for this request URL
945 * @param ResourceLoaderContext $context Context in which to generate a response
946 * @param string $etag ETag header value
947 * @return bool If this found a cache file and handled the response
948 */
949 protected function tryRespondFromFileCache(
950 ResourceFileCache $fileCache,
951 ResourceLoaderContext $context,
952 $etag
953 ) {
954 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
955 // Buffer output to catch warnings.
956 ob_start();
957 // Get the maximum age the cache can be
958 $maxage = is_null( $context->getVersion() )
959 ? $rlMaxage['unversioned']['server']
960 : $rlMaxage['versioned']['server'];
961 // Minimum timestamp the cache file must have
962 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
963 if ( !$good ) {
964 try { // RL always hits the DB on file cache miss...
965 wfGetDB( DB_REPLICA );
966 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
967 $good = $fileCache->isCacheGood(); // cache existence check
968 }
969 }
970 if ( $good ) {
971 $ts = $fileCache->cacheTimestamp();
972 // Send content type and cache headers
973 $this->sendResponseHeaders( $context, $etag, false );
974 $response = $fileCache->fetchText();
975 // Capture any PHP warnings from the output buffer and append them to the
976 // response in a comment if we're in debug mode.
977 if ( $context->getDebug() ) {
978 $warnings = ob_get_contents();
979 if ( strlen( $warnings ) ) {
980 $response = self::makeComment( $warnings ) . $response;
981 }
982 }
983 // Remove the output buffer and output the response
984 ob_end_clean();
985 echo $response . "\n/* Cached {$ts} */";
986 return true; // cache hit
987 }
988 // Clear buffer
989 ob_end_clean();
990
991 return false; // cache miss
992 }
993
994 /**
995 * Generate a CSS or JS comment block.
996 *
997 * Only use this for public data, not error message details.
998 *
999 * @param string $text
1000 * @return string
1001 */
1002 public static function makeComment( $text ) {
1003 $encText = str_replace( '*/', '* /', $text );
1004 return "/*\n$encText\n*/\n";
1005 }
1006
1007 /**
1008 * Handle exception display.
1009 *
1010 * @param Exception $e Exception to be shown to the user
1011 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
1012 */
1013 public static function formatException( $e ) {
1014 return self::makeComment( self::formatExceptionNoComment( $e ) );
1015 }
1016
1017 /**
1018 * Handle exception display.
1019 *
1020 * @since 1.25
1021 * @param Exception $e Exception to be shown to the user
1022 * @return string Sanitized text that can be returned to the user
1023 */
1024 protected static function formatExceptionNoComment( $e ) {
1025 global $wgShowExceptionDetails;
1026
1027 if ( !$wgShowExceptionDetails ) {
1028 return MWExceptionHandler::getPublicLogMessage( $e );
1029 }
1030
1031 return MWExceptionHandler::getLogMessage( $e ) .
1032 "\nBacktrace:\n" .
1033 MWExceptionHandler::getRedactedTraceAsString( $e );
1034 }
1035
1036 /**
1037 * Generate code for a response.
1038 *
1039 * Calling this method also populates the `errors` and `headers` members,
1040 * later used by respond().
1041 *
1042 * @param ResourceLoaderContext $context Context in which to generate a response
1043 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1044 * @param string[] $missing List of requested module names that are unregistered (optional)
1045 * @return string Response data
1046 */
1047 public function makeModuleResponse( ResourceLoaderContext $context,
1048 array $modules, array $missing = []
1049 ) {
1050 $out = '';
1051 $states = [];
1052
1053 if ( $modules === [] && $missing === [] ) {
1054 return <<<MESSAGE
1055 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1056 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1057 no modules were requested. Max made me put this here. */
1058 MESSAGE;
1059 }
1060
1061 $image = $context->getImageObj();
1062 if ( $image ) {
1063 $data = $image->getImageData( $context );
1064 if ( $data === false ) {
1065 $data = '';
1066 $this->errors[] = 'Image generation failed';
1067 }
1068 return $data;
1069 }
1070
1071 foreach ( $missing as $name ) {
1072 $states[$name] = 'missing';
1073 }
1074
1075 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
1076
1077 foreach ( $modules as $name => $module ) {
1078 try {
1079 $content = $module->getModuleContent( $context );
1080 $implementKey = $name . '@' . $module->getVersionHash( $context );
1081 $strContent = '';
1082
1083 if ( isset( $content['headers'] ) ) {
1084 $this->extraHeaders = array_merge( $this->extraHeaders, $content['headers'] );
1085 }
1086
1087 // Append output
1088 switch ( $context->getOnly() ) {
1089 case 'scripts':
1090 $scripts = $content['scripts'];
1091 if ( is_string( $scripts ) ) {
1092 // Load scripts raw...
1093 $strContent = $scripts;
1094 } elseif ( is_array( $scripts ) ) {
1095 // ...except when $scripts is an array of URLs or an associative array
1096 $strContent = self::makeLoaderImplementScript(
1097 $context,
1098 $implementKey,
1099 $scripts,
1100 [],
1101 [],
1102 []
1103 );
1104 }
1105 break;
1106 case 'styles':
1107 $styles = $content['styles'];
1108 // We no longer separate into media, they are all combined now with
1109 // custom media type groups into @media .. {} sections as part of the css string.
1110 // Module returns either an empty array or a numerical array with css strings.
1111 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1112 break;
1113 default:
1114 $scripts = $content['scripts'] ?? '';
1115 if ( is_string( $scripts ) ) {
1116 if ( $name === 'site' || $name === 'user' ) {
1117 // Legacy scripts that run in the global scope without a closure.
1118 // mw.loader.implement will use globalEval if scripts is a string.
1119 // Minify manually here, because general response minification is
1120 // not effective due it being a string literal, not a function.
1121 if ( !$context->getDebug() ) {
1122 $scripts = self::filter( 'minify-js', $scripts ); // T107377
1123 }
1124 } else {
1125 $scripts = new XmlJsCode( $scripts );
1126 }
1127 }
1128 $strContent = self::makeLoaderImplementScript(
1129 $context,
1130 $implementKey,
1131 $scripts,
1132 $content['styles'] ?? [],
1133 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [],
1134 $content['templates'] ?? []
1135 );
1136 break;
1137 }
1138
1139 if ( !$context->getDebug() ) {
1140 $strContent = self::filter( $filter, $strContent );
1141 } else {
1142 // In debug mode, separate each response by a new line.
1143 // For example, between 'mw.loader.implement();' statements.
1144 $strContent = $this->ensureNewline( $strContent );
1145 }
1146
1147 if ( $context->getOnly() === 'scripts' ) {
1148 // Use a linebreak between module scripts (T162719)
1149 $out .= $this->ensureNewline( $strContent );
1150 } else {
1151 $out .= $strContent;
1152 }
1153
1154 } catch ( Exception $e ) {
1155 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1156
1157 // Respond to client with error-state instead of module implementation
1158 $states[$name] = 'error';
1159 unset( $modules[$name] );
1160 }
1161 }
1162
1163 // Update module states
1164 if ( $context->shouldIncludeScripts() && !$context->getRaw() ) {
1165 if ( $modules && $context->getOnly() === 'scripts' ) {
1166 // Set the state of modules loaded as only scripts to ready as
1167 // they don't have an mw.loader.implement wrapper that sets the state
1168 foreach ( $modules as $name => $module ) {
1169 $states[$name] = 'ready';
1170 }
1171 }
1172
1173 // Set the state of modules we didn't respond to with mw.loader.implement
1174 if ( $states ) {
1175 $stateScript = self::makeLoaderStateScript( $context, $states );
1176 if ( !$context->getDebug() ) {
1177 $stateScript = self::filter( 'minify-js', $stateScript );
1178 }
1179 // Use a linebreak between module script and state script (T162719)
1180 $out = $this->ensureNewline( $out ) . $stateScript;
1181 }
1182 } elseif ( $states ) {
1183 $this->errors[] = 'Problematic modules: '
1184 . $context->encodeJson( $states );
1185 }
1186
1187 return $out;
1188 }
1189
1190 /**
1191 * Ensure the string is either empty or ends in a line break
1192 * @param string $str
1193 * @return string
1194 */
1195 private function ensureNewline( $str ) {
1196 $end = substr( $str, -1 );
1197 if ( $end === false || $end === '' || $end === "\n" ) {
1198 return $str;
1199 }
1200 return $str . "\n";
1201 }
1202
1203 /**
1204 * Get names of modules that use a certain message.
1205 *
1206 * @param string $messageKey
1207 * @return array List of module names
1208 */
1209 public function getModulesByMessage( $messageKey ) {
1210 $moduleNames = [];
1211 foreach ( $this->getModuleNames() as $moduleName ) {
1212 $module = $this->getModule( $moduleName );
1213 if ( in_array( $messageKey, $module->getMessages() ) ) {
1214 $moduleNames[] = $moduleName;
1215 }
1216 }
1217 return $moduleNames;
1218 }
1219
1220 /**
1221 * Return JS code that calls mw.loader.implement with given module properties.
1222 *
1223 * @param ResourceLoaderContext $context
1224 * @param string $name Module name or implement key (format "`[name]@[version]`")
1225 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1226 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1227 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1228 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1229 * to CSS files keyed by media type
1230 * @param mixed $messages List of messages associated with this module. May either be an
1231 * associative array mapping message key to value, or a JSON-encoded message blob containing
1232 * the same data, wrapped in an XmlJsCode object.
1233 * @param array $templates Keys are name of templates and values are the source of
1234 * the template.
1235 * @throws MWException
1236 * @return string JavaScript code
1237 */
1238 private static function makeLoaderImplementScript(
1239 ResourceLoaderContext $context, $name, $scripts, $styles, $messages, $templates
1240 ) {
1241 if ( $scripts instanceof XmlJsCode ) {
1242 if ( $scripts->value === '' ) {
1243 $scripts = null;
1244 } elseif ( $context->getDebug() ) {
1245 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1246 } else {
1247 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value . '}' );
1248 }
1249 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1250 $files = $scripts['files'];
1251 foreach ( $files as $path => &$file ) {
1252 // $file is changed (by reference) from a descriptor array to the content of the file
1253 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1254 if ( $file['type'] === 'script' ) {
1255 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1256 if ( $context->getDebug() ) {
1257 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1258 } else {
1259 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1260 }
1261 } else {
1262 $file = $file['content'];
1263 }
1264 }
1265 $scripts = XmlJsCode::encodeObject( [
1266 'main' => $scripts['main'],
1267 'files' => XmlJsCode::encodeObject( $files, $context->getDebug() )
1268 ], $context->getDebug() );
1269 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1270 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1271 }
1272
1273 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1274 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1275 // of "{}". Force them to objects.
1276 $module = [
1277 $name,
1278 $scripts,
1279 (object)$styles,
1280 (object)$messages,
1281 (object)$templates
1282 ];
1283 self::trimArray( $module );
1284
1285 return Xml::encodeJsCall( 'mw.loader.implement', $module, $context->getDebug() );
1286 }
1287
1288 /**
1289 * Returns JS code which, when called, will register a given list of messages.
1290 *
1291 * @param mixed $messages Associative array mapping message key to value.
1292 * @return string JavaScript code
1293 */
1294 public static function makeMessageSetScript( $messages ) {
1295 return 'mw.messages.set('
1296 . self::encodeJsonForScript( (object)$messages )
1297 . ');';
1298 }
1299
1300 /**
1301 * Combines an associative array mapping media type to CSS into a
1302 * single stylesheet with "@media" blocks.
1303 *
1304 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1305 * @return array
1306 */
1307 public static function makeCombinedStyles( array $stylePairs ) {
1308 $out = [];
1309 foreach ( $stylePairs as $media => $styles ) {
1310 // ResourceLoaderFileModule::getStyle can return the styles
1311 // as a string or an array of strings. This is to allow separation in
1312 // the front-end.
1313 $styles = (array)$styles;
1314 foreach ( $styles as $style ) {
1315 $style = trim( $style );
1316 // Don't output an empty "@media print { }" block (T42498)
1317 if ( $style !== '' ) {
1318 // Transform the media type based on request params and config
1319 // The way that this relies on $wgRequest to propagate request params is slightly evil
1320 $media = OutputPage::transformCssMedia( $media );
1321
1322 if ( $media === '' || $media == 'all' ) {
1323 $out[] = $style;
1324 } elseif ( is_string( $media ) ) {
1325 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1326 }
1327 // else: skip
1328 }
1329 }
1330 }
1331 return $out;
1332 }
1333
1334 /**
1335 * Wrapper around json_encode that avoids needless escapes,
1336 * and pretty-prints in debug mode.
1337 *
1338 * @internal
1339 * @since 1.32
1340 * @param mixed $data
1341 * @return string|false JSON string, false on error
1342 */
1343 public static function encodeJsonForScript( $data ) {
1344 // Keep output as small as possible by disabling needless escape modes
1345 // that PHP uses by default.
1346 // However, while most module scripts are only served on HTTP responses
1347 // for JavaScript, some modules can also be embedded in the HTML as inline
1348 // scripts. This, and the fact that we sometimes need to export strings
1349 // containing user-generated content and labels that may genuinely contain
1350 // a sequences like "</script>", we need to encode either '/' or '<'.
1351 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1352 // and allows URLs to mostly remain readable.
1353 $jsonFlags = JSON_UNESCAPED_SLASHES |
1354 JSON_UNESCAPED_UNICODE |
1355 JSON_HEX_TAG |
1356 JSON_HEX_AMP;
1357 if ( self::inDebugMode() ) {
1358 $jsonFlags |= JSON_PRETTY_PRINT;
1359 }
1360 return json_encode( $data, $jsonFlags );
1361 }
1362
1363 /**
1364 * Returns a JS call to mw.loader.state, which sets the state of one
1365 * ore more modules to a given value. Has two calling conventions:
1366 *
1367 * - ResourceLoader::makeLoaderStateScript( $context, $name, $state ):
1368 * Set the state of a single module called $name to $state
1369 *
1370 * - ResourceLoader::makeLoaderStateScript( $context, [ $name => $state, ... ] ):
1371 * Set the state of modules with the given names to the given states
1372 *
1373 * @internal
1374 * @param ResourceLoaderContext $context
1375 * @param array|string $states
1376 * @param string|null $state
1377 * @return string JavaScript code
1378 */
1379 public static function makeLoaderStateScript(
1380 ResourceLoaderContext $context, $states, $state = null
1381 ) {
1382 if ( !is_array( $states ) ) {
1383 $states = [ $states => $state ];
1384 }
1385 return 'mw.loader.state('
1386 . $context->encodeJson( $states )
1387 . ');';
1388 }
1389
1390 private static function isEmptyObject( stdClass $obj ) {
1391 foreach ( $obj as $key => $value ) {
1392 return false;
1393 }
1394 return true;
1395 }
1396
1397 /**
1398 * Remove empty values from the end of an array.
1399 *
1400 * Values considered empty:
1401 *
1402 * - null
1403 * - []
1404 * - new XmlJsCode( '{}' )
1405 * - new stdClass() // (object) []
1406 *
1407 * @param array $array
1408 */
1409 private static function trimArray( array &$array ) {
1410 $i = count( $array );
1411 while ( $i-- ) {
1412 if ( $array[$i] === null
1413 || $array[$i] === []
1414 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1415 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1416 ) {
1417 unset( $array[$i] );
1418 } else {
1419 break;
1420 }
1421 }
1422 }
1423
1424 /**
1425 * Returns JS code which calls mw.loader.register with the given
1426 * parameter.
1427 *
1428 * @par Example
1429 * @code
1430 *
1431 * ResourceLoader::makeLoaderRegisterScript( $context, [
1432 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1433 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1434 * ...
1435 * ] ):
1436 * @endcode
1437 *
1438 * @internal For use by ResourceLoaderStartUpModule only
1439 * @param ResourceLoaderContext $context
1440 * @param array $modules Array of module registration arrays, each containing
1441 * - string: module name
1442 * - string: module version
1443 * - array|null: List of dependencies (optional)
1444 * - string|null: Module group (optional)
1445 * - string|null: Name of foreign module source, or 'local' (optional)
1446 * - string|null: Script body of a skip function (optional)
1447 * @return string JavaScript code
1448 */
1449 public static function makeLoaderRegisterScript(
1450 ResourceLoaderContext $context, array $modules
1451 ) {
1452 // Optimisation: Transform dependency names into indexes when possible
1453 // to produce smaller output. They are expanded by mw.loader.register on
1454 // the other end using resolveIndexedDependencies().
1455 $index = [];
1456 foreach ( $modules as $i => &$module ) {
1457 // Build module name index
1458 $index[$module[0]] = $i;
1459 }
1460 foreach ( $modules as &$module ) {
1461 if ( isset( $module[2] ) ) {
1462 foreach ( $module[2] as &$dependency ) {
1463 if ( isset( $index[$dependency] ) ) {
1464 // Replace module name in dependency list with index
1465 $dependency = $index[$dependency];
1466 }
1467 }
1468 }
1469 }
1470
1471 array_walk( $modules, [ self::class, 'trimArray' ] );
1472
1473 return 'mw.loader.register('
1474 . $context->encodeJson( $modules )
1475 . ');';
1476 }
1477
1478 /**
1479 * Returns JS code which calls mw.loader.addSource() with the given
1480 * parameters. Has two calling conventions:
1481 *
1482 * - ResourceLoader::makeLoaderSourcesScript( $context, $id, $properties ):
1483 * Register a single source
1484 *
1485 * - ResourceLoader::makeLoaderSourcesScript( $context,
1486 * [ $id1 => $loadUrl, $id2 => $loadUrl, ... ]
1487 * );
1488 * Register sources with the given IDs and properties.
1489 *
1490 * @internal For use by ResourceLoaderStartUpModule only
1491 * @param ResourceLoaderContext $context
1492 * @param string|array $sources Source ID
1493 * @param string|null $loadUrl load.php url
1494 * @return string JavaScript code
1495 */
1496 public static function makeLoaderSourcesScript(
1497 ResourceLoaderContext $context, $sources, $loadUrl = null
1498 ) {
1499 if ( !is_array( $sources ) ) {
1500 $sources = [ $sources => $loadUrl ];
1501 }
1502 return 'mw.loader.addSource('
1503 . $context->encodeJson( $sources )
1504 . ');';
1505 }
1506
1507 /**
1508 * Wraps JavaScript code to run after the startup module.
1509 *
1510 * @param string $script JavaScript code
1511 * @return string JavaScript code
1512 */
1513 public static function makeLoaderConditionalScript( $script ) {
1514 // Adds a function to lazy-created RLQ
1515 return '(RLQ=window.RLQ||[]).push(function(){' .
1516 trim( $script ) . '});';
1517 }
1518
1519 /**
1520 * Wraps JavaScript code to run after a required module.
1521 *
1522 * @since 1.32
1523 * @param string|string[] $modules Module name(s)
1524 * @param string $script JavaScript code
1525 * @return string JavaScript code
1526 */
1527 public static function makeInlineCodeWithModule( $modules, $script ) {
1528 // Adds an array to lazy-created RLQ
1529 return '(RLQ=window.RLQ||[]).push(['
1530 . self::encodeJsonForScript( $modules ) . ','
1531 . 'function(){' . trim( $script ) . '}'
1532 . ']);';
1533 }
1534
1535 /**
1536 * Returns an HTML script tag that runs given JS code after startup and base modules.
1537 *
1538 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1539 * startup module if the client has adequate support for MediaWiki JavaScript code.
1540 *
1541 * @param string $script JavaScript code
1542 * @param string|null $nonce [optional] Content-Security-Policy nonce
1543 * (from OutputPage::getCSPNonce)
1544 * @return string|WrappedString HTML
1545 */
1546 public static function makeInlineScript( $script, $nonce = null ) {
1547 $js = self::makeLoaderConditionalScript( $script );
1548 $escNonce = '';
1549 if ( $nonce === null ) {
1550 wfWarn( __METHOD__ . " did not get nonce. Will break CSP" );
1551 } elseif ( $nonce !== false ) {
1552 // If it was false, CSP is disabled, so no nonce attribute.
1553 // Nonce should be only base64 characters, so should be safe,
1554 // but better to be safely escaped than sorry.
1555 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1556 }
1557
1558 return new WrappedString(
1559 Html::inlineScript( $js, $nonce ),
1560 "<script$escNonce>(RLQ=window.RLQ||[]).push(function(){",
1561 '});</script>'
1562 );
1563 }
1564
1565 /**
1566 * Returns JS code which will set the MediaWiki configuration array to
1567 * the given value.
1568 *
1569 * @param array $configuration List of configuration values keyed by variable name
1570 * @return string JavaScript code
1571 * @throws Exception
1572 */
1573 public static function makeConfigSetScript( array $configuration ) {
1574 $json = self::encodeJsonForScript( $configuration );
1575 if ( $json === false ) {
1576 $e = new Exception(
1577 'JSON serialization of config data failed. ' .
1578 'This usually means the config data is not valid UTF-8.'
1579 );
1580 MWExceptionHandler::logException( $e );
1581 return 'mw.log.error(' . self::encodeJsonForScript( $e->__toString() ) . ');';
1582 }
1583 return "mw.config.set($json);";
1584 }
1585
1586 /**
1587 * Convert an array of module names to a packed query string.
1588 *
1589 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1590 * becomes `'foo.bar,baz|bar.baz,quux'`.
1591 *
1592 * This process is reversed by ResourceLoader::expandModuleNames().
1593 * See also mw.loader#buildModulesString() which is a port of this, used
1594 * on the client-side.
1595 *
1596 * @param array $modules List of module names (strings)
1597 * @return string Packed query string
1598 */
1599 public static function makePackedModulesString( $modules ) {
1600 $moduleMap = []; // [ prefix => [ suffixes ] ]
1601 foreach ( $modules as $module ) {
1602 $pos = strrpos( $module, '.' );
1603 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1604 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1605 $moduleMap[$prefix][] = $suffix;
1606 }
1607
1608 $arr = [];
1609 foreach ( $moduleMap as $prefix => $suffixes ) {
1610 $p = $prefix === '' ? '' : $prefix . '.';
1611 $arr[] = $p . implode( ',', $suffixes );
1612 }
1613 return implode( '|', $arr );
1614 }
1615
1616 /**
1617 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
1618 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
1619 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
1620 *
1621 * This process is reversed by ResourceLoader::makePackedModulesString().
1622 *
1623 * @since 1.33
1624 * @param string $modules Packed module name list
1625 * @return array Array of module names
1626 */
1627 public static function expandModuleNames( $modules ) {
1628 $retval = [];
1629 $exploded = explode( '|', $modules );
1630 foreach ( $exploded as $group ) {
1631 if ( strpos( $group, ',' ) === false ) {
1632 // This is not a set of modules in foo.bar,baz notation
1633 // but a single module
1634 $retval[] = $group;
1635 } else {
1636 // This is a set of modules in foo.bar,baz notation
1637 $pos = strrpos( $group, '.' );
1638 if ( $pos === false ) {
1639 // Prefixless modules, i.e. without dots
1640 $retval = array_merge( $retval, explode( ',', $group ) );
1641 } else {
1642 // We have a prefix and a bunch of suffixes
1643 $prefix = substr( $group, 0, $pos ); // 'foo'
1644 $suffixes = explode( ',', substr( $group, $pos + 1 ) ); // [ 'bar', 'baz' ]
1645 foreach ( $suffixes as $suffix ) {
1646 $retval[] = "$prefix.$suffix";
1647 }
1648 }
1649 }
1650 }
1651 return $retval;
1652 }
1653
1654 /**
1655 * Determine whether debug mode was requested
1656 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1657 * @return bool
1658 */
1659 public static function inDebugMode() {
1660 if ( self::$debugMode === null ) {
1661 global $wgRequest, $wgResourceLoaderDebug;
1662 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1663 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1664 );
1665 }
1666 return self::$debugMode;
1667 }
1668
1669 /**
1670 * Reset static members used for caching.
1671 *
1672 * Global state and $wgRequest are evil, but we're using it right
1673 * now and sometimes we need to be able to force ResourceLoader to
1674 * re-evaluate the context because it has changed (e.g. in the test suite).
1675 *
1676 * @internal For use by unit tests
1677 * @codeCoverageIgnore
1678 */
1679 public static function clearCache() {
1680 self::$debugMode = null;
1681 }
1682
1683 /**
1684 * Build a load.php URL
1685 *
1686 * @since 1.24
1687 * @param string $source Name of the ResourceLoader source
1688 * @param ResourceLoaderContext $context
1689 * @param array $extraQuery
1690 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1691 */
1692 public function createLoaderURL( $source, ResourceLoaderContext $context,
1693 $extraQuery = []
1694 ) {
1695 $query = self::createLoaderQuery( $context, $extraQuery );
1696 $script = $this->getLoadScript( $source );
1697
1698 return wfAppendQuery( $script, $query );
1699 }
1700
1701 /**
1702 * Helper for createLoaderURL()
1703 *
1704 * @since 1.24
1705 * @see makeLoaderQuery
1706 * @param ResourceLoaderContext $context
1707 * @param array $extraQuery
1708 * @return array
1709 */
1710 protected static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = [] ) {
1711 return self::makeLoaderQuery(
1712 $context->getModules(),
1713 $context->getLanguage(),
1714 $context->getSkin(),
1715 $context->getUser(),
1716 $context->getVersion(),
1717 $context->getDebug(),
1718 $context->getOnly(),
1719 $context->getRequest()->getBool( 'printable' ),
1720 $context->getRequest()->getBool( 'handheld' ),
1721 $extraQuery
1722 );
1723 }
1724
1725 /**
1726 * Build a query array (array representation of query string) for load.php. Helper
1727 * function for createLoaderURL().
1728 *
1729 * @param array $modules
1730 * @param string $lang
1731 * @param string $skin
1732 * @param string|null $user
1733 * @param string|null $version
1734 * @param bool $debug
1735 * @param string|null $only
1736 * @param bool $printable
1737 * @param bool $handheld
1738 * @param array $extraQuery
1739 * @return array
1740 */
1741 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1742 $version = null, $debug = false, $only = null, $printable = false,
1743 $handheld = false, $extraQuery = []
1744 ) {
1745 $query = [
1746 'modules' => self::makePackedModulesString( $modules ),
1747 ];
1748 // Keep urls short by omitting query parameters that
1749 // match the defaults assumed by ResourceLoaderContext.
1750 // Note: This relies on the defaults either being insignificant or forever constant,
1751 // as otherwise cached urls could change in meaning when the defaults change.
1752 if ( $lang !== ResourceLoaderContext::DEFAULT_LANG ) {
1753 $query['lang'] = $lang;
1754 }
1755 if ( $skin !== ResourceLoaderContext::DEFAULT_SKIN ) {
1756 $query['skin'] = $skin;
1757 }
1758 if ( $debug === true ) {
1759 $query['debug'] = 'true';
1760 }
1761 if ( $user !== null ) {
1762 $query['user'] = $user;
1763 }
1764 if ( $version !== null ) {
1765 $query['version'] = $version;
1766 }
1767 if ( $only !== null ) {
1768 $query['only'] = $only;
1769 }
1770 if ( $printable ) {
1771 $query['printable'] = 1;
1772 }
1773 if ( $handheld ) {
1774 $query['handheld'] = 1;
1775 }
1776 $query += $extraQuery;
1777
1778 // Make queries uniform in order
1779 ksort( $query );
1780 return $query;
1781 }
1782
1783 /**
1784 * Check a module name for validity.
1785 *
1786 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1787 * at most 255 bytes.
1788 *
1789 * @param string $moduleName Module name to check
1790 * @return bool Whether $moduleName is a valid module name
1791 */
1792 public static function isValidModuleName( $moduleName ) {
1793 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1794 }
1795
1796 /**
1797 * Returns LESS compiler set up for use with MediaWiki
1798 *
1799 * @since 1.27
1800 * @param array $vars Associative array of variables that should be used
1801 * for compilation. Since 1.32, this method no longer automatically includes
1802 * global LESS vars from ResourceLoader::getLessVars (T191937).
1803 * @throws MWException
1804 * @return Less_Parser
1805 */
1806 public function getLessCompiler( $vars = [] ) {
1807 global $IP;
1808 // When called from the installer, it is possible that a required PHP extension
1809 // is missing (at least for now; see T49564). If this is the case, throw an
1810 // exception (caught by the installer) to prevent a fatal error later on.
1811 if ( !class_exists( 'Less_Parser' ) ) {
1812 throw new MWException( 'MediaWiki requires the less.php parser' );
1813 }
1814
1815 $parser = new Less_Parser;
1816 $parser->ModifyVars( $vars );
1817 $parser->SetImportDirs( [
1818 "$IP/resources/src/mediawiki.less/" => '',
1819 ] );
1820 $parser->SetOption( 'relativeUrls', false );
1821
1822 return $parser;
1823 }
1824
1825 /**
1826 * Get global LESS variables.
1827 *
1828 * @since 1.27
1829 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1830 * @return array Map of variable names to string CSS values.
1831 */
1832 public function getLessVars() {
1833 return [];
1834 }
1835 }