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