Merge "Made rollbackMasterChanges catch exceptions, throwing the last one"
[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
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 if ( !self::$lessVars ) {
1591 $lessVars = $config->get( 'ResourceLoaderLESSVars' );
1592 Hooks::run( 'ResourceLoaderGetLessVars', array( &$lessVars ) );
1593 // Sort by key to ensure consistent hashing for cache lookups.
1594 ksort( $lessVars );
1595 self::$lessVars = $lessVars;
1596 }
1597 return self::$lessVars;
1598 }
1599 }