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