c1c216c0d198ae3434c8a755eeda8c8ad415b062
[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\FileInterface;
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_scale_and_crop_summary' => [
156       'variables' => ['data' => NULL, 'effect' => []],
157     ],
158     'image_rotate_summary' => [
159       'variables' => ['data' => NULL, 'effect' => []],
160     ],
161
162     // Theme functions in image.field.inc.
163     'image_widget' => [
164       'render element' => 'element',
165       'file' => 'image.field.inc',
166     ],
167     'image_formatter' => [
168       'variables' => ['item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL],
169       'file' => 'image.field.inc',
170     ],
171   ];
172 }
173
174 /**
175  * Implements hook_file_download().
176  *
177  * Control the access to files underneath the styles directory.
178  */
179 function image_file_download($uri) {
180   $path = file_uri_target($uri);
181
182   // Private file access for image style derivatives.
183   if (strpos($path, 'styles/') === 0) {
184     $args = explode('/', $path);
185
186     // Discard "styles", style name, and scheme from the path
187     $args = array_slice($args, 3);
188
189     // Then the remaining parts are the path to the image.
190     $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
191
192     // Check that the file exists and is an image.
193     $image = \Drupal::service('image.factory')->get($uri);
194     if ($image->isValid()) {
195       // Check the permissions of the original to grant access to this image.
196       $headers = \Drupal::moduleHandler()->invokeAll('file_download', [$original_uri]);
197       // Confirm there's at least one module granting access and none denying access.
198       if (!empty($headers) && !in_array(-1, $headers)) {
199         return [
200           // Send headers describing the image's size, and MIME-type.
201           'Content-Type' => $image->getMimeType(),
202           'Content-Length' => $image->getFileSize(),
203           // By not explicitly setting them here, this uses normal Drupal
204           // Expires, Cache-Control and ETag headers to prevent proxy or
205           // browser caching of private images.
206         ];
207       }
208     }
209     return -1;
210   }
211 }
212
213 /**
214  * Implements hook_file_move().
215  */
216 function image_file_move(FileInterface $file, FileInterface $source) {
217   // Delete any image derivatives at the original image path.
218   image_path_flush($source->getFileUri());
219 }
220
221 /**
222  * Implements hook_ENTITY_TYPE_predelete() for file entities.
223  */
224 function image_file_predelete(FileInterface $file) {
225   // Delete any image derivatives of this image.
226   image_path_flush($file->getFileUri());
227 }
228
229 /**
230  * Clears cached versions of a specific file in all styles.
231  *
232  * @param $path
233  *   The Drupal file path to the original image.
234  */
235 function image_path_flush($path) {
236   $styles = ImageStyle::loadMultiple();
237   foreach ($styles as $style) {
238     $style->flush($path);
239   }
240 }
241
242 /**
243  * Gets an array of image styles suitable for using as select list options.
244  *
245  * @param $include_empty
246  *   If TRUE a '- None -' option will be inserted in the options array.
247  * @return
248  *   Array of image styles both key and value are set to style name.
249  */
250 function image_style_options($include_empty = TRUE) {
251   $styles = ImageStyle::loadMultiple();
252   $options = [];
253   if ($include_empty && !empty($styles)) {
254     $options[''] = t('- None -');
255   }
256   foreach ($styles as $name => $style) {
257     $options[$name] = $style->label();
258   }
259
260   if (empty($options)) {
261     $options[''] = t('No defined styles');
262   }
263   return $options;
264 }
265
266 /**
267  * Prepares variables for image style templates.
268  *
269  * Default template: image-style.html.twig.
270  *
271  * @param array $variables
272  *   An associative array containing:
273  *   - width: The width of the image.
274  *   - height: The height of the image.
275  *   - style_name: The name of the image style to be applied.
276  *   - attributes: Additional attributes to apply to the image.
277  *   - uri: URI of the source image before styling.
278  *   - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
279  *     always require an alt attribute. The HTML 5 draft allows the alt
280  *     attribute to be omitted in some cases. Therefore, this variable defaults
281  *     to an empty string, but can be set to NULL for the attribute to be
282  *     omitted. Usually, neither omission nor an empty string satisfies
283  *     accessibility requirements, so it is strongly encouraged for code using
284  *     '#theme' => 'image_style' to pass a meaningful value for this variable.
285  *     - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
286  *     - http://www.w3.org/TR/xhtml1/dtds.html
287  *     - http://dev.w3.org/html5/spec/Overview.html#alt
288  *   - title: The title text is displayed when the image is hovered in some
289  *     popular browsers.
290  *   - attributes: Associative array of attributes to be placed in the img tag.
291  */
292 function template_preprocess_image_style(&$variables) {
293   $style = ImageStyle::load($variables['style_name']);
294
295   // Determine the dimensions of the styled image.
296   $dimensions = [
297     'width' => $variables['width'],
298     'height' => $variables['height'],
299   ];
300
301   $style->transformDimensions($dimensions, $variables['uri']);
302
303   $variables['image'] = [
304     '#theme' => 'image',
305     '#width' => $dimensions['width'],
306     '#height' => $dimensions['height'],
307     '#attributes' => $variables['attributes'],
308     '#style_name' => $variables['style_name'],
309   ];
310
311   // If the current image toolkit supports this file type, prepare the URI for
312   // the derivative image. If not, just use the original image resized to the
313   // dimensions specified by the style.
314   if ($style->supportsUri($variables['uri'])) {
315     $variables['image']['#uri'] = $style->buildUrl($variables['uri']);
316   }
317   else {
318     $variables['image']['#uri'] = $variables['uri'];
319     // Don't render the image by default, but allow other preprocess functions
320     // to override that if they need to.
321     $variables['image']['#access'] = FALSE;
322
323     // Inform the site builders why their image didn't work.
324     \Drupal::logger('image')->warning('Could not apply @style image style to @uri because the style does not support it.', [
325       '@style' => $style->label(),
326       '@uri' => $variables['uri'],
327     ]);
328   }
329
330   if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
331     $variables['image']['#alt'] = $variables['alt'];
332   }
333   if (isset($variables['title']) || array_key_exists('title', $variables)) {
334     $variables['image']['#title'] = $variables['title'];
335   }
336
337 }
338
339 /**
340  * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
341  *
342  * @param $value
343  * @param $current_pixels
344  * @param $new_pixels
345  */
346 function image_filter_keyword($value, $current_pixels, $new_pixels) {
347   switch ($value) {
348     case 'top':
349     case 'left':
350       return 0;
351
352     case 'bottom':
353     case 'right':
354       return $current_pixels - $new_pixels;
355
356     case 'center':
357       return $current_pixels / 2 - $new_pixels / 2;
358   }
359   return $value;
360 }
361
362 /**
363  * Implements hook_entity_presave().
364  *
365  * Transforms default image of image field from array into single value at save.
366  */
367 function image_entity_presave(EntityInterface $entity) {
368   // Get the default image settings, return if not saving an image field storage
369   // or image field entity.
370   $default_image = [];
371   if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
372     $default_image = $entity->getSetting('default_image');
373   }
374   else {
375     return;
376   }
377
378   if ($entity->isSyncing()) {
379     return;
380   }
381
382   $uuid = $default_image['uuid'];
383   if ($uuid) {
384     $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
385     if ($uuid != $original_uuid) {
386       $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
387       if ($file) {
388         $image = \Drupal::service('image.factory')->get($file->getFileUri());
389         $default_image['width'] = $image->getWidth();
390         $default_image['height'] = $image->getHeight();
391       }
392       else {
393         $default_image['uuid'] = NULL;
394       }
395     }
396   }
397   // Both FieldStorageConfigInterface and FieldConfigInterface have a
398   // setSetting() method.
399   $entity->setSetting('default_image', $default_image);
400 }
401
402 /**
403  * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
404  */
405 function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
406   if ($field_storage->getType() != 'image') {
407     // Only act on image fields.
408     return;
409   }
410
411   $prior_field_storage = $field_storage->original;
412
413   // The value of a managed_file element can be an array if #extended == TRUE.
414   $uuid_new = $field_storage->getSetting('default_image')['uuid'];
415   $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];
416
417   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
418
419   if ($uuid_new != $uuid_old) {
420
421     // Is there a new file?
422     if ($file_new) {
423       $file_new->status = FILE_STATUS_PERMANENT;
424       $file_new->save();
425       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
426     }
427
428     // Is there an old file?
429     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
430       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
431     }
432   }
433
434   // If the upload destination changed, then move the file.
435   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
436     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
437     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
438     file_move($file_new, $directory . $file_new->getFilename());
439   }
440 }
441
442 /**
443  * Implements hook_ENTITY_TYPE_update() for 'field_config'.
444  */
445 function image_field_config_update(FieldConfigInterface $field) {
446   $field_storage = $field->getFieldStorageDefinition();
447   if ($field_storage->getType() != 'image') {
448     // Only act on image fields.
449     return;
450   }
451
452   $prior_instance = $field->original;
453
454   $uuid_new = $field->getSetting('default_image')['uuid'];
455   $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
456
457   // If the old and new files do not match, update the default accordingly.
458   $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
459   if ($uuid_new != $uuid_old) {
460     // Save the new file, if present.
461     if ($file_new) {
462       $file_new->status = FILE_STATUS_PERMANENT;
463       $file_new->save();
464       \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
465     }
466     // Delete the old file, if present.
467     if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
468       \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
469     }
470   }
471
472   // If the upload destination changed, then move the file.
473   if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
474     $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
475     file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
476     file_move($file_new, $directory . $file_new->getFilename());
477   }
478 }
479
480 /**
481  * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
482  */
483 function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
484   if ($field->getType() != 'image') {
485     // Only act on image fields.
486     return;
487   }
488
489   // The value of a managed_file element can be an array if #extended == TRUE.
490   $uuid = $field->getSetting('default_image')['uuid'];
491   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
492     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
493   }
494 }
495
496 /**
497  * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
498  */
499 function image_field_config_delete(FieldConfigInterface $field) {
500   $field_storage = $field->getFieldStorageDefinition();
501   if ($field_storage->getType() != 'image') {
502     // Only act on image fields.
503     return;
504   }
505
506   // The value of a managed_file element can be an array if #extended == TRUE.
507   $uuid = $field->getSetting('default_image')['uuid'];
508
509   // Remove the default image when the instance is deleted.
510   if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
511     \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
512   }
513 }