PageRenderTime 64ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/web/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php

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