PhotoCache.php 6.9 KB

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