OembedPlugin.php 20 KB

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