Merge "Remove id selector for toctitle"
[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, ResourceLoader::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 *
568 * @param string $name Module name
569 * @return bool
570 */
571 protected function isFileModule( $name ) {
572 if ( !isset( $this->moduleInfos[$name] ) ) {
573 return false;
574 }
575 $info = $this->moduleInfos[$name];
576 if (
577 isset( $info['object'] ) ||
578 // This special case is dumb, but we need $wgResourceModuleSkinStyles
579 // to work for 'oojs-ui-core.styles'. See T167042.
580 ( isset( $info['class'] ) && $info['class'] !== 'ResourceLoaderOOUIFileModule' )
581 ) {
582 return false;
583 }
584 return true;
585 }
586
587 /**
588 * Get the list of sources.
589 *
590 * @return array Like [ id => load.php url, ... ]
591 */
592 public function getSources() {
593 return $this->sources;
594 }
595
596 /**
597 * Get the URL to the load.php endpoint for the given
598 * ResourceLoader source
599 *
600 * @since 1.24
601 * @param string $source
602 * @throws MWException On an invalid $source name
603 * @return string
604 */
605 public function getLoadScript( $source ) {
606 if ( !isset( $this->sources[$source] ) ) {
607 throw new MWException( "The $source source was never registered in ResourceLoader." );
608 }
609 return $this->sources[$source];
610 }
611
612 /**
613 * @since 1.26
614 * @param string $value
615 * @return string Hash
616 */
617 public static function makeHash( $value ) {
618 $hash = hash( 'fnv132', $value );
619 return Wikimedia\base_convert( $hash, 16, 36, 7 );
620 }
621
622 /**
623 * Add an error to the 'errors' array and log it.
624 *
625 * Should only be called from within respond().
626 *
627 * @since 1.29
628 * @param Exception $e
629 * @param string $msg
630 * @param array $context
631 */
632 protected function outputErrorAndLog( Exception $e, $msg, array $context = [] ) {
633 MWExceptionHandler::logException( $e );
634 $this->logger->warning(
635 $msg,
636 $context + [ 'exception' => $e ]
637 );
638 $this->errors[] = self::formatExceptionNoComment( $e );
639 }
640
641 /**
642 * Helper method to get and combine versions of multiple modules.
643 *
644 * @since 1.26
645 * @param ResourceLoaderContext $context
646 * @param string[] $modules List of known module names
647 * @return string Hash
648 */
649 public function getCombinedVersion( ResourceLoaderContext $context, array $moduleNames ) {
650 if ( !$moduleNames ) {
651 return '';
652 }
653 $hashes = array_map( function ( $module ) use ( $context ) {
654 try {
655 return $this->getModule( $module )->getVersionHash( $context );
656 } catch ( Exception $e ) {
657 // If modules fail to compute a version, do still consider the versions
658 // of other modules - don't set an empty string E-Tag for the whole request.
659 // See also T152266 and StartupModule::getModuleRegistrations().
660 $this->outputErrorAndLog( $e,
661 'Calculating version for "{module}" failed: {exception}',
662 [
663 'module' => $module,
664 ]
665 );
666 return '';
667 }
668 }, $moduleNames );
669 return self::makeHash( implode( '', $hashes ) );
670 }
671
672 /**
673 * Get the expected value of the 'version' query parameter.
674 *
675 * This is used by respond() to set a short Cache-Control header for requests with
676 * information newer than the current server has. This avoids pollution of edge caches.
677 * Typically during deployment. (T117587)
678 *
679 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
680 *
681 * @since 1.28
682 * @param ResourceLoaderContext $context
683 * @param string[] $modules List of module names
684 * @return string Hash
685 */
686 public function makeVersionQuery( ResourceLoaderContext $context ) {
687 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
688 // version hashes. There is no technical reason for this to be same, and for years the
689 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
690 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
691 // query parameter), then this method must continue to match the JS one.
692 $moduleNames = [];
693 foreach ( $context->getModules() as $name ) {
694 if ( !$this->getModule( $name ) ) {
695 // If a versioned request contains a missing module, the version is a mismatch
696 // as the client considered a module (and version) we don't have.
697 return '';
698 }
699 $moduleNames[] = $name;
700 }
701 return $this->getCombinedVersion( $context, $moduleNames );
702 }
703
704 /**
705 * Output a response to a load request, including the content-type header.
706 *
707 * @param ResourceLoaderContext $context Context in which a response should be formed
708 */
709 public function respond( ResourceLoaderContext $context ) {
710 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
711 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
712 // is used: ob_clean() will clear the GZIP header in that case and it won't come
713 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
714 // the whole thing in our own output buffer to be sure the active buffer
715 // doesn't use ob_gzhandler.
716 // See https://bugs.php.net/bug.php?id=36514
717 ob_start();
718
719 // Find out which modules are missing and instantiate the others
720 $modules = [];
721 $missing = [];
722 foreach ( $context->getModules() as $name ) {
723 $module = $this->getModule( $name );
724 if ( $module ) {
725 // Do not allow private modules to be loaded from the web.
726 // This is a security issue, see T36907.
727 if ( $module->getGroup() === 'private' ) {
728 $this->logger->debug( "Request for private module '$name' denied" );
729 $this->errors[] = "Cannot show private module \"$name\"";
730 continue;
731 }
732 $modules[$name] = $module;
733 } else {
734 $missing[] = $name;
735 }
736 }
737
738 try {
739 // Preload for getCombinedVersion() and for batch makeModuleResponse()
740 $this->preloadModuleInfo( array_keys( $modules ), $context );
741 } catch ( Exception $e ) {
742 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
743 }
744
745 // Combine versions to propagate cache invalidation
746 $versionHash = '';
747 try {
748 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
749 } catch ( Exception $e ) {
750 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
751 }
752
753 // See RFC 2616 § 3.11 Entity Tags
754 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
755 $etag = 'W/"' . $versionHash . '"';
756
757 // Try the client-side cache first
758 if ( $this->tryRespondNotModified( $context, $etag ) ) {
759 return; // output handled (buffers cleared)
760 }
761
762 // Use file cache if enabled and available...
763 if ( $this->config->get( 'UseFileCache' ) ) {
764 $fileCache = ResourceFileCache::newFromContext( $context );
765 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
766 return; // output handled
767 }
768 }
769
770 // Generate a response
771 $response = $this->makeModuleResponse( $context, $modules, $missing );
772
773 // Capture any PHP warnings from the output buffer and append them to the
774 // error list if we're in debug mode.
775 if ( $context->getDebug() ) {
776 $warnings = ob_get_contents();
777 if ( strlen( $warnings ) ) {
778 $this->errors[] = $warnings;
779 }
780 }
781
782 // Save response to file cache unless there are errors
783 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
784 // Cache single modules and images...and other requests if there are enough hits
785 if ( ResourceFileCache::useFileCache( $context ) ) {
786 if ( $fileCache->isCacheWorthy() ) {
787 $fileCache->saveText( $response );
788 } else {
789 $fileCache->incrMissesRecent( $context->getRequest() );
790 }
791 }
792 }
793
794 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors );
795
796 // Remove the output buffer and output the response
797 ob_end_clean();
798
799 if ( $context->getImageObj() && $this->errors ) {
800 // We can't show both the error messages and the response when it's an image.
801 $response = implode( "\n\n", $this->errors );
802 } elseif ( $this->errors ) {
803 $errorText = implode( "\n\n", $this->errors );
804 $errorResponse = self::makeComment( $errorText );
805 if ( $context->shouldIncludeScripts() ) {
806 $errorResponse .= 'if (window.console && console.error) {'
807 . Xml::encodeJsCall( 'console.error', [ $errorText ] )
808 . "}\n";
809 }
810
811 // Prepend error info to the response
812 $response = $errorResponse . $response;
813 }
814
815 $this->errors = [];
816 echo $response;
817 }
818
819 /**
820 * Send main response headers to the client.
821 *
822 * Deals with Content-Type, CORS (for stylesheets), and caching.
823 *
824 * @param ResourceLoaderContext $context
825 * @param string $etag ETag header value
826 * @param bool $errors Whether there are errors in the response
827 * @return void
828 */
829 protected function sendResponseHeaders( ResourceLoaderContext $context, $etag, $errors ) {
830 \MediaWiki\HeaderCallback::warnIfHeadersSent();
831 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
832 // Use a short cache expiry so that updates propagate to clients quickly, if:
833 // - No version specified (shared resources, e.g. stylesheets)
834 // - There were errors (recover quickly)
835 // - Version mismatch (T117587, T47877)
836 if ( is_null( $context->getVersion() )
837 || $errors
838 || $context->getVersion() !== $this->makeVersionQuery( $context )
839 ) {
840 $maxage = $rlMaxage['unversioned']['client'];
841 $smaxage = $rlMaxage['unversioned']['server'];
842 // If a version was specified we can use a longer expiry time since changing
843 // version numbers causes cache misses
844 } else {
845 $maxage = $rlMaxage['versioned']['client'];
846 $smaxage = $rlMaxage['versioned']['server'];
847 }
848 if ( $context->getImageObj() ) {
849 // Output different headers if we're outputting textual errors.
850 if ( $errors ) {
851 header( 'Content-Type: text/plain; charset=utf-8' );
852 } else {
853 $context->getImageObj()->sendResponseHeaders( $context );
854 }
855 } elseif ( $context->getOnly() === 'styles' ) {
856 header( 'Content-Type: text/css; charset=utf-8' );
857 header( 'Access-Control-Allow-Origin: *' );
858 } else {
859 header( 'Content-Type: text/javascript; charset=utf-8' );
860 }
861 // See RFC 2616 § 14.19 ETag
862 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
863 header( 'ETag: ' . $etag );
864 if ( $context->getDebug() ) {
865 // Do not cache debug responses
866 header( 'Cache-Control: private, no-cache, must-revalidate' );
867 header( 'Pragma: no-cache' );
868 } else {
869 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
870 $exp = min( $maxage, $smaxage );
871 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
872 }
873 }
874
875 /**
876 * Respond with HTTP 304 Not Modified if appropiate.
877 *
878 * If there's an If-None-Match header, respond with a 304 appropriately
879 * and clear out the output buffer. If the client cache is too old then do nothing.
880 *
881 * @param ResourceLoaderContext $context
882 * @param string $etag ETag header value
883 * @return bool True if HTTP 304 was sent and output handled
884 */
885 protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
886 // See RFC 2616 § 14.26 If-None-Match
887 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
888 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
889 // Never send 304s in debug mode
890 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
891 // There's another bug in ob_gzhandler (see also the comment at
892 // the top of this function) that causes it to gzip even empty
893 // responses, meaning it's impossible to produce a truly empty
894 // response (because the gzip header is always there). This is
895 // a problem because 304 responses have to be completely empty
896 // per the HTTP spec, and Firefox behaves buggily when they're not.
897 // See also https://bugs.php.net/bug.php?id=51579
898 // To work around this, we tear down all output buffering before
899 // sending the 304.
900 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
901
902 HttpStatus::header( 304 );
903
904 $this->sendResponseHeaders( $context, $etag, false );
905 return true;
906 }
907 return false;
908 }
909
910 /**
911 * Send out code for a response from file cache if possible.
912 *
913 * @param ResourceFileCache $fileCache Cache object for this request URL
914 * @param ResourceLoaderContext $context Context in which to generate a response
915 * @param string $etag ETag header value
916 * @return bool If this found a cache file and handled the response
917 */
918 protected function tryRespondFromFileCache(
919 ResourceFileCache $fileCache,
920 ResourceLoaderContext $context,
921 $etag
922 ) {
923 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
924 // Buffer output to catch warnings.
925 ob_start();
926 // Get the maximum age the cache can be
927 $maxage = is_null( $context->getVersion() )
928 ? $rlMaxage['unversioned']['server']
929 : $rlMaxage['versioned']['server'];
930 // Minimum timestamp the cache file must have
931 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
932 if ( !$good ) {
933 try { // RL always hits the DB on file cache miss...
934 wfGetDB( DB_REPLICA );
935 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
936 $good = $fileCache->isCacheGood(); // cache existence check
937 }
938 }
939 if ( $good ) {
940 $ts = $fileCache->cacheTimestamp();
941 // Send content type and cache headers
942 $this->sendResponseHeaders( $context, $etag, false );
943 $response = $fileCache->fetchText();
944 // Capture any PHP warnings from the output buffer and append them to the
945 // response in a comment if we're in debug mode.
946 if ( $context->getDebug() ) {
947 $warnings = ob_get_contents();
948 if ( strlen( $warnings ) ) {
949 $response = self::makeComment( $warnings ) . $response;
950 }
951 }
952 // Remove the output buffer and output the response
953 ob_end_clean();
954 echo $response . "\n/* Cached {$ts} */";
955 return true; // cache hit
956 }
957 // Clear buffer
958 ob_end_clean();
959
960 return false; // cache miss
961 }
962
963 /**
964 * Generate a CSS or JS comment block.
965 *
966 * Only use this for public data, not error message details.
967 *
968 * @param string $text
969 * @return string
970 */
971 public static function makeComment( $text ) {
972 $encText = str_replace( '*/', '* /', $text );
973 return "/*\n$encText\n*/\n";
974 }
975
976 /**
977 * Handle exception display.
978 *
979 * @param Exception $e Exception to be shown to the user
980 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
981 */
982 public static function formatException( $e ) {
983 return self::makeComment( self::formatExceptionNoComment( $e ) );
984 }
985
986 /**
987 * Handle exception display.
988 *
989 * @since 1.25
990 * @param Exception $e Exception to be shown to the user
991 * @return string Sanitized text that can be returned to the user
992 */
993 protected static function formatExceptionNoComment( $e ) {
994 global $wgShowExceptionDetails;
995
996 if ( !$wgShowExceptionDetails ) {
997 return MWExceptionHandler::getPublicLogMessage( $e );
998 }
999
1000 return MWExceptionHandler::getLogMessage( $e ) .
1001 "\nBacktrace:\n" .
1002 MWExceptionHandler::getRedactedTraceAsString( $e );
1003 }
1004
1005 /**
1006 * Generate code for a response.
1007 *
1008 * @param ResourceLoaderContext $context Context in which to generate a response
1009 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
1010 * @param string[] $missing List of requested module names that are unregistered (optional)
1011 * @return string Response data
1012 */
1013 public function makeModuleResponse( ResourceLoaderContext $context,
1014 array $modules, array $missing = []
1015 ) {
1016 $out = '';
1017 $states = [];
1018
1019 if ( !count( $modules ) && !count( $missing ) ) {
1020 return <<<MESSAGE
1021 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1022 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1023 no modules were requested. Max made me put this here. */
1024 MESSAGE;
1025 }
1026
1027 $image = $context->getImageObj();
1028 if ( $image ) {
1029 $data = $image->getImageData( $context );
1030 if ( $data === false ) {
1031 $data = '';
1032 $this->errors[] = 'Image generation failed';
1033 }
1034 return $data;
1035 }
1036
1037 foreach ( $missing as $name ) {
1038 $states[$name] = 'missing';
1039 }
1040
1041 // Generate output
1042 $isRaw = false;
1043
1044 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
1045
1046 foreach ( $modules as $name => $module ) {
1047 try {
1048 $content = $module->getModuleContent( $context );
1049 $implementKey = $name . '@' . $module->getVersionHash( $context );
1050 $strContent = '';
1051
1052 // Append output
1053 switch ( $context->getOnly() ) {
1054 case 'scripts':
1055 $scripts = $content['scripts'];
1056 if ( is_string( $scripts ) ) {
1057 // Load scripts raw...
1058 $strContent = $scripts;
1059 } elseif ( is_array( $scripts ) ) {
1060 // ...except when $scripts is an array of URLs
1061 $strContent = self::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1062 }
1063 break;
1064 case 'styles':
1065 $styles = $content['styles'];
1066 // We no longer seperate into media, they are all combined now with
1067 // custom media type groups into @media .. {} sections as part of the css string.
1068 // Module returns either an empty array or a numerical array with css strings.
1069 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1070 break;
1071 default:
1072 $scripts = isset( $content['scripts'] ) ? $content['scripts'] : '';
1073 if ( is_string( $scripts ) ) {
1074 if ( $name === 'site' || $name === 'user' ) {
1075 // Legacy scripts that run in the global scope without a closure.
1076 // mw.loader.implement will use globalEval if scripts is a string.
1077 // Minify manually here, because general response minification is
1078 // not effective due it being a string literal, not a function.
1079 if ( !ResourceLoader::inDebugMode() ) {
1080 $scripts = self::filter( 'minify-js', $scripts ); // T107377
1081 }
1082 } else {
1083 $scripts = new XmlJsCode( $scripts );
1084 }
1085 }
1086 $strContent = self::makeLoaderImplementScript(
1087 $implementKey,
1088 $scripts,
1089 isset( $content['styles'] ) ? $content['styles'] : [],
1090 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : [],
1091 isset( $content['templates'] ) ? $content['templates'] : []
1092 );
1093 break;
1094 }
1095
1096 if ( !$context->getDebug() ) {
1097 $strContent = self::filter( $filter, $strContent );
1098 }
1099
1100 $out .= $strContent;
1101
1102 } catch ( Exception $e ) {
1103 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1104
1105 // Respond to client with error-state instead of module implementation
1106 $states[$name] = 'error';
1107 unset( $modules[$name] );
1108 }
1109 $isRaw |= $module->isRaw();
1110 }
1111
1112 // Update module states
1113 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1114 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1115 // Set the state of modules loaded as only scripts to ready as
1116 // they don't have an mw.loader.implement wrapper that sets the state
1117 foreach ( $modules as $name => $module ) {
1118 $states[$name] = 'ready';
1119 }
1120 }
1121
1122 // Set the state of modules we didn't respond to with mw.loader.implement
1123 if ( count( $states ) ) {
1124 $stateScript = self::makeLoaderStateScript( $states );
1125 if ( !$context->getDebug() ) {
1126 $stateScript = self::filter( 'minify-js', $stateScript );
1127 }
1128 $out .= $stateScript;
1129 }
1130 } else {
1131 if ( count( $states ) ) {
1132 $this->errors[] = 'Problematic modules: ' .
1133 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1134 }
1135 }
1136
1137 return $out;
1138 }
1139
1140 /**
1141 * Get names of modules that use a certain message.
1142 *
1143 * @param string $messageKey
1144 * @return array List of module names
1145 */
1146 public function getModulesByMessage( $messageKey ) {
1147 $moduleNames = [];
1148 foreach ( $this->getModuleNames() as $moduleName ) {
1149 $module = $this->getModule( $moduleName );
1150 if ( in_array( $messageKey, $module->getMessages() ) ) {
1151 $moduleNames[] = $moduleName;
1152 }
1153 }
1154 return $moduleNames;
1155 }
1156
1157 /* Static Methods */
1158
1159 /**
1160 * Return JS code that calls mw.loader.implement with given module properties.
1161 *
1162 * @param string $name Module name or implement key (format "`[name]@[version]`")
1163 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1164 * list of URLs to JavaScript files, or a string of JavaScript for `$.globalEval`.
1165 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1166 * to CSS files keyed by media type
1167 * @param mixed $messages List of messages associated with this module. May either be an
1168 * associative array mapping message key to value, or a JSON-encoded message blob containing
1169 * the same data, wrapped in an XmlJsCode object.
1170 * @param array $templates Keys are name of templates and values are the source of
1171 * the template.
1172 * @throws MWException
1173 * @return string JavaScript code
1174 */
1175 protected static function makeLoaderImplementScript(
1176 $name, $scripts, $styles, $messages, $templates
1177 ) {
1178 if ( $scripts instanceof XmlJsCode ) {
1179 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1180 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1181 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1182 }
1183 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1184 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1185 // of "{}". Force them to objects.
1186 $module = [
1187 $name,
1188 $scripts,
1189 (object)$styles,
1190 (object)$messages,
1191 (object)$templates,
1192 ];
1193 self::trimArray( $module );
1194
1195 return Xml::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader::inDebugMode() );
1196 }
1197
1198 /**
1199 * Returns JS code which, when called, will register a given list of messages.
1200 *
1201 * @param mixed $messages Either an associative array mapping message key to value, or a
1202 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1203 * @return string JavaScript code
1204 */
1205 public static function makeMessageSetScript( $messages ) {
1206 return Xml::encodeJsCall(
1207 'mw.messages.set',
1208 [ (object)$messages ],
1209 ResourceLoader::inDebugMode()
1210 );
1211 }
1212
1213 /**
1214 * Combines an associative array mapping media type to CSS into a
1215 * single stylesheet with "@media" blocks.
1216 *
1217 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1218 * @return array
1219 */
1220 public static function makeCombinedStyles( array $stylePairs ) {
1221 $out = [];
1222 foreach ( $stylePairs as $media => $styles ) {
1223 // ResourceLoaderFileModule::getStyle can return the styles
1224 // as a string or an array of strings. This is to allow separation in
1225 // the front-end.
1226 $styles = (array)$styles;
1227 foreach ( $styles as $style ) {
1228 $style = trim( $style );
1229 // Don't output an empty "@media print { }" block (T42498)
1230 if ( $style !== '' ) {
1231 // Transform the media type based on request params and config
1232 // The way that this relies on $wgRequest to propagate request params is slightly evil
1233 $media = OutputPage::transformCssMedia( $media );
1234
1235 if ( $media === '' || $media == 'all' ) {
1236 $out[] = $style;
1237 } elseif ( is_string( $media ) ) {
1238 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1239 }
1240 // else: skip
1241 }
1242 }
1243 }
1244 return $out;
1245 }
1246
1247 /**
1248 * Returns a JS call to mw.loader.state, which sets the state of a
1249 * module or modules to a given value. Has two calling conventions:
1250 *
1251 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1252 * Set the state of a single module called $name to $state
1253 *
1254 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1255 * Set the state of modules with the given names to the given states
1256 *
1257 * @param string $name
1258 * @param string $state
1259 * @return string JavaScript code
1260 */
1261 public static function makeLoaderStateScript( $name, $state = null ) {
1262 if ( is_array( $name ) ) {
1263 return Xml::encodeJsCall(
1264 'mw.loader.state',
1265 [ $name ],
1266 ResourceLoader::inDebugMode()
1267 );
1268 } else {
1269 return Xml::encodeJsCall(
1270 'mw.loader.state',
1271 [ $name, $state ],
1272 ResourceLoader::inDebugMode()
1273 );
1274 }
1275 }
1276
1277 /**
1278 * Returns JS code which calls the script given by $script. The script will
1279 * be called with local variables name, version, dependencies and group,
1280 * which will have values corresponding to $name, $version, $dependencies
1281 * and $group as supplied.
1282 *
1283 * @param string $name Module name
1284 * @param string $version Module version hash
1285 * @param array $dependencies List of module names on which this module depends
1286 * @param string $group Group which the module is in.
1287 * @param string $source Source of the module, or 'local' if not foreign.
1288 * @param string $script JavaScript code
1289 * @return string JavaScript code
1290 */
1291 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1292 $group, $source, $script
1293 ) {
1294 $script = str_replace( "\n", "\n\t", trim( $script ) );
1295 return Xml::encodeJsCall(
1296 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1297 [ $name, $version, $dependencies, $group, $source ],
1298 ResourceLoader::inDebugMode()
1299 );
1300 }
1301
1302 private static function isEmptyObject( stdClass $obj ) {
1303 foreach ( $obj as $key => $value ) {
1304 return false;
1305 }
1306 return true;
1307 }
1308
1309 /**
1310 * Remove empty values from the end of an array.
1311 *
1312 * Values considered empty:
1313 *
1314 * - null
1315 * - []
1316 * - new XmlJsCode( '{}' )
1317 * - new stdClass() // (object) []
1318 *
1319 * @param Array $array
1320 */
1321 private static function trimArray( array &$array ) {
1322 $i = count( $array );
1323 while ( $i-- ) {
1324 if ( $array[$i] === null
1325 || $array[$i] === []
1326 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1327 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1328 ) {
1329 unset( $array[$i] );
1330 } else {
1331 break;
1332 }
1333 }
1334 }
1335
1336 /**
1337 * Returns JS code which calls mw.loader.register with the given
1338 * parameters. Has three calling conventions:
1339 *
1340 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1341 * $dependencies, $group, $source, $skip
1342 * ):
1343 * Register a single module.
1344 *
1345 * - ResourceLoader::makeLoaderRegisterScript( [ $name1, $name2 ] ):
1346 * Register modules with the given names.
1347 *
1348 * - ResourceLoader::makeLoaderRegisterScript( [
1349 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1350 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1351 * ...
1352 * ] ):
1353 * Registers modules with the given names and parameters.
1354 *
1355 * @param string $name Module name
1356 * @param string $version Module version hash
1357 * @param array $dependencies List of module names on which this module depends
1358 * @param string $group Group which the module is in
1359 * @param string $source Source of the module, or 'local' if not foreign
1360 * @param string $skip Script body of the skip function
1361 * @return string JavaScript code
1362 */
1363 public static function makeLoaderRegisterScript( $name, $version = null,
1364 $dependencies = null, $group = null, $source = null, $skip = null
1365 ) {
1366 if ( is_array( $name ) ) {
1367 // Build module name index
1368 $index = [];
1369 foreach ( $name as $i => &$module ) {
1370 $index[$module[0]] = $i;
1371 }
1372
1373 // Transform dependency names into indexes when possible, they will be resolved by
1374 // mw.loader.register on the other end
1375 foreach ( $name as &$module ) {
1376 if ( isset( $module[2] ) ) {
1377 foreach ( $module[2] as &$dependency ) {
1378 if ( isset( $index[$dependency] ) ) {
1379 $dependency = $index[$dependency];
1380 }
1381 }
1382 }
1383 }
1384
1385 array_walk( $name, [ 'self', 'trimArray' ] );
1386
1387 return Xml::encodeJsCall(
1388 'mw.loader.register',
1389 [ $name ],
1390 ResourceLoader::inDebugMode()
1391 );
1392 } else {
1393 $registration = [ $name, $version, $dependencies, $group, $source, $skip ];
1394 self::trimArray( $registration );
1395 return Xml::encodeJsCall(
1396 'mw.loader.register',
1397 $registration,
1398 ResourceLoader::inDebugMode()
1399 );
1400 }
1401 }
1402
1403 /**
1404 * Returns JS code which calls mw.loader.addSource() with the given
1405 * parameters. Has two calling conventions:
1406 *
1407 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1408 * Register a single source
1409 *
1410 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1411 * Register sources with the given IDs and properties.
1412 *
1413 * @param string $id Source ID
1414 * @param string $loadUrl load.php url
1415 * @return string JavaScript code
1416 */
1417 public static function makeLoaderSourcesScript( $id, $loadUrl = null ) {
1418 if ( is_array( $id ) ) {
1419 return Xml::encodeJsCall(
1420 'mw.loader.addSource',
1421 [ $id ],
1422 ResourceLoader::inDebugMode()
1423 );
1424 } else {
1425 return Xml::encodeJsCall(
1426 'mw.loader.addSource',
1427 [ $id, $loadUrl ],
1428 ResourceLoader::inDebugMode()
1429 );
1430 }
1431 }
1432
1433 /**
1434 * Returns JS code which runs given JS code if the client-side framework is
1435 * present.
1436 *
1437 * @deprecated since 1.25; use makeInlineScript instead
1438 * @param string $script JavaScript code
1439 * @return string JavaScript code
1440 */
1441 public static function makeLoaderConditionalScript( $script ) {
1442 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1443 trim( $script ) . '});';
1444 }
1445
1446 /**
1447 * Construct an inline script tag with given JS code.
1448 *
1449 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1450 * only if the client has adequate support for MediaWiki JavaScript code.
1451 *
1452 * @param string $script JavaScript code
1453 * @return WrappedString HTML
1454 */
1455 public static function makeInlineScript( $script ) {
1456 $js = self::makeLoaderConditionalScript( $script );
1457 return new WrappedString(
1458 Html::inlineScript( $js ),
1459 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1460 '});</script>'
1461 );
1462 }
1463
1464 /**
1465 * Returns JS code which will set the MediaWiki configuration array to
1466 * the given value.
1467 *
1468 * @param array $configuration List of configuration values keyed by variable name
1469 * @return string JavaScript code
1470 */
1471 public static function makeConfigSetScript( array $configuration ) {
1472 return Xml::encodeJsCall(
1473 'mw.config.set',
1474 [ $configuration ],
1475 ResourceLoader::inDebugMode()
1476 );
1477 }
1478
1479 /**
1480 * Convert an array of module names to a packed query string.
1481 *
1482 * For example, [ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]
1483 * becomes 'foo.bar,baz|bar.baz,quux'
1484 * @param array $modules List of module names (strings)
1485 * @return string Packed query string
1486 */
1487 public static function makePackedModulesString( $modules ) {
1488 $groups = []; // [ prefix => [ suffixes ] ]
1489 foreach ( $modules as $module ) {
1490 $pos = strrpos( $module, '.' );
1491 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1492 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1493 $groups[$prefix][] = $suffix;
1494 }
1495
1496 $arr = [];
1497 foreach ( $groups as $prefix => $suffixes ) {
1498 $p = $prefix === '' ? '' : $prefix . '.';
1499 $arr[] = $p . implode( ',', $suffixes );
1500 }
1501 $str = implode( '|', $arr );
1502 return $str;
1503 }
1504
1505 /**
1506 * Determine whether debug mode was requested
1507 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1508 * @return bool
1509 */
1510 public static function inDebugMode() {
1511 if ( self::$debugMode === null ) {
1512 global $wgRequest, $wgResourceLoaderDebug;
1513 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1514 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1515 );
1516 }
1517 return self::$debugMode;
1518 }
1519
1520 /**
1521 * Reset static members used for caching.
1522 *
1523 * Global state and $wgRequest are evil, but we're using it right
1524 * now and sometimes we need to be able to force ResourceLoader to
1525 * re-evaluate the context because it has changed (e.g. in the test suite).
1526 */
1527 public static function clearCache() {
1528 self::$debugMode = null;
1529 }
1530
1531 /**
1532 * Build a load.php URL
1533 *
1534 * @since 1.24
1535 * @param string $source Name of the ResourceLoader source
1536 * @param ResourceLoaderContext $context
1537 * @param array $extraQuery
1538 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1539 */
1540 public function createLoaderURL( $source, ResourceLoaderContext $context,
1541 $extraQuery = []
1542 ) {
1543 $query = self::createLoaderQuery( $context, $extraQuery );
1544 $script = $this->getLoadScript( $source );
1545
1546 return wfAppendQuery( $script, $query );
1547 }
1548
1549 /**
1550 * Helper for createLoaderURL()
1551 *
1552 * @since 1.24
1553 * @see makeLoaderQuery
1554 * @param ResourceLoaderContext $context
1555 * @param array $extraQuery
1556 * @return array
1557 */
1558 protected static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = [] ) {
1559 return self::makeLoaderQuery(
1560 $context->getModules(),
1561 $context->getLanguage(),
1562 $context->getSkin(),
1563 $context->getUser(),
1564 $context->getVersion(),
1565 $context->getDebug(),
1566 $context->getOnly(),
1567 $context->getRequest()->getBool( 'printable' ),
1568 $context->getRequest()->getBool( 'handheld' ),
1569 $extraQuery
1570 );
1571 }
1572
1573 /**
1574 * Build a query array (array representation of query string) for load.php. Helper
1575 * function for createLoaderURL().
1576 *
1577 * @param array $modules
1578 * @param string $lang
1579 * @param string $skin
1580 * @param string $user
1581 * @param string $version
1582 * @param bool $debug
1583 * @param string $only
1584 * @param bool $printable
1585 * @param bool $handheld
1586 * @param array $extraQuery
1587 *
1588 * @return array
1589 */
1590 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1591 $version = null, $debug = false, $only = null, $printable = false,
1592 $handheld = false, $extraQuery = []
1593 ) {
1594 $query = [
1595 'modules' => self::makePackedModulesString( $modules ),
1596 'lang' => $lang,
1597 'skin' => $skin,
1598 'debug' => $debug ? 'true' : 'false',
1599 ];
1600 if ( $user !== null ) {
1601 $query['user'] = $user;
1602 }
1603 if ( $version !== null ) {
1604 $query['version'] = $version;
1605 }
1606 if ( $only !== null ) {
1607 $query['only'] = $only;
1608 }
1609 if ( $printable ) {
1610 $query['printable'] = 1;
1611 }
1612 if ( $handheld ) {
1613 $query['handheld'] = 1;
1614 }
1615 $query += $extraQuery;
1616
1617 // Make queries uniform in order
1618 ksort( $query );
1619 return $query;
1620 }
1621
1622 /**
1623 * Check a module name for validity.
1624 *
1625 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1626 * at most 255 bytes.
1627 *
1628 * @param string $moduleName Module name to check
1629 * @return bool Whether $moduleName is a valid module name
1630 */
1631 public static function isValidModuleName( $moduleName ) {
1632 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1633 }
1634
1635 /**
1636 * Returns LESS compiler set up for use with MediaWiki
1637 *
1638 * @since 1.27
1639 * @param array $extraVars Associative array of extra (i.e., other than the
1640 * globally-configured ones) that should be used for compilation.
1641 * @throws MWException
1642 * @return Less_Parser
1643 */
1644 public function getLessCompiler( $extraVars = [] ) {
1645 // When called from the installer, it is possible that a required PHP extension
1646 // is missing (at least for now; see T49564). If this is the case, throw an
1647 // exception (caught by the installer) to prevent a fatal error later on.
1648 if ( !class_exists( 'Less_Parser' ) ) {
1649 throw new MWException( 'MediaWiki requires the less.php parser' );
1650 }
1651
1652 $parser = new Less_Parser;
1653 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1654 $parser->SetImportDirs(
1655 array_fill_keys( $this->config->get( 'ResourceLoaderLESSImportPaths' ), '' )
1656 );
1657 $parser->SetOption( 'relativeUrls', false );
1658
1659 return $parser;
1660 }
1661
1662 /**
1663 * Get global LESS variables.
1664 *
1665 * @since 1.27
1666 * @return array Map of variable names to string CSS values.
1667 */
1668 public function getLessVars() {
1669 if ( !$this->lessVars ) {
1670 $lessVars = $this->config->get( 'ResourceLoaderLESSVars' );
1671 Hooks::run( 'ResourceLoaderGetLessVars', [ &$lessVars ] );
1672 $this->lessVars = $lessVars;
1673 }
1674 return $this->lessVars;
1675 }
1676 }