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