LinkReferenceProvider.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCP\Collaboration\Reference;
  8. use Fusonic\OpenGraph\Consumer;
  9. use GuzzleHttp\Psr7\LimitStream;
  10. use GuzzleHttp\Psr7\Utils;
  11. use OC\Security\RateLimiting\Exception\RateLimitExceededException;
  12. use OC\Security\RateLimiting\Limiter;
  13. use OC\SystemConfig;
  14. use OCP\Files\AppData\IAppDataFactory;
  15. use OCP\Files\NotFoundException;
  16. use OCP\Http\Client\IClientService;
  17. use OCP\IRequest;
  18. use OCP\IURLGenerator;
  19. use OCP\IUserSession;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * @since 29.0.0
  23. */
  24. class LinkReferenceProvider implements IReferenceProvider, IPublicReferenceProvider {
  25. /**
  26. * for image size and webpage header
  27. * @since 29.0.0
  28. */
  29. public const MAX_CONTENT_LENGTH = 5 * 1024 * 1024;
  30. /**
  31. * @since 29.0.0
  32. */
  33. public const ALLOWED_CONTENT_TYPES = [
  34. 'image/png',
  35. 'image/jpg',
  36. 'image/jpeg',
  37. 'image/gif',
  38. 'image/svg+xml',
  39. 'image/webp'
  40. ];
  41. /**
  42. * @since 29.0.0
  43. */
  44. public function __construct(
  45. private IClientService $clientService,
  46. private LoggerInterface $logger,
  47. private SystemConfig $systemConfig,
  48. private IAppDataFactory $appDataFactory,
  49. private IURLGenerator $urlGenerator,
  50. private Limiter $limiter,
  51. private IUserSession $userSession,
  52. private IRequest $request,
  53. ) {
  54. }
  55. /**
  56. * @inheritDoc
  57. * @since 29.0.0
  58. */
  59. public function matchReference(string $referenceText): bool {
  60. if ($this->systemConfig->getValue('reference_opengraph', true) !== true) {
  61. return false;
  62. }
  63. return (bool)preg_match(IURLGenerator::URL_REGEX, $referenceText);
  64. }
  65. /**
  66. * @inheritDoc
  67. * @since 29.0.0
  68. */
  69. public function resolveReference(string $referenceText): ?IReference {
  70. if ($this->matchReference($referenceText)) {
  71. $reference = new Reference($referenceText);
  72. $this->fetchReference($reference);
  73. return $reference;
  74. }
  75. return null;
  76. }
  77. /**
  78. * @inheritDoc
  79. * @since 30.0.0
  80. */
  81. public function resolveReferencePublic(string $referenceText, string $sharingToken): ?IReference {
  82. return $this->resolveReference($referenceText);
  83. }
  84. /**
  85. * Populates the reference with OpenGraph data
  86. *
  87. * @param Reference $reference
  88. * @since 29.0.0
  89. */
  90. private function fetchReference(Reference $reference): void {
  91. try {
  92. $user = $this->userSession->getUser();
  93. if ($user) {
  94. $this->limiter->registerUserRequest('opengraph', 10, 120, $user);
  95. } else {
  96. $this->limiter->registerAnonRequest('opengraph', 10, 120, $this->request->getRemoteAddress());
  97. }
  98. } catch (RateLimitExceededException $e) {
  99. return;
  100. }
  101. $client = $this->clientService->newClient();
  102. try {
  103. $headResponse = $client->head($reference->getId(), [ 'timeout' => 10 ]);
  104. } catch (\Exception $e) {
  105. $this->logger->debug('Failed to perform HEAD request to get target metadata', ['exception' => $e]);
  106. return;
  107. }
  108. $linkContentLength = $headResponse->getHeader('Content-Length');
  109. if (is_numeric($linkContentLength) && (int) $linkContentLength > self::MAX_CONTENT_LENGTH) {
  110. $this->logger->debug('Skip resolving links pointing to content length > 5 MiB');
  111. return;
  112. }
  113. $linkContentType = $headResponse->getHeader('Content-Type');
  114. $expectedContentTypeRegex = '/^text\/html;?/i';
  115. // check the header begins with the expected content type
  116. if (!preg_match($expectedContentTypeRegex, $linkContentType)) {
  117. $this->logger->debug('Skip resolving links pointing to content type that is not "text/html"');
  118. return;
  119. }
  120. try {
  121. $response = $client->get($reference->getId(), [ 'timeout' => 10 ]);
  122. } catch (\Exception $e) {
  123. $this->logger->debug('Failed to fetch link for obtaining open graph data', ['exception' => $e]);
  124. return;
  125. }
  126. $responseBody = (string)$response->getBody();
  127. // OpenGraph handling
  128. $consumer = new Consumer();
  129. $consumer->useFallbackMode = true;
  130. $object = $consumer->loadHtml($responseBody);
  131. $reference->setUrl($reference->getId());
  132. if ($object->title) {
  133. $reference->setTitle($object->title);
  134. }
  135. if ($object->description) {
  136. $reference->setDescription($object->description);
  137. }
  138. if ($object->images) {
  139. try {
  140. $host = parse_url($object->images[0]->url, PHP_URL_HOST);
  141. if ($host === false || $host === null) {
  142. $this->logger->warning('Could not detect host of open graph image URI for ' . $reference->getId());
  143. return;
  144. }
  145. $appData = $this->appDataFactory->get('core');
  146. try {
  147. $folder = $appData->getFolder('opengraph');
  148. } catch (NotFoundException $e) {
  149. $folder = $appData->newFolder('opengraph');
  150. }
  151. $response = $client->get($object->images[0]->url, ['timeout' => 10]);
  152. $contentType = $response->getHeader('Content-Type');
  153. $contentLength = $response->getHeader('Content-Length');
  154. if (in_array($contentType, self::ALLOWED_CONTENT_TYPES, true) && $contentLength < self::MAX_CONTENT_LENGTH) {
  155. $stream = Utils::streamFor($response->getBody());
  156. $bodyStream = new LimitStream($stream, self::MAX_CONTENT_LENGTH, 0);
  157. $reference->setImageContentType($contentType);
  158. $folder->newFile(md5($reference->getId()), $bodyStream->getContents());
  159. $reference->setImageUrl($this->urlGenerator->linkToRouteAbsolute('core.Reference.preview', ['referenceId' => md5($reference->getId())]));
  160. }
  161. } catch (\Exception $e) {
  162. $this->logger->debug('Failed to fetch and store the open graph image for ' . $reference->getId(), ['exception' => $e]);
  163. }
  164. }
  165. }
  166. /**
  167. * @inheritDoc
  168. * @since 29.0.0
  169. */
  170. public function getCachePrefix(string $referenceId): string {
  171. return $referenceId;
  172. }
  173. /**
  174. * @inheritDoc
  175. * @since 29.0.0
  176. */
  177. public function getCacheKey(string $referenceId): ?string {
  178. return null;
  179. }
  180. /**
  181. * @inheritDoc
  182. * @since 30.0.0
  183. */
  184. public function getCacheKeyPublic(string $referenceId, string $sharingToken): ?string {
  185. return null;
  186. }
  187. }