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