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