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