LinkReferenceProvider.php 6.0 KB

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