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