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