EmbedPlugin.php 29 KB

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