3 if (!defined('GNUSOCIAL')) { exit(1); }
5 class OembedPlugin extends Plugin
7 // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
8 // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
9 public $domain_whitelist = array( // hostname => service provider
10 '^i\d*\.ytimg\.com$' => 'YouTube',
11 '^i\d*\.vimeocdn\.com$' => 'Vimeo',
13 public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
14 public $check_whitelist = false; // security/abuse precaution
16 protected $imgData = array();
18 // these should be declared protected everywhere
19 public function initialize()
23 $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
26 public function onCheckSchema()
28 $schema = Schema::get();
29 $schema->ensureTable('file_oembed', File_oembed::schemaDef());
33 public function onRouterInitialized(URLMapper $m)
35 $m->connect('main/oembed', array('action' => 'oembed'));
38 public function onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
41 common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
42 $api = oEmbedHelper::oEmbedEndpointFromHTML($dom);
43 common_log(LOG_INFO, 'Found oEmbed API endpoint ' . $api . ' for URL ' . $url);
45 'maxwidth' => common_config('thumbnail', 'width'),
46 'maxheight' => common_config('thumbnail', 'height'),
48 $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
50 // Facebook just gives us javascript in its oembed html,
51 // so use the content of the title element instead
52 if(strpos($url,'https://www.facebook.com/') === 0) {
53 $metadata->html = @$dom->getElementsByTagName('title')->item(0)->nodeValue;
56 // Wordpress sometimes also just gives us javascript, use og:description if it is available
57 $xpath = new DomXpath($dom);
58 $generatorNode = @$xpath->query('//meta[@name="generator"][1]')->item(0);
59 if ($generatorNode instanceof DomElement) {
60 // when wordpress only gives us javascript, the html stripped from tags
61 // is the same as the title, so this helps us to identify this (common) case
62 if(strpos($generatorNode->getAttribute('content'),'WordPress') === 0
63 && trim(strip_tags($metadata->html)) == trim($metadata->title)) {
64 $propertyNode = @$xpath->query('//meta[@property="og:description"][1]')->item(0);
65 if ($propertyNode instanceof DomElement) {
66 $metadata->html = $propertyNode->getAttribute('content');
70 } catch (Exception $e) {
71 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
73 $metadata = OpenGraphHelper::ogFromHtml($dom);
76 if (isset($metadata->thumbnail_url)) {
77 // sometimes sites serve the path, not the full URL, for images
78 // let's "be liberal in what you accept from others"!
79 // add protocol and host if the thumbnail_url starts with /
80 if(substr($metadata->thumbnail_url,0,1) == '/') {
81 $thumbnail_url_parsed = parse_url($metadata->url);
82 $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
85 // some wordpress opengraph implementations sometimes return a white blank image
86 // no need for us to save that!
87 if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
88 unset($metadata->thumbnail_url);
94 public function onEndShowHeadElements(Action $action)
96 switch ($action->getActionName()) {
98 $action->element('link',array('rel'=>'alternate',
99 'type'=>'application/json+oembed',
100 'href'=>common_local_url(
103 array('format'=>'json', 'url'=>
104 common_local_url('attachment',
105 array('attachment' => $action->attachment->getID())))),
107 $action->element('link',array('rel'=>'alternate',
108 'type'=>'text/xml+oembed',
109 'href'=>common_local_url(
112 array('format'=>'xml','url'=>
113 common_local_url('attachment',
114 array('attachment' => $action->attachment->getID())))),
118 if (!$action->notice->isLocal()) {
122 $action->element('link',array('rel'=>'alternate',
123 'type'=>'application/json+oembed',
124 'href'=>common_local_url(
127 array('format'=>'json','url'=>$action->notice->getUrl())),
129 $action->element('link',array('rel'=>'alternate',
130 'type'=>'text/xml+oembed',
131 'href'=>common_local_url(
134 array('format'=>'xml','url'=>$action->notice->getUrl())),
136 } catch (InvalidUrlException $e) {
137 // The notice is probably a share or similar, which don't
138 // have a representational URL of their own.
146 public function onEndShowStylesheets(Action $action) {
147 $action->cssLink($this->path('css/oembed.css'));
152 * Save embedding information for a File, if applicable.
154 * Normally this event is called through File::saveNew()
156 * @param File $file The newly inserted File object.
158 * @return boolean success
160 public function onEndFileSaveNew(File $file)
162 $fo = File_oembed::getKV('file_id', $file->getID());
163 if ($fo instanceof File_oembed) {
164 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->getID()}", __FILE__);
168 if (isset($file->mimetype)
169 && (('text/html' === substr($file->mimetype, 0, 9)
170 || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
173 $oembed_data = File_oembed::_getOembed($file->url);
174 if ($oembed_data === false) {
175 throw new Exception('Did not get oEmbed data from URL');
177 $file->setTitle($oembed_data->title);
178 } catch (Exception $e) {
179 common_log(LOG_WARNING, sprintf(__METHOD__.': %s thrown when getting oEmbed data: %s', get_class($e), _ve($e->getMessage())));
183 File_oembed::saveNew($oembed_data, $file->getID());
188 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
190 $oembed = File_oembed::getKV('file_id', $file->getID());
191 if (empty($oembed->author_name) && empty($oembed->provider)) {
194 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
195 if (!empty($oembed->author_name)) {
196 $out->elementStart('div', 'fn vcard author');
197 if (empty($oembed->author_url)) {
198 $out->text($oembed->author_name);
200 $out->element('a', array('href' => $oembed->author_url,
202 $oembed->author_name);
205 if (!empty($oembed->provider)) {
206 $out->elementStart('div', 'fn vcard');
207 if (empty($oembed->provider_url)) {
208 $out->text($oembed->provider);
210 $out->element('a', array('href' => $oembed->provider_url,
215 $out->elementEnd('div');
218 public function onFileEnclosureMetadata(File $file, &$enclosure)
220 // Never treat generic HTML links as an enclosure type!
221 // But if we have oEmbed info, we'll consider it golden.
222 $oembed = File_oembed::getKV('file_id', $file->getID());
223 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
227 foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
228 if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
229 $enclosure->{$key} = $oembed->{$key};
235 public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
238 $oembed = File_oembed::getByFile($file);
239 } catch (NoResultException $e) {
243 // Show thumbnail as usual if it's a photo.
244 if ($oembed->type === 'photo') {
248 $out->elementStart('article', ['class'=>'h-entry oembed']);
249 $out->elementStart('header');
251 $thumb = $file->getThumbnail(128, 128);
252 $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
254 } catch (Exception $e) {
255 $out->element('div', ['class'=>'error'], $e->getMessage());
257 $out->elementStart('h5', ['class'=>'p-name oembed']);
258 $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
259 $out->elementEnd('h5');
260 $out->elementStart('div', ['class'=>'p-author oembed']);
261 if (!empty($oembed->author_name)) {
262 // TRANS: text before the author name of oEmbed attachment representation
263 // FIXME: The whole "By x from y" should be i18n because of different language constructions.
264 $out->text(_('By '));
265 $attrs = ['class'=>'h-card p-author'];
266 if (!empty($oembed->author_url)) {
267 $attrs['href'] = $oembed->author_url;
272 $out->element($tag, $attrs, $oembed->author_name);
274 if (!empty($oembed->provider)) {
275 // TRANS: text between the oEmbed author name and provider url
276 // FIXME: The whole "By x from y" should be i18n because of different language constructions.
277 $out->text(_(' from '));
278 $attrs = ['class'=>'h-card'];
279 if (!empty($oembed->provider_url)) {
280 $attrs['href'] = $oembed->provider_url;
285 $out->element($tag, $attrs, $oembed->provider);
287 $out->elementEnd('div');
288 $out->elementEnd('header');
289 $out->elementStart('div', ['class'=>'p-summary oembed']);
290 $out->raw(common_purify($oembed->html));
291 $out->elementEnd('div');
292 $out->elementStart('footer');
293 $out->elementEnd('footer');
294 $out->elementEnd('article');
299 public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
302 $oembed = File_oembed::getByFile($file);
303 } catch (NoResultException $e) {
307 // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
308 switch ($oembed->type) {
311 if (!empty($oembed->html)
312 && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
313 require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
314 $purifier = new HTMLPurifier();
315 // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
316 $out->raw($purifier->purify($oembed->html));
325 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
327 // If we are on a private node, we won't do any remote calls (just as a precaution until
328 // we can configure this from config.php for the private nodes)
329 if (common_config('site', 'private')) {
333 // All our remote Oembed images lack a local filename property in the File object
334 if (!is_null($file->filename)) {
335 common_debug(sprintf('Filename of file id==%d is not null (%s), so nothing oEmbed should handle.', $file->getID(), _ve($file->filename)));
340 // If we have proper oEmbed data, there should be an entry in the File_oembed
341 // and File_thumbnail tables respectively. If not, we're not going to do anything.
342 $file_oembed = File_oembed::getByFile($file);
343 $thumbnail = File_thumbnail::byFile($file);
344 } catch (NoResultException $e) {
345 // Not Oembed data, or at least nothing we either can or want to use.
346 common_debug('No oEmbed data found for file id=='.$file->getID());
351 $this->storeRemoteFileThumbnail($thumbnail);
352 } catch (AlreadyFulfilledException $e) {
354 } catch (Exception $e) {
355 common_debug(sprintf('oEmbed encountered an exception (%s) for file id==%d: %s', get_class($e), $file->getID(), _ve($e->getMessage())));
359 $imgPath = $thumbnail->getPath();
365 * @return boolean false on no check made, provider name on success
366 * @throws ServerException if check is made but fails
368 protected function checkWhitelist($url)
370 if (!$this->check_whitelist) {
371 return false; // indicates "no check made"
374 $host = parse_url($url, PHP_URL_HOST);
375 foreach ($this->domain_whitelist as $regex => $provider) {
376 if (preg_match("/$regex/", $host)) {
377 return $provider; // we trust this source, return provider name
381 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
384 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
386 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
387 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->getFileId()));
390 $remoteUrl = $thumbnail->getUrl();
391 $this->checkWhitelist($remoteUrl);
393 $http = new HTTPClient();
394 // First see if it's too large for us
395 common_debug(__METHOD__ . ': '.sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $thumbnail->getFileId(), $remoteUrl));
396 $head = $http->head($remoteUrl);
397 if (!$head->isOk()) {
398 common_log(LOG_WARNING, 'HEAD request returned HTTP failure, so we will abort now and delete the thumbnail object.');
399 $thumbnail->delete();
402 common_debug('HEAD request returned HTTP success, so we will continue.');
404 $remoteUrl = $head->getEffectiveUrl(); // to avoid going through redirects again
406 $headers = $head->getHeader();
407 $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
409 // FIXME: I just copied some checks from StoreRemoteMedia, maybe we should have other checks for thumbnails? Or at least embed into some class somewhere.
410 if (empty($filesize)) {
411 // file size not specified on remote server
412 common_debug(sprintf('%s: Ignoring remote thumbnail because we did not get a content length for thumbnail for file id==%u', __CLASS__, $thumbnail->getFileId()));
414 } elseif ($filesize > common_config('attachments', 'file_quota')) {
415 // file too big according to site configuration
416 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()));
420 // Then we download the file to memory and test whether it's actually an image file
421 // FIXME: To support remote video/whatever files, this needs reworking.
422 common_debug(sprintf('Downloading remote thumbnail for file id==%u (should be size %u) with effective URL: %s', $thumbnail->getFileId(), $filesize, _ve($remoteUrl)));
423 $imgData = HTTPClient::quickGet($remoteUrl);
424 $info = @getimagesizefromstring($imgData);
425 if ($info === false) {
426 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
427 } elseif (!$info[0] || !$info[1]) {
428 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
431 $ext = File::guessMimeExtension($info['mime']);
433 $filename = sprintf('oembed-%d.%s', $thumbnail->getFileId(), $ext);
434 $fullpath = File_thumbnail::path($filename);
435 // Write the file to disk. Throw Exception on failure
436 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
437 throw new ServerException(_('Could not write downloaded file to disk.'));
439 // Get rid of the file from memory
442 // Updated our database for the file record
443 $orig = clone($thumbnail);
444 $thumbnail->filename = $filename;
445 $thumbnail->width = $info[0]; // array indexes documented on php.net:
446 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
447 // Throws exception on failure.
448 $thumbnail->updateWithKeys($orig);
451 public function onPluginVersion(array &$versions)
453 $versions[] = array('name' => 'Oembed',
454 'version' => GNUSOCIAL_VERSION,
455 'author' => 'Mikael Nordfeldth',
456 'homepage' => 'http://gnu.io/',
458 // TRANS: Plugin description.
459 _m('Plugin for using and representing Oembed data.'));