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