Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / image / image.module
1 <?php
2
3 /**
4  * @file
5  * Exposes global functionality for creating image styles.
6  */
7
8 use Drupal\Core\Entity\EntityInterface;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\file\Entity\File;
11 use Drupal\field\FieldStorageConfigInterface;
12 use Drupal\field\FieldConfigInterface;
13 use Drupal\image\Entity\ImageStyle;
14
15 /**
16  * Image style constant for user presets in the database.
17  *
18  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
19  *
20  * @see https://www.drupal.org/node/1820974
21  */
22 const IMAGE_STORAGE_NORMAL = 1;
23
24 /**
25  * Image style constant for user presets that override module-defined presets.
26  *
27  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
28  *
29  * @see https://www.drupal.org/node/1820974
30  */
31 const IMAGE_STORAGE_OVERRIDE = 2;
32
33 /**
34  * Image style constant for module-defined presets in code.
35  *
36  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
37  *
38  * @see https://www.drupal.org/node/1820974
39  */
40 const IMAGE_STORAGE_DEFAULT = 4;
41
42 /**
43  * Image style constant to represent an editable preset.
44  *
45  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
46  *
47  * @see https://www.drupal.org/node/1820974
48  */
49 define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
50
51 /**
52  * Image style constant to represent any module-based preset.
53  *
54  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
55  *
56  * @see https://www.drupal.org/node/1820974
57  */
58 define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
59
60 /**
61  * The name of the query parameter for image derivative tokens.
62  */
63 define('IMAGE_DERIVATIVE_TOKEN', 'itok');
64
65 /**
66  * Implements hook_help().
67  */
68 function image_help($route_name, RouteMatchInterface $route_match) {
69   switch ($route_name) {
70     case 'help.page.image':
71       $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
72
73       $output = '';
74       $output .= '<h3>' . t('About') . '</h3>';
75       $output .= '<p>' . t('The Image module allows you to create fields that contain image files and to configure <a href=":image_styles">Image styles</a> that can be used to manipulate the display of images. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for terminology and general information on entities, fields, and how to create and manage fields. For more information, see the <a href=":image_documentation">online documentation for the Image module</a>.', [':image_styles' => \Drupal::url('entity.image_style.collection'), ':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => $field_ui_url, ':image_documentation' => 'https://www.drupal.org/documentation/modules/image']) . '</p>';
76       $output .= '<h3>' . t('Uses') . '</h3>';
77       $output .= '<dt>' . t('Defining image styles') . '</dt>';
78       $output .= '<dd>' . t('The concept of image styles is that you can upload a single image but display it in several ways; each display variation, or <em>image style</em>, is the result of applying one or more <em>effects</em> to the original image. As an example, you might upload a high-resolution image with a 4:3 aspect ratio, and display it scaled down, square cropped, or black-and-white (or any combination of these effects). The Image module provides a way to do this efficiently: you configure an image style with the desired effects on the <a href=":image">Image styles page</a>, and the first time a particular image is requested in that style, the effects are applied. The resulting image is saved, and the next time that same style is requested, the saved image is retrieved without the need to recalculate the effects. Drupal core provides several effects that you can use to define styles; others may be provided by contributed modules.', [':image' => \Drupal::url('entity.image_style.collection')]);
79       $output .= '<dt>' . t('Naming image styles') . '</dt>';
80       $output .= '<dd>' . t('When you define an image style, you will need to choose a displayed name and a machine name. The displayed name is shown in administrative pages, and the machine name is used to generate the URL for accessing an image processed in that style. There are two common approaches to naming image styles: either based on the effects being applied (for example, <em>Square 85x85</em>), or based on where you plan to use it (for example, <em>Profile picture</em>).') . '</dd>';
81       $output .= '<dt>' . t('Configuring image fields') . '</dt>';
82       $output .= '<dd>' . t('A few of the settings for image fields are defined once when you create the field and cannot be changed later; these include the choice of public or private file storage and the number of images that can be stored in the field. The rest of the settings can be edited later; these settings include the field label, help text, allowed file extensions, image resolution restrictions, and the subdirectory in the public or private file storage where the images will be stored. The editable settings can also have different values for different entity sub-types; for instance, if your image field is used on both Page and Article content types, you can store the files in a different subdirectory for the two content types.') . '</dd>';
83       $output .= '<dd>' . t('For accessibility and search engine optimization, all images that convey meaning on web sites should have alternate text. Drupal also allows entry of title text for images, but it can lead to confusion for screen reader users and its use is not recommended. Image fields can be configured so that alternate and title text fields are enabled or disabled; if enabled, the fields can be set to be required. The recommended setting is to enable and require alternate text and disable title text.') . '</dd>';
84       $output .= '<dd>' . t('When you create an image field, you will need to choose whether the uploaded images will be stored in the public or private file directory defined in your settings.php file and shown on the <a href=":file-system">File system page</a>. This choice cannot be changed later. You can also configure your field to store files in a subdirectory of the public or private directory; this setting can be changed later and can be different for each entity sub-type using the field. For more information on file storage, see the <a href=":system-help">System module help page</a>.', [':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', ['name' => 'system'])]) . '</dd>';
85       $output .= '<dd>' . t('The maximum file size that can be uploaded is limited by PHP settings of the server, but you can restrict it further by configuring a <em>Maximum upload size</em> in the field settings (this setting can be changed later). The maximum file size, either from PHP server settings or field configuration, is automatically displayed to users in the help text of the image field.') . '</dd>';
86       $output .= '<dd>' . t('You can also configure a minimum and/or maximum resolution for uploaded images. Images that are too small will be rejected. Images that are to large will be resized. During the resizing the <a href="http://wikipedia.org/wiki/Exchangeable_image_file_format">EXIF data</a> in the image will be lost.') . '</dd>';
87       $output .= '<dd>' . t('You can also configure a default image that will be used if no image is uploaded in an image field. This default can be defined for all instances of the field in the field storage settings when you create a field, and the setting can be overridden for each entity sub-type that uses the field.') . '</dd>';
88       $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
89       $output .= '<dd>' . t('On the <em>Manage display</em> page, you can choose the image formatter, which determines the image style used to display the image in each display mode and whether or not to display the image as a link. On the <em>Manage form display</em> page, you can configure the image upload widget, including setting the preview image style shown on the entity edit form.') . '</dd>';
90       $output .= '</dl>';
91       return $output;
92
93     case 'entity.image_style.collection':
94       return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
95
96     case 'image.effect_add_form':
97       $effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($route_match->getParameter('image_effect'));
98       return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;
99
100     case 'image.effect_edit_form':
101       $effect = $route_match->getParameter('image_style')->getEffect($route_match->getParameter('image_effect'));
102       $effect_definition = $effect->getPluginDefinition();
103       return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
104   }
105 }
106
107 /**
108  * Implements hook_theme().
109  */
110 function image_theme() {
111   return [
112     // Theme functions in image.module.
113     'image_style' => [
114       // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
115       // allows the alt attribute to be omitted in some cases. Therefore,
116       // default the alt attribute to an empty string, but allow code using
117       // '#theme' => 'image_style' to pass explicit NULL for it to be omitted.
118       // Usually, neither omission nor an empty string satisfies accessibility
119       // requirements, so it is strongly encouraged for code using '#theme' =>
120       // 'image_style' to pass a meaningful value for the alt variable.
121       // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
122       // - http://www.w3.org/TR/xhtml1/dtds.html
123       // - http://dev.w3.org/html5/spec/Overview.html#alt
124       // The title attribute is optional in all cases, so it is omitted by
125       // default.
126       'variables' => [
127         'style_name' => NULL,
128         'uri' => NULL,
129         'width' => NULL,
130         'height' => NULL,
131         'alt' => '',
132         'title' => NULL,
133         'attributes' => [],
134       ],
135     ],
136
137     // Theme functions in image.admin.inc.
138     'image_style_preview' => [
139       'variables' => ['style' => NULL],
140       'file' => 'image.admin.inc',
141     ],
142     'image_anchor' => [
143       'render element' => 'element',
144       'file' => 'image.admin.inc',
145     ],
146     'image_resize_summary' => [
147       'variables' => ['data' => NULL, 'effect' => []],
148     ],
149     'image_scale_summary' => [
150       'variables' => ['data' => NULL, 'effect' => []],
151     ],
152     'image_crop_summary' => [
153       'variables' => ['data' => NULL, 'effect' => []],
154     ],
155     'image_rotate_summary' => [
156       'variables' => ['data' => NULL, 'effect' => []],
157     ],
158
159     // Theme functions in image.field.inc.
160     'image_widget' => [
161       'render element' => 'element',
162       'file' => 'image.field.inc',
163     ],
164     'image_formatter' => [
165       'variables' => ['item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL],
166       'file' => 'image.field.inc',
167     ],
168   ];
169 }
170
171 /**
172  * Implements hook_file_download().
173  *
174  * Control the access to files underneath the styles directory.
175  */
176 function image_file_download($uri) {
177   $path = file_uri_target($uri);
178
179   // Private file access for image style derivatives.
180   if (strpos($path, 'styles/') === 0) {
181     $args = explode('/', $path);
182
183     // Discard "styles", style name, and scheme from the path
184     $args = array_slice($args, 3);
185
186     // Then the remaining parts are the path to the image.
187     $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
188
189     // Check that the file exists and is an image.
190     $image = \Drupal::service('image.factory')->get($uri);
191     if ($image->isValid()) {
192       // Check the permissions of the original to grant access to this image.
193       $headers = \Drupal::moduleHandler()->invokeAll('file_download', [$original_uri]);
194       // Confirm there's at least one module granting access and none denying access.
195       if (!empty($headers) && !in_array(-1, $headers)) {
196         return [
197           // Send headers describing the image's size, and MIME-type.
198           'Content-Type' => $image->getMimeType(),
199           'Content-Length' => $image->getFileSize(),
200           // By not explicitly setting them here, this uses normal Drupal
201           // Expires, Cache-Control and ETag headers to prevent proxy or
202           // browser caching of private images.
203         ];
204       }
205     }
206     return -1;
207   }
208 }
209
210 /**
211  * Implements hook_file_move().
212  */
213 function image_file_move(File $file, File $source) {
214   // Delete any image derivatives at the original image path.
215   image_path_flush($source->getFileUri());
216 }
217
218 /**
219  * Implements hook_ENTITY_TYPE_predelete() for file entities.
220  */
221 function image_file_predelete(File $file) {
222   // Delete any image derivatives of this image.
223   image_path_flush($file->getFileUri());
224 }
225
226 /**
227  * Clears cached versions of a specific file in all styles.
228  *
229  * @param $path
230  *   The Drupal file path to the original image.
231  */
232 function image_path_flush($path) {
233   $styles = ImageStyle::loadMultiple();
234   foreach ($styles as $style) {
235     $style->flush($path);
236   }
237 }
238
239 /**
240  * Gets an array of image styles suitable for using as select list options.
241  *
242  * @param $include_empty
243  *   If TRUE a '- None -' option will be inserted in the options array.
244  * @return
245  *   Array of image styles both key and value are set to style name.
246  */
247 function image_style_options($include_empty = TRUE) {
248   $styles = ImageStyle::loadMultiple();
249   $options = [];
250   if ($include_empty && !empty($styles)) {
251     $options[''] = t('- None -');
252   }
253   foreach ($styles as $name => $style) {
254     $options[$name] = $style->label();
255   }
256
257   if (empty($options)) {
258     $options[''] = t('No defined styles');
259   }
260   return $options;
261 }
262
263 /**
264  * Prepares variables for image style templates.
265  *
266  * Default template: image-style.html.twig.
267  *
268  * @param array $variables
269  *   An associative array containing:
270  *   - width: The width of the image.
271  *   - height: The height of the image.
272  *   - style_name: The name of the image style to be applied.
273  *   - attributes: Additional attributes to apply to the image.
274  *   - uri: URI of the source image before styling.
275  *   - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
276  *     always require an alt attribute. The HTML 5 draft allows the alt
277  *     attribute to be omitted in some cases. Therefore, this variable defaults
278  *     to an empty string, but can be set to NULL for the attribute to be
279  *     omitted. Usually, neither omission nor an empty string satisfies
280  *     accessibility requirements, so it is strongly encouraged for code using
281  *     '#theme' => 'image_style' to pass a meaningful value for this variable.
282  *     - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
283  *     - http://www.w3.org/TR/xhtml1/dtds.html
284  *     - http://dev.w3.org/html5/spec/Overview.html#alt
285  *   - title: The title text is displayed when the image is hovered in some
286  *     popular browsers.
287  *   - attributes: Associative array of attributes to be placed in the img tag.
288  */
289 function template_preprocess_image_style(&$variables) {
290   $style = ImageStyle::load($variables['style_name']);
291
292   // Determine the dimensions of the styled image.
293   $dimensions = [
294     'width' => $variables['width'],
295     'height' => $variables['height'],
296   ];
297
298   $style->transformDimensions($dimensions, $variables['uri']);
299
300   $variables['image'] = [
301     '#theme' => 'image',
302     '#width' => $dimensions['width'],
303     '#height' => $dimensions['height'],
304     '#attributes' => $variables['attributes'],
305     '#style_name' => $variables['style_name'],
306   ];
307
308   // If the current image toolkit supports this file type, prepare the URI for
309   // the derivative image. If not, just use the original image resized to the
310   // dimensions specified by the style.
311   if ($style->supportsUri($variables['uri'])) {
312     $variables['image']['#uri'] = $style->buildUrl($variables['uri']);
313   }
314   else {
315     $variables['image']['#uri'] = $variables['uri'];
316     // Don't render the image by default, but allow other preprocess functions
317     // to override that if they need to.
318     $variables['image']['#access'] = FALSE;
319
320     // Inform the site builders why their image didn't work.
321     \Drupal::logger('image')->warning('Could not apply @style image style to @uri because the style does not support it.', [
322       '@style' => $style->label(),
323       '@uri' => $variables['uri'],
324     ]);
325   }
326
327   if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
328     $variables['image']['#alt'] = $variables['alt'];
329   }
330   if (isset($variables['title']) || array_key_exists('title', $variables)) {
331     $variables['image']['#title'] = $variables['title'];
332   }
333
334 }
335
336 /**
337  * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
338  *
339  * @param $value
340  * @param $current_pixels
341  * @param $new_pixels
342  */
343 function image_filter_keyword($value, $current_pixels, $new_pixels) {
344   switch ($value) {
345     case 'top':
346     case 'left':
347       return 0;
348
349     case 'bottom':
350     case 'right':
351       return $current_pixels - $new_pixels;
352
353     case 'center':
354       return $current_pixels / 2 - $new_pixels / 2;
355   }
356   return $value;
357 }
358
359 /**
360  * Implements hook_entity_presave().
361  *
362  * Transforms default image of image field from array into single value at save.
363  */
364 function image_entity_presave(EntityInterface $entity) {
365   // Get the default image settings, return if not saving an image field storage
366   // or image field entity.
367   $default_image = [];
368   if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
369     $default_image = $entity->getSetting('default_image');
370   }
371   else {
372     return;
373   }
374
375   if ($entity->isSyncing()) {
376     return;
377   }
378
379   $uuid = $default_image['uuid'];
380   if ($uuid) {
381     $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
382     if ($uuid != $original_uuid) {
383       $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
384       if ($file) {
385         $image = \Drupal::service('image.factory')->get($file->getFileUri());
386         $default_image['width'] = $image->getWidth();
387         $default_image['height'] = $image->getHeight();
388       }
389       else {
390         $default_image['uuid'] = NULL;
391       }
392     }
393   }
394   // Both FieldStorageConfigInterface and FieldConfigInterface have a
395   // setSetting() method.
396   $entity->setSetting('default_image', $default_image);
397 }
398
399 /**
400  * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
401  */
402 function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
403   if ($field_storage->getType() != 'image') {
404     // Only act on image fields.
405     return;
406   }
407
408   $prior_field_storage = $field_storage->original;
409
410   // The value of a managed_file element can be an array if #extended == TRUE.
411   $uuid_new = $field_storage->getSetting('default_image')['uuid'];
412   $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];
413
414   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
415
416   if ($uuid_new != $uuid_old) {
417
418     // Is there a new file?
419     if ($file_new) {
420       $file_new->status = FILE_STATUS_PERMANENT;
421       $file_new->save();
422       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
423     }
424
425     // Is there an old file?
426     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
427       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
428     }
429   }
430
431   // If the upload destination changed, then move the file.
432   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
433     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
434     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
435     file_move($file_new, $directory . $file_new->getFilename());
436   }
437 }
438
439 /**
440  * Implements hook_ENTITY_TYPE_update() for 'field_config'.
441  */
442 function image_field_config_update(FieldConfigInterface $field) {
443   $field_storage = $field->getFieldStorageDefinition();
444   if ($field_storage->getType() != 'image') {
445     // Only act on image fields.
446     return;
447   }
448
449   $prior_instance = $field->original;
450
451   $uuid_new = $field->getSetting('default_image')['uuid'];
452   $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
453
454   // If the old and new files do not match, update the default accordingly.
455   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
456   if ($uuid_new != $uuid_old) {
457     // Save the new file, if present.
458     if ($file_new) {
459       $file_new->status = FILE_STATUS_PERMANENT;
460       $file_new->save();
461       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
462     }
463     // Delete the old file, if present.
464     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
465       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
466     }
467   }
468
469   // If the upload destination changed, then move the file.
470   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
471     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
472     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
473     file_move($file_new, $directory . $file_new->getFilename());
474   }
475 }
476
477 /**
478  * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
479  */
480 function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
481   if ($field->getType() != 'image') {
482     // Only act on image fields.
483     return;
484   }
485
486   // The value of a managed_file element can be an array if #extended == TRUE.
487   $uuid = $field->getSetting('default_image')['uuid'];
488   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
489     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
490   }
491 }
492
493 /**
494  * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
495  */
496 function image_field_config_delete(FieldConfigInterface $field) {
497   $field_storage = $field->getFieldStorageDefinition();
498   if ($field_storage->getType() != 'image') {
499     // Only act on image fields.
500     return;
501   }
502
503   // The value of a managed_file element can be an array if #extended == TRUE.
504   $uuid = $field->getSetting('default_image')['uuid'];
505
506   // Remove the default image when the instance is deleted.
507   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
508     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
509   }
510 }