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