]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
c90f57439b3a2983ab9037ca43bce0e820603619
[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         // sometimes sites serve the path, not the full URL, for images
77         // let's "be liberal in what you accept from others"!
78         // add protocol and host if the thumbnail_url starts with /
79         if(substr($metadata->thumbnail_url,0,1) == '/') {
80             $thumbnail_url_parsed = parse_url($metadata->url);
81             $metadata->thumbnail_url = $thumbnail_url_parsed['scheme']."://".$thumbnail_url_parsed['host'].$metadata->thumbnail_url;
82         } 
83         
84         // some wordpress opengraph implementations sometimes return a white blank image
85         // no need for us to save that!
86         if($metadata->thumbnail_url == 'https://s0.wp.com/i/blank.jpg') {
87             unset($metadata->thumbnail_url);
88         }
89
90     }
91
92     public function onEndShowHeadElements(Action $action)
93     {
94         switch ($action->getActionName()) {
95         case 'attachment':
96             $action->element('link',array('rel'=>'alternate',
97                 'type'=>'application/json+oembed',
98                 'href'=>common_local_url(
99                     'oembed',
100                     array(),
101                     array('format'=>'json', 'url'=>
102                         common_local_url('attachment',
103                             array('attachment' => $action->attachment->id)))),
104                 'title'=>'oEmbed'),null);
105             $action->element('link',array('rel'=>'alternate',
106                 'type'=>'text/xml+oembed',
107                 'href'=>common_local_url(
108                     'oembed',
109                     array(),
110                     array('format'=>'xml','url'=>
111                         common_local_url('attachment',
112                             array('attachment' => $action->attachment->id)))),
113                 'title'=>'oEmbed'),null);
114             break;
115         case 'shownotice':
116             if (!$action->notice->isLocal()) {
117                 break;
118             }
119             try {
120                 $action->element('link',array('rel'=>'alternate',
121                     'type'=>'application/json+oembed',
122                     'href'=>common_local_url(
123                         'oembed',
124                         array(),
125                         array('format'=>'json','url'=>$action->notice->getUrl())),
126                     'title'=>'oEmbed'),null);
127                 $action->element('link',array('rel'=>'alternate',
128                     'type'=>'text/xml+oembed',
129                     'href'=>common_local_url(
130                         'oembed',
131                         array(),
132                         array('format'=>'xml','url'=>$action->notice->getUrl())),
133                     'title'=>'oEmbed'),null);
134             } catch (InvalidUrlException $e) {
135                 // The notice is probably a share or similar, which don't
136                 // have a representational URL of their own.
137             }
138             break;
139         }
140
141         return true;
142     }
143
144     /**
145      * Save embedding information for a File, if applicable.
146      *
147      * Normally this event is called through File::saveNew()
148      *
149      * @param File   $file       The newly inserted File object.
150      *
151      * @return boolean success
152      */
153     public function onEndFileSaveNew(File $file)
154     {
155         $fo = File_oembed::getKV('file_id', $file->id);
156         if ($fo instanceof File_oembed) {
157             common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file {$file->id}", __FILE__);
158             return true;
159         }
160
161         if (isset($file->mimetype)
162             && (('text/html' === substr($file->mimetype, 0, 9)
163             || 'application/xhtml+xml' === substr($file->mimetype, 0, 21)))) {
164
165             try {
166                 $oembed_data = File_oembed::_getOembed($file->url);
167                 if ($oembed_data === false) {
168                     throw new Exception('Did not get oEmbed data from URL');
169                 }
170             } catch (Exception $e) {
171                 return true;
172             }
173
174             File_oembed::saveNew($oembed_data, $file->id);
175         }
176         return true;
177     }
178
179     public function onEndShowAttachmentLink(HTMLOutputter $out, File $file)
180     {
181         $oembed = File_oembed::getKV('file_id', $file->id);
182         if (empty($oembed->author_name) && empty($oembed->provider)) {
183             return true;
184         }
185         $out->elementStart('div', array('id'=>'oembed_info', 'class'=>'e-content'));
186         if (!empty($oembed->author_name)) {
187             $out->elementStart('div', 'fn vcard author');
188             if (empty($oembed->author_url)) {
189                 $out->text($oembed->author_name);
190             } else {
191                 $out->element('a', array('href' => $oembed->author_url,
192                                          'class' => 'url'),
193                                 $oembed->author_name);
194             }
195         }
196         if (!empty($oembed->provider)) {
197             $out->elementStart('div', 'fn vcard');
198             if (empty($oembed->provider_url)) {
199                 $out->text($oembed->provider);
200             } else {
201                 $out->element('a', array('href' => $oembed->provider_url,
202                                          'class' => 'url'),
203                                 $oembed->provider);
204             }
205         }
206         $out->elementEnd('div');
207     }
208
209     public function onFileEnclosureMetadata(File $file, &$enclosure)
210     {
211         // Never treat generic HTML links as an enclosure type!
212         // But if we have oEmbed info, we'll consider it golden.
213         $oembed = File_oembed::getKV('file_id', $file->id);
214         if (!$oembed instanceof File_oembed || !in_array($oembed->type, array('photo', 'video'))) {
215             return true;
216         }
217
218         foreach (array('mimetype', 'url', 'title', 'modified', 'width', 'height') as $key) {
219             if (isset($oembed->{$key}) && !empty($oembed->{$key})) {
220                 $enclosure->{$key} = $oembed->{$key};
221             }
222         }
223         return true;
224     }
225     
226     public function onShowUnsupportedAttachmentRepresentation(HTMLOutputter $out, File $file)
227     {
228         try {
229             $oembed = File_oembed::getByFile($file);
230         } catch (NoResultException $e) {
231             return true;
232         }
233
234         // the 'photo' type is shown through ordinary means, using StartShowAttachmentRepresentation!
235         switch ($oembed->type) {
236         case 'video':
237         case 'link':
238             if (!empty($oembed->html)
239                     && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
240                 require_once INSTALLDIR.'/extlib/HTMLPurifier/HTMLPurifier.auto.php';
241                 $purifier = new HTMLPurifier();
242                 // FIXME: do we allow <object> and <embed> here? we did that when we used htmLawed, but I'm not sure anymore...
243                 $out->raw($purifier->purify($oembed->html));
244             }
245             return false;
246             break;
247         }
248
249         return true;
250     }
251
252     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
253     {
254         // If we are on a private node, we won't do any remote calls (just as a precaution until
255         // we can configure this from config.php for the private nodes)
256         if (common_config('site', 'private')) {
257             return true;
258         }
259
260         // All our remote Oembed images lack a local filename property in the File object
261         if (!is_null($file->filename)) {
262             return true;
263         }
264
265         try {
266             // If we have proper oEmbed data, there should be an entry in the File_oembed
267             // and File_thumbnail tables respectively. If not, we're not going to do anything.
268             $file_oembed = File_oembed::getByFile($file);
269             $thumbnail   = File_thumbnail::byFile($file);
270         } catch (NoResultException $e) {
271             // Not Oembed data, or at least nothing we either can or want to use.
272             return true;
273         }
274
275         try {
276             $this->storeRemoteFileThumbnail($thumbnail);
277         } catch (AlreadyFulfilledException $e) {
278             // aw yiss!
279         }
280
281         $imgPath = $thumbnail->getPath();
282
283         return false;
284     }
285
286     /**
287      * @return boolean          false on no check made, provider name on success
288      * @throws ServerException  if check is made but fails
289      */
290     protected function checkWhitelist($url)
291     {
292         if (!$this->check_whitelist) {
293             return false;   // indicates "no check made"
294         }
295
296         $host = parse_url($url, PHP_URL_HOST);
297         foreach ($this->domain_whitelist as $regex => $provider) {
298             if (preg_match("/$regex/", $host)) {
299                 return $provider;    // we trust this source, return provider name
300             }
301         }
302
303         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
304     }
305
306     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
307     {
308         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
309             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
310         }
311
312         $url = $thumbnail->getUrl();
313         $this->checkWhitelist($url);
314
315         // First we download the file to memory and test whether it's actually an image file
316         // FIXME: To support remote video/whatever files, this needs reworking.
317         common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
318         $imgData = HTTPClient::quickGet($url);
319         $info = @getimagesizefromstring($imgData);
320         if ($info === false) {
321             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
322         } elseif (!$info[0] || !$info[1]) {
323             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
324         }
325
326         // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
327         $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
328         $fullpath = File_thumbnail::path($filename);
329         // Write the file to disk. Throw Exception on failure
330         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
331             throw new ServerException(_('Could not write downloaded file to disk.'));
332         }
333         // Get rid of the file from memory
334         unset($imgData);
335
336         // Updated our database for the file record
337         $orig = clone($thumbnail);
338         $thumbnail->filename = $filename;
339         $thumbnail->width = $info[0];    // array indexes documented on php.net:
340         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
341         // Throws exception on failure.
342         $thumbnail->updateWithKeys($orig);
343     }
344
345     public function onPluginVersion(array &$versions)
346     {
347         $versions[] = array('name' => 'Oembed',
348                             'version' => GNUSOCIAL_VERSION,
349                             'author' => 'Mikael Nordfeldth',
350                             'homepage' => 'http://gnu.io/',
351                             'description' =>
352                             // TRANS: Plugin description.
353                             _m('Plugin for using and representing Oembed data.'));
354         return true;
355     }
356 }