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