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