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