OembedPlugin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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->id)))),
  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->id)))),
  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->id);
  146. if ($fo instanceof File_oembed) {
  147. common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __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. } catch (Exception $e) {
  159. return true;
  160. }
  161. File_oembed::saveNew($oembed_data, $file->id);
  162. }
  163. return true;
  164. }
  165. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  166. {
  167. $oembed = File_oembed::getKV('file_id', $file->id);
  168. if (empty($oembed->author_name) && empty($oembed->provider)) {
  169. return true;
  170. }
  171. $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
  172. if (!empty($oembed->author_name)) {
  173. $out->elementStart('div', 'fn vcard author');
  174. if (empty($oembed->author_url)) {
  175. $out->text($oembed->author_name);
  176. } else {
  177. $out->element('a', array('href' => $oembed->author_url,
  178. 'class' => 'url'),
  179. $oembed->author_name);
  180. }
  181. }
  182. if (!empty($oembed->provider)) {
  183. $out->elementStart('div', 'fn vcard');
  184. if (empty($oembed->provider_url)) {
  185. $out->text($oembed->provider);
  186. } else {
  187. $out->element('a', array('href' => $oembed->provider_url,
  188. 'class' => 'url'),
  189. $oembed->provider);
  190. }
  191. }
  192. $out->elementEnd('div');
  193. }
  194. public function onFileEnclosureMetadata(File $file, &$enclosure)
  195. {
  196. // Never treat generic HTML links as an enclosure type!
  197. // But if we have oEmbed info, we'll consider it golden.
  198. $oembed = File_oembed::getKV('file_id', $file->id);
  199. if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
  200. return true;
  201. }
  202. foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
  203. if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
  204. $enclosure->{$key} = $oembed->{$key};
  205. }
  206. }
  207. return true;
  208. }
  209. public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
  210. {
  211. try {
  212. $oembed = File_oembed::getByFile($file);
  213. } catch (NoResultException $e) {
  214. return true;
  215. }
  216. // Show thumbnail as usual if it's a photo.
  217. if ($oembed->type === 'photo') {
  218. return true;
  219. }
  220. $out->elementStart('article', ['class'=>'h-entry oembed']);
  221. $out->elementStart('header');
  222. try {
  223. $thumb = $file->getThumbnail(128, 128);
  224. $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
  225. unset($thumb);
  226. } catch (Exception $e) {
  227. $out->element('div', ['class'=>'error'], $e->getMessage());
  228. }
  229. $out->elementStart('h5', ['class'=>'p-name oembed']);
  230. $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
  231. $out->elementEnd('h5');
  232. $out->elementStart('div', ['class'=>'p-author oembed']);
  233. if (!empty($oembed->author_name)) {
  234. // TRANS: text before the author name of oEmbed attachment representation
  235. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  236. $out->text(_('By '));
  237. $attrs = ['class'=>'h-card p-author'];
  238. if (!empty($oembed->author_url)) {
  239. $attrs['href'] = $oembed->author_url;
  240. $tag = 'a';
  241. } else {
  242. $tag = 'span';
  243. }
  244. $out->element($tag, $attrs, $oembed->author_name);
  245. }
  246. if (!empty($oembed->provider)) {
  247. // TRANS: text between the oEmbed author name and provider url
  248. // FIXME: The whole "By x from y" should be i18n because of different language constructions.
  249. $out->text(_(' from '));
  250. $attrs = ['class'=>'h-card'];
  251. if (!empty($oembed->provider_url)) {
  252. $attrs['href'] = $oembed->provider_url;
  253. $tag = 'a';
  254. } else {
  255. $tag = 'span';
  256. }
  257. $out->element($tag, $attrs, $oembed->provider);
  258. }
  259. $out->elementEnd('div');
  260. $out->elementEnd('header');
  261. $out->elementStart('div', ['class'=>'p-summary oembed']);
  262. $out->raw(common_purify($oembed->html));
  263. $out->elementEnd('div');
  264. $out->elementStart('footer');
  265. $out->elementEnd('footer');
  266. $out->elementEnd('article');
  267. return false;
  268. }
  269. public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
  270. {
  271. try {
  272. $oembed = File_oembed::getByFile($file);
  273. } catch (NoResultException $e) {
  274. return true;
  275. }
  276. // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
  277. switch ($oembed->type) {
  278. case 'video':
  279. case 'link':
  280. if (!empty($oembed->html)
  281. && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
  282. require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
  283. $purifier = new HTMLPurifier();
  284. // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
  285. $out->raw($purifier->purify($oembed->html));
  286. }
  287. return false;
  288. break;
  289. }
  290. return true;
  291. }
  292. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  293. {
  294. // If we are on a private node, we won't do any remote calls (just as a precaution until
  295. // we can configure this from config.php for the private nodes)
  296. if (common_config('site', 'private')) {
  297. return true;
  298. }
  299. // All our remote Oembed images lack a local filename property in the File object
  300. if (!is_null($file->filename)) {
  301. return true;
  302. }
  303. try {
  304. // If we have proper oEmbed data, there should be an entry in the File_oembed
  305. // and File_thumbnail tables respectively. If not, we're not going to do anything.
  306. $file_oembed = File_oembed::getByFile($file);
  307. $thumbnail = File_thumbnail::byFile($file);
  308. } catch (NoResultException $e) {
  309. // Not Oembed data, or at least nothing we either can or want to use.
  310. return true;
  311. }
  312. try {
  313. $this->storeRemoteFileThumbnail($thumbnail);
  314. } catch (AlreadyFulfilledException $e) {
  315. // aw yiss!
  316. }
  317. $imgPath = $thumbnail->getPath();
  318. return false;
  319. }
  320. /**
  321. * @return boolean false on no check made, provider name on success
  322. * @throws ServerException if check is made but fails
  323. */
  324. protected function checkWhitelist($url)
  325. {
  326. if (!$this->check_whitelist) {
  327. return false; // indicates "no check made"
  328. }
  329. $host = parse_url($url, PHP_URL_HOST);
  330. foreach ($this->domain_whitelist as $regex => $provider) {
  331. if (preg_match("/$regex/", $host)) {
  332. return $provider; // we trust this source, return provider name
  333. }
  334. }
  335. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  336. }
  337. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  338. {
  339. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  340. throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
  341. }
  342. $url = $thumbnail->getUrl();
  343. $this->checkWhitelist($url);
  344. // First we download the file to memory and test whether it's actually an image file
  345. // FIXME: To support remote video/whatever files, this needs reworking.
  346. common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
  347. $imgData = HTTPClient::quickGet($url);
  348. $info = @getimagesizefromstring($imgData);
  349. if ($info === false) {
  350. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
  351. } elseif (!$info[0] || !$info[1]) {
  352. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  353. }
  354. $ext = File::guessMimeExtension($info['mime']);
  355. // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
  356. $filename = 'oembed-'.hash(File::FILEHASH_ALG, $imgData) . ".{$ext}";
  357. $fullpath = File_thumbnail::path($filename);
  358. // Write the file to disk. Throw Exception on failure
  359. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  360. throw new ServerException(_('Could not write downloaded file to disk.'));
  361. }
  362. // Get rid of the file from memory
  363. unset($imgData);
  364. // Updated our database for the file record
  365. $orig = clone($thumbnail);
  366. $thumbnail->filename = $filename;
  367. $thumbnail->width = $info[0]; // array indexes documented on php.net:
  368. $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  369. // Throws exception on failure.
  370. $thumbnail->updateWithKeys($orig);
  371. }
  372. public function onPluginVersion(array &$versions)
  373. {
  374. $versions[] = array('name' => 'Oembed',
  375. 'version' => GNUSOCIAL_VERSION,
  376. 'author' => 'Mikael Nordfeldth',
  377. 'homepage' => 'http://gnu.io/',
  378. 'description' =>
  379. // TRANS: Plugin description.
  380. _m('Plugin for using and representing Oembed data.'));
  381. return true;
  382. }
  383. }