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