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