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