OembedPlugin.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 = true; // 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 onEndShowHeadElements(Action $action)
  31. {
  32. switch ($action->getActionName()) {
  33. case 'attachment':
  34. $action->element('link',array('rel'=>'alternate',
  35. 'type'=>'application/json+oembed',
  36. 'href'=>common_local_url(
  37. 'oembed',
  38. array(),
  39. array('format'=>'json', 'url'=>
  40. common_local_url('attachment',
  41. array('attachment' => $action->attachment->id)))),
  42. 'title'=>'oEmbed'),null);
  43. $action->element('link',array('rel'=>'alternate',
  44. 'type'=>'text/xml+oembed',
  45. 'href'=>common_local_url(
  46. 'oembed',
  47. array(),
  48. array('format'=>'xml','url'=>
  49. common_local_url('attachment',
  50. array('attachment' => $action->attachment->id)))),
  51. 'title'=>'oEmbed'),null);
  52. break;
  53. case 'shownotice':
  54. try {
  55. $action->element('link',array('rel'=>'alternate',
  56. 'type'=>'application/json+oembed',
  57. 'href'=>common_local_url(
  58. 'oembed',
  59. array(),
  60. array('format'=>'json','url'=>$action->notice->getUrl())),
  61. 'title'=>'oEmbed'),null);
  62. $action->element('link',array('rel'=>'alternate',
  63. 'type'=>'text/xml+oembed',
  64. 'href'=>common_local_url(
  65. 'oembed',
  66. array(),
  67. array('format'=>'xml','url'=>$action->notice->getUrl())),
  68. 'title'=>'oEmbed'),null);
  69. } catch (InvalidUrlException $e) {
  70. // The notice is probably a share or similar, which don't
  71. // have a representational URL of their own.
  72. }
  73. break;
  74. }
  75. return true;
  76. }
  77. /**
  78. * Save embedding information for a File, if applicable.
  79. *
  80. * Normally this event is called through File::saveNew()
  81. *
  82. * @param File $file The newly inserted File object.
  83. * @param array $redir_data lookup data eg from File_redirection::where()
  84. * @param string $given_url
  85. *
  86. * @return boolean success
  87. */
  88. public function onEndFileSaveNew(File $file, array $redir_data, $given_url)
  89. {
  90. $fo = File_oembed::getKV('file_id', $file->id);
  91. if ($fo instanceof File_oembed) {
  92. common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
  93. return true;
  94. }
  95. if (isset($redir_data['oembed']['json'])
  96. && !empty($redir_data['oembed']['json'])) {
  97. File_oembed::saveNew($redir_data['oembed']['json'], $file->id);
  98. } elseif (isset($redir_data['type'])
  99. && (('text/html' === substr($redir_data['type'], 0, 9)
  100. || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
  101. try {
  102. $oembed_data = File_oembed::_getOembed($given_url);
  103. if ($oembed_data === false) {
  104. throw new Exception('Did not get oEmbed data from URL');
  105. }
  106. } catch (Exception $e) {
  107. return true;
  108. }
  109. File_oembed::saveNew($oembed_data, $file->id);
  110. }
  111. return true;
  112. }
  113. public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
  114. {
  115. $oembed = File_oembed::getKV('file_id', $file->id);
  116. if (empty($oembed->author_name) && empty($oembed->provider)) {
  117. return true;
  118. }
  119. $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
  120. if (!empty($oembed->author_name)) {
  121. $out->elementStart('div', 'fn vcard author');
  122. if (empty($oembed->author_url)) {
  123. $out->text($oembed->author_name);
  124. } else {
  125. $out->element('a', array('href' => $oembed->author_url,
  126. 'class' => 'url'),
  127. $oembed->author_name);
  128. }
  129. }
  130. if (!empty($oembed->provider)) {
  131. $out->elementStart('div', 'fn vcard');
  132. if (empty($oembed->provider_url)) {
  133. $out->text($oembed->provider);
  134. } else {
  135. $out->element('a', array('href' => $oembed->provider_url,
  136. 'class' => 'url'),
  137. $oembed->provider);
  138. }
  139. }
  140. $out->elementEnd('div');
  141. }
  142. public function onFileEnclosureMetadata(File $file, &$enclosure)
  143. {
  144. // Never treat generic HTML links as an enclosure type!
  145. // But if we have oEmbed info, we'll consider it golden.
  146. $oembed = File_oembed::getKV('file_id', $file->id);
  147. if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
  148. return true;
  149. }
  150. foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
  151. if (!empty($oembed->{$key})) {
  152. $enclosure->{$key} = $oembed->{$key};
  153. }
  154. }
  155. return true;
  156. }
  157. public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
  158. {
  159. $oembed = File_oembed::getKV('file_id', $file->id);
  160. if (empty($oembed->type)) {
  161. return true;
  162. }
  163. switch ($oembed->type) {
  164. case 'rich':
  165. case 'video':
  166. case 'link':
  167. if (!empty($oembed->html)
  168. && (StatusNet::isAjax() || common_config('attachments', 'show_html'))) {
  169. require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
  170. $config = array(
  171. 'safe'=>1,
  172. 'elements'=>'*+object+embed');
  173. $out->raw(htmLawed($oembed->html,$config));
  174. }
  175. break;
  176. case 'photo':
  177. $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
  178. break;
  179. default:
  180. Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
  181. }
  182. }
  183. public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
  184. {
  185. // If we are on a private node, we won't do any remote calls (just as a precaution until
  186. // we can configure this from config.php for the private nodes)
  187. if (common_config('site', 'private')) {
  188. return true;
  189. }
  190. // All our remote Oembed images lack a local filename property in the File object
  191. if ($file->filename !== null) {
  192. return true;
  193. }
  194. try {
  195. // If we have proper oEmbed data, there should be an entry in the File_oembed
  196. // and File_thumbnail tables respectively. If not, we're not going to do anything.
  197. $file_oembed = File_oembed::byFile($file);
  198. $thumbnail = File_thumbnail::byFile($file);
  199. } catch (Exception $e) {
  200. // Not Oembed data, or at least nothing we either can or want to use.
  201. return true;
  202. }
  203. try {
  204. $this->storeRemoteFileThumbnail($thumbnail);
  205. } catch (AlreadyFulfilledException $e) {
  206. // aw yiss!
  207. }
  208. $imgPath = $thumbnail->getPath();
  209. return false;
  210. }
  211. /**
  212. * @return boolean false on no check made, provider name on success
  213. * @throws ServerException if check is made but fails
  214. */
  215. protected function checkWhitelist($url)
  216. {
  217. if (!$this->check_whitelist) {
  218. return false; // indicates "no check made"
  219. }
  220. $host = parse_url($url, PHP_URL_HOST);
  221. foreach ($this->domain_whitelist as $regex => $provider) {
  222. if (preg_match("/$regex/", $host)) {
  223. return $provider; // we trust this source, return provider name
  224. }
  225. }
  226. throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
  227. }
  228. protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
  229. {
  230. if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
  231. throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
  232. }
  233. $url = $thumbnail->getUrl();
  234. $this->checkWhitelist($url);
  235. // First we download the file to memory and test whether it's actually an image file
  236. // FIXME: To support remote video/whatever files, this needs reworking.
  237. common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
  238. $imgData = HTTPClient::quickGet($url);
  239. $info = @getimagesizefromstring($imgData);
  240. if ($info === false) {
  241. throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
  242. } elseif (!$info[0] || !$info[1]) {
  243. throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
  244. }
  245. // We'll trust sha256 not to have collision issues any time soon :)
  246. $filename = hash('sha256', $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
  247. $fullpath = File_thumbnail::path($filename);
  248. // Write the file to disk. Throw Exception on failure
  249. if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
  250. throw new ServerException(_('Could not write downloaded file to disk.'));
  251. }
  252. // Get rid of the file from memory
  253. unset($imgData);
  254. // Updated our database for the file record
  255. $orig = clone($thumbnail);
  256. $thumbnail->filename = $filename;
  257. $thumbnail->width = $info[0]; // array indexes documented on php.net:
  258. $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
  259. // Throws exception on failure.
  260. $thumbnail->updateWithKeys($orig, 'file_id');
  261. }
  262. public function onPluginVersion(array &$versions)
  263. {
  264. $versions[] = array('name' => 'Oembed',
  265. 'version' => GNUSOCIAL_VERSION,
  266. 'author' => 'Mikael Nordfeldth',
  267. 'homepage' => 'http://gnu.io/',
  268. 'description' =>
  269. // TRANS: Plugin description.
  270. _m('Plugin for using and representing Oembed data.'));
  271. return true;
  272. }
  273. }