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