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