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