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 public $domain_whitelist = array( // hostname => service provider
9 'i.ytimg.com' => 'YouTube',
11 public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
12 public $check_whitelist = true; // security/abuse precaution
14 protected $imgData = array();
16 // these should be declared protected everywhere
17 public function initialize()
21 $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
24 public function onCheckSchema()
26 $schema = Schema::get();
27 $schema->ensureTable('file_oembed', File_oembed::schemaDef());
31 public function onRouterInitialized(URLMapper $m)
33 $m->connect('main/oembed', array('action' => 'oembed'));
36 public function onEndShowHeadElements(Action $action)
38 switch ($action->getActionName()) {
40 $action->element('link',array('rel'=>'alternate',
41 'type'=>'application/json+oembed',
42 'href'=>common_local_url(
45 array('format'=>'json', 'url'=>
46 common_local_url('attachment',
47 array('attachment' => $action->attachment->id)))),
48 'title'=>'oEmbed'),null);
49 $action->element('link',array('rel'=>'alternate',
50 'type'=>'text/xml+oembed',
51 'href'=>common_local_url(
54 array('format'=>'xml','url'=>
55 common_local_url('attachment',
56 array('attachment' => $action->attachment->id)))),
57 'title'=>'oEmbed'),null);
61 $action->element('link',array('rel'=>'alternate',
62 'type'=>'application/json+oembed',
63 'href'=>common_local_url(
66 array('format'=>'json','url'=>$action->notice->getUrl())),
67 'title'=>'oEmbed'),null);
68 $action->element('link',array('rel'=>'alternate',
69 'type'=>'text/xml+oembed',
70 'href'=>common_local_url(
73 array('format'=>'xml','url'=>$action->notice->getUrl())),
74 'title'=>'oEmbed'),null);
75 } catch (InvalidUrlException $e) {
76 // The notice is probably a share or similar, which don't
77 // have a representational URL of their own.
86 * Save embedding information for a File, if applicable.
88 * Normally this event is called through File::saveNew()
90 * @param File $file The newly inserted File object.
91 * @param array $redir_data lookup data eg from File_redirection::where()
92 * @param string $given_url
94 * @return boolean success
96 public function onEndFileSaveNew(File $file, array $redir_data, $given_url)
98 $fo = File_oembed::getKV('file_id', $file->id);
99 if ($fo instanceof File_oembed) {
100 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
104 if (isset($redir_data['oembed']['json'])
105 && !empty($redir_data['oembed']['json'])) {
106 File_oembed::saveNew($redir_data['oembed']['json'], $file->id);
107 } elseif (isset($redir_data['type'])
108 && (('text/html' === substr($redir_data['type'], 0, 9)
109 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
112 $oembed_data = File_oembed::_getOembed($given_url);
113 if ($oembed_data === false) {
114 throw new Exception('Did not get oEmbed data from URL');
116 } catch (Exception $e) {
120 File_oembed::saveNew($oembed_data, $file->id);
125 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
127 $oembed = File_oembed::getKV('file_id', $file->id);
128 if (empty($oembed->author_name) && empty($oembed->provider)) {
131 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
132 if (!empty($oembed->author_name)) {
133 $out->elementStart('div', 'fn vcard author');
134 if (empty($oembed->author_url)) {
135 $out->text($oembed->author_name);
137 $out->element('a', array('href' => $oembed->author_url,
139 $oembed->author_name);
142 if (!empty($oembed->provider)) {
143 $out->elementStart('div', 'fn vcard');
144 if (empty($oembed->provider_url)) {
145 $out->text($oembed->provider);
147 $out->element('a', array('href' => $oembed->provider_url,
152 $out->elementEnd('div');
155 public function onFileEnclosureMetadata(File $file, &$enclosure)
157 // Never treat generic HTML links as an enclosure type!
158 // But if we have oEmbed info, we'll consider it golden.
159 $oembed = File_oembed::getKV('file_id', $file->id);
160 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
164 foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
165 if (!empty($oembed->{$key})) {
166 $enclosure->{$key} = $oembed->{$key};
172 public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
174 $oembed = File_oembed::getKV('file_id', $file->id);
175 if (empty($oembed->type)) {
178 switch ($oembed->type) {
182 if (!empty($oembed->html)
183 && (StatusNet::isAjax() || common_config('attachments', 'show_html'))) {
184 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
187 'elements'=>'*+object+embed');
188 $out->raw(htmLawed($oembed->html,$config));
193 $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
197 Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
201 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
203 // If we are on a private node, we won't do any remote calls (just as a precaution until
204 // we can configure this from config.php for the private nodes)
205 if (common_config('site', 'private')) {
209 // All our remote Oembed images lack a local filename property in the File object
210 if ($file->filename !== null) {
215 // If we have proper oEmbed data, there should be an entry in the File_oembed
216 // and File_thumbnail tables respectively. If not, we're not going to do anything.
217 $file_oembed = File_oembed::byFile($file);
218 $thumbnail = File_thumbnail::byFile($file);
219 } catch (Exception $e) {
220 // Not Oembed data, or at least nothing we either can or want to use.
225 $this->storeRemoteFileThumbnail($thumbnail);
226 } catch (AlreadyFulfilledException $e) {
230 $imgPath = $thumbnail->getPath();
236 * @return boolean false on no check made, true on success
237 * @throws ServerException if check is made but fails
239 protected function checkWhitelist($url)
241 if (!$this->check_whitelist) {
242 return false; // indicates "no check made"
245 $host = parse_url($url, PHP_URL_HOST);
246 if (!in_array($host, array_keys($this->domain_whitelist))) {
247 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
250 return true; // we trust this source
253 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
255 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
256 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
259 $url = $thumbnail->getUrl();
260 $this->checkWhitelist($url);
262 // First we download the file to memory and test whether it's actually an image file
263 // FIXME: To support remote video/whatever files, this needs reworking.
264 common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
265 $imgData = HTTPClient::quickGet($url);
266 $info = @getimagesizefromstring($imgData);
267 if ($info === false) {
268 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
269 } elseif (!$info[0] || !$info[1]) {
270 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
273 // We'll trust sha256 not to have collision issues any time soon :)
274 $filename = hash('sha256', $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
275 $fullpath = File_thumbnail::path($filename);
276 // Write the file to disk. Throw Exception on failure
277 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
278 throw new ServerException(_('Could not write downloaded file to disk.'));
280 // Get rid of the file from memory
283 // Updated our database for the file record
284 $orig = clone($thumbnail);
285 $thumbnail->filename = $filename;
286 $thumbnail->width = $info[0]; // array indexes documented on php.net:
287 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
288 if (!$thumbnail->update($orig)) {
289 unlink($fullpath); // delete the file if database failed to write
290 throw new ServerException(_('Failed to update remotely downloaded file info in database.'));
294 public function onPluginVersion(array &$versions)
296 $versions[] = array('name' => 'Oembed',
297 'version' => GNUSOCIAL_VERSION,
298 'author' => 'Mikael Nordfeldth',
299 'homepage' => 'http://gnu.io/',
301 // TRANS: Plugin description.
302 _m('Plugin for using and representing Oembed data.'));