]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
Remote thumbnail fetching from trusted sources
[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     public $domain_whitelist = array(       // hostname => service provider
9                                     'i.ytimg.com' => 'YouTube',
10                                     );
11     public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
12     public $check_whitelist  = true;    // security/abuse precaution
13
14     protected $imgData = array();
15
16     // these should be declared protected everywhere
17     public function initialize()
18     {
19         parent::initialize();
20
21         $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
22     }
23
24     public function onCheckSchema()
25     {
26         $schema = Schema::get();
27         $schema->ensureTable('file_oembed', File_oembed::schemaDef());
28         return true;
29     }
30
31     public function onRouterInitialized(URLMapper $m)
32     {
33         $m->connect('main/oembed', array('action' => 'oembed'));
34     }
35
36     public function onEndShowHeadElements(Action $action)
37     {
38         switch ($action->getActionName()) {
39         case 'attachment':
40             $action->element('link',array('rel'=>'alternate',
41                 'type'=>'application/json+oembed',
42                 'href'=>common_local_url(
43                     'oembed',
44                     array(),
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(
52                     'oembed',
53                     array(),
54                     array('format'=>'xml','url'=>
55                         common_local_url('attachment',
56                             array('attachment' => $action->attachment->id)))),
57                 'title'=>'oEmbed'),null);
58             break;
59         case 'shownotice':
60             try {
61                 $action->element('link',array('rel'=>'alternate',
62                     'type'=>'application/json+oembed',
63                     'href'=>common_local_url(
64                         'oembed',
65                         array(),
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(
71                         'oembed',
72                         array(),
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.
78             }
79             break;
80         }
81
82         return true;
83     }
84
85     /**
86      * Save embedding information for a File, if applicable.
87      *
88      * Normally this event is called through File::saveNew()
89      *
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
93      *
94      * @return boolean success
95      */
96     public function onEndFileSaveNew(File $file, array $redir_data, $given_url)
97     {
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__);
101              return true;
102         }
103
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)))) {
110
111             try {
112                 $oembed_data = File_oembed::_getOembed($given_url);
113                 if ($oembed_data === false) {
114                     throw new Exception('Did not get oEmbed data from URL');
115                 }
116             } catch (Exception $e) {
117                 return true;
118             }
119
120             File_oembed::saveNew($oembed_data, $file->id);
121         }
122         return true;
123     }
124
125     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
126     {
127         $oembed = File_oembed::getKV('file_id', $file->id);
128         if (empty($oembed->author_name) && empty($oembed->provider)) {
129             return true;
130         }
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);
136             } else {
137                 $out->element('a', array('href' => $oembed->author_url,
138                                          'class' => 'url'),
139                                 $oembed->author_name);
140             }
141         }
142         if (!empty($oembed->provider)) {
143             $out->elementStart('div', 'fn vcard');
144             if (empty($oembed->provider_url)) {
145                 $out->text($oembed->provider);
146             } else {
147                 $out->element('a', array('href' => $oembed->provider_url,
148                                          'class' => 'url'),
149                                 $oembed->provider);
150             }
151         }
152         $out->elementEnd('div');
153     }
154
155     public function onFileEnclosureMetadata(File $file, &$enclosure)
156     {
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'))) {
161             return true;
162         }
163
164         foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
165             if (!empty($oembed->{$key})) {
166                 $enclosure->{$key} = $oembed->{$key};
167             }
168         }
169         return true;
170     }
171     
172     public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
173     {
174         $oembed = File_oembed::getKV('file_id', $file->id);
175         if (empty($oembed->type)) {
176             return true;
177         }
178         switch ($oembed->type) {
179         case 'rich':
180         case 'video':
181         case 'link':
182             if (!empty($oembed->html)
183                     && (StatusNet::isAjax() || common_config('attachments', 'show_html'))) {
184                 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
185                 $config = array(
186                     'safe'=>1,
187                     'elements'=>'*+object+embed');
188                 $out->raw(htmLawed($oembed->html,$config));
189             }
190             break;
191
192         case 'photo':
193             $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
194             break;
195
196         default:
197             Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
198         }
199     }
200
201     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
202     {
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')) {
206             return true;
207         }
208
209         // All our remote Oembed images lack a local filename property in the File object
210         if ($file->filename !== null) {
211             return true;
212         }
213
214         try {
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.
221             return true;
222         }
223
224         try {
225             $this->storeRemoteFileThumbnail($thumbnail);
226         } catch (AlreadyFulfilledException $e) {
227             // aw yiss!
228         }
229
230         $imgPath = $thumbnail->getPath();
231
232         return false;
233     }
234
235     /**
236      * @return boolean          false on no check made, true on success
237      * @throws ServerException  if check is made but fails
238      */
239     protected function checkWhitelist($url)
240     {
241         if (!$this->check_whitelist) {
242             return false;   // indicates "no check made"
243         }
244
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));
248         }
249
250         return true;    // we trust this source
251     }
252
253     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
254     {
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));
257         }
258
259         $url = $thumbnail->getUrl();
260         $this->checkWhitelist($url);
261
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)'));
271         }
272
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.'));
279         }
280         // Get rid of the file from memory
281         unset($imgData);
282
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.'));
291         }
292     }
293
294     public function onPluginVersion(array &$versions)
295     {
296         $versions[] = array('name' => 'Oembed',
297                             'version' => GNUSOCIAL_VERSION,
298                             'author' => 'Mikael Nordfeldth',
299                             'homepage' => 'http://gnu.io/',
300                             'description' =>
301                             // TRANS: Plugin description.
302                             _m('Plugin for using and representing Oembed data.'));
303         return true;
304     }
305 }