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