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