LinkReferenceProvider.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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' => 3 ]);
  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('[Head] 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' => 3, 'stream' => true ]);
  122. } catch (\Exception $e) {
  123. $this->logger->debug('Failed to fetch link for obtaining open graph data', ['exception' => $e]);
  124. return;
  125. }
  126. $body = $response->getBody();
  127. if (is_resource($body)) {
  128. $responseContent = fread($body, self::MAX_CONTENT_LENGTH);
  129. if (!feof($body)) {
  130. $this->logger->debug('[Get] Skip resolving links pointing to content length > 5 MiB');
  131. return;
  132. }
  133. } else {
  134. $this->logger->error('[Get] Impossible to check content length');
  135. return;
  136. }
  137. // OpenGraph handling
  138. $consumer = new Consumer();
  139. $consumer->useFallbackMode = true;
  140. $object = $consumer->loadHtml($responseContent);
  141. $reference->setUrl($reference->getId());
  142. if ($object->title) {
  143. $reference->setTitle($object->title);
  144. }
  145. if ($object->description) {
  146. $reference->setDescription($object->description);
  147. }
  148. if ($object->images) {
  149. try {
  150. $host = parse_url($object->images[0]->url, PHP_URL_HOST);
  151. if ($host === false || $host === null) {
  152. $this->logger->warning('Could not detect host of open graph image URI for ' . $reference->getId());
  153. return;
  154. }
  155. $appData = $this->appDataFactory->get('core');
  156. try {
  157. $folder = $appData->getFolder('opengraph');
  158. } catch (NotFoundException $e) {
  159. $folder = $appData->newFolder('opengraph');
  160. }
  161. $response = $client->get($object->images[0]->url, ['timeout' => 3]);
  162. $contentType = $response->getHeader('Content-Type');
  163. $contentLength = $response->getHeader('Content-Length');
  164. if (in_array($contentType, self::ALLOWED_CONTENT_TYPES, true) && $contentLength < self::MAX_CONTENT_LENGTH) {
  165. $stream = Utils::streamFor($response->getBody());
  166. $bodyStream = new LimitStream($stream, self::MAX_CONTENT_LENGTH, 0);
  167. $reference->setImageContentType($contentType);
  168. $folder->newFile(md5($reference->getId()), $bodyStream->getContents());
  169. $reference->setImageUrl($this->urlGenerator->linkToRouteAbsolute('core.Reference.preview', ['referenceId' => md5($reference->getId())]));
  170. }
  171. } catch (\Exception $e) {
  172. $this->logger->debug('Failed to fetch and store the open graph image for ' . $reference->getId(), ['exception' => $e]);
  173. }
  174. }
  175. }
  176. /**
  177. * @inheritDoc
  178. * @since 29.0.0
  179. */
  180. public function getCachePrefix(string $referenceId): string {
  181. return $referenceId;
  182. }
  183. /**
  184. * @inheritDoc
  185. * @since 29.0.0
  186. */
  187. public function getCacheKey(string $referenceId): ?string {
  188. return null;
  189. }
  190. /**
  191. * @inheritDoc
  192. * @since 30.0.0
  193. */
  194. public function getCacheKeyPublic(string $referenceId, string $sharingToken): ?string {
  195. return null;
  196. }
  197. }