1
0

PhotoCache.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\DAV\CardDAV;
  7. use OCP\Files\IAppData;
  8. use OCP\Files\NotFoundException;
  9. use OCP\Files\NotPermittedException;
  10. use OCP\Files\SimpleFS\ISimpleFile;
  11. use OCP\Files\SimpleFS\ISimpleFolder;
  12. use Psr\Log\LoggerInterface;
  13. use Sabre\CardDAV\Card;
  14. use Sabre\VObject\Document;
  15. use Sabre\VObject\Parameter;
  16. use Sabre\VObject\Property\Binary;
  17. use Sabre\VObject\Reader;
  18. class PhotoCache {
  19. /** @var array */
  20. public const ALLOWED_CONTENT_TYPES = [
  21. 'image/png' => 'png',
  22. 'image/jpeg' => 'jpg',
  23. 'image/gif' => 'gif',
  24. 'image/vnd.microsoft.icon' => 'ico',
  25. ];
  26. protected IAppData $appData;
  27. protected LoggerInterface $logger;
  28. /**
  29. * PhotoCache constructor.
  30. */
  31. public function __construct(IAppData $appData, LoggerInterface $logger) {
  32. $this->appData = $appData;
  33. $this->logger = $logger;
  34. }
  35. /**
  36. * @throws NotFoundException
  37. */
  38. public function get(int $addressBookId, string $cardUri, int $size, Card $card): ISimpleFile {
  39. $folder = $this->getFolder($addressBookId, $cardUri);
  40. if ($this->isEmpty($folder)) {
  41. $this->init($folder, $card);
  42. }
  43. if (!$this->hasPhoto($folder)) {
  44. throw new NotFoundException();
  45. }
  46. if ($size !== -1) {
  47. $size = 2 ** ceil(log($size) / log(2));
  48. }
  49. return $this->getFile($folder, $size);
  50. }
  51. private function isEmpty(ISimpleFolder $folder): bool {
  52. return $folder->getDirectoryListing() === [];
  53. }
  54. /**
  55. * @throws NotPermittedException
  56. */
  57. private function init(ISimpleFolder $folder, Card $card): void {
  58. $data = $this->getPhoto($card);
  59. if ($data === false || !isset($data['Content-Type'])) {
  60. $folder->newFile('nophoto', '');
  61. return;
  62. }
  63. $contentType = $data['Content-Type'];
  64. $extension = self::ALLOWED_CONTENT_TYPES[$contentType] ?? null;
  65. if ($extension === null) {
  66. $folder->newFile('nophoto', '');
  67. return;
  68. }
  69. $file = $folder->newFile('photo.' . $extension);
  70. $file->putContent($data['body']);
  71. }
  72. private function hasPhoto(ISimpleFolder $folder): bool {
  73. return !$folder->fileExists('nophoto');
  74. }
  75. /**
  76. * @param float|-1 $size
  77. */
  78. private function getFile(ISimpleFolder $folder, $size): ISimpleFile {
  79. $ext = $this->getExtension($folder);
  80. if ($size === -1) {
  81. $path = 'photo.' . $ext;
  82. } else {
  83. $path = 'photo.' . $size . '.' . $ext;
  84. }
  85. try {
  86. $file = $folder->getFile($path);
  87. } catch (NotFoundException $e) {
  88. if ($size <= 0) {
  89. throw new NotFoundException;
  90. }
  91. $photo = new \OCP\Image();
  92. /** @var ISimpleFile $file */
  93. $file = $folder->getFile('photo.' . $ext);
  94. $photo->loadFromData($file->getContent());
  95. $ratio = $photo->width() / $photo->height();
  96. if ($ratio < 1) {
  97. $ratio = 1 / $ratio;
  98. }
  99. $size = (int)($size * $ratio);
  100. if ($size !== -1) {
  101. $photo->resize($size);
  102. }
  103. try {
  104. $file = $folder->newFile($path);
  105. $file->putContent($photo->data());
  106. } catch (NotPermittedException $e) {
  107. }
  108. }
  109. return $file;
  110. }
  111. /**
  112. * @throws NotFoundException
  113. * @throws NotPermittedException
  114. */
  115. private function getFolder(int $addressBookId, string $cardUri, bool $createIfNotExists = true): ISimpleFolder {
  116. $hash = md5($addressBookId . ' ' . $cardUri);
  117. try {
  118. return $this->appData->getFolder($hash);
  119. } catch (NotFoundException $e) {
  120. if ($createIfNotExists) {
  121. return $this->appData->newFolder($hash);
  122. } else {
  123. throw $e;
  124. }
  125. }
  126. }
  127. /**
  128. * Get the extension of the avatar. If there is no avatar throw Exception
  129. *
  130. * @throws NotFoundException
  131. */
  132. private function getExtension(ISimpleFolder $folder): string {
  133. foreach (self::ALLOWED_CONTENT_TYPES as $extension) {
  134. if ($folder->fileExists('photo.' . $extension)) {
  135. return $extension;
  136. }
  137. }
  138. throw new NotFoundException('Avatar not found');
  139. }
  140. /**
  141. * @param Card $node
  142. * @return false|array{body: string, Content-Type: string}
  143. */
  144. private function getPhoto(Card $node) {
  145. try {
  146. $vObject = $this->readCard($node->get());
  147. return $this->getPhotoFromVObject($vObject);
  148. } catch (\Exception $e) {
  149. $this->logger->error('Exception during vcard photo parsing', [
  150. 'exception' => $e
  151. ]);
  152. }
  153. return false;
  154. }
  155. /**
  156. * @return false|array{body: string, Content-Type: string}
  157. */
  158. public function getPhotoFromVObject(Document $vObject) {
  159. try {
  160. if (!$vObject->PHOTO) {
  161. return false;
  162. }
  163. $photo = $vObject->PHOTO;
  164. $val = $photo->getValue();
  165. // handle data URI. e.g PHOTO;VALUE=URI:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQE
  166. if ($photo->getValueType() === 'URI') {
  167. $parsed = \Sabre\URI\parse($val);
  168. // only allow data://
  169. if ($parsed['scheme'] !== 'data') {
  170. return false;
  171. }
  172. if (substr_count($parsed['path'], ';') === 1) {
  173. [$type] = explode(';', $parsed['path']);
  174. }
  175. $val = file_get_contents($val);
  176. } else {
  177. // get type if binary data
  178. $type = $this->getBinaryType($photo);
  179. }
  180. if (empty($type) || !isset(self::ALLOWED_CONTENT_TYPES[$type])) {
  181. $type = 'application/octet-stream';
  182. }
  183. return [
  184. 'Content-Type' => $type,
  185. 'body' => $val
  186. ];
  187. } catch (\Exception $e) {
  188. $this->logger->error('Exception during vcard photo parsing', [
  189. 'exception' => $e
  190. ]);
  191. }
  192. return false;
  193. }
  194. private function readCard(string $cardData): Document {
  195. return Reader::read($cardData);
  196. }
  197. /**
  198. * @param Binary $photo
  199. * @return string
  200. */
  201. private function getBinaryType(Binary $photo) {
  202. $params = $photo->parameters();
  203. if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) {
  204. /** @var Parameter $typeParam */
  205. $typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE'];
  206. $type = (string)$typeParam->getValue();
  207. if (str_starts_with($type, 'image/')) {
  208. return $type;
  209. } else {
  210. return 'image/' . strtolower($type);
  211. }
  212. }
  213. return '';
  214. }
  215. /**
  216. * @param int $addressBookId
  217. * @param string $cardUri
  218. * @throws NotPermittedException
  219. */
  220. public function delete($addressBookId, $cardUri) {
  221. try {
  222. $folder = $this->getFolder($addressBookId, $cardUri, false);
  223. $folder->delete();
  224. } catch (NotFoundException $e) {
  225. // that's OK, nothing to do
  226. }
  227. }
  228. }