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