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