EmbedPlugin.php 24 KB

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