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