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