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