e2fab5b9ccc2da5ca54918300a7a775d73368989
[yaffs-website] / web / modules / contrib / media_entity_image / src / Plugin / MediaEntity / Type / Image.php
1 <?php
2
3 namespace Drupal\media_entity_image\Plugin\MediaEntity\Type;
4
5 use Drupal\Core\Config\Config;
6 use Drupal\Core\Datetime\DrupalDateTime;
7 use Drupal\Core\Entity\EntityFieldManagerInterface;
8 use Drupal\Core\Entity\EntityTypeManagerInterface;
9 use Drupal\Core\Image\ImageFactory;
10 use Drupal\media_entity\MediaInterface;
11 use Drupal\media_entity\MediaTypeBase;
12 use Symfony\Component\DependencyInjection\ContainerInterface;
13 use Drupal\Core\Form\FormStateInterface;
14
15 /**
16  * Provides media type plugin for Image.
17  *
18  * @MediaType(
19  *   id = "image",
20  *   label = @Translation("Image"),
21  *   description = @Translation("Provides business logic and metadata for local images.")
22  * )
23  */
24 class Image extends MediaTypeBase {
25
26   /**
27    * The image factory service..
28    *
29    * @var \Drupal\Core\Image\ImageFactory
30    */
31   protected $imageFactory;
32
33   /**
34    * The exif data.
35    *
36    * @var array
37    */
38   protected $exif;
39
40   /**
41    * Constructs a new class instance.
42    *
43    * @param array $configuration
44    *   A configuration array containing information about the plugin instance.
45    * @param string $plugin_id
46    *   The plugin_id for the plugin instance.
47    * @param mixed $plugin_definition
48    *   The plugin implementation definition.
49    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
50    *   Entity type manager service.
51    * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
52    *   Entity field manager service.
53    * @param \Drupal\Core\Image\ImageFactory $image_factory
54    *   The image factory.
55    * @param \Drupal\Core\Config\Config $config
56    *   Media entity config object.
57    */
58   public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ImageFactory $image_factory, Config $config) {
59     parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $config);
60     $this->imageFactory = $image_factory;
61   }
62
63   /**
64    * {@inheritdoc}
65    */
66   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
67     return new static(
68       $configuration,
69       $plugin_id,
70       $plugin_definition,
71       $container->get('entity_type.manager'),
72       $container->get('entity_field.manager'),
73       $container->get('image.factory'),
74       $container->get('config.factory')->get('media_entity.settings')
75     );
76   }
77
78   /**
79    * {@inheritdoc}
80    */
81   public function providedFields() {
82     $fields = array(
83       'mime' => $this->t('File MIME'),
84       'width' => $this->t('Width'),
85       'height' => $this->t('Height'),
86     );
87
88     if (!empty($this->configuration['gather_exif'])) {
89       $fields += array(
90         'model' => $this->t('Camera model'),
91         'created' => $this->t('Image creation datetime'),
92         'iso' => $this->t('Iso'),
93         'exposure' => $this->t('Exposure time'),
94         'aperture' => $this->t('Aperture value'),
95         'focal_length' => $this->t('Focal length'),
96       );
97     }
98     return $fields;
99   }
100
101   /**
102    * {@inheritdoc}
103    */
104   public function getField(MediaInterface $media, $name) {
105     $source_field = $this->configuration['source_field'];
106
107     // Get the file, image and exif data.
108     /** @var \Drupal\file\FileInterface $file */
109     $file = $media->{$source_field}->entity;
110     $image = $this->imageFactory->get($file->getFileUri());
111     $uri = $file->getFileUri();
112
113     // Return the field.
114     switch ($name) {
115       case 'mime':
116         return !$file->filemime->isEmpty() ? $file->getMimeType() : FALSE;
117
118       case 'width':
119         $width = $image->getWidth();
120         return $width ? $width : FALSE;
121
122       case 'height':
123         $height = $image->getHeight();
124         return $height ? $height : FALSE;
125
126       case 'size':
127         $size = $file->getSize();
128         return $size ? $size : FALSE;
129     }
130
131     if (!empty($this->configuration['gather_exif']) && function_exists('exif_read_data')) {
132       switch ($name) {
133         case 'model':
134           return $this->getExifField($uri, 'Model');
135
136         case 'created':
137           $date = new DrupalDateTime($this->getExifField($uri, 'DateTimeOriginal'));
138           return $date->getTimestamp();
139
140         case 'iso':
141           return $this->getExifField($uri, 'ISOSpeedRatings');
142
143         case 'exposure':
144           return $this->getExifField($uri, 'ExposureTime');
145
146         case 'aperture':
147           return $this->getExifField($uri, 'FNumber');
148
149         case 'focal_length':
150           return $this->getExifField($uri, 'FocalLength');
151       }
152     }
153
154     return FALSE;
155   }
156
157   /**
158    * {@inheritdoc}
159    */
160   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
161     /** @var \Drupal\media_entity\MediaBundleInterface $bundle */
162     $bundle = $form_state->getFormObject()->getEntity();
163     $options = [];
164     $allowed_field_types = ['file', 'image'];
165     foreach ($this->entityFieldManager->getFieldDefinitions('media', $bundle->id()) as $field_name => $field) {
166       if (in_array($field->getType(), $allowed_field_types) && !$field->getFieldStorageDefinition()->isBaseField()) {
167         $options[$field_name] = $field->getLabel();
168       }
169     }
170
171     $form['source_field'] = [
172       '#type' => 'select',
173       '#title' => $this->t('Field with source information'),
174       '#description' => $this->t('Field on media entity that stores Image file. You can create a bundle without selecting a value for this dropdown initially. This dropdown can be populated after adding fields to the bundle.'),
175       '#default_value' => empty($this->configuration['source_field']) ? NULL : $this->configuration['source_field'],
176       '#options' => $options,
177     ];
178
179     $form['gather_exif'] = [
180       '#type' => 'select',
181       '#title' => $this->t('Whether to gather exif data.'),
182       '#description' => $this->t('Gather exif data using exif_read_data().'),
183       '#default_value' => empty($this->configuration['gather_exif']) || !function_exists('exif_read_data') ? 0 : $this->configuration['gather_exif'],
184       '#options' => [
185         0 => $this->t('No'),
186         1 => $this->t('Yes'),
187       ],
188       '#ajax' => [
189         'callback' => '::ajaxTypeProviderData',
190       ],
191       '#disabled' => (function_exists('exif_read_data')) ? FALSE : TRUE,
192     ];
193
194     return $form;
195   }
196
197   /**
198    * {@inheritdoc}
199    */
200   public function getDefaultThumbnail() {
201     return $this->config->get('icon_base') . '/image.png';
202   }
203
204   /**
205    * {@inheritdoc}
206    */
207   public function thumbnail(MediaInterface $media) {
208     $source_field = $this->configuration['source_field'];
209
210     /** @var \Drupal\file\FileInterface $file */
211     if ($file = $media->{$source_field}->entity) {
212       return $file->getFileUri();
213     }
214
215     return $this->getDefaultThumbnail();
216   }
217
218   /**
219    * Get exif field value.
220    *
221    * @param string $uri
222    *   The uri for the file that we are getting the Exif.
223    * @param string $field
224    *   The name of the exif field.
225    *
226    * @return string|bool
227    *   The value for the requested field or FALSE if is not set.
228    */
229   protected function getExifField($uri, $field) {
230     if (empty($this->exif)) {
231       $this->exif = $this->getExif($uri);
232     }
233     return !empty($this->exif[$field]) ? $this->exif[$field] : FALSE;
234   }
235
236   /**
237    * Read EXIF.
238    *
239    * @param string $uri
240    *   The uri for the file that we are getting the Exif.
241    *
242    * @return array|bool
243    *   An associative array where the array indexes are the header names and
244    *   the array values are the values associated with those headers or FALSE
245    *   if the data can't be read.
246    */
247   protected function getExif($uri) {
248     return exif_read_data($uri, 'EXIF');
249   }
250
251   /**
252    * {@inheritdoc}
253    */
254   public function getDefaultName(MediaInterface $media) {
255     // The default name will be the filename of the source_field, if present,
256     // or the parent's defaultName implementation if it was not possible to
257     // retrieve the filename.
258     $source_field = $this->configuration['source_field'];
259
260     /** @var \Drupal\file\FileInterface $file */
261     if (!empty($source_field) && ($file = $media->{$source_field}->entity)) {
262       return $file->getFilename();
263     }
264
265     return parent::getDefaultName($media);
266   }
267
268 }