OembedPlugin.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. if (!defined('GNUSOCIAL')) { exit(1); }
  3. class OembedPlugin extends Plugin
  4. {
  5. // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
  6. // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
  7. public $domain_whitelist = array( // hostname => service provider
  8. '^i\d*\.ytimg\.com$' => 'YouTube',
  9. '^i\d*\.vimeocdn\.com$' => 'Vimeo',
  10. );
  11. public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
  12. public $check_whitelist = false; // security/abuse precaution
  13. protected $imgData = array();
  14. // these should be declared protected everywhere
  15. public function initialize()
  16. {
  17. parent::initialize();
  18. $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
  19. }
  20. public function onCheckSchema()
  21. {
  22. $schema = Schema::get();
  23. $schema->ensureTable('file_oembed', File_oembed::schemaDef());
  24. return true;
  25. }
  26. public function onRouterInitialized(URLMapper $m)
  27. {
  28. $m->connect('main/oembed', array('action' => 'oembed'));
  29. }
  30. public function onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
  31. {
  32. try {
  33. common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
  34. $api = oEmbedHelper::oEmbedEndpointFromHTML($dom);
  35. common_log(LOG_INFO, 'Found oEmbed API endpoint ' . $api . ' for URL ' . $url);
  36. $params = array(
  37. 'maxwidth' => common_config('thumbnail', 'width'),
  38. 'maxheight' => common_config('thumbnail', 'height'),
  39. );
  40. $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
  41. // Facebook just gives us javascript in its oembed html,
  42. // so use the content of the title element instead
  43. if(strpos($url,'https://www.facebook.com/') === 0) {
  44. $metadata->html = @$dom->getElementsByTagName('title')->item(0)->nodeValue;
  45. }
  46. // Wordpress sometimes also just gives us javascript, use og:description if it is available
  47. $xpath = new DomXpath($dom);
  48. $generatorNode = @$xpath->query('//meta[@name="generator"][1]')->item(0);
  49. if ($generatorNode instanceof DomElement) {
  50. // when wordpress only gives us javascript, the html stripped from tags
  51. // is the same as the title, so this helps us to identify this (common) case
  52. if(strpos($generatorNode->getAttribute('content'),'WordPress') === 0
  53. && trim(strip_tags($metadata->html)) == trim($metadata->title)) {
  54. $propertyNode = @$xpath->query('//meta[@property="og:description"][1]')->item(0);
  55. if ($propertyNode instanceof DomElement) {
  56. $metadata->html = $propertyNode->getAttribute('content');
  57. }
  58. }
  59. }
  60. } catch (Exception $e) {
  61. common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
  62. // Just ignore it!
  63. $metadata = OpenGraphHelper::ogFromHtml($dom);
  64. }
  65. if (isset($metadata->thumbnail_url)) {
  66. // sometimes sites serve the path, not the full URL, for images
  67. // let's "be liberal in what you accept from others"!
  68. // add protocol and host if the thumbnail_url starts with /
  69. if(substr($metadata->thumbnail_url,0,1) == '/') {
  70. $thumbnail_url_parsed = parse_url($metadata->url);
  71. $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
  72. }
  73. // some wordpress opengraph implementations sometimes return a white blank image
  74. // no need for us to save that!
  75. if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
  76. unset($metadata->thumbnail_url);
  77. }
  78. }
  79. }
  80. public function onEndShowHeadElements(Action $action)
  81. {
  82. switch ($action->getActionName()) {
  83. case 'attachment':
  84. $action->element('link',array('rel'=>'alternate',
  85. 'type'=>'application/json+oembed',
  86. 'href'=>common_local_url(
  87. 'oembed',
  88. array(),
  89. array('format'=>'json', 'url'=>
  90. common_local_url('attachment',
  91. array('attachment' => $action->attachment->getID())))),
  92. 'title'=>'oEmbed'),null);
  93. $action->element('link',array('rel'=>'alternate',
  94. 'type'=>'text/xml+oembed',
  95. 'href'=>common_local_url(
  96. 'oembed',
  97. array(),
  98. array('format'=>'xml','url'=>
  99. common_local_url('attachment',
  100. array('attachment' => $action->attachment->getID())))),
  101. 'title'=>'oEmbed'),null);
  102. break;
  103. case 'shownotice':
  104. if (!$action->notice->isLocal()) {
  105. break;
  106. }
  107. try {
  108. $action->element('link',array('rel'=>'alternate',
  109. 'type'=>'application/json+oembed',
  110. 'href'=>common_local_url(
  111. 'oembed',
  112. array(),
  113. array('format'=>'json','url'=>$action->notice->getUrl())),
  114. 'title'=>'oEmbed'),null);
  115. $action->element('link',array('rel'=>'alternate',
  116. 'type'=>'text/xml+oembed',
  117. 'href'=>common_local_url(
  118. 'oembed',
  119. array(),
  120. array('format'=>'xml','url'=>$action->notice->getUrl())),
  121. 'title'=>'oEmbed'),null);
  122. } catch (InvalidUrlException $e) {
  123. // The notice is probably a share or similar, which don't
  124. // have a representational URL of their own.
  125. }
  126. break;
  127. }
  128. return true;
  129. }
  130. public function onEndShowStylesheets(Action $action) {
  131. $action->cssLink($this->path('css/oembed.css'));
  132. return true;
  133. }
  134. /**
  135. * Save embedding information for a File, if applicable.
  136. *
  137. * Normally this event is called through File::saveNew()
  138. *
  139. * @param File $file The newly inserted File object.
  140. *
  141. * @return boolean success
  142. */
  143. public function onEndFileSaveNew(File $file)
  144. {
  145. $fo = File_oembed::getKV('file_id', $file->getID());
  146. if ($fo instanceof File_oembed) {
  147. common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->getID()}", __FILE__);
  148. return true;
  149. }
  150. if (isset($file->mimetype)
  151. && (('text/html' === substr($file->mimetype, 0, 9)
  152. || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
  153. try {
  154. $oembed_data = File_oembed::_getOembed($file->url);
  155. if ($oembed_data === false) {
  156. throw new Exception('Did not get oEmbed data from URL');
  157. }
  158. $file->setTitle($oembed_data->title);
  159. } catch (Exception $e) {
  160. common_log(LOG_WARNING, sprintf(__METHOD__.': %s thrown when getting oEmbed data: %s', get_class($e), _ve($e->getMessage())));
  161. return true;
  162. }
  163. File_oembed::saveNew($oembed_data, $file->getID());
  164. }
  165. return true;
  166. }
  167. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  168. {
  169. $oembed = File_oembed::getKV('file_id', $file->getID());
  170. if (empty($oembed->author_name) && empty($oembed->provider)) {
  171. return true;
  172. }
  173. $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
  174. if (!empty($oembed->author_name)) {
  175. $out->elementStart('div', 'fn vcard author');
  176. if (empty($oembed->author_url)) {
  177. $out->text($oembed->author_name);
  178. } else {
  179. $out->element('a', array('href' => $oembed->author_url,
  180. 'class' => 'url'),
  181. $oembed->author_name);
  182. }
  183. }
  184. if (!empty($oembed->provider)) {
  185. $out->elementStart('div', 'fn vcard');
  186. if (empty($oembed->provider_url)) {
  187. $out->text($oembed->provider);
  188. } else {
  189. $out->element('a', array('href' => $oembed->provider_url,
  190. 'class' => 'url'),
  191. $oembed->provider);
  192. }
  193. }
  194. $out->elementEnd('div');
  195. }
  196. public function onFileEnclosureMetadata(File $file, &$enclosure)
  197. {
  198. // Never treat generic HTML links as an enclosure type!
  199. // But if we have oEmbed info, we'll consider it golden.
  200. $oembed = File_oembed::getKV('file_id', $file->getID());
  201. if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
  202. return true;
  203. }
  204. foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
  205. if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
  206. $enclosure->{$key} = $oembed->{$key};
  207. }
  208. }
  209. return true;
  210. }
  211. public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
  212. {
  213. try {
  214. $oembed = File_oembed::getByFile($file);
  215. } catch (NoResultException $e) {
  216. return true;
  217. }
  218. // Show thumbnail as usual if it's a photo.
  219. if ($oembed->type === 'photo') {
  220. return true;
  221. }
  222. $out->elementStart('article', ['class'=>'h-entry oembed']);
  223. $out->elementStart('header');
  224. try {
  225. $thumb = $file->getThumbnail(128, 128);
  226. $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
  227. unset($thumb);
  228. } catch (Exception $e) {
  229. $out->element('div', ['class'=>'error'], $e->getMessage());
  230. }
  231. $out->elementStart('h5', ['class'=>'p-name oembed']);
  232. $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
  233. $out->elementEnd('h5');
  234. $out->elementStart('div', ['class'=>'p-author oembed']);
  235. if (!empty($oembed->author_name)) {
  236. // TRANS: text before the author name of oEmbed attachment representation
  237. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  238. $out->text(_('By '));
  239. $attrs = ['class'=>'h-card p-author'];
  240. if (!empty($oembed->author_url)) {
  241. $attrs['href'] = $oembed->author_url;
  242. $tag = 'a';
  243. } else {
  244. $tag = 'span';
  245. }
  246. $out->element($tag, $attrs, $oembed->author_name);
  247. }
  248. if (!empty($oembed->provider)) {
  249. // TRANS: text between the oEmbed author name and provider url
  250. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  251. $out->text(_(' from '));
  252. $attrs = ['class'=>'h-card'];
  253. if (!empty($oembed->provider_url)) {
  254. $attrs['href'] = $oembed->provider_url;
  255. $tag = 'a';
  256. } else {
  257. $tag = 'span';
  258. }
  259. $out->element($tag, $attrs, $oembed->provider);
  260. }
  261. $out->elementEnd('div');
  262. $out->elementEnd('header');
  263. $out->elementStart('div', ['class'=>'p-summary oembed']);
  264. $out->raw(common_purify($oembed->html));
  265. $out->elementEnd('div');
  266. $out->elementStart('footer');
  267. $out->elementEnd('footer');
  268. $out->elementEnd('article');
  269. return false;
  270. }
  271. public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
  272. {
  273. try {
  274. $oembed = File_oembed::getByFile($file);
  275. } catch (NoResultException $e) {
  276. return true;
  277. }
  278. // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
  279. switch ($oembed->type) {
  280. case 'video':
  281. case 'link':
  282. if (!empty($oembed->html)
  283. && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
  284. require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
  285. $purifier = new HTMLPurifier();
  286. // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
  287. $out->raw($purifier->purify($oembed->html));
  288. }
  289. return false;
  290. break;
  291. }
  292. return true;
  293. }
  294. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  295. {
  296. // If we are on a private node, we won't do any remote calls (just as a precaution until
  297. // we can configure this from config.php for the private nodes)
  298. if (common_config('site', 'private')) {
  299. return true;
  300. }
  301. // All our remote Oembed images lack a local filename property in the File object
  302. if (!is_null($file->filename)) {
  303. common_debug(sprintf('Filename of file id==%d is not null (%s), so nothing oEmbed should handle.', $file->getID(), _ve($file->filename)));
  304. return true;
  305. }
  306. try {
  307. // If we have proper oEmbed data, there should be an entry in the File_oembed
  308. // and File_thumbnail tables respectively. If not, we're not going to do anything.
  309. $file_oembed = File_oembed::getByFile($file);
  310. $thumbnail = File_thumbnail::byFile($file);
  311. } catch (NoResultException $e) {
  312. // Not Oembed data, or at least nothing we either can or want to use.
  313. common_debug('No oEmbed data found for file id=='.$file->getID());
  314. return true;
  315. }
  316. try {
  317. $this->storeRemoteFileThumbnail($thumbnail);
  318. } catch (AlreadyFulfilledException $e) {
  319. // aw yiss!
  320. } catch (Exception $e) {
  321. common_debug(sprintf('oEmbed encountered an exception (%s) for file id==%d: %s', get_class($e), $file->getID(), _ve($e->getMessage())));
  322. throw $e;
  323. }
  324. $imgPath = $thumbnail->getPath();
  325. return false;
  326. }
  327. /**
  328. * @return boolean false on no check made, provider name on success
  329. * @throws ServerException if check is made but fails
  330. */
  331. protected function checkWhitelist($url)
  332. {
  333. if (!$this->check_whitelist) {
  334. return false; // indicates "no check made"
  335. }
  336. $host = parse_url($url, PHP_URL_HOST);
  337. foreach ($this->domain_whitelist as $regex => $provider) {
  338. if (preg_match("/$regex/", $host)) {
  339. return $provider; // we trust this source, return provider name
  340. }
  341. }
  342. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  343. }
  344. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  345. {
  346. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  347. throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->getFileId()));
  348. }
  349. $remoteUrl = $thumbnail->getUrl();
  350. $this->checkWhitelist($remoteUrl);
  351. $http = new HTTPClient();
  352. // First see if it's too large for us
  353. common_debug(__METHOD__ . ': '.sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $thumbnail->getFileId(), $remoteUrl));
  354. $head = $http->head($remoteUrl);
  355. if (!$head->isOk()) {
  356. common_log(LOG_WARNING, 'HEAD request returned HTTP failure, so we will abort now and delete the thumbnail object.');
  357. $thumbnail->delete();
  358. return false;
  359. } else {
  360. common_debug('HEAD request returned HTTP success, so we will continue.');
  361. }
  362. $remoteUrl = $head->getEffectiveUrl(); // to avoid going through redirects again
  363. $headers = $head->getHeader();
  364. $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
  365. // FIXME: I just copied some checks from StoreRemoteMedia, maybe we should have other checks for thumbnails? Or at least embed into some class somewhere.
  366. if (empty($filesize)) {
  367. // file size not specified on remote server
  368. common_debug(sprintf('%s: Ignoring remote thumbnail because we did not get a content length for thumbnail for file id==%u', __CLASS__, $thumbnail->getFileId()));
  369. return true;
  370. } elseif ($filesize > common_config('attachments', 'file_quota')) {
  371. // file too big according to site configuration
  372. common_debug(sprintf('%s: Skip downloading remote thumbnail because content length (%u) is larger than file_quota (%u) for file id==%u', __CLASS__, intval($filesize), common_config('attachments', 'file_quota'), $thumbnail->getFileId()));
  373. return true;
  374. }
  375. // Then we download the file to memory and test whether it's actually an image file
  376. // FIXME: To support remote video/whatever files, this needs reworking.
  377. common_debug(sprintf('Downloading remote thumbnail for file id==%u (should be size %u) with effective URL: %s', $thumbnail->getFileId(), $filesize, _ve($remoteUrl)));
  378. $imgData = HTTPClient::quickGet($remoteUrl);
  379. $info = @getimagesizefromstring($imgData);
  380. if ($info === false) {
  381. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
  382. } elseif (!$info[0] || !$info[1]) {
  383. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  384. }
  385. $ext = File::guessMimeExtension($info['mime']);
  386. $filename = sprintf('oembed-%d.%s', $thumbnail->getFileId(), $ext);
  387. $fullpath = File_thumbnail::path($filename);
  388. // Write the file to disk. Throw Exception on failure
  389. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  390. throw new ServerException(_('Could not write downloaded file to disk.'));
  391. }
  392. // Get rid of the file from memory
  393. unset($imgData);
  394. // Updated our database for the file record
  395. $orig = clone($thumbnail);
  396. $thumbnail->filename = $filename;
  397. $thumbnail->width = $info[0]; // array indexes documented on php.net:
  398. $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  399. // Throws exception on failure.
  400. $thumbnail->updateWithKeys($orig);
  401. }
  402. public function onPluginVersion(array &$versions)
  403. {
  404. $versions[] = array('name' => 'Oembed',
  405. 'version' => GNUSOCIAL_VERSION,
  406. 'author' => 'Mikael Nordfeldth',
  407. 'homepage' => 'http://gnu.io/',
  408. 'description' =>
  409. // TRANS: Plugin description.
  410. _m('Plugin for using and representing Oembed data.'));
  411. return true;
  412. }
  413. }