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