EmbedPlugin.php 27 KB

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