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