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