ExifProvider.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright 2022 Carl Schwan <carl@carlschwan.eu>
  5. * @copyright Copyright 2022 Louis Chmn <louis@chmn.me>
  6. * @license AGPL-3.0-or-later
  7. *
  8. * This code is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License, version 3,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License, version 3,
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>
  19. *
  20. */
  21. namespace OC\Metadata\Provider;
  22. use OC\Metadata\FileMetadata;
  23. use OC\Metadata\IMetadataProvider;
  24. use OCP\Files\File;
  25. use Psr\Log\LoggerInterface;
  26. class ExifProvider implements IMetadataProvider {
  27. private LoggerInterface $logger;
  28. public function __construct(
  29. LoggerInterface $logger
  30. ) {
  31. $this->logger = $logger;
  32. }
  33. public static function groupsProvided(): array {
  34. return ['size', 'gps'];
  35. }
  36. public static function isAvailable(): bool {
  37. return extension_loaded('exif');
  38. }
  39. /** @return array{'gps'?: FileMetadata, 'size'?: FileMetadata} */
  40. public function execute(File $file): array {
  41. $exifData = [];
  42. $fileDescriptor = $file->fopen('rb');
  43. if ($fileDescriptor === false) {
  44. return [];
  45. }
  46. $data = null;
  47. try {
  48. // Needed to make reading exif data reliable.
  49. // This is to trigger this condition: https://github.com/php/php-src/blob/d64aa6f646a7b5e58359dc79479860164239580a/main/streams/streams.c#L710
  50. // But I don't understand why 1 as a special meaning.
  51. // Revert right after reading the exif data.
  52. $oldBufferSize = stream_set_chunk_size($fileDescriptor, 1);
  53. $data = @exif_read_data($fileDescriptor, 'ANY_TAG', true);
  54. stream_set_chunk_size($fileDescriptor, $oldBufferSize);
  55. } catch (\Exception $ex) {
  56. $this->logger->info("Couldn't extract metadata for ".$file->getId(), ['exception' => $ex]);
  57. }
  58. $size = new FileMetadata();
  59. $size->setGroupName('size');
  60. $size->setId($file->getId());
  61. $size->setArrayAsValue([]);
  62. if (!$data) {
  63. $sizeResult = getimagesizefromstring($file->getContent());
  64. if ($sizeResult !== false) {
  65. $size->setArrayAsValue([
  66. 'width' => $sizeResult[0],
  67. 'height' => $sizeResult[1],
  68. ]);
  69. $exifData['size'] = $size;
  70. }
  71. } elseif (array_key_exists('COMPUTED', $data)) {
  72. if (array_key_exists('Width', $data['COMPUTED']) && array_key_exists('Height', $data['COMPUTED'])) {
  73. $size->setArrayAsValue([
  74. 'width' => $data['COMPUTED']['Width'],
  75. 'height' => $data['COMPUTED']['Height'],
  76. ]);
  77. $exifData['size'] = $size;
  78. }
  79. }
  80. if ($data && array_key_exists('GPS', $data)
  81. && array_key_exists('GPSLatitude', $data['GPS']) && array_key_exists('GPSLatitudeRef', $data['GPS'])
  82. && array_key_exists('GPSLongitude', $data['GPS']) && array_key_exists('GPSLongitudeRef', $data['GPS'])
  83. ) {
  84. $gps = new FileMetadata();
  85. $gps->setGroupName('gps');
  86. $gps->setId($file->getId());
  87. $gps->setArrayAsValue([
  88. 'latitude' => $this->gpsDegreesToDecimal($data['GPS']['GPSLatitude'], $data['GPS']['GPSLatitudeRef']),
  89. 'longitude' => $this->gpsDegreesToDecimal($data['GPS']['GPSLongitude'], $data['GPS']['GPSLongitudeRef']),
  90. ]);
  91. $exifData['gps'] = $gps;
  92. }
  93. return $exifData;
  94. }
  95. public static function getMimetypesSupported(): string {
  96. return '/image\/(png|jpeg|heif|webp|tiff)/';
  97. }
  98. /**
  99. * @param array|string $coordinates
  100. */
  101. private static function gpsDegreesToDecimal($coordinates, ?string $hemisphere): float {
  102. if (is_string($coordinates)) {
  103. $coordinates = array_map("trim", explode(",", $coordinates));
  104. }
  105. if (count($coordinates) !== 3) {
  106. throw new \Exception('Invalid coordinate format: ' . json_encode($coordinates));
  107. }
  108. [$degrees, $minutes, $seconds] = array_map(function (string $rawDegree) {
  109. $parts = explode('/', $rawDegree);
  110. if ($parts[1] === '0') {
  111. return 0;
  112. }
  113. return floatval($parts[0]) / floatval($parts[1] ?? 1);
  114. }, $coordinates);
  115. $sign = ($hemisphere === 'W' || $hemisphere === 'S') ? -1 : 1;
  116. return $sign * ($degrees + $minutes / 60 + $seconds / 3600);
  117. }
  118. }