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