]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
Merge branch 'master' into mmn_fixes
[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->id)))),
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->id)))),
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->id);
163         if ($fo instanceof File_oembed) {
164             common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __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             } catch (Exception $e) {
178                 return true;
179             }
180
181             File_oembed::saveNew($oembed_data, $file->id);
182         }
183         return true;
184     }
185
186     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
187     {
188         $oembed = File_oembed::getKV('file_id', $file->id);
189         if (empty($oembed->author_name) && empty($oembed->provider)) {
190             return true;
191         }
192         $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
193         if (!empty($oembed->author_name)) {
194             $out->elementStart('div', 'fn vcard author');
195             if (empty($oembed->author_url)) {
196                 $out->text($oembed->author_name);
197             } else {
198                 $out->element('a', array('href' => $oembed->author_url,
199                                          'class' => 'url'),
200                                 $oembed->author_name);
201             }
202         }
203         if (!empty($oembed->provider)) {
204             $out->elementStart('div', 'fn vcard');
205             if (empty($oembed->provider_url)) {
206                 $out->text($oembed->provider);
207             } else {
208                 $out->element('a', array('href' => $oembed->provider_url,
209                                          'class' => 'url'),
210                                 $oembed->provider);
211             }
212         }
213         $out->elementEnd('div');
214     }
215
216     public function onFileEnclosureMetadata(File $file, &$enclosure)
217     {
218         // Never treat generic HTML links as an enclosure type!
219         // But if we have oEmbed info, we'll consider it golden.
220         $oembed = File_oembed::getKV('file_id', $file->id);
221         if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
222             return true;
223         }
224
225         foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
226             if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
227                 $enclosure->{$key} = $oembed->{$key};
228             }
229         }
230         return true;
231     }
232
233     public function onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
234     {
235         try {
236             $oembed = File_oembed::getByFile($file);
237         } catch (NoResultException $e) {
238             return true;
239         }
240
241         $out->elementStart('article', ['class'=>'oembed-item']);
242         $out->elementStart('header');
243         try  {
244             $thumb = $file->getThumbnail(128, 128);
245             $out->element('img', $thumb->getHtmlAttrs(['class'=>'oembed-thumb']));
246             unset($thumb);
247         } catch (Exception $e) {
248             $out->element('div', ['class'=>'error'], $e->getMessage());
249         }
250         $out->elementStart('h5', ['class'=>'oembed-title']);
251         $out->element('a', ['href'=>$file->getUrl()], common_strip_html($oembed->title));
252         $out->elementEnd('h5');
253         $out->elementStart('div', ['class'=>'oembed-source']);
254         if (!empty($oembed->author_name)) {
255             // TRANS: text before the author name of oEmbed attachment representation
256             // FIXME: The whole "By x from y" should be i18n because of different language constructions.
257             $out->text(_('By '));
258             $attrs = ['class'=>'h-card'];
259             if (!empty($oembed->author_url)) {
260                 $attrs['href'] = $oembed->author_url;
261                 $tag = 'a';
262             } else {
263                 $tag = 'span';
264             }
265             $out->element($tag, $attrs, $oembed->author_name);
266         }
267         if (!empty($oembed->provider)) {
268             // TRANS: text between the oEmbed author name and provider url
269             // FIXME: The whole "By x from y" should be i18n because of different language constructions.
270             $out->text(_(' from '));
271             $attrs = ['class'=>'h-card'];
272             if (!empty($oembed->provider_url)) {
273                 $attrs['href'] = $oembed->provider_url;
274                 $tag = 'a';
275             } else {
276                 $tag = 'span';
277             }
278             $out->element($tag, $attrs, $oembed->provider);
279         }
280         $out->elementEnd('div');
281         $out->elementEnd('header');
282         $out->elementStart('div', ['class'=>'oembed-html']);
283         $out->raw(common_purify($oembed->html));
284         $out->elementEnd('div');
285         $out->elementStart('footer');
286         $out->elementEnd('footer');
287         $out->elementEnd('article');
288
289         return false;
290     }
291     
292     public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
293     {
294         try {
295             $oembed = File_oembed::getByFile($file);
296         } catch (NoResultException $e) {
297             return true;
298         }
299
300         // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
301         switch ($oembed->type) {
302         case 'video':
303         case 'link':
304             if (!empty($oembed->html)
305                     && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
306                 require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
307                 $purifier = new HTMLPurifier();
308                 // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
309                 $out->raw($purifier->purify($oembed->html));
310             }
311             return false;
312             break;
313         }
314
315         return true;
316     }
317
318     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
319     {
320         // If we are on a private node, we won't do any remote calls (just as a precaution until
321         // we can configure this from config.php for the private nodes)
322         if (common_config('site', 'private')) {
323             return true;
324         }
325
326         // All our remote Oembed images lack a local filename property in the File object
327         if (!is_null($file->filename)) {
328             return true;
329         }
330
331         try {
332             // If we have proper oEmbed data, there should be an entry in the File_oembed
333             // and File_thumbnail tables respectively. If not, we're not going to do anything.
334             $file_oembed = File_oembed::getByFile($file);
335             $thumbnail   = File_thumbnail::byFile($file);
336         } catch (NoResultException $e) {
337             // Not Oembed data, or at least nothing we either can or want to use.
338             return true;
339         }
340
341         try {
342             $this->storeRemoteFileThumbnail($thumbnail);
343         } catch (AlreadyFulfilledException $e) {
344             // aw yiss!
345         }
346
347         $imgPath = $thumbnail->getPath();
348
349         return false;
350     }
351
352     /**
353      * @return boolean          false on no check made, provider name on success
354      * @throws ServerException  if check is made but fails
355      */
356     protected function checkWhitelist($url)
357     {
358         if (!$this->check_whitelist) {
359             return false;   // indicates "no check made"
360         }
361
362         $host = parse_url($url, PHP_URL_HOST);
363         foreach ($this->domain_whitelist as $regex => $provider) {
364             if (preg_match("/$regex/", $host)) {
365                 return $provider;    // we trust this source, return provider name
366             }
367         }
368
369         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
370     }
371
372     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
373     {
374         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
375             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
376         }
377
378         $url = $thumbnail->getUrl();
379         $this->checkWhitelist($url);
380
381         // First we download the file to memory and test whether it's actually an image file
382         // FIXME: To support remote video/whatever files, this needs reworking.
383         common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
384         $imgData = HTTPClient::quickGet($url);
385         $info = @getimagesizefromstring($imgData);
386         if ($info === false) {
387             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
388         } elseif (!$info[0] || !$info[1]) {
389             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
390         }
391
392         $ext = File::guessMimeExtension($info['mime']);
393
394         // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
395         $filename = 'oembed-'.hash(File::FILEHASH_ALG, $imgData) . ".{$ext}";
396         $fullpath = File_thumbnail::path($filename);
397         // Write the file to disk. Throw Exception on failure
398         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
399             throw new ServerException(_('Could not write downloaded file to disk.'));
400         }
401         // Get rid of the file from memory
402         unset($imgData);
403
404         // Updated our database for the file record
405         $orig = clone($thumbnail);
406         $thumbnail->filename = $filename;
407         $thumbnail->width = $info[0];    // array indexes documented on php.net:
408         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
409         // Throws exception on failure.
410         $thumbnail->updateWithKeys($orig);
411     }
412
413     public function onPluginVersion(array &$versions)
414     {
415         $versions[] = array('name' => 'Oembed',
416                             'version' => GNUSOCIAL_VERSION,
417                             'author' => 'Mikael Nordfeldth',
418                             'homepage' => 'http://gnu.io/',
419                             'description' =>
420                             // TRANS: Plugin description.
421                             _m('Plugin for using and representing Oembed data.'));
422         return true;
423     }
424 }