Upgraded drupal core with security updates
[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 const IMAGE_STORAGE_NORMAL = 1;
21
22 /**
23  * Image style constant for user presets that override module-defined presets.
24  *
25  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
26  */
27 const IMAGE_STORAGE_OVERRIDE = 2;
28
29 /**
30  * Image style constant for module-defined presets in code.
31  *
32  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
33  */
34 const IMAGE_STORAGE_DEFAULT = 4;
35
36 /**
37  * Image style constant to represent an editable preset.
38  *
39  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
40  */
41 define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
42
43 /**
44  * Image style constant to represent any module-based preset.
45  *
46  * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
47  */
48 define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
49
50 /**
51  * The name of the query parameter for image derivative tokens.
52  */
53 define('IMAGE_DERIVATIVE_TOKEN', 'itok');
54
55 /**
56  * Implements hook_help().
57  */
58 function image_help($route_name, RouteMatchInterface $route_match) {
59   switch ($route_name) {
60     case 'help.page.image':
61       $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
62
63       $output = '';
64       $output .= '<h3>' . t('About') . '</h3>';
65       $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>';
66       $output .= '<h3>' . t('Uses') . '</h3>';
67       $output .= '<dt>' . t('Defining image styles') . '</dt>';
68       $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')]);
69       $output .= '<dt>' . t('Naming image styles') . '</dt>';
70       $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>';
71       $output .= '<dt>' . t('Configuring image fields') . '</dt>';
72       $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>';
73       $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>';
74       $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>';
75       $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>';
76       $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>';
77       $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>';
78       $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
79       $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>';
80       $output .= '</dl>';
81       return $output;
82
83     case 'entity.image_style.collection':
84       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>';
85
86     case 'image.effect_add_form':
87       $effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($route_match->getParameter('image_effect'));
88       return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;
89
90     case 'image.effect_edit_form':
91       $effect = $route_match->getParameter('image_style')->getEffect($route_match->getParameter('image_effect'));
92       $effect_definition = $effect->getPluginDefinition();
93       return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
94   }
95 }
96
97 /**
98  * Implements hook_theme().
99  */
100 function image_theme() {
101   return [
102     // Theme functions in image.module.
103     'image_style' => [
104       // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
105       // allows the alt attribute to be omitted in some cases. Therefore,
106       // default the alt attribute to an empty string, but allow code using
107       // '#theme' => 'image_style' to pass explicit NULL for it to be omitted.
108       // Usually, neither omission nor an empty string satisfies accessibility
109       // requirements, so it is strongly encouraged for code using '#theme' =>
110       // 'image_style' to pass a meaningful value for the alt variable.
111       // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
112       // - http://www.w3.org/TR/xhtml1/dtds.html
113       // - http://dev.w3.org/html5/spec/Overview.html#alt
114       // The title attribute is optional in all cases, so it is omitted by
115       // default.
116       'variables' => [
117         'style_name' => NULL,
118         'uri' => NULL,
119         'width' => NULL,
120         'height' => NULL,
121         'alt' => '',
122         'title' => NULL,
123         'attributes' => [],
124       ],
125     ],
126
127     // Theme functions in image.admin.inc.
128     'image_style_preview' => [
129       'variables' => ['style' => NULL],
130       'file' => 'image.admin.inc',
131     ],
132     'image_anchor' => [
133       'render element' => 'element',
134       'file' => 'image.admin.inc',
135     ],
136     'image_resize_summary' => [
137       'variables' => ['data' => NULL, 'effect' => []],
138     ],
139     'image_scale_summary' => [
140       'variables' => ['data' => NULL, 'effect' => []],
141     ],
142     'image_crop_summary' => [
143       'variables' => ['data' => NULL, 'effect' => []],
144     ],
145     'image_rotate_summary' => [
146       'variables' => ['data' => NULL, 'effect' => []],
147     ],
148
149     // Theme functions in image.field.inc.
150     'image_widget' => [
151       'render element' => 'element',
152       'file' => 'image.field.inc',
153     ],
154     'image_formatter' => [
155       'variables' => ['item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL],
156       'file' => 'image.field.inc',
157     ],
158   ];
159 }
160
161 /**
162  * Implements hook_file_download().
163  *
164  * Control the access to files underneath the styles directory.
165  */
166 function image_file_download($uri) {
167   $path = file_uri_target($uri);
168
169   // Private file access for image style derivatives.
170   if (strpos($path, 'styles/') === 0) {
171     $args = explode('/', $path);
172
173     // Discard "styles", style name, and scheme from the path
174     $args = array_slice($args, 3);
175
176     // Then the remaining parts are the path to the image.
177     $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
178
179     // Check that the file exists and is an image.
180     $image = \Drupal::service('image.factory')->get($uri);
181     if ($image->isValid()) {
182       // Check the permissions of the original to grant access to this image.
183       $headers = \Drupal::moduleHandler()->invokeAll('file_download', [$original_uri]);
184       // Confirm there's at least one module granting access and none denying access.
185       if (!empty($headers) && !in_array(-1, $headers)) {
186         return [
187           // Send headers describing the image's size, and MIME-type.
188           'Content-Type' => $image->getMimeType(),
189           'Content-Length' => $image->getFileSize(),
190           // By not explicitly setting them here, this uses normal Drupal
191           // Expires, Cache-Control and ETag headers to prevent proxy or
192           // browser caching of private images.
193         ];
194       }
195     }
196     return -1;
197   }
198 }
199
200 /**
201  * Implements hook_file_move().
202  */
203 function image_file_move(File $file, File $source) {
204   // Delete any image derivatives at the original image path.
205   image_path_flush($source->getFileUri());
206 }
207
208 /**
209  * Implements hook_ENTITY_TYPE_predelete() for file entities.
210  */
211 function image_file_predelete(File $file) {
212   // Delete any image derivatives of this image.
213   image_path_flush($file->getFileUri());
214 }
215
216 /**
217  * Clears cached versions of a specific file in all styles.
218  *
219  * @param $path
220  *   The Drupal file path to the original image.
221  */
222 function image_path_flush($path) {
223   $styles = ImageStyle::loadMultiple();
224   foreach ($styles as $style) {
225     $style->flush($path);
226   }
227 }
228
229 /**
230  * Gets an array of image styles suitable for using as select list options.
231  *
232  * @param $include_empty
233  *   If TRUE a '- None -' option will be inserted in the options array.
234  * @return
235  *   Array of image styles both key and value are set to style name.
236  */
237 function image_style_options($include_empty = TRUE) {
238   $styles = ImageStyle::loadMultiple();
239   $options = [];
240   if ($include_empty && !empty($styles)) {
241     $options[''] = t('- None -');
242   }
243   foreach ($styles as $name => $style) {
244     $options[$name] = $style->label();
245   }
246
247   if (empty($options)) {
248     $options[''] = t('No defined styles');
249   }
250   return $options;
251 }
252
253 /**
254  * Prepares variables for image style templates.
255  *
256  * Default template: image-style.html.twig.
257  *
258  * @param array $variables
259  *   An associative array containing:
260  *   - width: The width of the image.
261  *   - height: The height of the image.
262  *   - style_name: The name of the image style to be applied.
263  *   - attributes: Additional attributes to apply to the image.
264  *   - uri: URI of the source image before styling.
265  *   - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
266  *     always require an alt attribute. The HTML 5 draft allows the alt
267  *     attribute to be omitted in some cases. Therefore, this variable defaults
268  *     to an empty string, but can be set to NULL for the attribute to be
269  *     omitted. Usually, neither omission nor an empty string satisfies
270  *     accessibility requirements, so it is strongly encouraged for code using
271  *     '#theme' => 'image_style' to pass a meaningful value for this variable.
272  *     - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
273  *     - http://www.w3.org/TR/xhtml1/dtds.html
274  *     - http://dev.w3.org/html5/spec/Overview.html#alt
275  *   - title: The title text is displayed when the image is hovered in some
276  *     popular browsers.
277  *   - attributes: Associative array of attributes to be placed in the img tag.
278  */
279 function template_preprocess_image_style(&$variables) {
280   $style = ImageStyle::load($variables['style_name']);
281
282   // Determine the dimensions of the styled image.
283   $dimensions = [
284     'width' => $variables['width'],
285     'height' => $variables['height'],
286   ];
287
288   $style->transformDimensions($dimensions, $variables['uri']);
289
290   $variables['image'] = [
291     '#theme' => 'image',
292     '#width' => $dimensions['width'],
293     '#height' => $dimensions['height'],
294     '#attributes' => $variables['attributes'],
295     '#uri' => $style->buildUrl($variables['uri']),
296     '#style_name' => $variables['style_name'],
297   ];
298
299   if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
300     $variables['image']['#alt'] = $variables['alt'];
301   }
302   if (isset($variables['title']) || array_key_exists('title', $variables)) {
303     $variables['image']['#title'] = $variables['title'];
304   }
305
306 }
307
308 /**
309  * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
310  *
311  * @param $value
312  * @param $current_pixels
313  * @param $new_pixels
314  */
315 function image_filter_keyword($value, $current_pixels, $new_pixels) {
316   switch ($value) {
317     case 'top':
318     case 'left':
319       return 0;
320
321     case 'bottom':
322     case 'right':
323       return $current_pixels - $new_pixels;
324
325     case 'center':
326       return $current_pixels / 2 - $new_pixels / 2;
327   }
328   return $value;
329 }
330
331 /**
332  * Implements hook_entity_presave().
333  *
334  * Transforms default image of image field from array into single value at save.
335  */
336 function image_entity_presave(EntityInterface $entity) {
337   // Get the default image settings, return if not saving an image field storage
338   // or image field entity.
339   $default_image = [];
340   if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
341     $default_image = $entity->getSetting('default_image');
342   }
343   else {
344     return;
345   }
346
347   if ($entity->isSyncing()) {
348     return;
349   }
350
351   $uuid = $default_image['uuid'];
352   if ($uuid) {
353     $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
354     if ($uuid != $original_uuid) {
355       $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
356       if ($file) {
357         $image = \Drupal::service('image.factory')->get($file->getFileUri());
358         $default_image['width'] = $image->getWidth();
359         $default_image['height'] = $image->getHeight();
360       }
361       else {
362         $default_image['uuid'] = NULL;
363       }
364     }
365   }
366   // Both FieldStorageConfigInterface and FieldConfigInterface have a
367   // setSetting() method.
368   $entity->setSetting('default_image', $default_image);
369 }
370
371 /**
372  * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
373  */
374 function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
375   if ($field_storage->getType() != 'image') {
376     // Only act on image fields.
377     return;
378   }
379
380   $prior_field_storage = $field_storage->original;
381
382   // The value of a managed_file element can be an array if #extended == TRUE.
383   $uuid_new = $field_storage->getSetting('default_image')['uuid'];
384   $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];
385
386   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
387
388   if ($uuid_new != $uuid_old) {
389
390     // Is there a new file?
391     if ($file_new) {
392       $file_new->status = FILE_STATUS_PERMANENT;
393       $file_new->save();
394       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
395     }
396
397     // Is there an old file?
398     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
399       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
400     }
401   }
402
403   // If the upload destination changed, then move the file.
404   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
405     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
406     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
407     file_move($file_new, $directory . $file_new->filename);
408   }
409 }
410
411 /**
412  * Implements hook_ENTITY_TYPE_update() for 'field_config'.
413  */
414 function image_field_config_update(FieldConfigInterface $field) {
415   $field_storage = $field->getFieldStorageDefinition();
416   if ($field_storage->getType() != 'image') {
417     // Only act on image fields.
418     return;
419   }
420
421   $prior_instance = $field->original;
422
423   $uuid_new = $field->getSetting('default_image')['uuid'];
424   $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
425
426   // If the old and new files do not match, update the default accordingly.
427   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
428   if ($uuid_new != $uuid_old) {
429     // Save the new file, if present.
430     if ($file_new) {
431       $file_new->status = FILE_STATUS_PERMANENT;
432       $file_new->save();
433       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
434     }
435     // Delete the old file, if present.
436     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
437       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
438     }
439   }
440
441   // If the upload destination changed, then move the file.
442   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
443     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
444     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
445     file_move($file_new, $directory . $file_new->filename);
446   }
447 }
448
449 /**
450  * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
451  */
452 function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
453   if ($field->getType() != 'image') {
454     // Only act on image fields.
455     return;
456   }
457
458   // The value of a managed_file element can be an array if #extended == TRUE.
459   $uuid = $field->getSetting('default_image')['uuid'];
460   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
461     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
462   }
463 }
464
465 /**
466  * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
467  */
468 function image_field_config_delete(FieldConfigInterface $field) {
469   $field_storage = $field->getFieldStorageDefinition();
470   if ($field_storage->getType() != 'image') {
471     // Only act on image fields.
472     return;
473   }
474
475   // The value of a managed_file element can be an array if #extended == TRUE.
476   $uuid = $field->getSetting('default_image')['uuid'];
477
478   // Remove the default image when the instance is deleted.
479   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
480     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
481   }
482 }