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 7.0KB

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