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