1
0

PhotoCache.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Jacob Neplokh <me@jacobneplokh.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OCA\DAV\CardDAV;
  31. use OCP\Files\IAppData;
  32. use OCP\Files\NotFoundException;
  33. use OCP\Files\NotPermittedException;
  34. use OCP\Files\SimpleFS\ISimpleFile;
  35. use OCP\Files\SimpleFS\ISimpleFolder;
  36. use Sabre\CardDAV\Card;
  37. use Sabre\VObject\Document;
  38. use Sabre\VObject\Parameter;
  39. use Sabre\VObject\Property\Binary;
  40. use Sabre\VObject\Reader;
  41. use Psr\Log\LoggerInterface;
  42. class PhotoCache {
  43. /** @var array */
  44. public const ALLOWED_CONTENT_TYPES = [
  45. 'image/png' => 'png',
  46. 'image/jpeg' => 'jpg',
  47. 'image/gif' => 'gif',
  48. 'image/vnd.microsoft.icon' => 'ico',
  49. ];
  50. protected IAppData $appData;
  51. protected LoggerInterface $logger;
  52. /**
  53. * PhotoCache constructor.
  54. */
  55. public function __construct(IAppData $appData, LoggerInterface $logger) {
  56. $this->appData = $appData;
  57. $this->logger = $logger;
  58. }
  59. /**
  60. * @throws NotFoundException
  61. */
  62. public function get(int $addressBookId, string $cardUri, int $size, Card $card): ISimpleFile {
  63. $folder = $this->getFolder($addressBookId, $cardUri);
  64. if ($this->isEmpty($folder)) {
  65. $this->init($folder, $card);
  66. }
  67. if (!$this->hasPhoto($folder)) {
  68. throw new NotFoundException();
  69. }
  70. if ($size !== -1) {
  71. $size = 2 ** ceil(log($size) / log(2));
  72. }
  73. return $this->getFile($folder, $size);
  74. }
  75. private function isEmpty(ISimpleFolder $folder): bool {
  76. return $folder->getDirectoryListing() === [];
  77. }
  78. /**
  79. * @throws NotPermittedException
  80. */
  81. private function init(ISimpleFolder $folder, Card $card): void {
  82. $data = $this->getPhoto($card);
  83. if ($data === false || !isset($data['Content-Type'])) {
  84. $folder->newFile('nophoto', '');
  85. return;
  86. }
  87. $contentType = $data['Content-Type'];
  88. $extension = self::ALLOWED_CONTENT_TYPES[$contentType] ?? null;
  89. if ($extension === null) {
  90. $folder->newFile('nophoto', '');
  91. return;
  92. }
  93. $file = $folder->newFile('photo.' . $extension);
  94. $file->putContent($data['body']);
  95. }
  96. private function hasPhoto(ISimpleFolder $folder): bool {
  97. return !$folder->fileExists('nophoto');
  98. }
  99. /**
  100. * @param float|-1 $size
  101. */
  102. private function getFile(ISimpleFolder $folder, $size): ISimpleFile {
  103. $ext = $this->getExtension($folder);
  104. if ($size === -1) {
  105. $path = 'photo.' . $ext;
  106. } else {
  107. $path = 'photo.' . $size . '.' . $ext;
  108. }
  109. try {
  110. $file = $folder->getFile($path);
  111. } catch (NotFoundException $e) {
  112. if ($size <= 0) {
  113. throw new NotFoundException;
  114. }
  115. $photo = new \OCP\Image();
  116. /** @var ISimpleFile $file */
  117. $file = $folder->getFile('photo.' . $ext);
  118. $photo->loadFromData($file->getContent());
  119. $ratio = $photo->width() / $photo->height();
  120. if ($ratio < 1) {
  121. $ratio = 1 / $ratio;
  122. }
  123. $size = (int) ($size * $ratio);
  124. if ($size !== -1) {
  125. $photo->resize($size);
  126. }
  127. try {
  128. $file = $folder->newFile($path);
  129. $file->putContent($photo->data());
  130. } catch (NotPermittedException $e) {
  131. }
  132. }
  133. return $file;
  134. }
  135. /**
  136. * @throws NotFoundException
  137. * @throws NotPermittedException
  138. */
  139. private function getFolder(int $addressBookId, string $cardUri, bool $createIfNotExists = true): ISimpleFolder {
  140. $hash = md5($addressBookId . ' ' . $cardUri);
  141. try {
  142. return $this->appData->getFolder($hash);
  143. } catch (NotFoundException $e) {
  144. if ($createIfNotExists) {
  145. return $this->appData->newFolder($hash);
  146. } else {
  147. throw $e;
  148. }
  149. }
  150. }
  151. /**
  152. * Get the extension of the avatar. If there is no avatar throw Exception
  153. *
  154. * @throws NotFoundException
  155. */
  156. private function getExtension(ISimpleFolder $folder): string {
  157. foreach (self::ALLOWED_CONTENT_TYPES as $extension) {
  158. if ($folder->fileExists('photo.' . $extension)) {
  159. return $extension;
  160. }
  161. }
  162. throw new NotFoundException('Avatar not found');
  163. }
  164. /**
  165. * @param Card $node
  166. * @return false|array{body: string, Content-Type: string}
  167. */
  168. private function getPhoto(Card $node) {
  169. try {
  170. $vObject = $this->readCard($node->get());
  171. return $this->getPhotoFromVObject($vObject);
  172. } catch (\Exception $e) {
  173. $this->logger->error('Exception during vcard photo parsing', [
  174. 'exception' => $e
  175. ]);
  176. }
  177. return false;
  178. }
  179. /**
  180. * @return false|array{body: string, Content-Type: string}
  181. */
  182. public function getPhotoFromVObject(Document $vObject) {
  183. try {
  184. if (!$vObject->PHOTO) {
  185. return false;
  186. }
  187. $photo = $vObject->PHOTO;
  188. $val = $photo->getValue();
  189. // handle data URI. e.g PHOTO;VALUE=URI:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQE
  190. if ($photo->getValueType() === 'URI') {
  191. $parsed = \Sabre\URI\parse($val);
  192. // only allow data://
  193. if ($parsed['scheme'] !== 'data') {
  194. return false;
  195. }
  196. if (substr_count($parsed['path'], ';') === 1) {
  197. [$type] = explode(';', $parsed['path']);
  198. }
  199. $val = file_get_contents($val);
  200. } else {
  201. // get type if binary data
  202. $type = $this->getBinaryType($photo);
  203. }
  204. if (empty($type) || !isset(self::ALLOWED_CONTENT_TYPES[$type])) {
  205. $type = 'application/octet-stream';
  206. }
  207. return [
  208. 'Content-Type' => $type,
  209. 'body' => $val
  210. ];
  211. } catch (\Exception $e) {
  212. $this->logger->error('Exception during vcard photo parsing', [
  213. 'exception' => $e
  214. ]);
  215. }
  216. return false;
  217. }
  218. private function readCard(string $cardData): Document {
  219. return Reader::read($cardData);
  220. }
  221. /**
  222. * @param Binary $photo
  223. * @return string
  224. */
  225. private function getBinaryType(Binary $photo) {
  226. $params = $photo->parameters();
  227. if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) {
  228. /** @var Parameter $typeParam */
  229. $typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE'];
  230. $type = $typeParam->getValue();
  231. if (strpos($type, 'image/') === 0) {
  232. return $type;
  233. } else {
  234. return 'image/' . strtolower($type);
  235. }
  236. }
  237. return '';
  238. }
  239. /**
  240. * @param int $addressBookId
  241. * @param string $cardUri
  242. * @throws NotPermittedException
  243. */
  244. public function delete($addressBookId, $cardUri) {
  245. try {
  246. $folder = $this->getFolder($addressBookId, $cardUri, false);
  247. $folder->delete();
  248. } catch (NotFoundException $e) {
  249. // that's OK, nothing to do
  250. }
  251. }
  252. }