Embed.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * OEmbed and OpenGraph implementation for GNU social
  18. *
  19. * @package GNUsocial
  20. *
  21. * @author Mikael Nordfeldth
  22. * @author Stephen Paul Weber
  23. * @author hannes
  24. * @author Mikael Nordfeldth
  25. * @author Diogo Peralta Cordeiro
  26. * @author Miguel Dantas
  27. * @author Diogo Peralta Cordeiro
  28. * @copyright 2014-2021 Free Software Foundation, Inc http://www.fsf.org
  29. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  30. */
  31. namespace Plugin\Embed;
  32. use App\Core\Modules\Module;
  33. /**
  34. * Base class for the Embed plugin that does most of the heavy lifting to get
  35. * and display representations for remote content.
  36. *
  37. * @copyright 2014-2021 Free Software Foundation, Inc http://www.fsf.org
  38. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  39. */
  40. class Embed extends Module
  41. {
  42. const PLUGIN_VERSION = '2.1.0';
  43. // settings which can be set in config.php with addPlugin('Embed', ['param'=>'value', ...]);
  44. // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end ('$') your strings
  45. public $domain_whitelist = [
  46. // hostname => service provider
  47. '^i\d*\.ytimg\.com$' => 'YouTube',
  48. '^i\d*\.vimeocdn\.com$' => 'Vimeo',
  49. ];
  50. public $append_whitelist = []; // fill this array as domain_whitelist to add more trusted sources
  51. public $check_whitelist = false; // security/abuse precaution
  52. public $thumbnail_width = 128;
  53. public $thumbnail_height = 128;
  54. public $crop = true;
  55. public $max_size;
  56. protected $imgData = [];
  57. /**
  58. * Initialize the Embed plugin and set up the environment it needs for it.
  59. * Returns true if it initialized properly, the exception object if it
  60. * doesn't.
  61. */
  62. public function initialize()
  63. {
  64. parent::initialize();
  65. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  66. // Load global configuration if specific not provided
  67. $this->thumbnail_width = $this->thumbnail_width ?? common_config('thumbnail', 'width');
  68. $this->thumbnail_height = $this->thumbnail_height ?? common_config('thumbnail', 'height');
  69. $this->max_size = $this->max_size ?? common_config('attachments', 'file_quota');
  70. $this->crop = $this->crop ?? common_config('thumbnail', 'crop');
  71. }
  72. /**
  73. * The code executed on GNU social checking the database schema, which in
  74. * this case is to make sure we have the plugin table we need.
  75. *
  76. * @return bool true if it ran successfully, the exception object if it doesn't.
  77. */
  78. public function onCheckSchema()
  79. {
  80. $this->onEndUpgrade(); // Ensure rename
  81. $schema = Schema::get();
  82. $schema->ensureTable('file_embed', File_embed::schemaDef());
  83. return true;
  84. }
  85. public function onEndUpgrade()
  86. {
  87. $schema = Schema::get();
  88. return $schema->renameTable('file_oembed', 'file_embed');
  89. }
  90. /**
  91. * This code executes when GNU social creates the page routing, and we hook
  92. * on this event to add our action handler for Embed.
  93. *
  94. * @param $m URLMapper the router that was initialized.
  95. *
  96. * @throws Exception
  97. *
  98. * @return void true if successful, the exception object if it isn't.
  99. */
  100. public function onRouterInitialized(URLMapper $m)
  101. {
  102. $m->connect('main/oembed', ['action' => 'oembed']);
  103. }
  104. /**
  105. * This event executes when GNU social encounters a remote URL we then decide
  106. * to interrogate for metadata. Embed gloms onto it to see if we have an
  107. * oEmbed endpoint or image to try to represent in the post.
  108. *
  109. * @param $url string the remote URL we're looking at
  110. * @param $dom DOMDocument the document we're getting metadata from
  111. * @param $metadata stdClass class representing the metadata
  112. *
  113. * @return bool true if successful, the exception object if it isn't.
  114. */
  115. public function onGetRemoteUrlMetadataFromDom(string $url, DOMDocument $dom, stdClass &$metadata)
  116. {
  117. try {
  118. common_log(LOG_INFO, "Trying to find Embed data for {$url} with 'oscarotero/Embed'");
  119. $info = self::create($url);
  120. $metadata->version = '1.0'; // Yes.
  121. $metadata->provider_name = $info->authorName;
  122. $metadata->title = $info->title;
  123. $metadata->html = common_purify($info->description);
  124. $metadata->type = $info->type;
  125. $metadata->url = $info->url;
  126. $metadata->thumbnail_height = $info->imageHeight;
  127. $metadata->thumbnail_width = $info->imageWidth;
  128. if (substr($info->image, 0, 4) === 'data') {
  129. // Inline image
  130. $imgData = base64_decode(substr($info->image, stripos($info->image, 'base64,') + 7));
  131. list($filename) = $this->validateAndWriteImage($imgData);
  132. // Use a file URI for images, as file_embed can't store a filename
  133. $metadata->thumbnail_url = 'file://' . File_thumbnail::path($filename);
  134. } else {
  135. $metadata->thumbnail_url = $info->image;
  136. }
  137. } catch (Exception $e) {
  138. common_log(LOG_INFO, "Failed to find Embed data for {$url} with 'oscarotero/Embed'" .
  139. ', got exception: ' . get_class($e));
  140. }
  141. if (isset($metadata->thumbnail_url)) {
  142. // sometimes sites serve the path, not the full URL, for images
  143. // let's "be liberal in what you accept from others"!
  144. // add protocol and host if the thumbnail_url starts with /
  145. if ($metadata->thumbnail_url[0] == '/') {
  146. $thumbnail_url_parsed = parse_url($metadata->url);
  147. $metadata->thumbnail_url = "{$thumbnail_url_parsed['scheme']}://" .
  148. "{$thumbnail_url_parsed['host']}$metadata->thumbnail_url";
  149. }
  150. // some wordpress opengraph implementations sometimes return a white blank image
  151. // no need for us to save that!
  152. if ($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
  153. $metadata->thumbnail_url = null;
  154. }
  155. // FIXME: this is also true of locally-installed wordpress so we should watch out for that.
  156. }
  157. return true;
  158. }
  159. /** Placeholder */
  160. public function onEndShowHeadElements(Action $action)
  161. {
  162. switch ($action->getActionName()) {
  163. case 'attachment':
  164. $url = common_local_url('attachment', ['attachment' => $action->attachment->getID()]);
  165. break;
  166. case 'shownotice':
  167. if (!$action->notice->isLocal()) {
  168. return true;
  169. }
  170. try {
  171. $url = $action->notice->getUrl();
  172. } catch (InvalidUrlException $e) {
  173. // The notice is probably a share or similar, which don't
  174. // have a representational URL of their own.
  175. return true;
  176. }
  177. break;
  178. }
  179. if (isset($url)) {
  180. foreach (['xml', 'json'] as $format) {
  181. $action->element(
  182. 'link',
  183. [
  184. 'rel' => 'alternate',
  185. 'type' => "application/{$format}+oembed",
  186. 'href' => common_local_url('oembed', [], ['format' => $format, 'url' => $url]),
  187. 'title' => 'oEmbed',
  188. ]
  189. );
  190. }
  191. }
  192. return true;
  193. }
  194. /** Placeholder */
  195. public function onEndShowStylesheets(Action $action)
  196. {
  197. $action->cssLink($this->path('css/embed.css'));
  198. return true;
  199. }
  200. /**
  201. * Save embedding information for a File, if applicable.
  202. *
  203. * Normally this event is called through File::saveNew()
  204. *
  205. * @param File $file The newly inserted File object.
  206. *
  207. * @return bool success
  208. */
  209. public function onEndFileSaveNew(File $file)
  210. {
  211. $fe = File_embed::getKV('file_id', $file->getID());
  212. if ($fe instanceof File_embed) {
  213. common_log(LOG_WARNING, "Strangely, a File_embed object exists for new file {$file->getID()}", __FILE__);
  214. return true;
  215. }
  216. if (isset($file->mimetype)
  217. && (('text/html' === substr($file->mimetype, 0, 9) || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
  218. try {
  219. $embed_data = File_embed::getEmbed($file->url);
  220. if ($embed_data === false) {
  221. throw new Exception("Did not get Embed data from URL {$file->url}");
  222. }
  223. $file->setTitle($embed_data->title);
  224. } catch (Exception $e) {
  225. common_log(LOG_WARNING, sprintf(
  226. __METHOD__ . ': %s thrown when getting embed data: %s',
  227. get_class($e),
  228. _ve($e->getMessage())
  229. ));
  230. return true;
  231. }
  232. File_embed::saveNew($embed_data, $file->getID());
  233. }
  234. return true;
  235. }
  236. /** Placeholder */
  237. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  238. {
  239. $embed = File_embed::getKV('file_id', $file->getID());
  240. if (empty($embed->author_name) && empty($embed->provider)) {
  241. return true;
  242. }
  243. $out->elementStart('div', ['id' => 'oembed_info', 'class' => 'e-content']);
  244. foreach (['author_name' => ['class' => ' author', 'url' => 'author_url'],
  245. 'provider' => ['class' => '', 'url' => 'provider_url'], ]
  246. as $field => $options) {
  247. if (!empty($embed->{$field})) {
  248. $out->elementStart('div', 'fn vcard' . $options['class']);
  249. if (empty($embed->{$options['url']})) {
  250. $out->text($embed->{$field});
  251. } else {
  252. $out->element(
  253. 'a',
  254. ['href' => $embed->{$options['url']},
  255. 'class' => 'url', ],
  256. $embed->{$field}
  257. );
  258. }
  259. }
  260. }
  261. $out->elementEnd('div');
  262. return false;
  263. }
  264. /** Placeholder */
  265. public function onFileEnclosureMetadata(File $file, &$enclosure)
  266. {
  267. // Never treat generic HTML links as an enclosure type!
  268. // But if we have embed info, we'll consider it golden.
  269. $embed = File_embed::getKV('file_id', $file->getID());
  270. if (!$embed instanceof File_embed || !in_array($embed->type, ['photo', 'video'])) {
  271. return true;
  272. }
  273. foreach (['mimetype', 'url', 'title', 'modified', 'width', 'height'] as $key) {
  274. if (isset($embed->{$key}) && !empty($embed->{$key})) {
  275. $enclosure->{$key} = $embed->{$key};
  276. }
  277. }
  278. return true;
  279. }
  280. /** Placeholder */
  281. public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
  282. {
  283. try {
  284. $embed = File_embed::getByFile($file);
  285. } catch (NoResultException $e) {
  286. return true;
  287. }
  288. // Show thumbnail as usual if it's a photo.
  289. if ($embed->type === 'photo') {
  290. return true;
  291. }
  292. $out->elementStart('article', ['class' => 'h-entry embed']);
  293. $out->elementStart('header');
  294. try {
  295. $thumb = $file->getThumbnail($this->thumbnail_width, $this->thumbnail_height);
  296. $out->element('img', $thumb->getHtmlAttrs(['class' => 'u-photo embed']));
  297. unset($thumb);
  298. } catch (FileNotFoundException $e) {
  299. // Nothing to show
  300. } catch (Exception $e) {
  301. $out->element('div', ['class' => 'error'], $e->getMessage());
  302. }
  303. $out->elementStart('h5', ['class' => 'p-name embed']);
  304. $out->element('a', ['class' => 'u-url', 'href' => $file->getUrl()], common_strip_html($embed->title));
  305. $out->elementEnd('h5');
  306. $out->elementStart('div', ['class' => 'p-author embed']);
  307. if (!empty($embed->author_name)) {
  308. // TRANS: text before the author name of embed attachment representation
  309. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  310. $out->text(_('By '));
  311. $attrs = ['class' => 'h-card p-author'];
  312. if (!empty($embed->author_url)) {
  313. $attrs['href'] = $embed->author_url;
  314. $tag = 'a';
  315. } else {
  316. $tag = 'span';
  317. }
  318. $out->element($tag, $attrs, $embed->author_name);
  319. }
  320. if (!empty($embed->provider)) {
  321. // TRANS: text between the embed author name and provider url
  322. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  323. $out->text(_(' from '));
  324. $attrs = ['class' => 'h-card'];
  325. if (!empty($embed->provider_url)) {
  326. $attrs['href'] = $embed->provider_url;
  327. $tag = 'a';
  328. } else {
  329. $tag = 'span';
  330. }
  331. $out->element($tag, $attrs, $embed->provider);
  332. }
  333. $out->elementEnd('div');
  334. $out->elementEnd('header');
  335. $out->elementStart('div', ['class' => 'p-summary embed']);
  336. $out->raw(common_purify($embed->html));
  337. $out->elementEnd('div');
  338. $out->elementStart('footer');
  339. $out->elementEnd('footer');
  340. $out->elementEnd('article');
  341. return false;
  342. }
  343. /** Placeholder */
  344. public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
  345. {
  346. try {
  347. $embed = File_embed::getByFile($file);
  348. } catch (NoResultException $e) {
  349. return true;
  350. }
  351. // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
  352. switch ($embed->type) {
  353. case 'video':
  354. case 'link':
  355. if (!empty($embed->html)
  356. && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
  357. $purifier = new HTMLPurifier();
  358. // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed,
  359. // but I'm not sure anymore...
  360. $out->raw($purifier->purify($embed->html));
  361. }
  362. return false;
  363. }
  364. return true;
  365. }
  366. /**
  367. * This event executes when GNU social is creating a file thumbnail entry in
  368. * the database. We glom onto this to create proper information for Embed
  369. * object thumbnails.
  370. *
  371. * @param $file File the file of the created thumbnail
  372. * @param &$imgPath null|string = the path to the created thumbnail (output)
  373. * @param $media string = media type
  374. *
  375. * @throws FileNotFoundException
  376. * @throws NoResultException
  377. * @throws ServerException
  378. *
  379. * @return bool true if it succeeds (including non-action
  380. * states where it isn't oEmbed data, so it doesn't mess up the event handle
  381. * for other things hooked into it), or the exception if it fails.
  382. */
  383. public function onCreateFileImageThumbnailSource(File $file, ?string &$imgPath, string $media): bool
  384. {
  385. // If we are on a private node, we won't do any remote calls (just as a precaution until
  386. // we can configure this from config.php for the private nodes)
  387. if (common_config('site', 'private')) {
  388. return true;
  389. }
  390. // All our remote Embed images lack a local filename property in the File object
  391. if ($file->isLocal()) {
  392. common_debug(sprintf('File of id==%d is local (filename: %s), so nothing Embed ' .
  393. 'should handle.', $file->getID(), _ve($file->filename)));
  394. return true;
  395. }
  396. try {
  397. // If we have proper Embed data, there should be an entry in the File_thumbnail table.
  398. // If not, we're not going to do anything.
  399. $thumbnail = File_thumbnail::byFile($file);
  400. } catch (NoResultException $e) {
  401. // Not Embed data, or at least nothing we either can or want to use.
  402. common_debug('No Embed data found for file id==' . $file->getID());
  403. return true;
  404. }
  405. try {
  406. $this->storeRemoteFileThumbnail($thumbnail);
  407. } catch (AlreadyFulfilledException $e) {
  408. // aw yiss!
  409. } catch (Exception $e) {
  410. common_debug(sprintf(
  411. 'Embed encountered an exception (%s) for file id==%d: %s',
  412. get_class($e),
  413. $file->getID(),
  414. _ve($e->getMessage())
  415. ));
  416. throw $e;
  417. }
  418. // Out
  419. $imgPath = $thumbnail->getPath();
  420. return !file_exists($imgPath);
  421. }
  422. public function onFileDeleteRelated(File $file, array &$related): bool
  423. {
  424. $related[] = 'File_embed';
  425. return true;
  426. }
  427. /**
  428. * @param mixed $url
  429. *
  430. * @throws ServerException if check is made but fails
  431. *
  432. * @return bool false on no check made, provider name on success
  433. */
  434. protected function checkWhitelist($url)
  435. {
  436. if (!$this->check_whitelist) {
  437. return false; // indicates "no check made"
  438. }
  439. $host = parse_url($url, PHP_URL_HOST);
  440. foreach ($this->domain_whitelist as $regex => $provider) {
  441. if (preg_match("/{$regex}/", $host)) {
  442. return $provider; // we trust this source, return provider name
  443. }
  444. }
  445. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  446. }
  447. /**
  448. * Check the file size of a remote file using a HEAD request and checking
  449. * the content-length variable returned. This isn't 100% foolproof but is
  450. * reliable enough for our purposes.
  451. *
  452. * @param mixed $url
  453. * @param null|mixed $headers
  454. *
  455. * @return bool|string the file size if it succeeds, false otherwise.
  456. */
  457. private function getRemoteFileSize($url, $headers = null)
  458. {
  459. try {
  460. if ($headers === null) {
  461. if (!common_valid_http_url($url)) {
  462. common_log(LOG_ERR, 'Invalid URL in Embed::getRemoteFileSize()');
  463. return false;
  464. }
  465. $head = (new HTTPClient())->head($url);
  466. $headers = $head->getHeader();
  467. $headers = array_change_key_case($headers, CASE_LOWER);
  468. }
  469. return $headers['content-length'] ?? false;
  470. } catch (Exception $err) {
  471. common_log(LOG_ERR, __CLASS__ . ': getRemoteFileSize on URL : ' . _ve($url) .
  472. ' threw exception: ' . $err->getMessage());
  473. return false;
  474. }
  475. }
  476. /**
  477. * A private helper function that uses a CURL lookup to check the mime type
  478. * of a remote URL to see it it's an image.
  479. *
  480. * @param mixed $url
  481. * @param null|mixed $headers
  482. *
  483. * @return bool true if the remote URL is an image, or false otherwise.
  484. */
  485. private function isRemoteImage($url, $headers = null)
  486. {
  487. if (empty($headers)) {
  488. if (!common_valid_http_url($url)) {
  489. common_log(LOG_ERR, 'Invalid URL in Embed::isRemoteImage()');
  490. return false;
  491. }
  492. $head = (new HTTPClient())->head($url);
  493. $headers = $head->getHeader();
  494. $headers = array_change_key_case($headers, CASE_LOWER);
  495. }
  496. return !empty($headers['content-type']) && common_get_mime_media($headers['content-type']) === 'image';
  497. }
  498. /**
  499. * Validate that $imgData is a valid image before writing it to
  500. * disk, as well as resizing it to at most $this->thumbnail_width
  501. * by $this->thumbnail_height
  502. *
  503. * @param $imgData - The image data to validate. Taken by reference to avoid copying
  504. * @param null|string $url - The url where the image came from, to fetch metadata
  505. * @param null|array $headers - The headers possible previous request to $url
  506. * @param null|int $file_id - The id of the file this image belongs to, used for logging
  507. */
  508. protected function validateAndWriteImage(&$imgData, ?string $url = null, ?array $headers = null, ?int $file_id = null): array
  509. {
  510. $info = @getimagesizefromstring($imgData);
  511. // array indexes documented on php.net:
  512. // https://php.net/manual/en/function.getimagesize.php
  513. if ($info === false) {
  514. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
  515. } elseif (!$info[0] || !$info[1]) {
  516. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  517. }
  518. $width = min($info[0], $this->thumbnail_width);
  519. $height = min($info[1], $this->thumbnail_height);
  520. $filehash = hash(File::FILEHASH_ALG, $imgData);
  521. try {
  522. if (!empty($url)) {
  523. $original_name = HTTPClient::get_filename($url, $headers);
  524. }
  525. $filename = MediaFile::encodeFilename($original_name ?? _m('Untitled attachment'), $filehash);
  526. } catch (Exception $err) {
  527. common_log(LOG_ERR, 'Went to write a thumbnail to disk in StoreRemoteMediaPlugin::storeRemoteThumbnail ' .
  528. "but encountered error: {$err}");
  529. throw $err;
  530. }
  531. try {
  532. $fullpath = File_thumbnail::path($filename);
  533. // Write the file to disk. Throw Exception on failure
  534. if (!file_exists($fullpath)) {
  535. if (strpos($fullpath, INSTALLDIR) !== 0 || file_put_contents($fullpath, $imgData) === false) {
  536. throw new ServerException(_('Could not write downloaded file to disk.'));
  537. }
  538. if (common_get_mime_media(MediaFile::getUploadedMimeType($fullpath)) !== 'image') {
  539. @unlink($fullpath);
  540. throw new UnsupportedMediaException(
  541. _('Remote file format was not identified as an image.'),
  542. $url
  543. );
  544. }
  545. // If the image is not of the desired size, resize it
  546. if ($this->crop && ($info[0] > $this->thumbnail_width || $info[1] > $this->thumbnail_height)) {
  547. try {
  548. // Temporary object, not stored in DB
  549. $img = new ImageFile(-1, $fullpath);
  550. list($width, $height, $x, $y, $w, $h) = $img->scaleToFit($this->thumbnail_width, $this->thumbnail_height, $this->crop);
  551. // The boundary box for our resizing
  552. $box = [
  553. 'width' => $width, 'height' => $height,
  554. 'x' => $x, 'y' => $y,
  555. 'w' => $w, 'h' => $h,
  556. ];
  557. $width = $box['width'];
  558. $height = $box['height'];
  559. $img->resizeTo($fullpath, $box);
  560. } catch (\Intervention\Image\Exception\NotReadableException $e) {
  561. common_log(LOG_ERR, "StoreRemoteMediaPlugin::storeRemoteThumbnail was unable to decode image with Intervention: {$e}");
  562. // No need to interrupt processing
  563. }
  564. }
  565. } else {
  566. throw new AlreadyFulfilledException('A thumbnail seems to already exist for remote file' .
  567. ($file_id ? 'with id==' . $file_id : '') . ' at path ' . $fullpath);
  568. }
  569. } catch (AlreadyFulfilledException $e) {
  570. // Carry on
  571. } catch (Exception $err) {
  572. common_log(LOG_ERR, 'Went to write a thumbnail to disk in EmbedPlugin::storeRemoteThumbnail ' .
  573. "but encountered error: {$err}");
  574. throw $err;
  575. } finally {
  576. unset($imgData);
  577. }
  578. return [$filename, $width, $height];
  579. }
  580. /**
  581. * Function to create and store a thumbnail representation of a remote image
  582. *
  583. * @param $thumbnail File_thumbnail object containing the file thumbnail
  584. *
  585. * @return bool true if it succeeded, the exception if it fails, or false if it
  586. * is limited by system limits (ie the file is too large.)
  587. */
  588. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  589. {
  590. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  591. throw new AlreadyFulfilledException(
  592. sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id)
  593. );
  594. }
  595. $url = $thumbnail->url; // Important not to use the getter here.
  596. if (substr($url, 0, 7) == 'file://') {
  597. $filename = substr($url, 7);
  598. $info = getimagesize($filename);
  599. $filename = basename($filename);
  600. $width = $info[0];
  601. $height = $info[1];
  602. } else {
  603. $this->checkWhitelist($url);
  604. $head = (new HTTPClient())->head($url);
  605. $headers = $head->getHeader();
  606. $headers = array_change_key_case($headers, CASE_LOWER);
  607. try {
  608. $is_image = $this->isRemoteImage($url, $headers);
  609. if ($is_image == true) {
  610. $file_size = $this->getRemoteFileSize($url, $headers);
  611. if (($file_size != false) && ($file_size > $this->max_size)) {
  612. common_debug('Went to store remote thumbnail of size ' . $file_size .
  613. ' but the upload limit is ' . $this->max_size . ' so we aborted.');
  614. return false;
  615. }
  616. } else {
  617. return false;
  618. }
  619. } catch (Exception $err) {
  620. common_debug('Could not determine size of remote image, aborted local storage.');
  621. throw $err;
  622. }
  623. // First we download the file to memory and test whether it's actually an image file
  624. // FIXME: To support remote video/whatever files, this needs reworking.
  625. common_debug(sprintf(
  626. 'Downloading remote thumbnail for file id==%u with thumbnail URL: %s',
  627. $thumbnail->file_id,
  628. $url
  629. ));
  630. try {
  631. $imgData = HTTPClient::quickGet($url);
  632. if (isset($imgData)) {
  633. list($filename, $width, $height) = $this->validateAndWriteImage(
  634. $imgData,
  635. $url,
  636. $headers,
  637. $thumbnail->file_id
  638. );
  639. } else {
  640. throw new UnsupportedMediaException('HTTPClient returned an empty result');
  641. }
  642. } catch (UnsupportedMediaException $e) {
  643. // Couldn't find anything that looks like an image, nothing to do
  644. common_debug("Embed was not able to find an image for URL `{$url}`: " . $e->getMessage());
  645. return false;
  646. }
  647. }
  648. try {
  649. // Update our database for the thumbnail record
  650. $orig = clone $thumbnail;
  651. $thumbnail->filename = $filename;
  652. $thumbnail->width = $width;
  653. $thumbnail->height = $height;
  654. // Throws exception on failure.
  655. $thumbnail->updateWithKeys($orig);
  656. } catch (Exception $err) {
  657. common_log(LOG_ERR, 'Went to write a thumbnail entry to the database in ' .
  658. 'EmbedPlugin::storeRemoteThumbnail but encountered error: ' . $err);
  659. throw $err;
  660. }
  661. return true;
  662. }
  663. /**
  664. * Event raised when GNU social polls the plugin for information about it.
  665. * Adds this plugin's version information to $versions array
  666. *
  667. * @param &$versions array inherited from parent
  668. *
  669. * @return bool true hook value
  670. */
  671. public function onPluginVersion(array &$versions): bool
  672. {
  673. $versions[] = ['name' => 'Embed',
  674. 'version' => self::PLUGIN_VERSION,
  675. 'author' => 'Mikael Nordfeldth',
  676. 'homepage' => GNUSOCIAL_ENGINE_URL,
  677. 'description' => // TRANS: Plugin description.
  678. _m('Plugin for using and representing oEmbed, OpenGraph and other data.'), ];
  679. return true;
  680. }
  681. }