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