1
0

LinkReferenceProvider.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2022 Julius Härtl <jus@bitgrid.net>
  5. *
  6. * @author Julius Härtl <jus@bitgrid.net>
  7. * @author Anupam Kumar <kyteinsky@gmail.com>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. namespace OCP\Collaboration\Reference;
  25. use Fusonic\OpenGraph\Consumer;
  26. use GuzzleHttp\Exception\GuzzleException;
  27. use GuzzleHttp\Psr7\LimitStream;
  28. use GuzzleHttp\Psr7\Utils;
  29. use OC\Security\RateLimiting\Exception\RateLimitExceededException;
  30. use OC\Security\RateLimiting\Limiter;
  31. use OC\SystemConfig;
  32. use OCP\Files\AppData\IAppDataFactory;
  33. use OCP\Files\NotFoundException;
  34. use OCP\Http\Client\IClientService;
  35. use OCP\IRequest;
  36. use OCP\IURLGenerator;
  37. use OCP\IUserSession;
  38. use Psr\Log\LoggerInterface;
  39. /**
  40. * @since 29.0.0
  41. */
  42. class LinkReferenceProvider implements IReferenceProvider {
  43. /**
  44. * for image size and webpage header
  45. * @since 29.0.0
  46. */
  47. public const MAX_CONTENT_LENGTH = 5 * 1024 * 1024;
  48. /**
  49. * @since 29.0.0
  50. */
  51. public const ALLOWED_CONTENT_TYPES = [
  52. 'image/png',
  53. 'image/jpg',
  54. 'image/jpeg',
  55. 'image/gif',
  56. 'image/svg+xml',
  57. 'image/webp'
  58. ];
  59. /**
  60. * @since 29.0.0
  61. */
  62. public function __construct(
  63. private IClientService $clientService,
  64. private LoggerInterface $logger,
  65. private SystemConfig $systemConfig,
  66. private IAppDataFactory $appDataFactory,
  67. private IURLGenerator $urlGenerator,
  68. private Limiter $limiter,
  69. private IUserSession $userSession,
  70. private IRequest $request,
  71. ) {
  72. }
  73. /**
  74. * @inheritDoc
  75. * @since 29.0.0
  76. */
  77. public function matchReference(string $referenceText): bool {
  78. if ($this->systemConfig->getValue('reference_opengraph', true) !== true) {
  79. return false;
  80. }
  81. return (bool)preg_match(IURLGenerator::URL_REGEX, $referenceText);
  82. }
  83. /**
  84. * @inheritDoc
  85. * @since 29.0.0
  86. */
  87. public function resolveReference(string $referenceText): ?IReference {
  88. if ($this->matchReference($referenceText)) {
  89. $reference = new Reference($referenceText);
  90. $this->fetchReference($reference);
  91. return $reference;
  92. }
  93. return null;
  94. }
  95. /**
  96. * Populates the reference with OpenGraph data
  97. *
  98. * @param Reference $reference
  99. * @since 29.0.0
  100. */
  101. private function fetchReference(Reference $reference): void {
  102. try {
  103. $user = $this->userSession->getUser();
  104. if ($user) {
  105. $this->limiter->registerUserRequest('opengraph', 10, 120, $user);
  106. } else {
  107. $this->limiter->registerAnonRequest('opengraph', 10, 120, $this->request->getRemoteAddress());
  108. }
  109. } catch (RateLimitExceededException $e) {
  110. return;
  111. }
  112. $client = $this->clientService->newClient();
  113. try {
  114. $headResponse = $client->head($reference->getId(), [ 'timeout' => 10 ]);
  115. } catch (\Exception $e) {
  116. $this->logger->debug('Failed to perform HEAD request to get target metadata', ['exception' => $e]);
  117. return;
  118. }
  119. $linkContentLength = $headResponse->getHeader('Content-Length');
  120. if (is_numeric($linkContentLength) && (int) $linkContentLength > self::MAX_CONTENT_LENGTH) {
  121. $this->logger->debug('Skip resolving links pointing to content length > 5 MiB');
  122. return;
  123. }
  124. $linkContentType = $headResponse->getHeader('Content-Type');
  125. $expectedContentTypeRegex = '/^text\/html;?/i';
  126. // check the header begins with the expected content type
  127. if (!preg_match($expectedContentTypeRegex, $linkContentType)) {
  128. $this->logger->debug('Skip resolving links pointing to content type that is not "text/html"');
  129. return;
  130. }
  131. try {
  132. $response = $client->get($reference->getId(), [ 'timeout' => 10 ]);
  133. } catch (\Exception $e) {
  134. $this->logger->debug('Failed to fetch link for obtaining open graph data', ['exception' => $e]);
  135. return;
  136. }
  137. $responseBody = (string)$response->getBody();
  138. // OpenGraph handling
  139. $consumer = new Consumer();
  140. $consumer->useFallbackMode = true;
  141. $object = $consumer->loadHtml($responseBody);
  142. $reference->setUrl($reference->getId());
  143. if ($object->title) {
  144. $reference->setTitle($object->title);
  145. }
  146. if ($object->description) {
  147. $reference->setDescription($object->description);
  148. }
  149. if ($object->images) {
  150. try {
  151. $host = parse_url($object->images[0]->url, PHP_URL_HOST);
  152. if ($host === false || $host === null) {
  153. $this->logger->warning('Could not detect host of open graph image URI for ' . $reference->getId());
  154. return;
  155. }
  156. $appData = $this->appDataFactory->get('core');
  157. try {
  158. $folder = $appData->getFolder('opengraph');
  159. } catch (NotFoundException $e) {
  160. $folder = $appData->newFolder('opengraph');
  161. }
  162. $response = $client->get($object->images[0]->url, ['timeout' => 10]);
  163. $contentType = $response->getHeader('Content-Type');
  164. $contentLength = $response->getHeader('Content-Length');
  165. if (in_array($contentType, self::ALLOWED_CONTENT_TYPES, true) && $contentLength < self::MAX_CONTENT_LENGTH) {
  166. $stream = Utils::streamFor($response->getBody());
  167. $bodyStream = new LimitStream($stream, self::MAX_CONTENT_LENGTH, 0);
  168. $reference->setImageContentType($contentType);
  169. $folder->newFile(md5($reference->getId()), $bodyStream->getContents());
  170. $reference->setImageUrl($this->urlGenerator->linkToRouteAbsolute('core.Reference.preview', ['referenceId' => md5($reference->getId())]));
  171. }
  172. } catch (GuzzleException $e) {
  173. $this->logger->info('Failed to fetch and store the open graph image for ' . $reference->getId(), ['exception' => $e]);
  174. } catch (\Throwable $e) {
  175. $this->logger->error('Failed to fetch and store the open graph image for ' . $reference->getId(), ['exception' => $e]);
  176. }
  177. }
  178. }
  179. /**
  180. * @inheritDoc
  181. * @since 29.0.0
  182. */
  183. public function getCachePrefix(string $referenceId): string {
  184. return $referenceId;
  185. }
  186. /**
  187. * @inheritDoc
  188. * @since 29.0.0
  189. */
  190. public function getCacheKey(string $referenceId): ?string {
  191. return null;
  192. }
  193. }