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