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