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