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