You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PhotoCache.php 6.8KB

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