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',
12 public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
13 public $check_whitelist = true; // security/abuse precaution
15 protected $imgData = array();
17 // these should be declared protected everywhere
18 public function initialize()
22 $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
25 public function onCheckSchema()
27 $schema = Schema::get();
28 $schema->ensureTable('file_oembed', File_oembed::schemaDef());
32 public function onRouterInitialized(URLMapper $m)
34 $m->connect('main/oembed', array('action' => 'oembed'));
37 public function onEndShowHeadElements(Action $action)
39 switch ($action->getActionName()) {
41 $action->element('link',array('rel'=>'alternate',
42 'type'=>'application/json+oembed',
43 'href'=>common_local_url(
46 array('format'=>'json', 'url'=>
47 common_local_url('attachment',
48 array('attachment' => $action->attachment->id)))),
49 'title'=>'oEmbed'),null);
50 $action->element('link',array('rel'=>'alternate',
51 'type'=>'text/xml+oembed',
52 'href'=>common_local_url(
55 array('format'=>'xml','url'=>
56 common_local_url('attachment',
57 array('attachment' => $action->attachment->id)))),
58 'title'=>'oEmbed'),null);
62 $action->element('link',array('rel'=>'alternate',
63 'type'=>'application/json+oembed',
64 'href'=>common_local_url(
67 array('format'=>'json','url'=>$action->notice->getUrl())),
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'=>$action->notice->getUrl())),
75 'title'=>'oEmbed'),null);
76 } catch (InvalidUrlException $e) {
77 // The notice is probably a share or similar, which don't
78 // have a representational URL of their own.
87 * Save embedding information for a File, if applicable.
89 * Normally this event is called through File::saveNew()
91 * @param File $file The newly inserted File object.
92 * @param array $redir_data lookup data eg from File_redirection::where()
93 * @param string $given_url
95 * @return boolean success
97 public function onEndFileSaveNew(File $file, array $redir_data, $given_url)
99 $fo = File_oembed::getKV('file_id', $file->id);
100 if ($fo instanceof File_oembed) {
101 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
105 if (isset($redir_data['oembed']['json'])
106 && !empty($redir_data['oembed']['json'])) {
107 File_oembed::saveNew($redir_data['oembed']['json'], $file->id);
108 } elseif (isset($redir_data['type'])
109 && (('text/html' === substr($redir_data['type'], 0, 9)
110 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
113 $oembed_data = File_oembed::_getOembed($given_url);
114 if ($oembed_data === false) {
115 throw new Exception('Did not get oEmbed data from URL');
117 } catch (Exception $e) {
121 File_oembed::saveNew($oembed_data, $file->id);
126 public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
128 $oembed = File_oembed::getKV('file_id', $file->id);
129 if (empty($oembed->author_name) && empty($oembed->provider)) {
132 $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
133 if (!empty($oembed->author_name)) {
134 $out->elementStart('div', 'fn vcard author');
135 if (empty($oembed->author_url)) {
136 $out->text($oembed->author_name);
138 $out->element('a', array('href' => $oembed->author_url,
140 $oembed->author_name);
143 if (!empty($oembed->provider)) {
144 $out->elementStart('div', 'fn vcard');
145 if (empty($oembed->provider_url)) {
146 $out->text($oembed->provider);
148 $out->element('a', array('href' => $oembed->provider_url,
153 $out->elementEnd('div');
156 public function onFileEnclosureMetadata(File $file, &$enclosure)
158 // Never treat generic HTML links as an enclosure type!
159 // But if we have oEmbed info, we'll consider it golden.
160 $oembed = File_oembed::getKV('file_id', $file->id);
161 if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
165 foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
166 if (!empty($oembed->{$key})) {
167 $enclosure->{$key} = $oembed->{$key};
173 public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
175 $oembed = File_oembed::getKV('file_id', $file->id);
176 if (empty($oembed->type)) {
179 switch ($oembed->type) {
183 if (!empty($oembed->html)
184 && (StatusNet::isAjax() || common_config('attachments', 'show_html'))) {
185 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
188 'elements'=>'*+object+embed');
189 $out->raw(htmLawed($oembed->html,$config));
194 $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
198 Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
202 public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
204 // If we are on a private node, we won't do any remote calls (just as a precaution until
205 // we can configure this from config.php for the private nodes)
206 if (common_config('site', 'private')) {
210 // All our remote Oembed images lack a local filename property in the File object
211 if ($file->filename !== null) {
216 // If we have proper oEmbed data, there should be an entry in the File_oembed
217 // and File_thumbnail tables respectively. If not, we're not going to do anything.
218 $file_oembed = File_oembed::byFile($file);
219 $thumbnail = File_thumbnail::byFile($file);
220 } catch (Exception $e) {
221 // Not Oembed data, or at least nothing we either can or want to use.
226 $this->storeRemoteFileThumbnail($thumbnail);
227 } catch (AlreadyFulfilledException $e) {
231 $imgPath = $thumbnail->getPath();
237 * @return boolean false on no check made, provider name on success
238 * @throws ServerException if check is made but fails
240 protected function checkWhitelist($url)
242 if (!$this->check_whitelist) {
243 return false; // indicates "no check made"
246 $host = parse_url($url, PHP_URL_HOST);
247 foreach ($this->domain_whitelist as $regex => $provider) {
248 if (preg_match("/$regex/", $host)) {
249 return $provider; // we trust this source, return provider name
253 throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
256 protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
258 if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
259 throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
262 $url = $thumbnail->getUrl();
263 $this->checkWhitelist($url);
265 // First we download the file to memory and test whether it's actually an image file
266 // FIXME: To support remote video/whatever files, this needs reworking.
267 common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
268 $imgData = HTTPClient::quickGet($url);
269 $info = @getimagesizefromstring($imgData);
270 if ($info === false) {
271 throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
272 } elseif (!$info[0] || !$info[1]) {
273 throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
276 // We'll trust sha256 not to have collision issues any time soon :)
277 $filename = hash('sha256', $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
278 $fullpath = File_thumbnail::path($filename);
279 // Write the file to disk. Throw Exception on failure
280 if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
281 throw new ServerException(_('Could not write downloaded file to disk.'));
283 // Get rid of the file from memory
286 // Updated our database for the file record
287 $orig = clone($thumbnail);
288 $thumbnail->filename = $filename;
289 $thumbnail->width = $info[0]; // array indexes documented on php.net:
290 $thumbnail->height = $info[1]; // https://php.net/manual/en/function.getimagesize.php
291 // Throws exception on failure.
292 $thumbnail->updateWithKeys($orig);
295 public function onPluginVersion(array &$versions)
297 $versions[] = array('name' => 'Oembed',
298 'version' => GNUSOCIAL_VERSION,
299 'author' => 'Mikael Nordfeldth',
300 'homepage' => 'http://gnu.io/',
302 // TRANS: Plugin description.
303 _m('Plugin for using and representing Oembed data.'));