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