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