]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
Vimeo oEmbed thumbnail host added to whitelist
[quix0rs-gnu-social.git] / plugins / Oembed / OembedPlugin.php
1 <?php
2
3 if (!defined('GNUSOCIAL')) { exit(1); }
4
5 class OembedPlugin extends Plugin
6 {
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',
12                                     );
13     public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
14     public $check_whitelist  = true;    // security/abuse precaution
15
16     protected $imgData = array();
17
18     // these should be declared protected everywhere
19     public function initialize()
20     {
21         parent::initialize();
22
23         $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
24     }
25
26     public function onCheckSchema()
27     {
28         $schema = Schema::get();
29         $schema->ensureTable('file_oembed', File_oembed::schemaDef());
30         return true;
31     }
32
33     public function onRouterInitialized(URLMapper $m)
34     {
35         $m->connect('main/oembed', array('action' => 'oembed'));
36     }
37
38     public function onEndShowHeadElements(Action $action)
39     {
40         switch ($action->getActionName()) {
41         case 'attachment':
42             $action->element('link',array('rel'=>'alternate',
43                 'type'=>'application/json+oembed',
44                 'href'=>common_local_url(
45                     'oembed',
46                     array(),
47                     array('format'=>'json', 'url'=>
48                         common_local_url('attachment',
49                             array('attachment' => $action->attachment->id)))),
50                 'title'=>'oEmbed'),null);
51             $action->element('link',array('rel'=>'alternate',
52                 'type'=>'text/xml+oembed',
53                 'href'=>common_local_url(
54                     'oembed',
55                     array(),
56                     array('format'=>'xml','url'=>
57                         common_local_url('attachment',
58                             array('attachment' => $action->attachment->id)))),
59                 'title'=>'oEmbed'),null);
60             break;
61         case 'shownotice':
62             try {
63                 $action->element('link',array('rel'=>'alternate',
64                     'type'=>'application/json+oembed',
65                     'href'=>common_local_url(
66                         'oembed',
67                         array(),
68                         array('format'=>'json','url'=>$action->notice->getUrl())),
69                     'title'=>'oEmbed'),null);
70                 $action->element('link',array('rel'=>'alternate',
71                     'type'=>'text/xml+oembed',
72                     'href'=>common_local_url(
73                         'oembed',
74                         array(),
75                         array('format'=>'xml','url'=>$action->notice->getUrl())),
76                     'title'=>'oEmbed'),null);
77             } catch (InvalidUrlException $e) {
78                 // The notice is probably a share or similar, which don't
79                 // have a representational URL of their own.
80             }
81             break;
82         }
83
84         return true;
85     }
86
87     /**
88      * Save embedding information for a File, if applicable.
89      *
90      * Normally this event is called through File::saveNew()
91      *
92      * @param File   $file       The newly inserted File object.
93      * @param array  $redir_data lookup data eg from File_redirection::where()
94      * @param string $given_url
95      *
96      * @return boolean success
97      */
98     public function onEndFileSaveNew(File $file, array $redir_data, $given_url)
99     {
100         $fo = File_oembed::getKV('file_id', $file->id);
101         if ($fo instanceof File_oembed) {
102             common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
103              return true;
104         }
105
106         if (isset($redir_data['oembed']['json'])
107                 && !empty($redir_data['oembed']['json'])) {
108             File_oembed::saveNew($redir_data['oembed']['json'], $file->id);
109         } elseif (isset($redir_data['type'])
110                 && (('text/html' === substr($redir_data['type'], 0, 9)
111                 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
112
113             try {
114                 $oembed_data = File_oembed::_getOembed($given_url);
115                 if ($oembed_data === false) {
116                     throw new Exception('Did not get oEmbed data from URL');
117                 }
118             } catch (Exception $e) {
119                 return true;
120             }
121
122             File_oembed::saveNew($oembed_data, $file->id);
123         }
124         return true;
125     }
126
127     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
128     {
129         $oembed = File_oembed::getKV('file_id', $file->id);
130         if (empty($oembed->author_name) && empty($oembed->provider)) {
131             return true;
132         }
133         $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
134         if (!empty($oembed->author_name)) {
135             $out->elementStart('div', 'fn vcard author');
136             if (empty($oembed->author_url)) {
137                 $out->text($oembed->author_name);
138             } else {
139                 $out->element('a', array('href' => $oembed->author_url,
140                                          'class' => 'url'),
141                                 $oembed->author_name);
142             }
143         }
144         if (!empty($oembed->provider)) {
145             $out->elementStart('div', 'fn vcard');
146             if (empty($oembed->provider_url)) {
147                 $out->text($oembed->provider);
148             } else {
149                 $out->element('a', array('href' => $oembed->provider_url,
150                                          'class' => 'url'),
151                                 $oembed->provider);
152             }
153         }
154         $out->elementEnd('div');
155     }
156
157     public function onFileEnclosureMetadata(File $file, &$enclosure)
158     {
159         // Never treat generic HTML links as an enclosure type!
160         // But if we have oEmbed info, we'll consider it golden.
161         $oembed = File_oembed::getKV('file_id', $file->id);
162         if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
163             return true;
164         }
165
166         foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
167             if (!empty($oembed->{$key})) {
168                 $enclosure->{$key} = $oembed->{$key};
169             }
170         }
171         return true;
172     }
173     
174     public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
175     {
176         $oembed = File_oembed::getKV('file_id', $file->id);
177         if (empty($oembed->type)) {
178             return true;
179         }
180         switch ($oembed->type) {
181         case 'rich':
182         case 'video':
183         case 'link':
184             if (!empty($oembed->html)
185                     && (StatusNet::isAjax() || common_config('attachments', 'show_html'))) {
186                 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
187                 $config = array(
188                     'safe'=>1,
189                     'elements'=>'*+object+embed');
190                 $out->raw(htmLawed($oembed->html,$config));
191             }
192             break;
193
194         case 'photo':
195             $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
196             break;
197
198         default:
199             Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
200         }
201     }
202
203     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
204     {
205         // If we are on a private node, we won't do any remote calls (just as a precaution until
206         // we can configure this from config.php for the private nodes)
207         if (common_config('site', 'private')) {
208             return true;
209         }
210
211         // All our remote Oembed images lack a local filename property in the File object
212         if ($file->filename !== null) {
213             return true;
214         }
215
216         try {
217             // If we have proper oEmbed data, there should be an entry in the File_oembed
218             // and File_thumbnail tables respectively. If not, we're not going to do anything.
219             $file_oembed = File_oembed::byFile($file);
220             $thumbnail   = File_thumbnail::byFile($file);
221         } catch (Exception $e) {
222             // Not Oembed data, or at least nothing we either can or want to use.
223             return true;
224         }
225
226         try {
227             $this->storeRemoteFileThumbnail($thumbnail);
228         } catch (AlreadyFulfilledException $e) {
229             // aw yiss!
230         }
231
232         $imgPath = $thumbnail->getPath();
233
234         return false;
235     }
236
237     /**
238      * @return boolean          false on no check made, provider name on success
239      * @throws ServerException  if check is made but fails
240      */
241     protected function checkWhitelist($url)
242     {
243         if (!$this->check_whitelist) {
244             return false;   // indicates "no check made"
245         }
246
247         $host = parse_url($url, PHP_URL_HOST);
248         foreach ($this->domain_whitelist as $regex => $provider) {
249             if (preg_match("/$regex/", $host)) {
250                 return $provider;    // we trust this source, return provider name
251             }
252         }
253
254         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
255     }
256
257     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
258     {
259         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
260             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
261         }
262
263         $url = $thumbnail->getUrl();
264         $this->checkWhitelist($url);
265
266         // First we download the file to memory and test whether it's actually an image file
267         // FIXME: To support remote video/whatever files, this needs reworking.
268         common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
269         $imgData = HTTPClient::quickGet($url);
270         $info = @getimagesizefromstring($imgData);
271         if ($info === false) {
272             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
273         } elseif (!$info[0] || !$info[1]) {
274             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
275         }
276
277         // We'll trust sha256 not to have collision issues any time soon :)
278         $filename = hash('sha256', $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
279         $fullpath = File_thumbnail::path($filename);
280         // Write the file to disk. Throw Exception on failure
281         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
282             throw new ServerException(_('Could not write downloaded file to disk.'));
283         }
284         // Get rid of the file from memory
285         unset($imgData);
286
287         // Updated our database for the file record
288         $orig = clone($thumbnail);
289         $thumbnail->filename = $filename;
290         $thumbnail->width = $info[0];    // array indexes documented on php.net:
291         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
292         // Throws exception on failure.
293         $thumbnail->updateWithKeys($orig, 'file_id');
294     }
295
296     public function onPluginVersion(array &$versions)
297     {
298         $versions[] = array('name' => 'Oembed',
299                             'version' => GNUSOCIAL_VERSION,
300                             'author' => 'Mikael Nordfeldth',
301                             'homepage' => 'http://gnu.io/',
302                             'description' =>
303                             // TRANS: Plugin description.
304                             _m('Plugin for using and representing Oembed data.'));
305         return true;
306     }
307 }