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);
49 } catch (Exception $e) {
50 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
52 $metadata = OpenGraphHelper::ogFromHtml($dom);
56 public function onEndShowHeadElements(Action $action)
58 switch ($action->getActionName()) {
60 $action->element('link',array('rel'=>'alternate',
61 'type'=>'application/json+oembed',
62 'href'=>common_local_url(
65 array('format'=>'json', 'url'=>
66 common_local_url('attachment',
67 array('attachment' => $action->attachment->id)))),
68 'title'=>'oEmbed'),null);
69 $action->element('link',array('rel'=>'alternate',
70 'type'=>'text/xml+oembed',
71 'href'=>common_local_url(
74 array('format'=>'xml','url'=>
75 common_local_url('attachment',
76 array('attachment' => $action->attachment->id)))),
77 'title'=>'oEmbed'),null);
80 if (!$action->notice->isLocal()) {
84 $action->element('link',array('rel'=>'alternate',
85 'type'=>'application/json+oembed',
86 'href'=>common_local_url(
89 array('format'=>'json','url'=>$action->notice->getUrl())),
90 'title'=>'oEmbed'),null);
91 $action->element('link',array('rel'=>'alternate',
92 'type'=>'text/xml+oembed',
93 'href'=>common_local_url(
96 array('format'=>'xml','url'=>$action->notice->getUrl())),
97 'title'=>'oEmbed'),null);
98 } catch (InvalidUrlException $e) {
99 // The notice is probably a share or similar, which don't
100 // have a representational URL of their own.
109 * Save embedding information for a File, if applicable.
111 * Normally this event is called through File::saveNew()
113 * @param File $file The newly inserted File object.
115 * @return boolean success
117 public function onEndFileSaveNew(File $file)
119 $fo = File_oembed::getKV('file_id', $file->id);
120 if ($fo instanceof File_oembed) {
121 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __FILE__);
125 if (isset($file->mimetype)
126 && (('text/html' === substr($file->mimetype, 0, 9)
127 || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
130 $oembed_data = File_oembed::_getOembed($file->url);
131 if ($oembed_data === false) {
132 throw new Exception('Did not get oEmbed data from URL');
134 } catch (Exception $e) {
138 File_oembed::saveNew($oembed_data, $file->id);
143 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
145 $oembed = File_oembed::getKV('file_id', $file->id);
146 if (empty($oembed->author_name) && empty($oembed->provider)) {
149 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
150 if (!empty($oembed->author_name)) {
151 $out->elementStart('div', 'fn vcard author');
152 if (empty($oembed->author_url)) {
153 $out->text($oembed->author_name);
155 $out->element('a', array('href' => $oembed->author_url,
157 $oembed->author_name);
160 if (!empty($oembed->provider)) {
161 $out->elementStart('div', 'fn vcard');
162 if (empty($oembed->provider_url)) {
163 $out->text($oembed->provider);
165 $out->element('a', array('href' => $oembed->provider_url,
170 $out->elementEnd('div');
173 public function onFileEnclosureMetadata(File $file, &$enclosure)
175 // Never treat generic HTML links as an enclosure type!
176 // But if we have oEmbed info, we'll consider it golden.
177 $oembed = File_oembed::getKV('file_id', $file->id);
178 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
182 foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
183 if (!empty($oembed->{$key})) {
184 $enclosure->{$key} = $oembed->{$key};
190 public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
193 $oembed = File_oembed::getByFile($file);
194 } catch (NoResultException $e) {
198 // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
199 switch ($oembed->type) {
203 if (!empty($oembed->html)
204 && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
205 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
208 'elements'=>'*+object+embed');
209 $out->raw(htmLawed($oembed->html,$config));
218 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
220 // If we are on a private node, we won't do any remote calls (just as a precaution until
221 // we can configure this from config.php for the private nodes)
222 if (common_config('site', 'private')) {
226 // All our remote Oembed images lack a local filename property in the File object
227 if (!is_null($file->filename)) {
232 // If we have proper oEmbed data, there should be an entry in the File_oembed
233 // and File_thumbnail tables respectively. If not, we're not going to do anything.
234 $file_oembed = File_oembed::getByFile($file);
235 $thumbnail = File_thumbnail::byFile($file);
236 } catch (Exception $e) {
237 // Not Oembed data, or at least nothing we either can or want to use.
242 $this->storeRemoteFileThumbnail($thumbnail);
243 } catch (AlreadyFulfilledException $e) {
247 $imgPath = $thumbnail->getPath();
253 * @return boolean false on no check made, provider name on success
254 * @throws ServerException if check is made but fails
256 protected function checkWhitelist($url)
258 if (!$this->check_whitelist) {
259 return false; // indicates "no check made"
262 $host = parse_url($url, PHP_URL_HOST);
263 foreach ($this->domain_whitelist as $regex => $provider) {
264 if (preg_match("/$regex/", $host)) {
265 return $provider; // we trust this source, return provider name
269 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
272 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
274 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
275 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
278 $url = $thumbnail->getUrl();
279 $this->checkWhitelist($url);
281 // First we download the file to memory and test whether it's actually an image file
282 // FIXME: To support remote video/whatever files, this needs reworking.
283 common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
284 $imgData = HTTPClient::quickGet($url);
285 $info = @getimagesizefromstring($imgData);
286 if ($info === false) {
287 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
288 } elseif (!$info[0] || !$info[1]) {
289 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
292 // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
293 $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
294 $fullpath = File_thumbnail::path($filename);
295 // Write the file to disk. Throw Exception on failure
296 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
297 throw new ServerException(_('Could not write downloaded file to disk.'));
299 // Get rid of the file from memory
302 // Updated our database for the file record
303 $orig = clone($thumbnail);
304 $thumbnail->filename = $filename;
305 $thumbnail->width = $info[0]; // array indexes documented on php.net:
306 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
307 // Throws exception on failure.
308 $thumbnail->updateWithKeys($orig, 'file_id');
311 public function onPluginVersion(array &$versions)
313 $versions[] = array('name' => 'Oembed',
314 'version' => GNUSOCIAL_VERSION,
315 'author' => 'Mikael Nordfeldth',
316 'homepage' => 'http://gnu.io/',
318 // TRANS: Plugin description.
319 _m('Plugin for using and representing Oembed data.'));