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