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 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 } catch (Exception $e) {
51 common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
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 onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
193 $oembed = File_oembed::getByFile($file);
194 } catch (NoResultException $e) {
198 switch ($oembed->type) {
202 if (!empty($oembed->html)
203 && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
204 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
207 'elements'=>'*+object+embed');
208 $out->raw(htmLawed($oembed->html,$config));
213 $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
217 Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
221 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
223 // If we are on a private node, we won't do any remote calls (just as a precaution until
224 // we can configure this from config.php for the private nodes)
225 if (common_config('site', 'private')) {
229 // All our remote Oembed images lack a local filename property in the File object
230 if (!is_null($file->filename)) {
235 // If we have proper oEmbed data, there should be an entry in the File_oembed
236 // and File_thumbnail tables respectively. If not, we're not going to do anything.
237 $file_oembed = File_oembed::getByFile($file);
238 $thumbnail = File_thumbnail::byFile($file);
239 } catch (Exception $e) {
240 // Not Oembed data, or at least nothing we either can or want to use.
245 $this->storeRemoteFileThumbnail($thumbnail);
246 } catch (AlreadyFulfilledException $e) {
250 $imgPath = $thumbnail->getPath();
256 * @return boolean false on no check made, provider name on success
257 * @throws ServerException if check is made but fails
259 protected function checkWhitelist($url)
261 if (!$this->check_whitelist) {
262 return false; // indicates "no check made"
265 $host = parse_url($url, PHP_URL_HOST);
266 foreach ($this->domain_whitelist as $regex => $provider) {
267 if (preg_match("/$regex/", $host)) {
268 return $provider; // we trust this source, return provider name
272 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
275 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
277 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
278 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
281 $url = $thumbnail->getUrl();
282 $this->checkWhitelist($url);
284 // First we download the file to memory and test whether it's actually an image file
285 // FIXME: To support remote video/whatever files, this needs reworking.
286 common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
287 $imgData = HTTPClient::quickGet($url);
288 $info = @getimagesizefromstring($imgData);
289 if ($info === false) {
290 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
291 } elseif (!$info[0] || !$info[1]) {
292 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
295 // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
296 $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
297 $fullpath = File_thumbnail::path($filename);
298 // Write the file to disk. Throw Exception on failure
299 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
300 throw new ServerException(_('Could not write downloaded file to disk.'));
302 // Get rid of the file from memory
305 // Updated our database for the file record
306 $orig = clone($thumbnail);
307 $thumbnail->filename = $filename;
308 $thumbnail->width = $info[0]; // array indexes documented on php.net:
309 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
310 // Throws exception on failure.
311 $thumbnail->updateWithKeys($orig, 'file_id');
314 public function onPluginVersion(array &$versions)
316 $versions[] = array('name' => 'Oembed',
317 'version' => GNUSOCIAL_VERSION,
318 'author' => 'Mikael Nordfeldth',
319 'homepage' => 'http://gnu.io/',
321 // TRANS: Plugin description.
322 _m('Plugin for using and representing Oembed data.'));