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