]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
[TRANSLATION] Update license and copyright notice in translation files
[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     const PLUGIN_VERSION = '2.0.0';
8
9     // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
10     // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
11     public $domain_whitelist = array(       // hostname => service provider
12                                     '^i\d*\.ytimg\.com$' => 'YouTube',
13                                     '^i\d*\.vimeocdn\.com$' => 'Vimeo',
14                                     );
15     public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
16     public $check_whitelist  = false;    // security/abuse precaution
17
18     protected $imgData = array();
19
20     // these should be declared protected everywhere
21     public function initialize()
22     {
23         parent::initialize();
24
25         $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
26     }
27
28     public function onCheckSchema()
29     {
30         $schema = Schema::get();
31         $schema->ensureTable('file_oembed', File_oembed::schemaDef());
32         return true;
33     }
34
35     public function onRouterInitialized(URLMapper $m)
36     {
37         $m->connect('main/oembed', array('action' => 'oembed'));
38     }
39
40     public function onGetRemoteUrlMetadataFromDom($url, DOMDocument $dom, stdClass &$metadata)
41     {
42         try {
43             common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.');
44             $api = oEmbedHelper::oEmbedEndpointFromHTML($dom);
45             common_log(LOG_INFO, 'Found oEmbed API endpoint ' . $api . ' for URL ' . $url);
46             $params = array(
47                 'maxwidth' => common_config('thumbnail', 'width'),
48                 'maxheight' => common_config('thumbnail', 'height'),
49             );
50             $metadata = oEmbedHelper::getOembedFrom($api, $url, $params);
51             
52             // Facebook just gives us javascript in its oembed html, 
53             // so use the content of the title element instead
54             if(strpos($url,'https://www.facebook.com/') === 0) {
55               $metadata->html = @$dom->getElementsByTagName('title')->item(0)->nodeValue;
56             }
57         
58             // Wordpress sometimes also just gives us javascript, use og:description if it is available
59             $xpath = new DomXpath($dom);
60             $generatorNode = @$xpath->query('//meta[@name="generator"][1]')->item(0);
61             if ($generatorNode instanceof DomElement) {
62                 // when wordpress only gives us javascript, the html stripped from tags
63                 // is the same as the title, so this helps us to identify this (common) case
64                 if(strpos($generatorNode->getAttribute('content'),'WordPress') === 0
65                 && trim(strip_tags($metadata->html)) == trim($metadata->title)) {
66                     $propertyNode = @$xpath->query('//meta[@property="og:description"][1]')->item(0);
67                     if ($propertyNode instanceof DomElement) {
68                         $metadata->html = $propertyNode->getAttribute('content');
69                     }
70                 }
71             }
72         } catch (Exception $e) {
73             common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers, trying OpenGraph from HTML.');
74             // Just ignore it!
75             $metadata = OpenGraphHelper::ogFromHtml($dom);
76         }
77
78         if (isset($metadata->thumbnail_url)) {
79             // sometimes sites serve the path, not the full URL, for images
80             // let's "be liberal in what you accept from others"!
81             // add protocol and host if the thumbnail_url starts with /
82             if(substr($metadata->thumbnail_url,0,1) == '/') {
83                 $thumbnail_url_parsed = parse_url($metadata->url);
84                 $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
85             }
86         
87             // some wordpress opengraph implementations sometimes return a white blank image
88             // no need for us to save that!
89             if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
90                 unset($metadata->thumbnail_url);
91             }
92         }
93
94     }
95
96     public function onEndShowHeadElements(Action $action)
97     {
98         switch ($action->getActionName()) {
99         case 'attachment':
100             $action->element('link',array('rel'=>'alternate',
101                 'type'=>'application/json+oembed',
102                 'href'=>common_local_url(
103                     'oembed',
104                     array(),
105                     array('format'=>'json', 'url'=>
106                         common_local_url('attachment',
107                             array('attachment' => $action->attachment->getID())))),
108                 'title'=>'oEmbed'));
109             $action->element('link',array('rel'=>'alternate',
110                 'type'=>'text/xml+oembed',
111                 'href'=>common_local_url(
112                     'oembed',
113                     array(),
114                     array('format'=>'xml','url'=>
115                         common_local_url('attachment',
116                             array('attachment' => $action->attachment->getID())))),
117                 'title'=>'oEmbed'));
118             break;
119         case 'shownotice':
120             if (!$action->notice->isLocal()) {
121                 break;
122             }
123             try {
124                 $action->element('link',array('rel'=>'alternate',
125                     'type'=>'application/json+oembed',
126                     'href'=>common_local_url(
127                         'oembed',
128                         array(),
129                         array('format'=>'json','url'=>$action->notice->getUrl())),
130                     'title'=>'oEmbed'));
131                 $action->element('link',array('rel'=>'alternate',
132                     'type'=>'text/xml+oembed',
133                     'href'=>common_local_url(
134                         'oembed',
135                         array(),
136                         array('format'=>'xml','url'=>$action->notice->getUrl())),
137                     'title'=>'oEmbed'));
138             } catch (InvalidUrlException $e) {
139                 // The notice is probably a share or similar, which don't
140                 // have a representational URL of their own.
141             }
142             break;
143         }
144
145         return true;
146     }
147
148     public function onEndShowStylesheets(Action $action) {
149         $action->cssLink($this->path('css/oembed.css'));
150         return true;
151     }
152
153     /**
154      * Save embedding information for a File, if applicable.
155      *
156      * Normally this event is called through File::saveNew()
157      *
158      * @param File   $file       The newly inserted File object.
159      *
160      * @return boolean success
161      */
162     public function onEndFileSaveNew(File $file)
163     {
164         $fo = File_oembed::getKV('file_id', $file->getID());
165         if ($fo instanceof File_oembed) {
166             common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->getID()}", __FILE__);
167             return true;
168         }
169
170         if (isset($file->mimetype)
171             && (('text/html' === substr($file->mimetype, 0, 9)
172             || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
173
174             try {
175                 $oembed_data = File_oembed::_getOembed($file->url);
176                 if ($oembed_data === false) {
177                     throw new Exception('Did not get oEmbed data from URL');
178                 }
179                 $file->setTitle($oembed_data->title);
180             } catch (Exception $e) {
181                 common_log(LOG_WARNING, sprintf(__METHOD__.': %s thrown when getting oEmbed data: %s', get_class($e), _ve($e->getMessage())));
182                 return true;
183             }
184
185             File_oembed::saveNew($oembed_data, $file->getID());
186         }
187         return true;
188     }
189
190     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
191     {
192         $oembed = File_oembed::getKV('file_id', $file->getID());
193         if (empty($oembed->author_name) && empty($oembed->provider)) {
194             return true;
195         }
196         $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
197         if (!empty($oembed->author_name)) {
198             $out->elementStart('div', 'fn vcard author');
199             if (empty($oembed->author_url)) {
200                 $out->text($oembed->author_name);
201             } else {
202                 $out->element('a', array('href' => $oembed->author_url,
203                                          'class' => 'url'),
204                                 $oembed->author_name);
205             }
206         }
207         if (!empty($oembed->provider)) {
208             $out->elementStart('div', 'fn vcard');
209             if (empty($oembed->provider_url)) {
210                 $out->text($oembed->provider);
211             } else {
212                 $out->element('a', array('href' => $oembed->provider_url,
213                                          'class' => 'url'),
214                                 $oembed->provider);
215             }
216         }
217         $out->elementEnd('div');
218     }
219
220     public function onFileEnclosureMetadata(File $file, &$enclosure)
221     {
222         // Never treat generic HTML links as an enclosure type!
223         // But if we have oEmbed info, we'll consider it golden.
224         $oembed = File_oembed::getKV('file_id', $file->getID());
225         if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
226             return true;
227         }
228
229         foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
230             if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
231                 $enclosure->{$key} = $oembed->{$key};
232             }
233         }
234         return true;
235     }
236
237     public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
238     {
239         try {
240             $oembed = File_oembed::getByFile($file);
241         } catch (NoResultException $e) {
242             return true;
243         }
244
245         // Show thumbnail as usual if it's a photo.
246         if ($oembed->type === 'photo') {
247             return true;
248         }
249
250         $out->elementStart('article', ['class'=>'h-entry oembed']);
251         $out->elementStart('header');
252         try  {
253             $thumb = $file->getThumbnail(128, 128);
254             $out->element('img', $thumb->getHtmlAttrs(['class'=>'u-photo oembed']));
255             unset($thumb);
256         } catch (Exception $e) {
257             $out->element('div', ['class'=>'error'], $e->getMessage());
258         }
259         $out->elementStart('h5', ['class'=>'p-name oembed']);
260         $out->element('a', ['class'=>'u-url', 'href'=>$file->getUrl()], common_strip_html($oembed->title));
261         $out->elementEnd('h5');
262         $out->elementStart('div', ['class'=>'p-author oembed']);
263         if (!empty($oembed->author_name)) {
264             // TRANS: text before the author name of oEmbed attachment representation
265             // FIXME: The whole "By x from y" should be i18n because of different language constructions.
266             $out->text(_('By '));
267             $attrs = ['class'=>'h-card p-author'];
268             if (!empty($oembed->author_url)) {
269                 $attrs['href'] = $oembed->author_url;
270                 $tag = 'a';
271             } else {
272                 $tag = 'span';
273             }
274             $out->element($tag, $attrs, $oembed->author_name);
275         }
276         if (!empty($oembed->provider)) {
277             // TRANS: text between the oEmbed author name and provider url
278             // FIXME: The whole "By x from y" should be i18n because of different language constructions.
279             $out->text(_(' from '));
280             $attrs = ['class'=>'h-card'];
281             if (!empty($oembed->provider_url)) {
282                 $attrs['href'] = $oembed->provider_url;
283                 $tag = 'a';
284             } else {
285                 $tag = 'span';
286             }
287             $out->element($tag, $attrs, $oembed->provider);
288         }
289         $out->elementEnd('div');
290         $out->elementEnd('header');
291         $out->elementStart('div', ['class'=>'p-summary oembed']);
292         $out->raw(common_purify($oembed->html));
293         $out->elementEnd('div');
294         $out->elementStart('footer');
295         $out->elementEnd('footer');
296         $out->elementEnd('article');
297
298         return false;
299     }
300     
301     public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
302     {
303         try {
304             $oembed = File_oembed::getByFile($file);
305         } catch (NoResultException $e) {
306             return true;
307         }
308
309         // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
310         switch ($oembed->type) {
311         case 'video':
312         case 'link':
313             if (!empty($oembed->html)
314                     && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
315                 require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
316                 $purifier = new HTMLPurifier();
317                 // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
318                 $out->raw($purifier->purify($oembed->html));
319             }
320             return false;
321             break;
322         }
323
324         return true;
325     }
326
327     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
328     {
329         // If we are on a private node, we won't do any remote calls (just as a precaution until
330         // we can configure this from config.php for the private nodes)
331         if (common_config('site', 'private')) {
332             return true;
333         }
334
335         // All our remote Oembed images lack a local filename property in the File object
336         if (!is_null($file->filename)) {
337             common_debug(sprintf('Filename of file id==%d is not null (%s), so nothing oEmbed should handle.', $file->getID(), _ve($file->filename)));
338             return true;
339         }
340
341         try {
342             // If we have proper oEmbed data, there should be an entry in the File_oembed
343             // and File_thumbnail tables respectively. If not, we're not going to do anything.
344             $file_oembed = File_oembed::getByFile($file);
345             $thumbnail   = File_thumbnail::byFile($file);
346         } catch (NoResultException $e) {
347             // Not Oembed data, or at least nothing we either can or want to use.
348             common_debug('No oEmbed data found for file id=='.$file->getID());
349             return true;
350         }
351
352         try {
353             $this->storeRemoteFileThumbnail($thumbnail);
354         } catch (AlreadyFulfilledException $e) {
355             // aw yiss!
356         } catch (Exception $e) {
357             common_debug(sprintf('oEmbed encountered an exception (%s) for file id==%d: %s', get_class($e), $file->getID(), _ve($e->getMessage())));
358             throw $e;
359         }
360
361         $imgPath = $thumbnail->getPath();
362
363         return false;
364     }
365
366     /**
367      * @return boolean          false on no check made, provider name on success
368      * @throws ServerException  if check is made but fails
369      */
370     protected function checkWhitelist($url)
371     {
372         if (!$this->check_whitelist) {
373             return false;   // indicates "no check made"
374         }
375
376         $host = parse_url($url, PHP_URL_HOST);
377         foreach ($this->domain_whitelist as $regex => $provider) {
378             if (preg_match("/$regex/", $host)) {
379                 return $provider;    // we trust this source, return provider name
380             }
381         }
382
383         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
384     }
385
386     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
387     {
388         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
389             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->getFileId()));
390         }
391
392         $remoteUrl = $thumbnail->getUrl();
393         $this->checkWhitelist($remoteUrl);
394
395         $http = new HTTPClient();
396         // First see if it's too large for us
397         common_debug(__METHOD__ . ': '.sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $thumbnail->getFileId(), $remoteUrl));
398         $head = $http->head($remoteUrl);
399         if (!$head->isOk()) {
400             common_log(LOG_WARNING, 'HEAD request returned HTTP failure, so we will abort now and delete the thumbnail object.');
401             $thumbnail->delete();
402             return false;
403         } else {
404             common_debug('HEAD request returned HTTP success, so we will continue.');
405         }
406         $remoteUrl = $head->getEffectiveUrl();   // to avoid going through redirects again
407
408         $headers = $head->getHeader();
409         $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
410
411         // FIXME: I just copied some checks from StoreRemoteMedia, maybe we should have other checks for thumbnails? Or at least embed into some class somewhere.
412         if (empty($filesize)) {
413             // file size not specified on remote server
414             common_debug(sprintf('%s: Ignoring remote thumbnail because we did not get a content length for thumbnail for file id==%u', __CLASS__, $thumbnail->getFileId()));
415             return true;
416         } elseif ($filesize > common_config('attachments', 'file_quota')) {
417             // file too big according to site configuration
418             common_debug(sprintf('%s: Skip downloading remote thumbnail because content length (%u) is larger than file_quota (%u) for file id==%u', __CLASS__, intval($filesize), common_config('attachments', 'file_quota'), $thumbnail->getFileId()));
419             return true;
420         }
421
422         // Then we download the file to memory and test whether it's actually an image file
423         // FIXME: To support remote video/whatever files, this needs reworking.
424         common_debug(sprintf('Downloading remote thumbnail for file id==%u (should be size %u) with effective URL: %s', $thumbnail->getFileId(), $filesize, _ve($remoteUrl)));
425         $imgData = HTTPClient::quickGet($remoteUrl);
426         $info = @getimagesizefromstring($imgData);
427         if ($info === false) {
428             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
429         } elseif (!$info[0] || !$info[1]) {
430             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
431         }
432
433         $ext = File::guessMimeExtension($info['mime']);
434
435         $filename = sprintf('oembed-%d.%s', $thumbnail->getFileId(), $ext);
436         $fullpath = File_thumbnail::path($filename);
437         // Write the file to disk. Throw Exception on failure
438         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
439             throw new ServerException(_('Could not write downloaded file to disk.'));
440         }
441         // Get rid of the file from memory
442         unset($imgData);
443
444         // Updated our database for the file record
445         $orig = clone($thumbnail);
446         $thumbnail->filename = $filename;
447         $thumbnail->width = $info[0];    // array indexes documented on php.net:
448         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
449         // Throws exception on failure.
450         $thumbnail->updateWithKeys($orig);
451     }
452
453     public function onPluginVersion(array &$versions)
454     {
455         $versions[] = array('name' => 'Oembed',
456                             'version' => self::PLUGIN_VERSION,
457                             'author' => 'Mikael Nordfeldth',
458                             'homepage' => 'http://gnu.io/',
459                             'description' =>
460                             // TRANS: Plugin description.
461                             _m('Plugin for using and representing Oembed data.'));
462         return true;
463     }
464 }