3 if (!defined('GNUSOCIAL')) { exit(1); }
5 class OembedPlugin extends Plugin
7 const PLUGIN_VERSION = '2.0.0';
9 // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
10 // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
11 public $domain_whitelist = array( // hostname => service provider
12 '^i\d*\.ytimg\.com$' => 'YouTube',
13 '^i\d*\.vimeocdn\.com$' => 'Vimeo',
15 public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
16 public $check_whitelist = false; // security/abuse precaution
18 protected $imgData = array();
20 // these should be declared protected everywhere
21 public function initialize()
25 $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
28 public function onCheckSchema()
30 $schema = Schema::get();
31 $schema->ensureTable('file_oembed', File_oembed::schemaDef());
35 public function onRouterInitialized(URLMapper $m)
37 $m->connect('main/oembed', array('action' => 'oembed'));
40 public function onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
43 common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
44 $api = oEmbedHelper::oEmbedEndpointFromHTML($dom);
45 common_log(LOG_INFO, 'Found oEmbed API endpoint ' . $api . ' for URL ' . $url);
47 'maxwidth' => common_config('thumbnail', 'width'),
48 'maxheight' => common_config('thumbnail', 'height'),
50 $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
52 // Facebook just gives us javascript in its oembed html,
53 // so use the content of the title element instead
54 if(strpos($url,'https://www.facebook.com/') === 0) {
55 $metadata->html = @$dom->getElementsByTagName('title')->item(0)->nodeValue;
58 // Wordpress sometimes also just gives us javascript, use og:description if it is available
59 $xpath = new DomXpath($dom);
60 $generatorNode = @$xpath->query('//meta[@name="generator"][1]')->item(0);
61 if ($generatorNode instanceof DomElement) {
62 // when wordpress only gives us javascript, the html stripped from tags
63 // is the same as the title, so this helps us to identify this (common) case
64 if(strpos($generatorNode->getAttribute('content'),'WordPress') === 0
65 && trim(strip_tags($metadata->html)) == trim($metadata->title)) {
66 $propertyNode = @$xpath->query('//meta[@property="og:description"][1]')->item(0);
67 if ($propertyNode instanceof DomElement) {
68 $metadata->html = $propertyNode->getAttribute('content');
72 } catch (Exception $e) {
73 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
75 $metadata = OpenGraphHelper::ogFromHtml($dom);
78 if (isset($metadata->thumbnail_url)) {
79 // sometimes sites serve the path, not the full URL, for images
80 // let's "be liberal in what you accept from others"!
81 // add protocol and host if the thumbnail_url starts with /
82 if(substr($metadata->thumbnail_url,0,1) == '/') {
83 $thumbnail_url_parsed = parse_url($metadata->url);
84 $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
87 // some wordpress opengraph implementations sometimes return a white blank image
88 // no need for us to save that!
89 if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
90 unset($metadata->thumbnail_url);
96 public function onEndShowHeadElements(Action $action)
98 switch ($action->getActionName()) {
100 $action->element('link',array('rel'=>'alternate',
101 'type'=>'application/json+oembed',
102 'href'=>common_local_url(
105 array('format'=>'json', 'url'=>
106 common_local_url('attachment',
107 array('attachment' => $action->attachment->getID())))),
109 $action->element('link',array('rel'=>'alternate',
110 'type'=>'text/xml+oembed',
111 'href'=>common_local_url(
114 array('format'=>'xml','url'=>
115 common_local_url('attachment',
116 array('attachment' => $action->attachment->getID())))),
120 if (!$action->notice->isLocal()) {
124 $action->element('link',array('rel'=>'alternate',
125 'type'=>'application/json+oembed',
126 'href'=>common_local_url(
129 array('format'=>'json','url'=>$action->notice->getUrl())),
131 $action->element('link',array('rel'=>'alternate',
132 'type'=>'text/xml+oembed',
133 'href'=>common_local_url(
136 array('format'=>'xml','url'=>$action->notice->getUrl())),
138 } catch (InvalidUrlException $e) {
139 // The notice is probably a share or similar, which don't
140 // have a representational URL of their own.
148 public function onEndShowStylesheets(Action $action) {
149 $action->cssLink($this->path('css/oembed.css'));
154 * Save embedding information for a File, if applicable.
156 * Normally this event is called through File::saveNew()
158 * @param File $file The newly inserted File object.
160 * @return boolean success
162 public function onEndFileSaveNew(File $file)
164 $fo = File_oembed::getKV('file_id', $file->getID());
165 if ($fo instanceof File_oembed) {
166 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->getID()}", __FILE__);
170 if (isset($file->mimetype)
171 && (('text/html' === substr($file->mimetype, 0, 9)
172 || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
175 $oembed_data = File_oembed::_getOembed($file->url);
176 if ($oembed_data === false) {
177 throw new Exception('Did not get oEmbed data from URL');
179 $file->setTitle($oembed_data->title);
180 } catch (Exception $e) {
181 common_log(LOG_WARNING, sprintf(__METHOD__.': %s thrown when getting oEmbed data: %s', get_class($e), _ve($e->getMessage())));
185 File_oembed::saveNew($oembed_data, $file->getID());
190 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
192 $oembed = File_oembed::getKV('file_id', $file->getID());
193 if (empty($oembed->author_name) && empty($oembed->provider)) {
196 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
197 if (!empty($oembed->author_name)) {
198 $out->elementStart('div', 'fn vcard author');
199 if (empty($oembed->author_url)) {
200 $out->text($oembed->author_name);
202 $out->element('a', array('href' => $oembed->author_url,
204 $oembed->author_name);
207 if (!empty($oembed->provider)) {
208 $out->elementStart('div', 'fn vcard');
209 if (empty($oembed->provider_url)) {
210 $out->text($oembed->provider);
212 $out->element('a', array('href' => $oembed->provider_url,
217 $out->elementEnd('div');
220 public function onFileEnclosureMetadata(File $file, &$enclosure)
222 // Never treat generic HTML links as an enclosure type!
223 // But if we have oEmbed info, we'll consider it golden.
224 $oembed = File_oembed::getKV('file_id', $file->getID());
225 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
229 foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
230 if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
231 $enclosure->{$key} = $oembed->{$key};
237 public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
240 $oembed = File_oembed::getByFile($file);
241 } catch (NoResultException $e) {
245 // Show thumbnail as usual if it's a photo.
246 if ($oembed->type === 'photo') {
250 $out->elementStart('article', ['class'=>'h-entry oembed']);
251 $out->elementStart('header');
253 $thumb = $file->getThumbnail(128, 128);
254 $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
256 } catch (Exception $e) {
257 $out->element('div', ['class'=>'error'], $e->getMessage());
259 $out->elementStart('h5', ['class'=>'p-name oembed']);
260 $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
261 $out->elementEnd('h5');
262 $out->elementStart('div', ['class'=>'p-author oembed']);
263 if (!empty($oembed->author_name)) {
264 // TRANS: text before the author name of oEmbed attachment representation
265 // FIXME: The whole "By x from y" should be i18n because of different language constructions.
266 $out->text(_('By '));
267 $attrs = ['class'=>'h-card p-author'];
268 if (!empty($oembed->author_url)) {
269 $attrs['href'] = $oembed->author_url;
274 $out->element($tag, $attrs, $oembed->author_name);
276 if (!empty($oembed->provider)) {
277 // TRANS: text between the oEmbed author name and provider url
278 // FIXME: The whole "By x from y" should be i18n because of different language constructions.
279 $out->text(_(' from '));
280 $attrs = ['class'=>'h-card'];
281 if (!empty($oembed->provider_url)) {
282 $attrs['href'] = $oembed->provider_url;
287 $out->element($tag, $attrs, $oembed->provider);
289 $out->elementEnd('div');
290 $out->elementEnd('header');
291 $out->elementStart('div', ['class'=>'p-summary oembed']);
292 $out->raw(common_purify($oembed->html));
293 $out->elementEnd('div');
294 $out->elementStart('footer');
295 $out->elementEnd('footer');
296 $out->elementEnd('article');
301 public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
304 $oembed = File_oembed::getByFile($file);
305 } catch (NoResultException $e) {
309 // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
310 switch ($oembed->type) {
313 if (!empty($oembed->html)
314 && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
315 require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
316 $purifier = new HTMLPurifier();
317 // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
318 $out->raw($purifier->purify($oembed->html));
327 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
329 // If we are on a private node, we won't do any remote calls (just as a precaution until
330 // we can configure this from config.php for the private nodes)
331 if (common_config('site', 'private')) {
335 // All our remote Oembed images lack a local filename property in the File object
336 if (!is_null($file->filename)) {
337 common_debug(sprintf('Filename of file id==%d is not null (%s), so nothing oEmbed should handle.', $file->getID(), _ve($file->filename)));
342 // If we have proper oEmbed data, there should be an entry in the File_oembed
343 // and File_thumbnail tables respectively. If not, we're not going to do anything.
344 $file_oembed = File_oembed::getByFile($file);
345 $thumbnail = File_thumbnail::byFile($file);
346 } catch (NoResultException $e) {
347 // Not Oembed data, or at least nothing we either can or want to use.
348 common_debug('No oEmbed data found for file id=='.$file->getID());
353 $this->storeRemoteFileThumbnail($thumbnail);
354 } catch (AlreadyFulfilledException $e) {
356 } catch (Exception $e) {
357 common_debug(sprintf('oEmbed encountered an exception (%s) for file id==%d: %s', get_class($e), $file->getID(), _ve($e->getMessage())));
361 $imgPath = $thumbnail->getPath();
367 * @return boolean false on no check made, provider name on success
368 * @throws ServerException if check is made but fails
370 protected function checkWhitelist($url)
372 if (!$this->check_whitelist) {
373 return false; // indicates "no check made"
376 $host = parse_url($url, PHP_URL_HOST);
377 foreach ($this->domain_whitelist as $regex => $provider) {
378 if (preg_match("/$regex/", $host)) {
379 return $provider; // we trust this source, return provider name
383 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
386 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
388 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
389 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->getFileId()));
392 $remoteUrl = $thumbnail->getUrl();
393 $this->checkWhitelist($remoteUrl);
395 $http = new HTTPClient();
396 // First see if it's too large for us
397 common_debug(__METHOD__ . ': '.sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $thumbnail->getFileId(), $remoteUrl));
398 $head = $http->head($remoteUrl);
399 if (!$head->isOk()) {
400 common_log(LOG_WARNING, 'HEAD request returned HTTP failure, so we will abort now and delete the thumbnail object.');
401 $thumbnail->delete();
404 common_debug('HEAD request returned HTTP success, so we will continue.');
406 $remoteUrl = $head->getEffectiveUrl(); // to avoid going through redirects again
408 $headers = $head->getHeader();
409 $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
411 // FIXME: I just copied some checks from StoreRemoteMedia, maybe we should have other checks for thumbnails? Or at least embed into some class somewhere.
412 if (empty($filesize)) {
413 // file size not specified on remote server
414 common_debug(sprintf('%s: Ignoring remote thumbnail because we did not get a content length for thumbnail for file id==%u', __CLASS__, $thumbnail->getFileId()));
416 } elseif ($filesize > common_config('attachments', 'file_quota')) {
417 // file too big according to site configuration
418 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()));
422 // Then we download the file to memory and test whether it's actually an image file
423 // FIXME: To support remote video/whatever files, this needs reworking.
424 common_debug(sprintf('Downloading remote thumbnail for file id==%u (should be size %u) with effective URL: %s', $thumbnail->getFileId(), $filesize, _ve($remoteUrl)));
425 $imgData = HTTPClient::quickGet($remoteUrl);
426 $info = @getimagesizefromstring($imgData);
427 if ($info === false) {
428 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
429 } elseif (!$info[0] || !$info[1]) {
430 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
433 $ext = File::guessMimeExtension($info['mime']);
435 $filename = sprintf('oembed-%d.%s', $thumbnail->getFileId(), $ext);
436 $fullpath = File_thumbnail::path($filename);
437 // Write the file to disk. Throw Exception on failure
438 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
439 throw new ServerException(_('Could not write downloaded file to disk.'));
441 // Get rid of the file from memory
444 // Updated our database for the file record
445 $orig = clone($thumbnail);
446 $thumbnail->filename = $filename;
447 $thumbnail->width = $info[0]; // array indexes documented on php.net:
448 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
449 // Throws exception on failure.
450 $thumbnail->updateWithKeys($orig);
453 public function onPluginVersion(array &$versions)
455 $versions[] = array('name' => 'Oembed',
456 'version' => self::PLUGIN_VERSION,
457 'author' => 'Mikael Nordfeldth',
458 'homepage' => 'http://gnu.io/',
460 // TRANS: Plugin description.
461 _m('Plugin for using and representing Oembed data.'));