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