Security update to Drupal 8.4.6
[yaffs-website] / web / core / modules / responsive_image / responsive_image.module
1 <?php
2
3 /**
4  * @file
5  * Responsive image display formatter for image fields.
6  */
7
8 use Drupal\Core\Template\Attribute;
9 use Drupal\Core\Logger\RfcLogLevel;
10 use Drupal\Component\Utility\Unicode;
11 use Drupal\Core\Routing\RouteMatchInterface;
12 use Drupal\image\Entity\ImageStyle;
13 use Drupal\responsive_image\Entity\ResponsiveImageStyle;
14 use Drupal\Core\Image\ImageInterface;
15 use Drupal\breakpoint\BreakpointInterface;
16
17 /**
18  * The machine name for the empty image breakpoint image style option.
19  *
20  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Use
21  *   Drupal\responsive_image\ResponsiveImageStyleInterface::EMPTY_IMAGE
22  *   instead.
23  *
24  * @see https://www.drupal.org/node/2831620
25  */
26 const RESPONSIVE_IMAGE_EMPTY_IMAGE = '_empty image_';
27
28 /**
29  * The machine name for the original image breakpoint image style option.
30  *
31  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Use
32  *   \Drupal\responsive_image\ResponsiveImageStyleInterface::ORIGINAL_IMAGE
33  *   instead.
34  *
35  * @see https://www.drupal.org/node/2831620
36  */
37 const RESPONSIVE_IMAGE_ORIGINAL_IMAGE = '_original image_';
38
39 /**
40  * Implements hook_help().
41  */
42 function responsive_image_help($route_name, RouteMatchInterface $route_match) {
43   switch ($route_name) {
44     case 'help.page.responsive_image':
45       $output = '';
46       $output .= '<h3>' . t('About') . '</h3>';
47       $output .= '<p>' . t('The Responsive Image module provides an image formatter that allows browsers to select which image file to display based on media queries or which image file types the browser supports, using the HTML 5 picture and source elements and/or the sizes, srcset and type attributes. For more information, see the <a href=":responsive_image">online documentation for the Responsive Image module</a>.', [':responsive_image' => 'https://www.drupal.org/documentation/modules/responsive_image']) . '</p>';
48       $output .= '<h3>' . t('Uses') . '</h3>';
49       $output .= '<dl>';
50       $output .= '<dt>' . t('Defining responsive image styles') . '</dt>';
51       $output .= '<dd>' . t('By creating responsive image styles you define which options the browser has in selecting which image file to display. In most cases this means providing different image sizes based on the viewport size. On the <a href=":responsive_image_style">Responsive image styles</a> page, click <em>Add responsive image style</em> to create a new style. First choose a label, a fallback image style and a breakpoint group and click Save.', [':responsive_image_style' => \Drupal::url('entity.responsive_image_style.collection')]) . '</dd>';
52       $output .= '<dl>';
53       $output .= '<dt>' . t('Fallback image style') . '</dt>';
54       $output .= '<dd>' . t('The fallback image style is typically the smallest size image you expect to appear in this space. Because the responsive images module uses the Picturefill library so that responsive images can work in older browsers, the fallback image should only appear on a site if an error occurs.') . '</dd>';
55       $output .= '<dt>' . t('Breakpoint groups: viewport sizing vs art direction') . '</dt>';
56       $output .= '<dd>' . t('The breakpoint group typically only needs a single breakpoint with an empty media query in order to do <em>viewport sizing.</em> Multiple breakpoints are used for changing the crop or aspect ratio of images at different viewport sizes, which is often referred to as <em>art direction.</em> Once you select a breakpoint group, you can choose which breakpoints to use for the responsive image style. By default, the option <em>do not use this breakpoint</em> is selected for each breakpoint. See the <a href=":breakpoint_help">help page of the Breakpoint module</a> for more information.', [':breakpoint_help' => \Drupal::url('help.page', ['name' => 'breakpoint'])]) . '</dd>';
57       $output .= '<dt>' . t('Breakpoint settings: sizes vs image styles') . '</dt>';
58       $output .= '<dd>' . t('While you have the option to provide only one image style per breakpoint, the sizes option allows you to provide more options to browsers as to which image file it can display, even when using multiple breakpoints for art direction. Breakpoints are defined in the configuration files of the theme.') . '</dd>';
59       $output .= '<dt>' . t('Sizes field') . '</dt>';
60       $output .= '<dd>' . t('Once the sizes option is selected, you can let the browser know the size of this image in relation to the site layout, using the <em>Sizes</em> field. For a hero image that always fills the entire screen, you could simply enter 100vw, which means 100% of the viewport width. For an image that fills 90% of the screen for small viewports, but only fills 40% of the screen when the viewport is larger than 40em (typically 640px), you could enter "(min-width: 40em) 40vw, 90vw" in the Sizes field. The last item in the comma-separated list is the smallest viewport size: other items in the comma-separated list should have a media condition paired with an image width. <em>Media conditions</em> are similar to a media query, often a min-width paired with a viewport width using em or px units: e.g. (min-width: 640px) or (min-width: 40em). This is paired with the <em>image width</em> at that viewport size using px, em or vw units. The vw unit is viewport width and is used instead of a percentage because the percentage always refers to the width of the entire viewport.') . '</dd>';
61       $output .= '<dt>' . t('Image styles for sizes') . '</dt>';
62       $output .= '<dd>' . t('Below the Sizes field you can choose multiple image styles so the browser can choose the best image file size to fill the space defined in the Sizes field. Typically you will want to use image styles that resize your image to have options that range from the smallest px width possible for the space the image will appear in to the largest px width possible, with a variety of widths in between. You may want to provide image styles with widths that are 1.5x to 2x the space available in the layout to account for high resolution screens. Image styles can be defined on the <a href=":image_styles">Image styles page</a> that is provided by the <a href=":image_help">Image module</a>.', [':image_styles' => \Drupal::url('entity.image_style.collection'), ':image_help' => \Drupal::url('help.page', ['name' => 'image'])]) . '</dd>';
63       $output .= '</dl></dd>';
64       $output .= '<dt>' . t('Using responsive image styles in Image fields') . '</dt>';
65       $output .= '<dd>' . t('After defining responsive image styles, you can use them in the display settings for your Image fields, so that the site displays responsive images using the HTML5 picture tag. Open the Manage display page for the entity type (content type, taxonomy vocabulary, etc.) that the Image field is attached to. Choose the format <em>Responsive image</em>, click the Edit icon, and select one of the responsive image styles that you have created. For general information on how to manage fields and their display see the <a href=":field_ui">Field UI module help page</a>. For background information about entities and fields see the <a href=":field_help">Field module help page</a>.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#', ':field_help' => \Drupal::url('help.page', ['name' => 'field'])]) . '</dd>';
66       $output .= '</dl>';
67       return $output;
68
69     case 'entity.responsive_image_style.collection':
70       return '<p>' . t('A responsive image style associates an image style with each breakpoint defined by your theme.') . '</p>';
71   }
72 }
73
74 /**
75  * Implements hook_theme().
76  */
77 function responsive_image_theme() {
78   return [
79     'responsive_image' => [
80       'variables' => [
81         'uri' => NULL,
82         'attributes' => [],
83         'responsive_image_style_id' => [],
84         'height' => NULL,
85         'width' => NULL,
86       ],
87     ],
88     'responsive_image_formatter' => [
89       'variables' => [
90         'item' => NULL,
91         'item_attributes' => NULL,
92         'url' => NULL,
93         'responsive_image_style_id' => NULL,
94       ],
95     ],
96   ];
97 }
98
99 /**
100  * Prepares variables for responsive image formatter templates.
101  *
102  * Default template: responsive-image-formatter.html.twig.
103  *
104  * @param array $variables
105  *   An associative array containing:
106  *   - item: An ImageItem object.
107  *   - item_attributes: An optional associative array of HTML attributes to be
108  *     placed in the img tag.
109  *   - responsive_image_style_id: A responsive image style.
110  *   - url: An optional \Drupal\Core\Url object.
111  */
112 function template_preprocess_responsive_image_formatter(&$variables) {
113   // Provide fallback to standard image if valid responsive image style is not
114   // provided in the responsive image formatter.
115   $responsive_image_style = ResponsiveImageStyle::load($variables['responsive_image_style_id']);
116   if ($responsive_image_style) {
117     $variables['responsive_image'] = [
118       '#type' => 'responsive_image',
119       '#responsive_image_style_id' => $variables['responsive_image_style_id'],
120     ];
121   }
122   else {
123     $variables['responsive_image'] = [
124       '#theme' => 'image',
125     ];
126   }
127   $item = $variables['item'];
128   $attributes = [];
129   // Do not output an empty 'title' attribute.
130   if (Unicode::strlen($item->title) != 0) {
131     $attributes['title'] = $item->title;
132   }
133   $attributes['alt'] = $item->alt;
134   // Need to check that item_attributes has a value since it can be NULL.
135   if ($variables['item_attributes']) {
136     $attributes += $variables['item_attributes'];
137   }
138   if (($entity = $item->entity) && empty($item->uri)) {
139     $variables['responsive_image']['#uri'] = $entity->getFileUri();
140   }
141   else {
142     $variables['responsive_image']['#uri'] = $item->uri;
143   }
144
145   foreach (['width', 'height'] as $key) {
146     $variables['responsive_image']["#$key"] = $item->$key;
147   }
148   $variables['responsive_image']['#attributes'] = $attributes;
149 }
150
151 /**
152  * Prepares variables for a responsive image.
153  *
154  * Default template: responsive-image.html.twig.
155  *
156  * @param $variables
157  *   An associative array containing:
158  *   - uri: The URI of the image.
159  *   - width: The width of the image (if known).
160  *   - height: The height of the image (if known).
161  *   - attributes: Associative array of attributes to be placed in the img tag.
162  *   - responsive_image_style_id: The ID of the responsive image style.
163  */
164 function template_preprocess_responsive_image(&$variables) {
165   // Make sure that width and height are proper values
166   // If they exists we'll output them
167   // @see http://www.w3.org/community/respimg/2012/06/18/florians-compromise/
168   if (isset($variables['width']) && empty($variables['width'])) {
169     unset($variables['width']);
170     unset($variables['height']);
171   }
172   elseif (isset($variables['height']) && empty($variables['height'])) {
173     unset($variables['width']);
174     unset($variables['height']);
175   }
176
177   $responsive_image_style = ResponsiveImageStyle::load($variables['responsive_image_style_id']);
178   // If a responsive image style is not selected, log the error and stop
179   // execution.
180   if (!$responsive_image_style) {
181     $variables['img_element'] = [];
182     \Drupal::logger('responsive_image')->log(RfcLogLevel::ERROR, 'Failed to load responsive image style: â€œ@style“ while displaying responsive image.', ['@style' => $variables['responsive_image_style_id']]);
183     return;
184   }
185   // Retrieve all breakpoints and multipliers and reverse order of breakpoints.
186   // By default, breakpoints are ordered from smallest weight to largest:
187   // the smallest weight is expected to have the smallest breakpoint width,
188   // while the largest weight is expected to have the largest breakpoint
189   // width. For responsive images, we need largest breakpoint widths first, so
190   // we need to reverse the order of these breakpoints.
191   $breakpoints = array_reverse(\Drupal::service('breakpoint.manager')->getBreakpointsByGroup($responsive_image_style->getBreakpointGroup()));
192   foreach ($responsive_image_style->getKeyedImageStyleMappings() as $breakpoint_id => $multipliers) {
193     if (isset($breakpoints[$breakpoint_id])) {
194       $variables['sources'][] = _responsive_image_build_source_attributes($variables, $breakpoints[$breakpoint_id], $multipliers);
195     }
196   }
197
198   if (isset($variables['sources']) && count($variables['sources']) === 1 && !isset($variables['sources'][0]['media'])) {
199     // There is only one source tag with an empty media attribute. This means
200     // we can output an image tag with the srcset attribute instead of a
201     // picture tag.
202     $variables['output_image_tag'] = TRUE;
203     foreach ($variables['sources'][0] as $attribute => $value) {
204       if ($attribute != 'type') {
205         $variables['attributes'][$attribute] = $value;
206       }
207     }
208     $variables['img_element'] = [
209       '#theme' => 'image',
210       '#uri' => _responsive_image_image_style_url($responsive_image_style->getFallbackImageStyle(), $variables['uri']),
211     ];
212   }
213   else {
214     $variables['output_image_tag'] = FALSE;
215     // Prepare the fallback image. We use the src attribute, which might cause
216     // double downloads in browsers that don't support the picture tag (might,
217     // because when picturefill kicks in, it cancels the download and triggers
218     // the download for the correct image).
219     $variables['img_element'] = [
220       '#theme' => 'image',
221       '#uri' => _responsive_image_image_style_url($responsive_image_style->getFallbackImageStyle(), $variables['uri']),
222     ];
223   }
224
225   if (isset($variables['attributes'])) {
226     if (isset($variables['attributes']['alt'])) {
227       $variables['img_element']['#alt'] = $variables['attributes']['alt'];
228       unset($variables['attributes']['alt']);
229     }
230     if (isset($variables['attributes']['title'])) {
231       $variables['img_element']['#title'] = $variables['attributes']['title'];
232       unset($variables['attributes']['title']);
233     }
234     $variables['img_element']['#attributes'] = $variables['attributes'];
235   }
236 }
237
238 /**
239  * Helper function for template_preprocess_responsive_image().
240  *
241  * @param \Drupal\Core\Image\ImageInterface $image
242  *   The image to build the <source> tags for.
243  * @param array $variables
244  *   An array with the following keys:
245  *     - responsive_image_style_id: The \Drupal\responsive_image\Entity\ResponsiveImageStyle
246  *       ID.
247  *     - width: The width of the image (if known).
248  *     - height: The height of the image (if known).
249  *     - uri: The URI of the image file.
250  * @param \Drupal\breakpoint\BreakpointInterface $breakpoint
251  *   The breakpoint for this source tag.
252  * @param array $multipliers
253  *   An array with multipliers as keys and image style mappings as values.
254  *
255  * @return \Drupal\Core\Template\Attribute[]
256  *   An array of attributes for the source tag.
257  *
258  * @deprecated in Drupal 8.3.x and will be removed before 9.0.0.
259  */
260 function responsive_image_build_source_attributes(ImageInterface $image, array $variables, BreakpointInterface $breakpoint, array $multipliers) {
261   return _responsive_image_build_source_attributes($variables, $breakpoint, $multipliers);
262 }
263
264 /**
265  * Helper function for template_preprocess_responsive_image().
266  *
267  * Builds an array of attributes for <source> tags to be used in a <picture>
268  * tag. In other words, this function provides the attributes for each <source>
269  * tag in a <picture> tag.
270  *
271  * In a responsive image style, each breakpoint has an image style mapping for
272  * each of its multipliers. An image style mapping can be either of two types:
273  * 'sizes' (meaning it will output a <source> tag with the 'sizes' attribute) or
274  * 'image_style' (meaning it will output a <source> tag based on the selected
275  * image style for this breakpoint and multiplier). A responsive image style
276  * can contain image style mappings of mixed types (both 'image_style' and
277  * 'sizes'). For example:
278  * @code
279  * $responsive_img_style = ResponsiveImageStyle::create(array(
280  *   'id' => 'style_one',
281  *   'label' => 'Style One',
282  *   'breakpoint_group' => 'responsive_image_test_module',
283  * ));
284  * $responsive_img_style->addImageStyleMapping('responsive_image_test_module.mobile', '1x', array(
285  *   'image_mapping_type' => 'image_style',
286  *   'image_mapping' => 'thumbnail',
287  * ))
288  * ->addImageStyleMapping('responsive_image_test_module.narrow', '1x', array(
289  *   'image_mapping_type' => 'sizes',
290  *   'image_mapping' => array(
291  *     'sizes' => '(min-width: 700px) 700px, 100vw',
292  *     'sizes_image_styles' => array(
293  *       'large' => 'large',
294  *       'medium' => 'medium',
295  *     ),
296  *   ),
297  * ))
298  * ->save();
299  * @endcode
300  * The above responsive image style will result in a <picture> tag like this:
301  * @code
302  * <picture>
303  *   <source media="(min-width: 0px)" srcset="sites/default/files/styles/thumbnail/image.jpeg" />
304  *   <source media="(min-width: 560px)" sizes="(min-width: 700px) 700px, 100vw" srcset="sites/default/files/styles/large/image.jpeg 480w, sites/default/files/styles/medium/image.jpeg 220w" />
305  *   <img src="fallback.jpeg" />
306  * </picture>
307  * @endcode
308  *
309  * When all the images in the 'srcset' attribute of a <source> tag have the same
310  * MIME type, the source tag will get a 'mime-type' attribute as well. This way
311  * we can gain some front-end performance because browsers can select which
312  * image (<source> tag) to load based on the MIME types they support (which, for
313  * instance, can be beneficial for browsers supporting WebP).
314  * For example:
315  * A <source> tag can contain multiple images:
316  * @code
317  * <source [...] srcset="image1.jpeg 1x, image2.jpeg 2x, image3.jpeg 3x" />
318  * @endcode
319  * In the above example we can add the 'mime-type' attribute ('image/jpeg')
320  * since all images in the 'srcset' attribute of the <source> tag have the same
321  * MIME type.
322  * If a <source> tag were to look like this:
323  * @code
324  * <source [...] srcset="image1.jpeg 1x, image2.webp 2x, image3.jpeg 3x" />
325  * @endcode
326  * We can't add the 'mime-type' attribute ('image/jpeg' vs 'image/webp'). So in
327  * order to add the 'mime-type' attribute to the <source> tag all images in the
328  * 'srcset' attribute of the <source> tag need to be of the same MIME type. This
329  * way, a <picture> tag could look like this:
330  * @code
331  * <picture>
332  *   <source [...] mime-type="image/webp" srcset="image1.webp 1x, image2.webp 2x, image3.webp 3x"/>
333  *   <source [...] mime-type="image/jpeg" srcset="image1.jpeg 1x, image2.jpeg 2x, image3.jpeg 3x"/>
334  *   <img src="fallback.jpeg" />
335  * </picture>
336  * @endcode
337  * This way a browser can decide which <source> tag is preferred based on the
338  * MIME type. In other words, the MIME types of all images in one <source> tag
339  * need to be the same in order to set the 'mime-type' attribute but not all
340  * MIME types within the <picture> tag need to be the same.
341  *
342  * For image style mappings of the type 'sizes', a width descriptor is added to
343  * each source. For example:
344  * @code
345  * <source media="(min-width: 0px)" srcset="image1.jpeg 100w" />
346  * @endcode
347  * The width descriptor here is "100w". This way the browser knows this image is
348  * 100px wide without having to load it. According to the spec, a multiplier can
349  * not be present if a width descriptor is.
350  * For example:
351  * Valid:
352  * @code
353  * <source media="(min-width:0px)" srcset="img1.jpeg 50w, img2.jpeg=100w" />
354  * @endcode
355  * Invalid:
356  * @code
357  * <source media="(min-width:0px)" srcset="img1.jpeg 50w 1x, img2.jpeg=100w 1x" />
358  * @endcode
359  *
360  * Note: Since the specs do not allow width descriptors and multipliers combined
361  * inside one 'srcset' attribute, we either have to use something like
362  * @code
363  * <source [...] srcset="image1.jpeg 1x, image2.webp 2x, image3.jpeg 3x" />
364  * @endcode
365  * to support multipliers or
366  * @code
367  * <source [...] sizes"(min-width: 40em) 80vw, 100vw" srcset="image1.jpeg 300w, image2.webp 600w, image3.jpeg 1200w" />
368  * @endcode
369  * to support the 'sizes' attribute.
370  *
371  * In theory people could add an image style mapping for the same breakpoint
372  * (but different multiplier) so the array contains an entry for breakpointA.1x
373  * and breakpointA.2x. If we would output those we will end up with something
374  * like
375  * @code
376  * <source [...] sizes="(min-width: 40em) 80vw, 100vw" srcset="a1.jpeg 300w 1x, a2.jpeg 600w 1x, a3.jpeg 1200w 1x, b1.jpeg 250w 2x, b2.jpeg 680w 2x, b3.jpeg 1240w 2x" />
377  * @endcode
378  * which is illegal. So the solution is to merge both arrays into one and
379  * disregard the multiplier. Which, in this case, would output
380  * @code
381  * <source [...] sizes="(min-width: 40em) 80vw, 100vw" srcset="b1.jpeg 250w, a1.jpeg 300w, a2.jpeg 600w, b2.jpeg 680w, a3.jpeg 1200w,  b3.jpeg 1240w" />
382  * @endcode
383  * See http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#image-candidate-string
384  * for further information.
385  *
386  * @param array $variables
387  *   An array with the following keys:
388  *     - responsive_image_style_id: The \Drupal\responsive_image\Entity\ResponsiveImageStyle
389  *       ID.
390  *     - width: The width of the image (if known).
391  *     - height: The height of the image (if known).
392  *     - uri: The URI of the image file.
393  * @param \Drupal\breakpoint\BreakpointInterface $breakpoint
394  *   The breakpoint for this source tag.
395  * @param array $multipliers
396  *   An array with multipliers as keys and image style mappings as values.
397  *
398  * @return \Drupal\Core\Template\Attribute[]
399  *   An array of attributes for the source tag.
400  */
401 function _responsive_image_build_source_attributes(array $variables, BreakpointInterface $breakpoint, array $multipliers) {
402   if ((empty($variables['width']) || empty($variables['height']))) {
403     $image = \Drupal::service('image.factory')->get($variables['uri']);
404     $width = $image->getWidth();
405     $height = $image->getHeight();
406   }
407   else {
408     $width = $variables['width'];
409     $height = $variables['height'];
410   }
411   $extension = pathinfo($variables['uri'], PATHINFO_EXTENSION);
412   $sizes = [];
413   $srcset = [];
414   $derivative_mime_types = [];
415   foreach ($multipliers as $multiplier => $image_style_mapping) {
416     switch ($image_style_mapping['image_mapping_type']) {
417       // Create a <source> tag with the 'sizes' attribute.
418       case 'sizes':
419         // Loop through the image styles for this breakpoint and multiplier.
420         foreach ($image_style_mapping['image_mapping']['sizes_image_styles'] as $image_style_name) {
421           // Get the dimensions.
422           $dimensions = responsive_image_get_image_dimensions($image_style_name, ['width' => $width, 'height' => $height], $variables['uri']);
423           // Get MIME type.
424           $derivative_mime_type = responsive_image_get_mime_type($image_style_name, $extension);
425           $derivative_mime_types[] = $derivative_mime_type;
426
427           // Add the image source with its width descriptor. When a width
428           // descriptor is used in a srcset, we can't add a multiplier to
429           // it. Because of this, the image styles for all multipliers of
430           // this breakpoint should be merged into one srcset and the sizes
431           // attribute should be merged as well.
432           if (is_null($dimensions['width'])) {
433             throw new \LogicException("Could not determine image width for '{$variables['uri']}' using image style with ID: $image_style_name. This image style can not be used for a responsive image style mapping using the 'sizes' attribute.");
434           }
435           // Use the image width as key so we can sort the array later on.
436           // Images within a srcset should be sorted from small to large, since
437           // the first matching source will be used.
438           $srcset[intval($dimensions['width'])] = _responsive_image_image_style_url($image_style_name, $variables['uri']) . ' ' . $dimensions['width'] . 'w';
439           $sizes = array_merge(explode(',', $image_style_mapping['image_mapping']['sizes']), $sizes);
440         }
441         break;
442
443       case 'image_style':
444         // Get MIME type.
445         $derivative_mime_type = responsive_image_get_mime_type($image_style_mapping['image_mapping'], $extension);
446         $derivative_mime_types[] = $derivative_mime_type;
447         // Add the image source with its multiplier. Use the multiplier as key
448         // so we can sort the array later on. Multipliers within a srcset should
449         // be sorted from small to large, since the first matching source will
450         // be used. We multiply it by 100 so multipliers with up to two decimals
451         // can be used.
452         $srcset[intval(Unicode::substr($multiplier, 0, -1) * 100)] = _responsive_image_image_style_url($image_style_mapping['image_mapping'], $variables['uri']) . ' ' . $multiplier;
453         break;
454     }
455   }
456   // Sort the srcset from small to large image width or multiplier.
457   ksort($srcset);
458   $source_attributes = new Attribute([
459     'srcset' => implode(', ', array_unique($srcset)),
460   ]);
461   $media_query = trim($breakpoint->getMediaQuery());
462   if (!empty($media_query)) {
463     $source_attributes->setAttribute('media', $media_query);
464   }
465   if (count(array_unique($derivative_mime_types)) == 1) {
466     $source_attributes->setAttribute('type', $derivative_mime_types[0]);
467   }
468   if (!empty($sizes)) {
469     $source_attributes->setAttribute('sizes', implode(',', array_unique($sizes)));
470   }
471   return $source_attributes;
472 }
473
474 /**
475  * Determines the dimensions of an image.
476  *
477  * @param string $image_style_name
478  *   The name of the style to be used to alter the original image.
479  * @param array $dimensions
480  *   An associative array containing:
481  *   - width: The width of the source image (if known).
482  *   - height: The height of the source image (if known).
483  * @param string $uri
484  *   The URI of the image file.
485  *
486  * @return array
487  *   Dimensions to be modified - an array with components width and height, in
488  *   pixels.
489  */
490 function responsive_image_get_image_dimensions($image_style_name, array $dimensions, $uri) {
491   // Determine the dimensions of the styled image.
492   if ($image_style_name == RESPONSIVE_IMAGE_EMPTY_IMAGE) {
493     $dimensions = [
494       'width' => 1,
495       'height' => 1,
496     ];
497   }
498   elseif ($entity = ImageStyle::load($image_style_name)) {
499     $entity->transformDimensions($dimensions, $uri);
500   }
501
502   return $dimensions;
503 }
504
505 /**
506  * Determines the MIME type of an image.
507  *
508  * @param string $image_style_name
509  *   The image style that will be applied to the image.
510  * @param string $extension
511  *   The original extension of the image (without the leading dot).
512  *
513  * @return string
514  *   The MIME type of the image after the image style is applied.
515  */
516 function responsive_image_get_mime_type($image_style_name, $extension) {
517   if ($image_style_name == RESPONSIVE_IMAGE_EMPTY_IMAGE) {
518     return 'image/gif';
519   }
520   // The MIME type guesser needs a full path, not just an extension, but the
521   // file doesn't have to exist.
522   if ($image_style_name === RESPONSIVE_IMAGE_ORIGINAL_IMAGE) {
523     $fake_path = 'responsive_image.' . $extension;
524   }
525   else {
526     $fake_path = 'responsive_image.' . ImageStyle::load($image_style_name)->getDerivativeExtension($extension);
527   }
528   return Drupal::service('file.mime_type.guesser.extension')->guess($fake_path);
529 }
530
531 /**
532  * Wrapper around image_style_url() so we can return an empty image.
533  */
534 function _responsive_image_image_style_url($style_name, $path) {
535   if ($style_name == RESPONSIVE_IMAGE_EMPTY_IMAGE) {
536     // The smallest data URI for a 1px square transparent GIF image.
537     // http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever
538     return 'data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
539   }
540   $entity = ImageStyle::load($style_name);
541   if ($entity instanceof ImageStyle) {
542     return file_url_transform_relative($entity->buildUrl($path));
543   }
544   return file_url_transform_relative(file_create_url($path));
545 }
546
547 /**
548  * Implements hook_library_info_alter().
549  *
550  * Load responsive_image.js whenever ajax is added.
551  */
552 function responsive_image_library_info_alter(array &$libraries, $module) {
553   if ($module === 'core' && isset($libraries['drupal.ajax'])) {
554     $libraries['drupal.ajax']['dependencies'][] = 'responsive_image/ajax';
555   }
556 }