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