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