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