OembedPlugin.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. /**
  131. * Save embedding information for a File, if applicable.
  132. *
  133. * Normally this event is called through File::saveNew()
  134. *
  135. * @param File $file The newly inserted File object.
  136. *
  137. * @return boolean success
  138. */
  139. public function onEndFileSaveNew(File $file)
  140. {
  141. $fo = File_oembed::getKV('file_id', $file->id);
  142. if ($fo instanceof File_oembed) {
  143. common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __FILE__);
  144. return true;
  145. }
  146. if (isset($file->mimetype)
  147. && (('text/html' === substr($file->mimetype, 0, 9)
  148. || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
  149. try {
  150. $oembed_data = File_oembed::_getOembed($file->url);
  151. if ($oembed_data === false) {
  152. throw new Exception('Did not get oEmbed data from URL');
  153. }
  154. } catch (Exception $e) {
  155. return true;
  156. }
  157. File_oembed::saveNew($oembed_data, $file->id);
  158. }
  159. return true;
  160. }
  161. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  162. {
  163. $oembed = File_oembed::getKV('file_id', $file->id);
  164. if (empty($oembed->author_name) && empty($oembed->provider)) {
  165. return true;
  166. }
  167. $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
  168. if (!empty($oembed->author_name)) {
  169. $out->elementStart('div', 'fn vcard author');
  170. if (empty($oembed->author_url)) {
  171. $out->text($oembed->author_name);
  172. } else {
  173. $out->element('a', array('href' => $oembed->author_url,
  174. 'class' => 'url'),
  175. $oembed->author_name);
  176. }
  177. }
  178. if (!empty($oembed->provider)) {
  179. $out->elementStart('div', 'fn vcard');
  180. if (empty($oembed->provider_url)) {
  181. $out->text($oembed->provider);
  182. } else {
  183. $out->element('a', array('href' => $oembed->provider_url,
  184. 'class' => 'url'),
  185. $oembed->provider);
  186. }
  187. }
  188. $out->elementEnd('div');
  189. }
  190. public function onFileEnclosureMetadata(File $file, &$enclosure)
  191. {
  192. // Never treat generic HTML links as an enclosure type!
  193. // But if we have oEmbed info, we'll consider it golden.
  194. $oembed = File_oembed::getKV('file_id', $file->id);
  195. if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
  196. return true;
  197. }
  198. foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
  199. if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
  200. $enclosure->{$key} = $oembed->{$key};
  201. }
  202. }
  203. return true;
  204. }
  205. public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
  206. {
  207. try {
  208. $oembed = File_oembed::getByFile($file);
  209. } catch (NoResultException $e) {
  210. return true;
  211. }
  212. // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
  213. switch ($oembed->type) {
  214. case 'video':
  215. case 'link':
  216. if (!empty($oembed->html)
  217. && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
  218. require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
  219. $purifier = new HTMLPurifier();
  220. // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
  221. $out->raw($purifier->purify($oembed->html));
  222. }
  223. return false;
  224. break;
  225. }
  226. return true;
  227. }
  228. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  229. {
  230. // If we are on a private node, we won't do any remote calls (just as a precaution until
  231. // we can configure this from config.php for the private nodes)
  232. if (common_config('site', 'private')) {
  233. return true;
  234. }
  235. // All our remote Oembed images lack a local filename property in the File object
  236. if (!is_null($file->filename)) {
  237. return true;
  238. }
  239. try {
  240. // If we have proper oEmbed data, there should be an entry in the File_oembed
  241. // and File_thumbnail tables respectively. If not, we're not going to do anything.
  242. $file_oembed = File_oembed::getByFile($file);
  243. $thumbnail = File_thumbnail::byFile($file);
  244. } catch (NoResultException $e) {
  245. // Not Oembed data, or at least nothing we either can or want to use.
  246. return true;
  247. }
  248. try {
  249. $this->storeRemoteFileThumbnail($thumbnail);
  250. } catch (AlreadyFulfilledException $e) {
  251. // aw yiss!
  252. }
  253. $imgPath = $thumbnail->getPath();
  254. return false;
  255. }
  256. /**
  257. * @return boolean false on no check made, provider name on success
  258. * @throws ServerException if check is made but fails
  259. */
  260. protected function checkWhitelist($url)
  261. {
  262. if (!$this->check_whitelist) {
  263. return false; // indicates "no check made"
  264. }
  265. $host = parse_url($url, PHP_URL_HOST);
  266. foreach ($this->domain_whitelist as $regex => $provider) {
  267. if (preg_match("/$regex/", $host)) {
  268. return $provider; // we trust this source, return provider name
  269. }
  270. }
  271. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  272. }
  273. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  274. {
  275. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  276. throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
  277. }
  278. $url = $thumbnail->getUrl();
  279. $this->checkWhitelist($url);
  280. // First we download the file to memory and test whether it's actually an image file
  281. // FIXME: To support remote video/whatever files, this needs reworking.
  282. common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
  283. $imgData = HTTPClient::quickGet($url);
  284. $info = @getimagesizefromstring($imgData);
  285. if ($info === false) {
  286. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
  287. } elseif (!$info[0] || !$info[1]) {
  288. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  289. }
  290. // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
  291. $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
  292. $fullpath = File_thumbnail::path($filename);
  293. // Write the file to disk. Throw Exception on failure
  294. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  295. throw new ServerException(_('Could not write downloaded file to disk.'));
  296. }
  297. // Get rid of the file from memory
  298. unset($imgData);
  299. // Updated our database for the file record
  300. $orig = clone($thumbnail);
  301. $thumbnail->filename = $filename;
  302. $thumbnail->width = $info[0]; // array indexes documented on php.net:
  303. $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  304. // Throws exception on failure.
  305. $thumbnail->updateWithKeys($orig);
  306. }
  307. public function onPluginVersion(array &$versions)
  308. {
  309. $versions[] = array('name' => 'Oembed',
  310. 'version' => GNUSOCIAL_VERSION,
  311. 'author' => 'Mikael Nordfeldth',
  312. 'homepage' => 'http://gnu.io/',
  313. 'description' =>
  314. // TRANS: Plugin description.
  315. _m('Plugin for using and representing Oembed data.'));
  316. return true;
  317. }
  318. }