PhotoCache.php 6.4 KB

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