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