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