818c5b5cf0ef13d28026ecb01243729e8c829841
[yaffs-website] / web / core / modules / system / src / Plugin / ImageToolkit / GDToolkit.php
1 <?php
2
3 namespace Drupal\system\Plugin\ImageToolkit;
4
5 use Drupal\Component\Utility\Color;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Config\ConfigFactoryInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\ImageToolkit\ImageToolkitBase;
10 use Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface;
11 use Drupal\Core\StreamWrapper\StreamWrapperInterface;
12 use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
13 use Psr\Log\LoggerInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15
16 /**
17  * Defines the GD2 toolkit for image manipulation within Drupal.
18  *
19  * @ImageToolkit(
20  *   id = "gd",
21  *   title = @Translation("GD2 image manipulation toolkit")
22  * )
23  */
24 class GDToolkit extends ImageToolkitBase {
25
26   /**
27    * A GD image resource.
28    *
29    * @var resource|null
30    */
31   protected $resource = NULL;
32
33   /**
34    * Image type represented by a PHP IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG).
35    *
36    * @var int
37    */
38   protected $type;
39
40   /**
41    * Image information from a file, available prior to loading the GD resource.
42    *
43    * This contains a copy of the array returned by executing getimagesize()
44    * on the image file when the image object is instantiated. It gets reset
45    * to NULL as soon as the GD resource is loaded.
46    *
47    * @var array|null
48    *
49    * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::parseFile()
50    * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::setResource()
51    * @see http://php.net/manual/function.getimagesize.php
52    */
53   protected $preLoadInfo = NULL;
54
55   /**
56    * The StreamWrapper manager.
57    *
58    * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
59    */
60   protected $streamWrapperManager;
61
62   /**
63    * Constructs a GDToolkit object.
64    *
65    * @param array $configuration
66    *   A configuration array containing information about the plugin instance.
67    * @param string $plugin_id
68    *   The plugin_id for the plugin instance.
69    * @param array $plugin_definition
70    *   The plugin implementation definition.
71    * @param \Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface $operation_manager
72    *   The toolkit operation manager.
73    * @param \Psr\Log\LoggerInterface $logger
74    *   A logger instance.
75    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
76    *   The config factory.
77    * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
78    *   The StreamWrapper manager.
79    */
80   public function __construct(array $configuration, $plugin_id, array $plugin_definition, ImageToolkitOperationManagerInterface $operation_manager, LoggerInterface $logger, ConfigFactoryInterface $config_factory, StreamWrapperManagerInterface $stream_wrapper_manager) {
81     parent::__construct($configuration, $plugin_id, $plugin_definition, $operation_manager, $logger, $config_factory);
82     $this->streamWrapperManager = $stream_wrapper_manager;
83   }
84
85   /**
86    * Destructs a GDToolkit object.
87    *
88    * Frees memory associated with a GD image resource.
89    */
90   public function __destruct() {
91     if (is_resource($this->resource)) {
92       imagedestroy($this->resource);
93     }
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
100     return new static(
101       $configuration,
102       $plugin_id,
103       $plugin_definition,
104       $container->get('image.toolkit.operation.manager'),
105       $container->get('logger.channel.image'),
106       $container->get('config.factory'),
107       $container->get('stream_wrapper_manager')
108     );
109   }
110
111   /**
112    * Sets the GD image resource.
113    *
114    * @param resource $resource
115    *   The GD image resource.
116    *
117    * @return \Drupal\system\Plugin\ImageToolkit\GDToolkit
118    *   An instance of the current toolkit object.
119    */
120   public function setResource($resource) {
121     if (!is_resource($resource) || get_resource_type($resource) != 'gd') {
122       throw new \InvalidArgumentException('Invalid resource argument');
123     }
124     $this->preLoadInfo = NULL;
125     $this->resource = $resource;
126     return $this;
127   }
128
129   /**
130    * Retrieves the GD image resource.
131    *
132    * @return resource|null
133    *   The GD image resource, or NULL if not available.
134    */
135   public function getResource() {
136     if (!is_resource($this->resource)) {
137       $this->load();
138     }
139     return $this->resource;
140   }
141
142   /**
143    * {@inheritdoc}
144    */
145   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
146     $form['image_jpeg_quality'] = [
147       '#type' => 'number',
148       '#title' => t('JPEG quality'),
149       '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'),
150       '#min' => 0,
151       '#max' => 100,
152       '#default_value' => $this->configFactory->getEditable('system.image.gd')->get('jpeg_quality', FALSE),
153       '#field_suffix' => t('%'),
154     ];
155     return $form;
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
162     $this->configFactory->getEditable('system.image.gd')
163       ->set('jpeg_quality', $form_state->getValue(['gd', 'image_jpeg_quality']))
164       ->save();
165   }
166
167   /**
168    * Loads a GD resource from a file.
169    *
170    * @return bool
171    *   TRUE or FALSE, based on success.
172    */
173   protected function load() {
174     // Return immediately if the image file is not valid.
175     if (!$this->isValid()) {
176       return FALSE;
177     }
178
179     $function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);
180     if (function_exists($function) && $resource = $function($this->getSource())) {
181       $this->setResource($resource);
182       if (imageistruecolor($resource)) {
183         return TRUE;
184       }
185       else {
186         // Convert indexed images to truecolor, copying the image to a new
187         // truecolor resource, so that filters work correctly and don't result
188         // in unnecessary dither.
189         $data = [
190           'width' => imagesx($resource),
191           'height' => imagesy($resource),
192           'extension' => image_type_to_extension($this->getType(), FALSE),
193           'transparent_color' => $this->getTransparentColor(),
194           'is_temp' => TRUE,
195         ];
196         if ($this->apply('create_new', $data)) {
197           imagecopy($this->getResource(), $resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
198           imagedestroy($resource);
199         }
200       }
201       return (bool) $this->getResource();
202     }
203     return FALSE;
204   }
205
206   /**
207    * {@inheritdoc}
208    */
209   public function isValid() {
210     return ((bool) $this->preLoadInfo || (bool) $this->resource);
211   }
212
213   /**
214    * {@inheritdoc}
215    */
216   public function save($destination) {
217     $scheme = file_uri_scheme($destination);
218     // Work around lack of stream wrapper support in imagejpeg() and imagepng().
219     if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
220       // If destination is not local, save image to temporary local file.
221       $local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
222       if (!isset($local_wrappers[$scheme])) {
223         $permanent_destination = $destination;
224         $destination = drupal_tempnam('temporary://', 'gd_');
225       }
226       // Convert stream wrapper URI to normal path.
227       $destination = drupal_realpath($destination);
228     }
229
230     $function = 'image' . image_type_to_extension($this->getType(), FALSE);
231     if (!function_exists($function)) {
232       return FALSE;
233     }
234     if ($this->getType() == IMAGETYPE_JPEG) {
235       $success = $function($this->getResource(), $destination, $this->configFactory->get('system.image.gd')->get('jpeg_quality'));
236     }
237     else {
238       // Always save PNG images with full transparency.
239       if ($this->getType() == IMAGETYPE_PNG) {
240         imagealphablending($this->getResource(), FALSE);
241         imagesavealpha($this->getResource(), TRUE);
242       }
243       $success = $function($this->getResource(), $destination);
244     }
245     // Move temporary local file to remote destination.
246     if (isset($permanent_destination) && $success) {
247       return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
248     }
249     return $success;
250   }
251
252   /**
253    * {@inheritdoc}
254    */
255   public function parseFile() {
256     $data = @getimagesize($this->getSource());
257     if ($data && in_array($data[2], static::supportedTypes())) {
258       $this->setType($data[2]);
259       $this->preLoadInfo = $data;
260       return TRUE;
261     }
262     return FALSE;
263   }
264
265   /**
266    * Gets the color set for transparency in GIF images.
267    *
268    * @return string|null
269    *   A color string like '#rrggbb', or NULL if not set or not relevant.
270    */
271   public function getTransparentColor() {
272     if (!$this->getResource() || $this->getType() != IMAGETYPE_GIF) {
273       return NULL;
274     }
275     // Find out if a transparent color is set, will return -1 if no
276     // transparent color has been defined in the image.
277     $transparent = imagecolortransparent($this->getResource());
278     if ($transparent >= 0) {
279       // Find out the number of colors in the image palette. It will be 0 for
280       // truecolor images.
281       $palette_size = imagecolorstotal($this->getResource());
282       if ($palette_size == 0 || $transparent < $palette_size) {
283         // Return the transparent color, either if it is a truecolor image
284         // or if the transparent color is part of the palette.
285         // Since the index of the transparent color is a property of the
286         // image rather than of the palette, it is possible that an image
287         // could be created with this index set outside the palette size.
288         // (see http://stackoverflow.com/a/3898007).
289         $rgb = imagecolorsforindex($this->getResource(), $transparent);
290         unset($rgb['alpha']);
291         return Color::rgbToHex($rgb);
292       }
293     }
294     return NULL;
295   }
296
297   /**
298    * {@inheritdoc}
299    */
300   public function getWidth() {
301     if ($this->preLoadInfo) {
302       return $this->preLoadInfo[0];
303     }
304     elseif ($res = $this->getResource()) {
305       return imagesx($res);
306     }
307     else {
308       return NULL;
309     }
310   }
311
312   /**
313    * {@inheritdoc}
314    */
315   public function getHeight() {
316     if ($this->preLoadInfo) {
317       return $this->preLoadInfo[1];
318     }
319     elseif ($res = $this->getResource()) {
320       return imagesy($res);
321     }
322     else {
323       return NULL;
324     }
325   }
326
327   /**
328    * Gets the PHP type of the image.
329    *
330    * @return int
331    *   The image type represented by a PHP IMAGETYPE_* constant (e.g.
332    *   IMAGETYPE_JPEG).
333    */
334   public function getType() {
335     return $this->type;
336   }
337
338   /**
339    * Sets the PHP type of the image.
340    *
341    * @param int $type
342    *   The image type represented by a PHP IMAGETYPE_* constant (e.g.
343    *   IMAGETYPE_JPEG).
344    *
345    * @return $this
346    */
347   public function setType($type) {
348     if (in_array($type, static::supportedTypes())) {
349       $this->type = $type;
350     }
351     return $this;
352   }
353
354   /**
355    * {@inheritdoc}
356    */
357   public function getMimeType() {
358     return $this->getType() ? image_type_to_mime_type($this->getType()) : '';
359   }
360
361   /**
362    * {@inheritdoc}
363    */
364   public function getRequirements() {
365     $requirements = [];
366
367     $info = gd_info();
368     $requirements['version'] = [
369       'title' => t('GD library'),
370       'value' => $info['GD Version'],
371     ];
372
373     // Check for filter and rotate support.
374     if (!function_exists('imagefilter') || !function_exists('imagerotate')) {
375       $requirements['version']['severity'] = REQUIREMENT_WARNING;
376       $requirements['version']['description'] = t('The GD Library for PHP is enabled, but was compiled without support for functions used by the rotate and desaturate effects. It was probably compiled using the official GD libraries from http://www.libgd.org instead of the GD library bundled with PHP. You should recompile PHP --with-gd using the bundled GD library. See <a href="http://php.net/manual/book.image.php">the PHP manual</a>.');
377     }
378
379     return $requirements;
380   }
381
382   /**
383    * {@inheritdoc}
384    */
385   public static function isAvailable() {
386     // GD2 support is available.
387     return function_exists('imagegd2');
388   }
389
390   /**
391    * {@inheritdoc}
392    */
393   public static function getSupportedExtensions() {
394     $extensions = [];
395     foreach (static::supportedTypes() as $image_type) {
396       // @todo Automatically fetch possible extensions for each mime type.
397       // @see https://www.drupal.org/node/2311679
398       $extension = Unicode::strtolower(image_type_to_extension($image_type, FALSE));
399       $extensions[] = $extension;
400       // Add some known similar extensions.
401       if ($extension === 'jpeg') {
402         $extensions[] = 'jpg';
403         $extensions[] = 'jpe';
404       }
405     }
406     return $extensions;
407   }
408
409   /**
410    * Returns the IMAGETYPE_xxx constant for the given extension.
411    *
412    * This is the reverse of the image_type_to_extension() function.
413    *
414    * @param string $extension
415    *   The extension to get the IMAGETYPE_xxx constant for.
416    *
417    * @return int
418    *   The IMAGETYPE_xxx constant for the given extension, or IMAGETYPE_UNKNOWN
419    *   for unsupported extensions.
420    *
421    * @see image_type_to_extension()
422    */
423   public function extensionToImageType($extension) {
424     if (in_array($extension, ['jpe', 'jpg'])) {
425       $extension = 'jpeg';
426     }
427     foreach ($this->supportedTypes() as $type) {
428       if (image_type_to_extension($type, FALSE) === $extension) {
429         return $type;
430       }
431     }
432     return IMAGETYPE_UNKNOWN;
433   }
434
435   /**
436    * Returns a list of image types supported by the toolkit.
437    *
438    * @return array
439    *   An array of available image types. An image type is represented by a PHP
440    *   IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG, IMAGETYPE_PNG, etc.).
441    */
442   protected static function supportedTypes() {
443     return [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF];
444   }
445
446 }