]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
think I have managed to show oEmbed images better now
[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  = false;    // 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 onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
39     {
40         try {
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);
44             $params = array(
45                 'maxwidth' => common_config('thumbnail', 'width'),
46                 'maxheight' => common_config('thumbnail', 'height'),
47             );
48             $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
49
50         } catch (Exception $e) {
51             common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.');
52             // Just ignore it!
53         }
54     }
55
56     public function onEndShowHeadElements(Action $action)
57     {
58         switch ($action->getActionName()) {
59         case 'attachment':
60             $action->element('link',array('rel'=>'alternate',
61                 'type'=>'application/json+oembed',
62                 'href'=>common_local_url(
63                     'oembed',
64                     array(),
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(
72                     'oembed',
73                     array(),
74                     array('format'=>'xml','url'=>
75                         common_local_url('attachment',
76                             array('attachment' => $action->attachment->id)))),
77                 'title'=>'oEmbed'),null);
78             break;
79         case 'shownotice':
80             if (!$action->notice->isLocal()) {
81                 break;
82             }
83             try {
84                 $action->element('link',array('rel'=>'alternate',
85                     'type'=>'application/json+oembed',
86                     'href'=>common_local_url(
87                         'oembed',
88                         array(),
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(
94                         'oembed',
95                         array(),
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.
101             }
102             break;
103         }
104
105         return true;
106     }
107
108     /**
109      * Save embedding information for a File, if applicable.
110      *
111      * Normally this event is called through File::saveNew()
112      *
113      * @param File   $file       The newly inserted File object.
114      *
115      * @return boolean success
116      */
117     public function onEndFileSaveNew(File $file)
118     {
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__);
122             return true;
123         }
124
125         if (isset($file->mimetype)
126             && (('text/html' === substr($file->mimetype, 0, 9)
127             || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
128
129             try {
130                 $oembed_data = File_oembed::_getOembed($file->url);
131                 if ($oembed_data === false) {
132                     throw new Exception('Did not get oEmbed data from URL');
133                 }
134             } catch (Exception $e) {
135                 return true;
136             }
137
138             File_oembed::saveNew($oembed_data, $file->id);
139         }
140         return true;
141     }
142
143     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
144     {
145         $oembed = File_oembed::getKV('file_id', $file->id);
146         if (empty($oembed->author_name) && empty($oembed->provider)) {
147             return true;
148         }
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);
154             } else {
155                 $out->element('a', array('href' => $oembed->author_url,
156                                          'class' => 'url'),
157                                 $oembed->author_name);
158             }
159         }
160         if (!empty($oembed->provider)) {
161             $out->elementStart('div', 'fn vcard');
162             if (empty($oembed->provider_url)) {
163                 $out->text($oembed->provider);
164             } else {
165                 $out->element('a', array('href' => $oembed->provider_url,
166                                          'class' => 'url'),
167                                 $oembed->provider);
168             }
169         }
170         $out->elementEnd('div');
171     }
172
173     public function onFileEnclosureMetadata(File $file, &$enclosure)
174     {
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'))) {
179             return true;
180         }
181
182         foreach (array('mimetype', 'url', 'title', 'modified') as $key) {
183             if (!empty($oembed->{$key})) {
184                 $enclosure->{$key} = $oembed->{$key};
185             }
186         }
187         return true;
188     }
189     
190     public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
191     {
192         try {
193             $oembed = File_oembed::getByFile($file);
194         } catch (NoResultException $e) {
195             return true;
196         }
197
198         // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
199         switch ($oembed->type) {
200         case 'rich':
201         case 'video':
202         case 'link':
203             if (!empty($oembed->html)
204                     && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
205                 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
206                 $config = array(
207                     'safe'=>1,
208                     'elements'=>'*+object+embed');
209                 $out->raw(htmLawed($oembed->html,$config));
210             }
211             return false;
212             break;
213         }
214
215         return true;
216     }
217
218     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
219     {
220         // If we are on a private node, we won't do any remote calls (just as a precaution until
221         // we can configure this from config.php for the private nodes)
222         if (common_config('site', 'private')) {
223             return true;
224         }
225
226         // All our remote Oembed images lack a local filename property in the File object
227         if (!is_null($file->filename)) {
228             return true;
229         }
230
231         try {
232             // If we have proper oEmbed data, there should be an entry in the File_oembed
233             // and File_thumbnail tables respectively. If not, we're not going to do anything.
234             $file_oembed = File_oembed::getByFile($file);
235             $thumbnail   = File_thumbnail::byFile($file);
236         } catch (Exception $e) {
237             // Not Oembed data, or at least nothing we either can or want to use.
238             return true;
239         }
240
241         try {
242             $this->storeRemoteFileThumbnail($thumbnail);
243         } catch (AlreadyFulfilledException $e) {
244             // aw yiss!
245         }
246
247         $imgPath = $thumbnail->getPath();
248
249         return false;
250     }
251
252     /**
253      * @return boolean          false on no check made, provider name on success
254      * @throws ServerException  if check is made but fails
255      */
256     protected function checkWhitelist($url)
257     {
258         if (!$this->check_whitelist) {
259             return false;   // indicates "no check made"
260         }
261
262         $host = parse_url($url, PHP_URL_HOST);
263         foreach ($this->domain_whitelist as $regex => $provider) {
264             if (preg_match("/$regex/", $host)) {
265                 return $provider;    // we trust this source, return provider name
266             }
267         }
268
269         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
270     }
271
272     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
273     {
274         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
275             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
276         }
277
278         $url = $thumbnail->getUrl();
279         $this->checkWhitelist($url);
280
281         // First we download the file to memory and test whether it's actually an image file
282         // FIXME: To support remote video/whatever files, this needs reworking.
283         common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
284         $imgData = HTTPClient::quickGet($url);
285         $info = @getimagesizefromstring($imgData);
286         if ($info === false) {
287             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
288         } elseif (!$info[0] || !$info[1]) {
289             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
290         }
291
292         // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
293         $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
294         $fullpath = File_thumbnail::path($filename);
295         // Write the file to disk. Throw Exception on failure
296         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
297             throw new ServerException(_('Could not write downloaded file to disk.'));
298         }
299         // Get rid of the file from memory
300         unset($imgData);
301
302         // Updated our database for the file record
303         $orig = clone($thumbnail);
304         $thumbnail->filename = $filename;
305         $thumbnail->width = $info[0];    // array indexes documented on php.net:
306         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
307         // Throws exception on failure.
308         $thumbnail->updateWithKeys($orig, 'file_id');
309     }
310
311     public function onPluginVersion(array &$versions)
312     {
313         $versions[] = array('name' => 'Oembed',
314                             'version' => GNUSOCIAL_VERSION,
315                             'author' => 'Mikael Nordfeldth',
316                             'homepage' => 'http://gnu.io/',
317                             'description' =>
318                             // TRANS: Plugin description.
319                             _m('Plugin for using and representing Oembed data.'));
320         return true;
321     }
322 }