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