Merge "Split out edit/create methods from doEditContent()"
[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::getLocalServerInstance( 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 $config [optional]
245 * @param LoggerInterface $logger [optional]
246 */
247 public function __construct( Config $config = null, LoggerInterface $logger = null ) {
248 global $IP;
249
250 if ( !$logger ) {
251 $logger = new NullLogger();
252 }
253 $this->setLogger( $logger );
254
255 if ( !$config ) {
256 $this->logger->debug( __METHOD__ . ' was called without providing a Config instance' );
257 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
258 }
259 $this->config = $config;
260
261 // Add 'local' source first
262 $this->addSource( 'local', wfScript( 'load' ) );
263
264 // Add other sources
265 $this->addSource( $config->get( 'ResourceLoaderSources' ) );
266
267 // Register core modules
268 $this->register( include "$IP/resources/Resources.php" );
269 $this->register( include "$IP/resources/ResourcesOOUI.php" );
270 // Register extension modules
271 $this->register( $config->get( 'ResourceModules' ) );
272 Hooks::run( 'ResourceLoaderRegisterModules', array( &$this ) );
273
274 if ( $config->get( 'EnableJavaScriptTest' ) === true ) {
275 $this->registerTestModules();
276 }
277
278 $this->setMessageBlobStore( new MessageBlobStore( $this ) );
279 }
280
281 /**
282 * @return Config
283 */
284 public function getConfig() {
285 return $this->config;
286 }
287
288 /**
289 * @since 1.26
290 * @param LoggerInterface $logger
291 */
292 public function setLogger( LoggerInterface $logger ) {
293 $this->logger = $logger;
294 }
295
296 /**
297 * @since 1.27
298 * @return LoggerInterface
299 */
300 public function getLogger() {
301 return $this->logger;
302 }
303
304 /**
305 * @since 1.26
306 * @return MessageBlobStore
307 */
308 public function getMessageBlobStore() {
309 return $this->blobStore;
310 }
311
312 /**
313 * @since 1.25
314 * @param MessageBlobStore $blobStore
315 */
316 public function setMessageBlobStore( MessageBlobStore $blobStore ) {
317 $this->blobStore = $blobStore;
318 }
319
320 /**
321 * Register a module with the ResourceLoader system.
322 *
323 * @param mixed $name Name of module as a string or List of name/object pairs as an array
324 * @param array $info Module info array. For backwards compatibility with 1.17alpha,
325 * this may also be a ResourceLoaderModule object. Optional when using
326 * multiple-registration calling style.
327 * @throws MWException If a duplicate module registration is attempted
328 * @throws MWException If a module name contains illegal characters (pipes or commas)
329 * @throws MWException If something other than a ResourceLoaderModule is being registered
330 * @return bool False if there were any errors, in which case one or more modules were
331 * not registered
332 */
333 public function register( $name, $info = null ) {
334
335 // Allow multiple modules to be registered in one call
336 $registrations = is_array( $name ) ? $name : array( $name => $info );
337 foreach ( $registrations as $name => $info ) {
338 // Warn on duplicate registrations
339 if ( isset( $this->moduleInfos[$name] ) ) {
340 // A module has already been registered by this name
341 $this->logger->warning(
342 'ResourceLoader duplicate registration warning. ' .
343 'Another module has already been registered as ' . $name
344 );
345 }
346
347 // Check $name for validity
348 if ( !self::isValidModuleName( $name ) ) {
349 throw new MWException( "ResourceLoader module name '$name' is invalid, "
350 . "see ResourceLoader::isValidModuleName()" );
351 }
352
353 // Attach module
354 if ( $info instanceof ResourceLoaderModule ) {
355 $this->moduleInfos[$name] = array( 'object' => $info );
356 $info->setName( $name );
357 $this->modules[$name] = $info;
358 } elseif ( is_array( $info ) ) {
359 // New calling convention
360 $this->moduleInfos[$name] = $info;
361 } else {
362 throw new MWException(
363 'ResourceLoader module info type error for module \'' . $name .
364 '\': expected ResourceLoaderModule or array (got: ' . gettype( $info ) . ')'
365 );
366 }
367
368 // Last-minute changes
369
370 // Apply custom skin-defined styles to existing modules.
371 if ( $this->isFileModule( $name ) ) {
372 foreach ( $this->config->get( 'ResourceModuleSkinStyles' ) as $skinName => $skinStyles ) {
373 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
374 if ( isset( $this->moduleInfos[$name]['skinStyles'][$skinName] ) ) {
375 continue;
376 }
377
378 // If $name is preceded with a '+', the defined style files will be added to 'default'
379 // skinStyles, otherwise 'default' will be ignored as it normally would be.
380 if ( isset( $skinStyles[$name] ) ) {
381 $paths = (array)$skinStyles[$name];
382 $styleFiles = array();
383 } elseif ( isset( $skinStyles['+' . $name] ) ) {
384 $paths = (array)$skinStyles['+' . $name];
385 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles']['default'] ) ?
386 (array)$this->moduleInfos[$name]['skinStyles']['default'] :
387 array();
388 } else {
389 continue;
390 }
391
392 // Add new file paths, remapping them to refer to our directories and not use settings
393 // from the module we're modifying, which come from the base definition.
394 list( $localBasePath, $remoteBasePath ) =
395 ResourceLoaderFileModule::extractBasePaths( $skinStyles );
396
397 foreach ( $paths as $path ) {
398 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
399 }
400
401 $this->moduleInfos[$name]['skinStyles'][$skinName] = $styleFiles;
402 }
403 }
404 }
405
406 }
407
408 /**
409 */
410 public function registerTestModules() {
411 global $IP;
412
413 if ( $this->config->get( 'EnableJavaScriptTest' ) !== true ) {
414 throw new MWException( 'Attempt to register JavaScript test modules '
415 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
416 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
417 }
418
419 // Get core test suites
420 $testModules = array();
421 $testModules['qunit'] = array();
422 // Get other test suites (e.g. from extensions)
423 Hooks::run( 'ResourceLoaderTestModules', array( &$testModules, &$this ) );
424
425 // Add the testrunner (which configures QUnit) to the dependencies.
426 // Since it must be ready before any of the test suites are executed.
427 foreach ( $testModules['qunit'] as &$module ) {
428 // Make sure all test modules are top-loading so that when QUnit starts
429 // on document-ready, it will run once and finish. If some tests arrive
430 // later (possibly after QUnit has already finished) they will be ignored.
431 $module['position'] = 'top';
432 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
433 }
434
435 $testModules['qunit'] =
436 ( include "$IP/tests/qunit/QUnitTestResources.php" ) + $testModules['qunit'];
437
438 foreach ( $testModules as $id => $names ) {
439 // Register test modules
440 $this->register( $testModules[$id] );
441
442 // Keep track of their names so that they can be loaded together
443 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
444 }
445
446 }
447
448 /**
449 * Add a foreign source of modules.
450 *
451 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
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() ) {
727 $warnings = ob_get_contents();
728 if ( strlen( $warnings ) ) {
729 $this->errors[] = $warnings;
730 }
731 }
732
733 // Save response to file cache unless there are errors
734 if ( isset( $fileCache ) && !$this->errors && !count( $missing ) ) {
735 // Cache single modules and images...and other requests if there are enough hits
736 if ( ResourceFileCache::useFileCache( $context ) ) {
737 if ( $fileCache->isCacheWorthy() ) {
738 $fileCache->saveText( $response );
739 } else {
740 $fileCache->incrMissesRecent( $context->getRequest() );
741 }
742 }
743 }
744
745 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors );
746
747 // Remove the output buffer and output the response
748 ob_end_clean();
749
750 if ( $context->getImageObj() && $this->errors ) {
751 // We can't show both the error messages and the response when it's an image.
752 $response = implode( "\n\n", $this->errors );
753 } elseif ( $this->errors ) {
754 $errorText = implode( "\n\n", $this->errors );
755 $errorResponse = self::makeComment( $errorText );
756 if ( $context->shouldIncludeScripts() ) {
757 $errorResponse .= 'if (window.console && console.error) {'
758 . Xml::encodeJsCall( 'console.error', array( $errorText ) )
759 . "}\n";
760 }
761
762 // Prepend error info to the response
763 $response = $errorResponse . $response;
764 }
765
766 $this->errors = array();
767 echo $response;
768
769 }
770
771 /**
772 * Send main response headers to the client.
773 *
774 * Deals with Content-Type, CORS (for stylesheets), and caching.
775 *
776 * @param ResourceLoaderContext $context
777 * @param string $etag ETag header value
778 * @param bool $errors Whether there are errors in the response
779 * @return void
780 */
781 protected function sendResponseHeaders( ResourceLoaderContext $context, $etag, $errors ) {
782 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
783 // If a version wasn't specified we need a shorter expiry time for updates
784 // to propagate to clients quickly
785 // If there were errors, we also need a shorter expiry time so we can recover quickly
786 if ( is_null( $context->getVersion() ) || $errors ) {
787 $maxage = $rlMaxage['unversioned']['client'];
788 $smaxage = $rlMaxage['unversioned']['server'];
789 // If a version was specified we can use a longer expiry time since changing
790 // version numbers causes cache misses
791 } else {
792 $maxage = $rlMaxage['versioned']['client'];
793 $smaxage = $rlMaxage['versioned']['server'];
794 }
795 if ( $context->getImageObj() ) {
796 // Output different headers if we're outputting textual errors.
797 if ( $errors ) {
798 header( 'Content-Type: text/plain; charset=utf-8' );
799 } else {
800 $context->getImageObj()->sendResponseHeaders( $context );
801 }
802 } elseif ( $context->getOnly() === 'styles' ) {
803 header( 'Content-Type: text/css; charset=utf-8' );
804 header( 'Access-Control-Allow-Origin: *' );
805 } else {
806 header( 'Content-Type: text/javascript; charset=utf-8' );
807 }
808 // See RFC 2616 § 14.19 ETag
809 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
810 header( 'ETag: ' . $etag );
811 if ( $context->getDebug() ) {
812 // Do not cache debug responses
813 header( 'Cache-Control: private, no-cache, must-revalidate' );
814 header( 'Pragma: no-cache' );
815 } else {
816 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
817 $exp = min( $maxage, $smaxage );
818 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $exp + time() ) );
819 }
820 }
821
822 /**
823 * Respond with HTTP 304 Not Modified if appropiate.
824 *
825 * If there's an If-None-Match header, respond with a 304 appropriately
826 * and clear out the output buffer. If the client cache is too old then do nothing.
827 *
828 * @param ResourceLoaderContext $context
829 * @param string $etag ETag header value
830 * @return bool True if HTTP 304 was sent and output handled
831 */
832 protected function tryRespondNotModified( ResourceLoaderContext $context, $etag ) {
833 // See RFC 2616 § 14.26 If-None-Match
834 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
835 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST );
836 // Never send 304s in debug mode
837 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
838 // There's another bug in ob_gzhandler (see also the comment at
839 // the top of this function) that causes it to gzip even empty
840 // responses, meaning it's impossible to produce a truly empty
841 // response (because the gzip header is always there). This is
842 // a problem because 304 responses have to be completely empty
843 // per the HTTP spec, and Firefox behaves buggily when they're not.
844 // See also http://bugs.php.net/bug.php?id=51579
845 // To work around this, we tear down all output buffering before
846 // sending the 304.
847 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
848
849 HttpStatus::header( 304 );
850
851 $this->sendResponseHeaders( $context, $etag, false );
852 return true;
853 }
854 return false;
855 }
856
857 /**
858 * Send out code for a response from file cache if possible.
859 *
860 * @param ResourceFileCache $fileCache Cache object for this request URL
861 * @param ResourceLoaderContext $context Context in which to generate a response
862 * @param string $etag ETag header value
863 * @return bool If this found a cache file and handled the response
864 */
865 protected function tryRespondFromFileCache(
866 ResourceFileCache $fileCache,
867 ResourceLoaderContext $context,
868 $etag
869 ) {
870 $rlMaxage = $this->config->get( 'ResourceLoaderMaxage' );
871 // Buffer output to catch warnings.
872 ob_start();
873 // Get the maximum age the cache can be
874 $maxage = is_null( $context->getVersion() )
875 ? $rlMaxage['unversioned']['server']
876 : $rlMaxage['versioned']['server'];
877 // Minimum timestamp the cache file must have
878 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW, time() - $maxage ) );
879 if ( !$good ) {
880 try { // RL always hits the DB on file cache miss...
881 wfGetDB( DB_SLAVE );
882 } catch ( DBConnectionError $e ) { // ...check if we need to fallback to cache
883 $good = $fileCache->isCacheGood(); // cache existence check
884 }
885 }
886 if ( $good ) {
887 $ts = $fileCache->cacheTimestamp();
888 // Send content type and cache headers
889 $this->sendResponseHeaders( $context, $etag, false );
890 $response = $fileCache->fetchText();
891 // Capture any PHP warnings from the output buffer and append them to the
892 // response in a comment if we're in debug mode.
893 if ( $context->getDebug() ) {
894 $warnings = ob_get_contents();
895 if ( strlen( $warnings ) ) {
896 $response = self::makeComment( $warnings ) . $response;
897 }
898 }
899 // Remove the output buffer and output the response
900 ob_end_clean();
901 echo $response . "\n/* Cached {$ts} */";
902 return true; // cache hit
903 }
904 // Clear buffer
905 ob_end_clean();
906
907 return false; // cache miss
908 }
909
910 /**
911 * Generate a CSS or JS comment block.
912 *
913 * Only use this for public data, not error message details.
914 *
915 * @param string $text
916 * @return string
917 */
918 public static function makeComment( $text ) {
919 $encText = str_replace( '*/', '* /', $text );
920 return "/*\n$encText\n*/\n";
921 }
922
923 /**
924 * Handle exception display.
925 *
926 * @param Exception $e Exception to be shown to the user
927 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
928 */
929 public static function formatException( $e ) {
930 return self::makeComment( self::formatExceptionNoComment( $e ) );
931 }
932
933 /**
934 * Handle exception display.
935 *
936 * @since 1.25
937 * @param Exception $e Exception to be shown to the user
938 * @return string Sanitized text that can be returned to the user
939 */
940 protected static function formatExceptionNoComment( $e ) {
941 global $wgShowExceptionDetails;
942
943 if ( !$wgShowExceptionDetails ) {
944 return MWExceptionHandler::getPublicLogMessage( $e );
945 }
946
947 return MWExceptionHandler::getLogMessage( $e );
948 }
949
950 /**
951 * Generate code for a response.
952 *
953 * @param ResourceLoaderContext $context Context in which to generate a response
954 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
955 * @param string[] $missing List of requested module names that are unregistered (optional)
956 * @return string Response data
957 */
958 public function makeModuleResponse( ResourceLoaderContext $context,
959 array $modules, array $missing = array()
960 ) {
961 $out = '';
962 $states = array();
963
964 if ( !count( $modules ) && !count( $missing ) ) {
965 return <<<MESSAGE
966 /* This file is the Web entry point for MediaWiki's ResourceLoader:
967 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
968 no modules were requested. Max made me put this here. */
969 MESSAGE;
970 }
971
972 $image = $context->getImageObj();
973 if ( $image ) {
974 $data = $image->getImageData( $context );
975 if ( $data === false ) {
976 $data = '';
977 $this->errors[] = 'Image generation failed';
978 }
979 return $data;
980 }
981
982 // Pre-fetch blobs
983 if ( $context->shouldIncludeMessages() ) {
984 try {
985 $this->blobStore->get( $this, $modules, $context->getLanguage() );
986 } catch ( Exception $e ) {
987 MWExceptionHandler::logException( $e );
988 $this->logger->warning( 'Prefetching MessageBlobStore failed: {exception}', array(
989 'exception' => $e
990 ) );
991 $this->errors[] = self::formatExceptionNoComment( $e );
992 }
993 }
994
995 foreach ( $missing as $name ) {
996 $states[$name] = 'missing';
997 }
998
999 // Generate output
1000 $isRaw = false;
1001
1002 $filter = $context->getOnly() === 'styles' ? 'minify-css' : 'minify-js';
1003
1004 foreach ( $modules as $name => $module ) {
1005 try {
1006 $content = $module->getModuleContent( $context );
1007 $strContent = '';
1008
1009 // Append output
1010 switch ( $context->getOnly() ) {
1011 case 'scripts':
1012 $scripts = $content['scripts'];
1013 if ( is_string( $scripts ) ) {
1014 // Load scripts raw...
1015 $strContent = $scripts;
1016 } elseif ( is_array( $scripts ) ) {
1017 // ...except when $scripts is an array of URLs
1018 $strContent = self::makeLoaderImplementScript( $name, $scripts, array(), array(), array() );
1019 }
1020 break;
1021 case 'styles':
1022 $styles = $content['styles'];
1023 // We no longer seperate into media, they are all combined now with
1024 // custom media type groups into @media .. {} sections as part of the css string.
1025 // Module returns either an empty array or a numerical array with css strings.
1026 $strContent = isset( $styles['css'] ) ? implode( '', $styles['css'] ) : '';
1027 break;
1028 default:
1029 $strContent = self::makeLoaderImplementScript(
1030 $name,
1031 isset( $content['scripts'] ) ? $content['scripts'] : '',
1032 isset( $content['styles'] ) ? $content['styles'] : array(),
1033 isset( $content['messagesBlob'] ) ? new XmlJsCode( $content['messagesBlob'] ) : array(),
1034 isset( $content['templates'] ) ? $content['templates'] : array()
1035 );
1036 break;
1037 }
1038
1039 if ( !$context->getDebug() ) {
1040 $strContent = self::filter( $filter, $strContent );
1041 }
1042
1043 $out .= $strContent;
1044
1045 } catch ( Exception $e ) {
1046 MWExceptionHandler::logException( $e );
1047 $this->logger->warning( 'Generating module package failed: {exception}', array(
1048 'exception' => $e
1049 ) );
1050 $this->errors[] = self::formatExceptionNoComment( $e );
1051
1052 // Respond to client with error-state instead of module implementation
1053 $states[$name] = 'error';
1054 unset( $modules[$name] );
1055 }
1056 $isRaw |= $module->isRaw();
1057 }
1058
1059 // Update module states
1060 if ( $context->shouldIncludeScripts() && !$context->getRaw() && !$isRaw ) {
1061 if ( count( $modules ) && $context->getOnly() === 'scripts' ) {
1062 // Set the state of modules loaded as only scripts to ready as
1063 // they don't have an mw.loader.implement wrapper that sets the state
1064 foreach ( $modules as $name => $module ) {
1065 $states[$name] = 'ready';
1066 }
1067 }
1068
1069 // Set the state of modules we didn't respond to with mw.loader.implement
1070 if ( count( $states ) ) {
1071 $stateScript = self::makeLoaderStateScript( $states );
1072 if ( !$context->getDebug() ) {
1073 $stateScript = self::filter( 'minify-js', $stateScript );
1074 }
1075 $out .= $stateScript;
1076 }
1077 } else {
1078 if ( count( $states ) ) {
1079 $this->errors[] = 'Problematic modules: ' .
1080 FormatJson::encode( $states, ResourceLoader::inDebugMode() );
1081 }
1082 }
1083
1084 return $out;
1085 }
1086
1087 /**
1088 * Get names of modules that use a certain message.
1089 *
1090 * @param string $messageKey
1091 * @return array List of module names
1092 */
1093 public function getModulesByMessage( $messageKey ) {
1094 $moduleNames = array();
1095 foreach ( $this->getModuleNames() as $moduleName ) {
1096 $module = $this->getModule( $moduleName );
1097 if ( in_array( $messageKey, $module->getMessages() ) ) {
1098 $moduleNames[] = $moduleName;
1099 }
1100 }
1101 return $moduleNames;
1102 }
1103
1104 /* Static Methods */
1105
1106 /**
1107 * Return JS code that calls mw.loader.implement with given module properties.
1108 *
1109 * @param string $name Module name
1110 * @param mixed $scripts List of URLs to JavaScript files or String of JavaScript code
1111 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1112 * to CSS files keyed by media type
1113 * @param mixed $messages List of messages associated with this module. May either be an
1114 * associative array mapping message key to value, or a JSON-encoded message blob containing
1115 * the same data, wrapped in an XmlJsCode object.
1116 * @param array $templates Keys are name of templates and values are the source of
1117 * the template.
1118 * @throws MWException
1119 * @return string
1120 */
1121 public static function makeLoaderImplementScript(
1122 $name, $scripts, $styles, $messages, $templates
1123 ) {
1124 if ( is_string( $scripts ) ) {
1125 // Site and user module are a legacy scripts that run in the global scope (no closure).
1126 // Transportation as string instructs mw.loader.implement to use globalEval.
1127 if ( $name === 'site' || $name === 'user' ) {
1128 // Minify manually because the general makeModuleResponse() minification won't be
1129 // effective here due to the script being a string instead of a function. (T107377)
1130 if ( !ResourceLoader::inDebugMode() ) {
1131 $scripts = self::filter( 'minify-js', $scripts );
1132 }
1133 } else {
1134 $scripts = new XmlJsCode( "function ( $, jQuery ) {\n{$scripts}\n}" );
1135 }
1136 } elseif ( !is_array( $scripts ) ) {
1137 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1138 }
1139 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1140 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1141 // of "{}". Force them to objects.
1142 $module = array(
1143 $name,
1144 $scripts,
1145 (object)$styles,
1146 (object)$messages,
1147 (object)$templates,
1148 );
1149 self::trimArray( $module );
1150
1151 return Xml::encodeJsCall( 'mw.loader.implement', $module, ResourceLoader::inDebugMode() );
1152 }
1153
1154 /**
1155 * Returns JS code which, when called, will register a given list of messages.
1156 *
1157 * @param mixed $messages Either an associative array mapping message key to value, or a
1158 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1159 * @return string
1160 */
1161 public static function makeMessageSetScript( $messages ) {
1162 return Xml::encodeJsCall(
1163 'mw.messages.set',
1164 array( (object)$messages ),
1165 ResourceLoader::inDebugMode()
1166 );
1167 }
1168
1169 /**
1170 * Combines an associative array mapping media type to CSS into a
1171 * single stylesheet with "@media" blocks.
1172 *
1173 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1174 * @return array
1175 */
1176 public static function makeCombinedStyles( array $stylePairs ) {
1177 $out = array();
1178 foreach ( $stylePairs as $media => $styles ) {
1179 // ResourceLoaderFileModule::getStyle can return the styles
1180 // as a string or an array of strings. This is to allow separation in
1181 // the front-end.
1182 $styles = (array)$styles;
1183 foreach ( $styles as $style ) {
1184 $style = trim( $style );
1185 // Don't output an empty "@media print { }" block (bug 40498)
1186 if ( $style !== '' ) {
1187 // Transform the media type based on request params and config
1188 // The way that this relies on $wgRequest to propagate request params is slightly evil
1189 $media = OutputPage::transformCssMedia( $media );
1190
1191 if ( $media === '' || $media == 'all' ) {
1192 $out[] = $style;
1193 } elseif ( is_string( $media ) ) {
1194 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1195 }
1196 // else: skip
1197 }
1198 }
1199 }
1200 return $out;
1201 }
1202
1203 /**
1204 * Returns a JS call to mw.loader.state, which sets the state of a
1205 * module or modules to a given value. Has two calling conventions:
1206 *
1207 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1208 * Set the state of a single module called $name to $state
1209 *
1210 * - ResourceLoader::makeLoaderStateScript( array( $name => $state, ... ) ):
1211 * Set the state of modules with the given names to the given states
1212 *
1213 * @param string $name
1214 * @param string $state
1215 * @return string
1216 */
1217 public static function makeLoaderStateScript( $name, $state = null ) {
1218 if ( is_array( $name ) ) {
1219 return Xml::encodeJsCall(
1220 'mw.loader.state',
1221 array( $name ),
1222 ResourceLoader::inDebugMode()
1223 );
1224 } else {
1225 return Xml::encodeJsCall(
1226 'mw.loader.state',
1227 array( $name, $state ),
1228 ResourceLoader::inDebugMode()
1229 );
1230 }
1231 }
1232
1233 /**
1234 * Returns JS code which calls the script given by $script. The script will
1235 * be called with local variables name, version, dependencies and group,
1236 * which will have values corresponding to $name, $version, $dependencies
1237 * and $group as supplied.
1238 *
1239 * @param string $name Module name
1240 * @param string $version Module version hash
1241 * @param array $dependencies List of module names on which this module depends
1242 * @param string $group Group which the module is in.
1243 * @param string $source Source of the module, or 'local' if not foreign.
1244 * @param string $script JavaScript code
1245 * @return string
1246 */
1247 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1248 $group, $source, $script
1249 ) {
1250 $script = str_replace( "\n", "\n\t", trim( $script ) );
1251 return Xml::encodeJsCall(
1252 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1253 array( $name, $version, $dependencies, $group, $source ),
1254 ResourceLoader::inDebugMode()
1255 );
1256 }
1257
1258 private static function isEmptyObject( stdClass $obj ) {
1259 foreach ( $obj as $key => $value ) {
1260 return false;
1261 }
1262 return true;
1263 }
1264
1265 /**
1266 * Remove empty values from the end of an array.
1267 *
1268 * Values considered empty:
1269 *
1270 * - null
1271 * - array()
1272 * - new XmlJsCode( '{}' )
1273 * - new stdClass() // (object) array()
1274 *
1275 * @param Array $array
1276 */
1277 private static function trimArray( Array &$array ) {
1278 $i = count( $array );
1279 while ( $i-- ) {
1280 if ( $array[$i] === null
1281 || $array[$i] === array()
1282 || ( $array[$i] instanceof XmlJsCode && $array[$i]->value === '{}' )
1283 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1284 ) {
1285 unset( $array[$i] );
1286 } else {
1287 break;
1288 }
1289 }
1290 }
1291
1292 /**
1293 * Returns JS code which calls mw.loader.register with the given
1294 * parameters. Has three calling conventions:
1295 *
1296 * - ResourceLoader::makeLoaderRegisterScript( $name, $version,
1297 * $dependencies, $group, $source, $skip
1298 * ):
1299 * Register a single module.
1300 *
1301 * - ResourceLoader::makeLoaderRegisterScript( array( $name1, $name2 ) ):
1302 * Register modules with the given names.
1303 *
1304 * - ResourceLoader::makeLoaderRegisterScript( array(
1305 * array( $name1, $version1, $dependencies1, $group1, $source1, $skip1 ),
1306 * array( $name2, $version2, $dependencies1, $group2, $source2, $skip2 ),
1307 * ...
1308 * ) ):
1309 * Registers modules with the given names and parameters.
1310 *
1311 * @param string $name Module name
1312 * @param string $version Module version hash
1313 * @param array $dependencies List of module names on which this module depends
1314 * @param string $group Group which the module is in
1315 * @param string $source Source of the module, or 'local' if not foreign
1316 * @param string $skip Script body of the skip function
1317 * @return string
1318 */
1319 public static function makeLoaderRegisterScript( $name, $version = null,
1320 $dependencies = null, $group = null, $source = null, $skip = null
1321 ) {
1322 if ( is_array( $name ) ) {
1323 // Build module name index
1324 $index = array();
1325 foreach ( $name as $i => &$module ) {
1326 $index[$module[0]] = $i;
1327 }
1328
1329 // Transform dependency names into indexes when possible, they will be resolved by
1330 // mw.loader.register on the other end
1331 foreach ( $name as &$module ) {
1332 if ( isset( $module[2] ) ) {
1333 foreach ( $module[2] as &$dependency ) {
1334 if ( isset( $index[$dependency] ) ) {
1335 $dependency = $index[$dependency];
1336 }
1337 }
1338 }
1339 }
1340
1341 array_walk( $name, array( 'self', 'trimArray' ) );
1342
1343 return Xml::encodeJsCall(
1344 'mw.loader.register',
1345 array( $name ),
1346 ResourceLoader::inDebugMode()
1347 );
1348 } else {
1349 $registration = array( $name, $version, $dependencies, $group, $source, $skip );
1350 self::trimArray( $registration );
1351 return Xml::encodeJsCall(
1352 'mw.loader.register',
1353 $registration,
1354 ResourceLoader::inDebugMode()
1355 );
1356 }
1357 }
1358
1359 /**
1360 * Returns JS code which calls mw.loader.addSource() with the given
1361 * parameters. Has two calling conventions:
1362 *
1363 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1364 * Register a single source
1365 *
1366 * - ResourceLoader::makeLoaderSourcesScript( array( $id1 => $loadUrl, $id2 => $loadUrl, ... ) );
1367 * Register sources with the given IDs and properties.
1368 *
1369 * @param string $id Source ID
1370 * @param array $properties Source properties (see addSource())
1371 * @return string
1372 */
1373 public static function makeLoaderSourcesScript( $id, $properties = null ) {
1374 if ( is_array( $id ) ) {
1375 return Xml::encodeJsCall(
1376 'mw.loader.addSource',
1377 array( $id ),
1378 ResourceLoader::inDebugMode()
1379 );
1380 } else {
1381 return Xml::encodeJsCall(
1382 'mw.loader.addSource',
1383 array( $id, $properties ),
1384 ResourceLoader::inDebugMode()
1385 );
1386 }
1387 }
1388
1389 /**
1390 * Returns JS code which runs given JS code if the client-side framework is
1391 * present.
1392 *
1393 * @deprecated since 1.25; use makeInlineScript instead
1394 * @param string $script JavaScript code
1395 * @return string
1396 */
1397 public static function makeLoaderConditionalScript( $script ) {
1398 return "window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n" .
1399 trim( $script ) . "\n} );";
1400 }
1401
1402 /**
1403 * Construct an inline script tag with given JS code.
1404 *
1405 * The code will be wrapped in a closure, and it will be executed by ResourceLoader
1406 * only if the client has adequate support for MediaWiki JavaScript code.
1407 *
1408 * @param string $script JavaScript code
1409 * @return WrappedString HTML
1410 */
1411 public static function makeInlineScript( $script ) {
1412 $js = self::makeLoaderConditionalScript( $script );
1413 return new WrappedString(
1414 Html::inlineScript( $js ),
1415 "<script>window.RLQ = window.RLQ || []; window.RLQ.push( function () {\n",
1416 "\n} );</script>"
1417 );
1418 }
1419
1420 /**
1421 * Returns JS code which will set the MediaWiki configuration array to
1422 * the given value.
1423 *
1424 * @param array $configuration List of configuration values keyed by variable name
1425 * @return string
1426 */
1427 public static function makeConfigSetScript( array $configuration ) {
1428 return Xml::encodeJsCall(
1429 'mw.config.set',
1430 array( $configuration ),
1431 ResourceLoader::inDebugMode()
1432 ) . ResourceLoader::FILTER_NOMIN;
1433 }
1434
1435 /**
1436 * Convert an array of module names to a packed query string.
1437 *
1438 * For example, array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' )
1439 * becomes 'foo.bar,baz|bar.baz,quux'
1440 * @param array $modules List of module names (strings)
1441 * @return string Packed query string
1442 */
1443 public static function makePackedModulesString( $modules ) {
1444 $groups = array(); // array( prefix => array( suffixes ) )
1445 foreach ( $modules as $module ) {
1446 $pos = strrpos( $module, '.' );
1447 $prefix = $pos === false ? '' : substr( $module, 0, $pos );
1448 $suffix = $pos === false ? $module : substr( $module, $pos + 1 );
1449 $groups[$prefix][] = $suffix;
1450 }
1451
1452 $arr = array();
1453 foreach ( $groups as $prefix => $suffixes ) {
1454 $p = $prefix === '' ? '' : $prefix . '.';
1455 $arr[] = $p . implode( ',', $suffixes );
1456 }
1457 $str = implode( '|', $arr );
1458 return $str;
1459 }
1460
1461 /**
1462 * Determine whether debug mode was requested
1463 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1464 * @return bool
1465 */
1466 public static function inDebugMode() {
1467 if ( self::$debugMode === null ) {
1468 global $wgRequest, $wgResourceLoaderDebug;
1469 self::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1470 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1471 );
1472 }
1473 return self::$debugMode;
1474 }
1475
1476 /**
1477 * Reset static members used for caching.
1478 *
1479 * Global state and $wgRequest are evil, but we're using it right
1480 * now and sometimes we need to be able to force ResourceLoader to
1481 * re-evaluate the context because it has changed (e.g. in the test suite).
1482 */
1483 public static function clearCache() {
1484 self::$debugMode = null;
1485 }
1486
1487 /**
1488 * Build a load.php URL
1489 *
1490 * @since 1.24
1491 * @param string $source Name of the ResourceLoader source
1492 * @param ResourceLoaderContext $context
1493 * @param array $extraQuery
1494 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1495 */
1496 public function createLoaderURL( $source, ResourceLoaderContext $context,
1497 $extraQuery = array()
1498 ) {
1499 $query = self::createLoaderQuery( $context, $extraQuery );
1500 $script = $this->getLoadScript( $source );
1501
1502 return wfAppendQuery( $script, $query );
1503 }
1504
1505 /**
1506 * Build a load.php URL
1507 * @deprecated since 1.24 Use createLoaderURL() instead
1508 * @param array $modules Array of module names (strings)
1509 * @param string $lang Language code
1510 * @param string $skin Skin name
1511 * @param string|null $user User name. If null, the &user= parameter is omitted
1512 * @param string|null $version Versioning timestamp
1513 * @param bool $debug Whether the request should be in debug mode
1514 * @param string|null $only &only= parameter
1515 * @param bool $printable Printable mode
1516 * @param bool $handheld Handheld mode
1517 * @param array $extraQuery Extra query parameters to add
1518 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1519 */
1520 public static function makeLoaderURL( $modules, $lang, $skin, $user = null,
1521 $version = null, $debug = false, $only = null, $printable = false,
1522 $handheld = false, $extraQuery = array()
1523 ) {
1524 global $wgLoadScript;
1525
1526 $query = self::makeLoaderQuery( $modules, $lang, $skin, $user, $version, $debug,
1527 $only, $printable, $handheld, $extraQuery
1528 );
1529
1530 return wfAppendQuery( $wgLoadScript, $query );
1531 }
1532
1533 /**
1534 * Helper for createLoaderURL()
1535 *
1536 * @since 1.24
1537 * @see makeLoaderQuery
1538 * @param ResourceLoaderContext $context
1539 * @param array $extraQuery
1540 * @return array
1541 */
1542 public static function createLoaderQuery( ResourceLoaderContext $context, $extraQuery = array() ) {
1543 return self::makeLoaderQuery(
1544 $context->getModules(),
1545 $context->getLanguage(),
1546 $context->getSkin(),
1547 $context->getUser(),
1548 $context->getVersion(),
1549 $context->getDebug(),
1550 $context->getOnly(),
1551 $context->getRequest()->getBool( 'printable' ),
1552 $context->getRequest()->getBool( 'handheld' ),
1553 $extraQuery
1554 );
1555 }
1556
1557 /**
1558 * Build a query array (array representation of query string) for load.php. Helper
1559 * function for makeLoaderURL().
1560 *
1561 * @param array $modules
1562 * @param string $lang
1563 * @param string $skin
1564 * @param string $user
1565 * @param string $version
1566 * @param bool $debug
1567 * @param string $only
1568 * @param bool $printable
1569 * @param bool $handheld
1570 * @param array $extraQuery
1571 *
1572 * @return array
1573 */
1574 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1575 $version = null, $debug = false, $only = null, $printable = false,
1576 $handheld = false, $extraQuery = array()
1577 ) {
1578 $query = array(
1579 'modules' => self::makePackedModulesString( $modules ),
1580 'lang' => $lang,
1581 'skin' => $skin,
1582 'debug' => $debug ? 'true' : 'false',
1583 );
1584 if ( $user !== null ) {
1585 $query['user'] = $user;
1586 }
1587 if ( $version !== null ) {
1588 $query['version'] = $version;
1589 }
1590 if ( $only !== null ) {
1591 $query['only'] = $only;
1592 }
1593 if ( $printable ) {
1594 $query['printable'] = 1;
1595 }
1596 if ( $handheld ) {
1597 $query['handheld'] = 1;
1598 }
1599 $query += $extraQuery;
1600
1601 // Make queries uniform in order
1602 ksort( $query );
1603 return $query;
1604 }
1605
1606 /**
1607 * Check a module name for validity.
1608 *
1609 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1610 * at most 255 bytes.
1611 *
1612 * @param string $moduleName Module name to check
1613 * @return bool Whether $moduleName is a valid module name
1614 */
1615 public static function isValidModuleName( $moduleName ) {
1616 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1617 }
1618
1619 /**
1620 * Returns LESS compiler set up for use with MediaWiki
1621 *
1622 * @since 1.22
1623 * @since 1.27 added $extraVars parameter
1624 * @param Config $config
1625 * @param array $extraVars Associative array of extra (i.e., other than the
1626 * globally-configured ones) that should be used for compilation.
1627 * @throws MWException
1628 * @return Less_Parser
1629 */
1630 public static function getLessCompiler( Config $config, $extraVars = array() ) {
1631 // When called from the installer, it is possible that a required PHP extension
1632 // is missing (at least for now; see bug 47564). If this is the case, throw an
1633 // exception (caught by the installer) to prevent a fatal error later on.
1634 if ( !class_exists( 'Less_Parser' ) ) {
1635 throw new MWException( 'MediaWiki requires the less.php parser' );
1636 }
1637
1638 $parser = new Less_Parser;
1639 $parser->ModifyVars( array_merge( self::getLessVars( $config ), $extraVars ) );
1640 $parser->SetImportDirs( array_fill_keys( $config->get( 'ResourceLoaderLESSImportPaths' ), '' ) );
1641 $parser->SetOption( 'relativeUrls', false );
1642 $parser->SetCacheDir( $config->get( 'CacheDirectory' ) ?: wfTempDir() );
1643
1644 return $parser;
1645 }
1646
1647 /**
1648 * Get global LESS variables.
1649 *
1650 * @param Config $config
1651 * @since 1.22
1652 * @return array Map of variable names to string CSS values.
1653 */
1654 public static function getLessVars( Config $config ) {
1655 if ( !self::$lessVars ) {
1656 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1657 Hooks::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1658 self::$lessVars = $lessVars;
1659 }
1660 return self::$lessVars;
1661 }
1662 }