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