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