resourceloader: Make ResourceLoader logger aware
[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 header( 'HTTP/1.0 304 Not Modified' );
825 header( 'Status: 304 Not Modified' );
826
827 $this->sendResponseHeaders( $context, $etag, false );
828 return true;
829 }
830 return false;
831 }
832
833 /**
834 * Send out code for a response from file cache if possible.
835 *
836 * @param ResourceFileCache $fileCache Cache object for this request URL
837 * @param ResourceLoaderContext $context Context in which to generate a response
838 * @param string $etag ETag header value
839 * @return bool If this found a cache file and handled the response
840 */
841 protected function tryRespondFromFileCache(
842 ResourceFileCache $fileCache,
843 ResourceLoaderContext $context,
844 $etag
845 ) {
846 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
847 // Buffer output to catch warnings.
848 ob_start();
849 // Get the maximum age the cache can be
850 $maxage = is_null( $context->getVersion() )
851 ? $rlMaxage['unversioned']['server']
852 : $rlMaxage['versioned']['server'];
853 // Minimum timestamp the cache file must have
854 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
855 if ( !$good ) {
856 try { // RL always hits the DB on file cache miss...
857 wfGetDB( DB_SLAVE );
858 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
859 $good = $fileCache->isCacheGood(); // cache existence check
860 }
861 }
862 if ( $good ) {
863 $ts = $fileCache->cacheTimestamp();
864 // Send content type and cache headers
865 $this->sendResponseHeaders( $context, $etag, false );
866 $response = $fileCache->fetchText();
867 // Capture any PHP warnings from the output buffer and append them to the
868 // response in a comment if we're in debug mode.
869 if ( $context->getDebug() && strlen( $warnings = ob_get_contents() ) ) {
870 $response = self::makeComment( $warnings ) . $response;
871 }
872 // Remove the output buffer and output the response
873 ob_end_clean();
874 echo $response . "\n/* Cached {$ts} */";
875 return true; // cache hit
876 }
877 // Clear buffer
878 ob_end_clean();
879
880 return false; // cache miss
881 }
882
883 /**
884 * Generate a CSS or JS comment block.
885 *
886 * Only use this for public data, not error message details.
887 *
888 * @param string $text
889 * @return string
890 */
891 public static function makeComment( $text ) {
892 $encText = str_replace( '*/', '* /', $text );
893 return "/*\n$encText\n*/\n";
894 }
895
896 /**
897 * Handle exception display.
898 *
899 * @param Exception $e Exception to be shown to the user
900 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
901 */
902 public static function formatException( $e ) {
903 return self::makeComment( self::formatExceptionNoComment( $e ) );
904 }
905
906 /**
907 * Handle exception display.
908 *
909 * @since 1.25
910 * @param Exception $e Exception to be shown to the user
911 * @return string Sanitized text that can be returned to the user
912 */
913 protected static function formatExceptionNoComment( $e ) {
914 global $wgShowExceptionDetails;
915
916 if ( $wgShowExceptionDetails ) {
917 return $e->__toString();
918 } else {
919 return wfMessage( 'internalerror' )->text();
920 }
921 }
922
923 /**
924 * Generate code for a response.
925 *
926 * @param ResourceLoaderContext $context Context in which to generate a response
927 * @param array $modules List of module objects keyed by module name
928 * @param array $missing List of requested module names that are unregistered (optional)
929 * @return string Response data
930 */
931 public function makeModuleResponse( ResourceLoaderContext $context,
932 array $modules, array $missing = array()
933 ) {
934 $out = '';
935 $states = array();
936
937 if ( !count( $modules ) && !count( $missing ) ) {
938 return <<<MESSAGE
939 /* This file is the Web entry point for MediaWiki's ResourceLoader:
940 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
941 no modules were requested. Max made me put this here. */
942 MESSAGE;
943 }
944
945 $image = $context->getImageObj();
946 if ( $image ) {
947 $data = $image->getImageData( $context );
948 if ( $data === false ) {
949 $data = '';
950 $this->errors[] = 'Image generation failed';
951 }
952 return $data;
953 }
954
955 // Pre-fetch blobs
956 if ( $context->shouldIncludeMessages() ) {
957 try {
958 $blobs = $this->blobStore->get( $this, $modules, $context->getLanguage() );
959 } catch ( Exception $e ) {
960 MWExceptionHandler::logException( $e );
961 $this->logger->info(
962 __METHOD__ . ": pre-fetching blobs from MessageBlobStore failed: $e"
963 );
964 $this->errors[] = self::formatExceptionNoComment( $e );
965 }
966 } else {
967 $blobs = array();
968 }
969
970 foreach ( $missing as $name ) {
971 $states[$name] = 'missing';
972 }
973
974 // Generate output
975 $isRaw = false;
976 foreach ( $modules as $name => $module ) {
977 /**
978 * @var $module ResourceLoaderModule
979 */
980
981 try {
982 $scripts = '';
983 if ( $context->shouldIncludeScripts() ) {
984 // If we are in debug mode, we'll want to return an array of URLs if possible
985 // However, we can't do this if the module doesn't support it
986 // We also can't do this if there is an only= parameter, because we have to give
987 // the module a way to return a load.php URL without causing an infinite loop
988 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
989 $scripts = $module->getScriptURLsForDebug( $context );
990 } else {
991 $scripts = $module->getScript( $context );
992 // rtrim() because there are usually a few line breaks
993 // after the last ';'. A new line at EOF, a new line
994 // added by ResourceLoaderFileModule::readScriptFiles, etc.
995 if ( is_string( $scripts )
996 && strlen( $scripts )
997 && substr( rtrim( $scripts ), -1 ) !== ';'
998 ) {
999 // Append semicolon to prevent weird bugs caused by files not
1000 // terminating their statements right (bug 27054)
1001 $scripts .= ";\n";
1002 }
1003 }
1004 }
1005 // Styles
1006 $styles = array();
1007 if ( $context->shouldIncludeStyles() ) {
1008 // Don't create empty stylesheets like array( '' => '' ) for modules
1009 // that don't *have* any stylesheets (bug 38024).
1010 $stylePairs = $module->getStyles( $context );
1011 if ( count( $stylePairs ) ) {
1012 // If we are in debug mode without &only= set, we'll want to return an array of URLs
1013 // See comment near shouldIncludeScripts() for more details
1014 if ( $context->getDebug() && !$context->getOnly() && $module->supportsURLLoading() ) {
1015 $styles = array(
1016 'url' => $module->getStyleURLsForDebug( $context )
1017 );
1018 } else {
1019 // Minify CSS before embedding in mw.loader.implement call
1020 // (unless in debug mode)
1021 if ( !$context->getDebug() ) {
1022 foreach ( $stylePairs as $media => $style ) {
1023 // Can be either a string or an array of strings.
1024 if ( is_array( $style ) ) {
1025 $stylePairs[$media] = array();
1026 foreach ( $style as $cssText ) {
1027 if ( is_string( $cssText ) ) {
1028 $stylePairs[$media][] = $this->filter( 'minify-css', $cssText );
1029 }
1030 }
1031 } elseif ( is_string( $style ) ) {
1032 $stylePairs[$media] = $this->filter( 'minify-css', $style );
1033 }
1034 }
1035 }
1036 // Wrap styles into @media groups as needed and flatten into a numerical array
1037 $styles = array(
1038 'css' => self::makeCombinedStyles( $stylePairs )
1039 );
1040 }
1041 }
1042 }
1043
1044 // Messages
1045 $messagesBlob = isset( $blobs[$name] ) ? $blobs[$name] : '{}';
1046
1047 // Append output
1048 switch ( $context->getOnly() ) {
1049 case 'scripts':
1050 if ( is_string( $scripts ) ) {
1051 // Load scripts raw...
1052 $out .= $scripts;
1053 } elseif ( is_array( $scripts ) ) {
1054 // ...except when $scripts is an array of URLs
1055 $out .= self::makeLoaderImplementScript( $name, $scripts, array(), array() );
1056 }
1057 break;
1058 case 'styles':
1059 // We no longer seperate into media, they are all combined now with
1060 // custom media type groups into @media .. {} sections as part of the css string.
1061 // Module returns either an empty array or a numerical array with css strings.
1062 $out .= isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1063 break;
1064 default:
1065 $out .= self::makeLoaderImplementScript(
1066 $name,
1067 $scripts,
1068 $styles,
1069 new XmlJsCode( $messagesBlob ),
1070 $module->getTemplates()
1071 );
1072 break;
1073 }
1074 } catch ( Exception $e ) {
1075 MWExceptionHandler::logException( $e );
1076 $this->logger->info( __METHOD__ . ": generating module package failed: $e" );
1077 $this->errors[] = self::formatExceptionNoComment( $e );
1078
1079 // Respond to client with error-state instead of module implementation
1080 $states[$name] = 'error';
1081 unset( $modules[$name] );
1082 }
1083 $isRaw |= $module->isRaw();
1084 }
1085
1086 // Update module states
1087 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1088 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1089 // Set the state of modules loaded as only scripts to ready as
1090 // they don't have an mw.loader.implement wrapper that sets the state
1091 foreach ( $modules as $name => $module ) {
1092 $states[$name] = 'ready';
1093 }
1094 }
1095
1096 // Set the state of modules we didn't respond to with mw.loader.implement
1097 if ( count( $states ) ) {
1098 $out .= self::makeLoaderStateScript( $states );
1099 }
1100 } else {
1101 if ( count( $states ) ) {
1102 $this->errors[] = 'Problematic modules: ' .
1103 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1104 }
1105 }
1106
1107 $enableFilterCache = true;
1108 if ( count( $modules ) === 1 && reset( $modules ) instanceof ResourceLoaderUserTokensModule ) {
1109 // If we're building the embedded user.tokens, don't cache (T84960)
1110 $enableFilterCache = false;
1111 }
1112
1113 if ( !$context->getDebug() ) {
1114 if ( $context->getOnly() === 'styles' ) {
1115 $out = $this->filter( 'minify-css', $out );
1116 } else {
1117 $out = $this->filter( 'minify-js', $out, array(
1118 'cache' => $enableFilterCache
1119 ) );
1120 }
1121 }
1122
1123 return $out;
1124 }
1125
1126 /* Static Methods */
1127
1128 /**
1129 * Return JS code that calls mw.loader.implement with given module properties.
1130 *
1131 * @param string $name Module name
1132 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1133 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1134 * to CSS files keyed by media type
1135 * @param mixed $messages List of messages associated with this module. May either be an
1136 * associative array mapping message key to value, or a JSON-encoded message blob containing
1137 * the same data, wrapped in an XmlJsCode object.
1138 * @param array $templates Keys are name of templates and values are the source of
1139 * the template.
1140 * @throws MWException
1141 * @return string
1142 */
1143 public static function makeLoaderImplementScript(
1144 $name, $scripts, $styles, $messages, $templates
1145 ) {
1146 if ( is_string( $scripts ) ) {
1147 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1148 } elseif ( !is_array( $scripts ) ) {
1149 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1150 }
1151 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1152 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1153 // of "{}". Force them to objects.
1154 $module = array(
1155 $name,
1156 $scripts,
1157 (object) $styles,
1158 (object) $messages,
1159 (object) $templates,
1160 );
1161 self::trimArray( $module );
1162
1163 return Xml::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader::inDebugMode() );
1164 }
1165
1166 /**
1167 * Returns JS code which, when called, will register a given list of messages.
1168 *
1169 * @param mixed $messages Either an associative array mapping message key to value, or a
1170 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1171 * @return string
1172 */
1173 public static function makeMessageSetScript( $messages ) {
1174 return Xml::encodeJsCall(
1175 'mw.messages.set',
1176 array( (object)$messages ),
1177 ResourceLoader::inDebugMode()
1178 );
1179 }
1180
1181 /**
1182 * Combines an associative array mapping media type to CSS into a
1183 * single stylesheet with "@media" blocks.
1184 *
1185 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1186 * @return array
1187 */
1188 public static function makeCombinedStyles( array $stylePairs ) {
1189 $out = array();
1190 foreach ( $stylePairs as $media => $styles ) {
1191 // ResourceLoaderFileModule::getStyle can return the styles
1192 // as a string or an array of strings. This is to allow separation in
1193 // the front-end.
1194 $styles = (array)$styles;
1195 foreach ( $styles as $style ) {
1196 $style = trim( $style );
1197 // Don't output an empty "@media print { }" block (bug 40498)
1198 if ( $style !== '' ) {
1199 // Transform the media type based on request params and config
1200 // The way that this relies on $wgRequest to propagate request params is slightly evil
1201 $media = OutputPage::transformCssMedia( $media );
1202
1203 if ( $media === '' || $media == 'all' ) {
1204 $out[] = $style;
1205 } elseif ( is_string( $media ) ) {
1206 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1207 }
1208 // else: skip
1209 }
1210 }
1211 }
1212 return $out;
1213 }
1214
1215 /**
1216 * Returns a JS call to mw.loader.state, which sets the state of a
1217 * module or modules to a given value. Has two calling conventions:
1218 *
1219 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1220 * Set the state of a single module called $name to $state
1221 *
1222 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1223 * Set the state of modules with the given names to the given states
1224 *
1225 * @param string $name
1226 * @param string $state
1227 * @return string
1228 */
1229 public static function makeLoaderStateScript( $name, $state = null ) {
1230 if ( is_array( $name ) ) {
1231 return Xml::encodeJsCall(
1232 'mw.loader.state',
1233 array( $name ),
1234 ResourceLoader::inDebugMode()
1235 );
1236 } else {
1237 return Xml::encodeJsCall(
1238 'mw.loader.state',
1239 array( $name, $state ),
1240 ResourceLoader::inDebugMode()
1241 );
1242 }
1243 }
1244
1245 /**
1246 * Returns JS code which calls the script given by $script. The script will
1247 * be called with local variables name, version, dependencies and group,
1248 * which will have values corresponding to $name, $version, $dependencies
1249 * and $group as supplied.
1250 *
1251 * @param string $name Module name
1252 * @param string $version Module version hash
1253 * @param array $dependencies List of module names on which this module depends
1254 * @param string $group Group which the module is in.
1255 * @param string $source Source of the module, or 'local' if not foreign.
1256 * @param string $script JavaScript code
1257 * @return string
1258 */
1259 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1260 $group, $source, $script
1261 ) {
1262 $script = str_replace( "\n", "\n\t", trim( $script ) );
1263 return Xml::encodeJsCall(
1264 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1265 array( $name, $version, $dependencies, $group, $source ),
1266 ResourceLoader::inDebugMode()
1267 );
1268 }
1269
1270 private static function isEmptyObject( stdClass $obj ) {
1271 foreach ( $obj as $key => &$value ) {
1272 return false;
1273 }
1274 return true;
1275 }
1276
1277 /**
1278 * Remove empty values from the end of an array.
1279 *
1280 * Values considered empty:
1281 *
1282 * - null
1283 * - array()
1284 * - new XmlJsCode( '{}' )
1285 * - new stdClass() // (object) array()
1286 *
1287 * @param Array $array
1288 */
1289 private static function trimArray( Array &$array ) {
1290 $i = count( $array );
1291 while ( $i-- ) {
1292 if ( $array[$i] === null
1293 || $array[$i] === array()
1294 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1295 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1296 ) {
1297 unset( $array[$i] );
1298 } else {
1299 break;
1300 }
1301 }
1302 }
1303
1304 /**
1305 * Returns JS code which calls mw.loader.register with the given
1306 * parameters. Has three calling conventions:
1307 *
1308 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1309 * $dependencies, $group, $source, $skip
1310 * ):
1311 * Register a single module.
1312 *
1313 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1314 * Register modules with the given names.
1315 *
1316 * - ResourceLoader::makeLoaderRegisterScript( array(
1317 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1318 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1319 * ...
1320 * ) ):
1321 * Registers modules with the given names and parameters.
1322 *
1323 * @param string $name Module name
1324 * @param string $version Module version hash
1325 * @param array $dependencies List of module names on which this module depends
1326 * @param string $group Group which the module is in
1327 * @param string $source Source of the module, or 'local' if not foreign
1328 * @param string $skip Script body of the skip function
1329 * @return string
1330 */
1331 public static function makeLoaderRegisterScript( $name, $version = null,
1332 $dependencies = null, $group = null, $source = null, $skip = null
1333 ) {
1334 if ( is_array( $name ) ) {
1335 // Build module name index
1336 $index = array();
1337 foreach ( $name as $i => &$module ) {
1338 $index[$module[0]] = $i;
1339 }
1340
1341 // Transform dependency names into indexes when possible, they will be resolved by
1342 // mw.loader.register on the other end
1343 foreach ( $name as &$module ) {
1344 if ( isset( $module[2] ) ) {
1345 foreach ( $module[2] as &$dependency ) {
1346 if ( isset( $index[$dependency] ) ) {
1347 $dependency = $index[$dependency];
1348 }
1349 }
1350 }
1351 }
1352
1353 array_walk( $name, array( 'self', 'trimArray' ) );
1354
1355 return Xml::encodeJsCall(
1356 'mw.loader.register',
1357 array( $name ),
1358 ResourceLoader::inDebugMode()
1359 );
1360 } else {
1361 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1362 self::trimArray( $registration );
1363 return Xml::encodeJsCall(
1364 'mw.loader.register',
1365 $registration,
1366 ResourceLoader::inDebugMode()
1367 );
1368 }
1369 }
1370
1371 /**
1372 * Returns JS code which calls mw.loader.addSource() with the given
1373 * parameters. Has two calling conventions:
1374 *
1375 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1376 * Register a single source
1377 *
1378 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1379 * Register sources with the given IDs and properties.
1380 *
1381 * @param string $id Source ID
1382 * @param array $properties Source properties (see addSource())
1383 * @return string
1384 */
1385 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1386 if ( is_array( $id ) ) {
1387 return Xml::encodeJsCall(
1388 'mw.loader.addSource',
1389 array( $id ),
1390 ResourceLoader::inDebugMode()
1391 );
1392 } else {
1393 return Xml::encodeJsCall(
1394 'mw.loader.addSource',
1395 array( $id, $properties ),
1396 ResourceLoader::inDebugMode()
1397 );
1398 }
1399 }
1400
1401 /**
1402 * Returns JS code which runs given JS code if the client-side framework is
1403 * present.
1404 *
1405 * @deprecated since 1.25; use makeInlineScript instead
1406 * @param string $script JavaScript code
1407 * @return string
1408 */
1409 public static function makeLoaderConditionalScript( $script ) {
1410 return "if(window.mw){\n" . trim( $script ) . "\n}";
1411 }
1412
1413 /**
1414 * Construct an inline script tag with given JS code.
1415 *
1416 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1417 * only if the client has adequate support for MediaWiki JavaScript code.
1418 *
1419 * @param string $script JavaScript code
1420 * @return string HTML
1421 */
1422 public static function makeInlineScript( $script ) {
1423 $js = self::makeLoaderConditionalScript( $script );
1424 return Html::inlineScript( $js );
1425 }
1426
1427 /**
1428 * Returns JS code which will set the MediaWiki configuration array to
1429 * the given value.
1430 *
1431 * @param array $configuration List of configuration values keyed by variable name
1432 * @return string
1433 */
1434 public static function makeConfigSetScript( array $configuration ) {
1435 return Xml::encodeJsCall(
1436 'mw.config.set',
1437 array( $configuration ),
1438 ResourceLoader::inDebugMode()
1439 );
1440 }
1441
1442 /**
1443 * Convert an array of module names to a packed query string.
1444 *
1445 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1446 * becomes 'foo.bar,baz|bar.baz,quux'
1447 * @param array $modules List of module names (strings)
1448 * @return string Packed query string
1449 */
1450 public static function makePackedModulesString( $modules ) {
1451 $groups = array(); // array( prefix => array( suffixes ) )
1452 foreach ( $modules as $module ) {
1453 $pos = strrpos( $module, '.' );
1454 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1455 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1456 $groups[$prefix][] = $suffix;
1457 }
1458
1459 $arr = array();
1460 foreach ( $groups as $prefix => $suffixes ) {
1461 $p = $prefix === '' ? '' : $prefix . '.';
1462 $arr[] = $p . implode( ',', $suffixes );
1463 }
1464 $str = implode( '|', $arr );
1465 return $str;
1466 }
1467
1468 /**
1469 * Determine whether debug mode was requested
1470 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1471 * @return bool
1472 */
1473 public static function inDebugMode() {
1474 if ( self::$debugMode === null ) {
1475 global $wgRequest, $wgResourceLoaderDebug;
1476 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1477 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1478 );
1479 }
1480 return self::$debugMode;
1481 }
1482
1483 /**
1484 * Reset static members used for caching.
1485 *
1486 * Global state and $wgRequest are evil, but we're using it right
1487 * now and sometimes we need to be able to force ResourceLoader to
1488 * re-evaluate the context because it has changed (e.g. in the test suite).
1489 */
1490 public static function clearCache() {
1491 self::$debugMode = null;
1492 }
1493
1494 /**
1495 * Build a load.php URL
1496 *
1497 * @since 1.24
1498 * @param string $source Name of the ResourceLoader source
1499 * @param ResourceLoaderContext $context
1500 * @param array $extraQuery
1501 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1502 */
1503 public function createLoaderURL( $source, ResourceLoaderContext $context,
1504 $extraQuery = array()
1505 ) {
1506 $query = self::createLoaderQuery( $context, $extraQuery );
1507 $script = $this->getLoadScript( $source );
1508
1509 // Prevent the IE6 extension check from being triggered (bug 28840)
1510 // by appending a character that's invalid in Windows extensions ('*')
1511 return wfExpandUrl( wfAppendQuery( $script, $query ) . '&*', PROTO_RELATIVE );
1512 }
1513
1514 /**
1515 * Build a load.php URL
1516 * @deprecated since 1.24 Use createLoaderURL() instead
1517 * @param array $modules Array of module names (strings)
1518 * @param string $lang Language code
1519 * @param string $skin Skin name
1520 * @param string|null $user User name. If null, the &user= parameter is omitted
1521 * @param string|null $version Versioning timestamp
1522 * @param bool $debug Whether the request should be in debug mode
1523 * @param string|null $only &only= parameter
1524 * @param bool $printable Printable mode
1525 * @param bool $handheld Handheld mode
1526 * @param array $extraQuery Extra query parameters to add
1527 * @return string URL to load.php. May be protocol-relative (if $wgLoadScript is procol-relative)
1528 */
1529 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1530 $version = null, $debug = false, $only = null, $printable = false,
1531 $handheld = false, $extraQuery = array()
1532 ) {
1533 global $wgLoadScript;
1534
1535 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1536 $only, $printable, $handheld, $extraQuery
1537 );
1538
1539 // Prevent the IE6 extension check from being triggered (bug 28840)
1540 // by appending a character that's invalid in Windows extensions ('*')
1541 return wfExpandUrl( wfAppendQuery( $wgLoadScript, $query ) . '&*', PROTO_RELATIVE );
1542 }
1543
1544 /**
1545 * Helper for createLoaderURL()
1546 *
1547 * @since 1.24
1548 * @see makeLoaderQuery
1549 * @param ResourceLoaderContext $context
1550 * @param array $extraQuery
1551 * @return array
1552 */
1553 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1554 return self::makeLoaderQuery(
1555 $context->getModules(),
1556 $context->getLanguage(),
1557 $context->getSkin(),
1558 $context->getUser(),
1559 $context->getVersion(),
1560 $context->getDebug(),
1561 $context->getOnly(),
1562 $context->getRequest()->getBool( 'printable' ),
1563 $context->getRequest()->getBool( 'handheld' ),
1564 $extraQuery
1565 );
1566 }
1567
1568 /**
1569 * Build a query array (array representation of query string) for load.php. Helper
1570 * function for makeLoaderURL().
1571 *
1572 * @param array $modules
1573 * @param string $lang
1574 * @param string $skin
1575 * @param string $user
1576 * @param string $version
1577 * @param bool $debug
1578 * @param string $only
1579 * @param bool $printable
1580 * @param bool $handheld
1581 * @param array $extraQuery
1582 *
1583 * @return array
1584 */
1585 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1586 $version = null, $debug = false, $only = null, $printable = false,
1587 $handheld = false, $extraQuery = array()
1588 ) {
1589 $query = array(
1590 'modules' => self::makePackedModulesString( $modules ),
1591 'lang' => $lang,
1592 'skin' => $skin,
1593 'debug' => $debug ? 'true' : 'false',
1594 );
1595 if ( $user !== null ) {
1596 $query['user'] = $user;
1597 }
1598 if ( $version !== null ) {
1599 $query['version'] = $version;
1600 }
1601 if ( $only !== null ) {
1602 $query['only'] = $only;
1603 }
1604 if ( $printable ) {
1605 $query['printable'] = 1;
1606 }
1607 if ( $handheld ) {
1608 $query['handheld'] = 1;
1609 }
1610 $query += $extraQuery;
1611
1612 // Make queries uniform in order
1613 ksort( $query );
1614 return $query;
1615 }
1616
1617 /**
1618 * Check a module name for validity.
1619 *
1620 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1621 * at most 255 bytes.
1622 *
1623 * @param string $moduleName Module name to check
1624 * @return bool Whether $moduleName is a valid module name
1625 */
1626 public static function isValidModuleName( $moduleName ) {
1627 return !preg_match( '/[|,!]/', $moduleName ) && strlen( $moduleName ) <= 255;
1628 }
1629
1630 /**
1631 * Returns LESS compiler set up for use with MediaWiki
1632 *
1633 * @param Config $config
1634 * @throws MWException
1635 * @since 1.22
1636 * @return lessc
1637 */
1638 public static function getLessCompiler( Config $config ) {
1639 // When called from the installer, it is possible that a required PHP extension
1640 // is missing (at least for now; see bug 47564). If this is the case, throw an
1641 // exception (caught by the installer) to prevent a fatal error later on.
1642 if ( !class_exists( 'lessc' ) ) {
1643 throw new MWException( 'MediaWiki requires the lessphp compiler' );
1644 }
1645 if ( !function_exists( 'ctype_digit' ) ) {
1646 throw new MWException( 'lessc requires the Ctype extension' );
1647 }
1648
1649 $less = new lessc();
1650 $less->setPreserveComments( true );
1651 $less->setVariables( self::getLessVars( $config ) );
1652 $less->setImportDir( $config->get( 'ResourceLoaderLESSImportPaths' ) );
1653 foreach ( $config->get( 'ResourceLoaderLESSFunctions' ) as $name => $func ) {
1654 $less->registerFunction( $name, $func );
1655 }
1656 return $less;
1657 }
1658
1659 /**
1660 * Get global LESS variables.
1661 *
1662 * @param Config $config
1663 * @since 1.22
1664 * @return array Map of variable names to string CSS values.
1665 */
1666 public static function getLessVars( Config $config ) {
1667 if ( !self::$lessVars ) {
1668 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1669 Hooks::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1670 // Sort by key to ensure consistent hashing for cache lookups.
1671 ksort( $lessVars );
1672 self::$lessVars = $lessVars;
1673 }
1674 return self::$lessVars;
1675 }
1676 }