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 // sometimes sites serve the path, not the full URL, for images
77 // let's "be liberal in what you accept from others"!
78 // add protocol and host if the thumbnail_url starts with /
79 if(substr($metadata->thumbnail_url,0,1) == '/') {
80 $thumbnail_url_parsed = parse_url($metadata->url);
81 $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
84 // some wordpress opengraph implementations sometimes return a white blank image
85 // no need for us to save that!
86 if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
87 unset($metadata->thumbnail_url);
92 public function onEndShowHeadElements(Action $action)
94 switch ($action->getActionName()) {
96 $action->element('link',array('rel'=>'alternate',
97 'type'=>'application/json+oembed',
98 'href'=>common_local_url(
101 array('format'=>'json', 'url'=>
102 common_local_url('attachment',
103 array('attachment' => $action->attachment->id)))),
104 'title'=>'oEmbed'),null);
105 $action->element('link',array('rel'=>'alternate',
106 'type'=>'text/xml+oembed',
107 'href'=>common_local_url(
110 array('format'=>'xml','url'=>
111 common_local_url('attachment',
112 array('attachment' => $action->attachment->id)))),
113 'title'=>'oEmbed'),null);
116 if (!$action->notice->isLocal()) {
120 $action->element('link',array('rel'=>'alternate',
121 'type'=>'application/json+oembed',
122 'href'=>common_local_url(
125 array('format'=>'json','url'=>$action->notice->getUrl())),
126 'title'=>'oEmbed'),null);
127 $action->element('link',array('rel'=>'alternate',
128 'type'=>'text/xml+oembed',
129 'href'=>common_local_url(
132 array('format'=>'xml','url'=>$action->notice->getUrl())),
133 'title'=>'oEmbed'),null);
134 } catch (InvalidUrlException $e) {
135 // The notice is probably a share or similar, which don't
136 // have a representational URL of their own.
145 * Save embedding information for a File, if applicable.
147 * Normally this event is called through File::saveNew()
149 * @param File $file The newly inserted File object.
151 * @return boolean success
153 public function onEndFileSaveNew(File $file)
155 $fo = File_oembed::getKV('file_id', $file->id);
156 if ($fo instanceof File_oembed) {
157 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __FILE__);
161 if (isset($file->mimetype)
162 && (('text/html' === substr($file->mimetype, 0, 9)
163 || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
166 $oembed_data = File_oembed::_getOembed($file->url);
167 if ($oembed_data === false) {
168 throw new Exception('Did not get oEmbed data from URL');
170 } catch (Exception $e) {
174 File_oembed::saveNew($oembed_data, $file->id);
179 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
181 $oembed = File_oembed::getKV('file_id', $file->id);
182 if (empty($oembed->author_name) && empty($oembed->provider)) {
185 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
186 if (!empty($oembed->author_name)) {
187 $out->elementStart('div', 'fn vcard author');
188 if (empty($oembed->author_url)) {
189 $out->text($oembed->author_name);
191 $out->element('a', array('href' => $oembed->author_url,
193 $oembed->author_name);
196 if (!empty($oembed->provider)) {
197 $out->elementStart('div', 'fn vcard');
198 if (empty($oembed->provider_url)) {
199 $out->text($oembed->provider);
201 $out->element('a', array('href' => $oembed->provider_url,
206 $out->elementEnd('div');
209 public function onFileEnclosureMetadata(File $file, &$enclosure)
211 // Never treat generic HTML links as an enclosure type!
212 // But if we have oEmbed info, we'll consider it golden.
213 $oembed = File_oembed::getKV('file_id', $file->id);
214 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
218 foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
219 if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
220 $enclosure->{$key} = $oembed->{$key};
226 public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
229 $oembed = File_oembed::getByFile($file);
230 } catch (NoResultException $e) {
234 // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
235 switch ($oembed->type) {
239 if (!empty($oembed->html)
240 && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
241 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
244 'elements'=>'*+object+embed');
245 $out->raw(htmLawed($oembed->html,$config));
254 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
256 // If we are on a private node, we won't do any remote calls (just as a precaution until
257 // we can configure this from config.php for the private nodes)
258 if (common_config('site', 'private')) {
262 // All our remote Oembed images lack a local filename property in the File object
263 if (!is_null($file->filename)) {
268 // If we have proper oEmbed data, there should be an entry in the File_oembed
269 // and File_thumbnail tables respectively. If not, we're not going to do anything.
270 $file_oembed = File_oembed::getByFile($file);
271 $thumbnail = File_thumbnail::byFile($file);
272 } catch (Exception $e) {
273 // Not Oembed data, or at least nothing we either can or want to use.
278 $this->storeRemoteFileThumbnail($thumbnail);
279 } catch (AlreadyFulfilledException $e) {
283 $imgPath = $thumbnail->getPath();
289 * @return boolean false on no check made, provider name on success
290 * @throws ServerException if check is made but fails
292 protected function checkWhitelist($url)
294 if (!$this->check_whitelist) {
295 return false; // indicates "no check made"
298 $host = parse_url($url, PHP_URL_HOST);
299 foreach ($this->domain_whitelist as $regex => $provider) {
300 if (preg_match("/$regex/", $host)) {
301 return $provider; // we trust this source, return provider name
305 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
308 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
310 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
311 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
314 $url = $thumbnail->getUrl();
315 $this->checkWhitelist($url);
317 // First we download the file to memory and test whether it's actually an image file
318 // FIXME: To support remote video/whatever files, this needs reworking.
319 common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
320 $imgData = HTTPClient::quickGet($url);
321 $info = @getimagesizefromstring($imgData);
322 if ($info === false) {
323 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
324 } elseif (!$info[0] || !$info[1]) {
325 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
328 // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
329 $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
330 $fullpath = File_thumbnail::path($filename);
331 // Write the file to disk. Throw Exception on failure
332 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
333 throw new ServerException(_('Could not write downloaded file to disk.'));
335 // Get rid of the file from memory
338 // Updated our database for the file record
339 $orig = clone($thumbnail);
340 $thumbnail->filename = $filename;
341 $thumbnail->width = $info[0]; // array indexes documented on php.net:
342 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
343 // Throws exception on failure.
344 $thumbnail->updateWithKeys($orig, 'file_id');
347 public function onPluginVersion(array &$versions)
349 $versions[] = array('name' => 'Oembed',
350 'version' => GNUSOCIAL_VERSION,
351 'author' => 'Mikael Nordfeldth',
352 'homepage' => 'http://gnu.io/',
354 // TRANS: Plugin description.
355 _m('Plugin for using and representing Oembed data.'));