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