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