]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Oembed/OembedPlugin.php
Merge branch 'nightly' into singpolyma/gnu-social-events-saveObjectFromActivity
[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 onStartShowAttachmentRepresentation(HTMLOutputter $out, File $file)
191     {
192         try {
193             $oembed = File_oembed::getByFile($file);
194         } catch (NoResultException $e) {
195             return true;
196         }
197
198         switch ($oembed->type) {
199         case 'rich':
200         case 'video':
201         case 'link':
202             if (!empty($oembed->html)
203                     && (GNUsocial::isAjax() || common_config('attachments', 'show_html'))) {
204                 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
205                 $config = array(
206                     'safe'=>1,
207                     'elements'=>'*+object+embed');
208                 $out->raw(htmLawed($oembed->html,$config));
209             }
210             break;
211
212         case 'photo':
213             $out->element('img', array('src' => $oembed->url, 'width' => $oembed->width, 'height' => $oembed->height, 'alt' => 'alt'));
214             break;
215
216         default:
217             Event::handle('ShowUnsupportedAttachmentRepresentation', array($out, $file));
218         }
219     }
220
221     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
222     {
223         // If we are on a private node, we won't do any remote calls (just as a precaution until
224         // we can configure this from config.php for the private nodes)
225         if (common_config('site', 'private')) {
226             return true;
227         }
228
229         // All our remote Oembed images lack a local filename property in the File object
230         if (!is_null($file->filename)) {
231             return true;
232         }
233
234         try {
235             // If we have proper oEmbed data, there should be an entry in the File_oembed
236             // and File_thumbnail tables respectively. If not, we're not going to do anything.
237             $file_oembed = File_oembed::getByFile($file);
238             $thumbnail   = File_thumbnail::byFile($file);
239         } catch (Exception $e) {
240             // Not Oembed data, or at least nothing we either can or want to use.
241             return true;
242         }
243
244         try {
245             $this->storeRemoteFileThumbnail($thumbnail);
246         } catch (AlreadyFulfilledException $e) {
247             // aw yiss!
248         }
249
250         $imgPath = $thumbnail->getPath();
251
252         return false;
253     }
254
255     /**
256      * @return boolean          false on no check made, provider name on success
257      * @throws ServerException  if check is made but fails
258      */
259     protected function checkWhitelist($url)
260     {
261         if (!$this->check_whitelist) {
262             return false;   // indicates "no check made"
263         }
264
265         $host = parse_url($url, PHP_URL_HOST);
266         foreach ($this->domain_whitelist as $regex => $provider) {
267             if (preg_match("/$regex/", $host)) {
268                 return $provider;    // we trust this source, return provider name
269             }
270         }
271
272         throw new ServerException(sprintf(_('Domain not in remote thumbnail source whitelist: %s'), $host));
273     }
274
275     protected function storeRemoteFileThumbnail(File_thumbnail $thumbnail)
276     {
277         if (!empty($thumbnail->filename) && file_exists($thumbnail->getPath())) {
278             throw new AlreadyFulfilledException(sprintf('A thumbnail seems to already exist for remote file with id==%u', $thumbnail->file_id));
279         }
280
281         $url = $thumbnail->getUrl();
282         $this->checkWhitelist($url);
283
284         // First we download the file to memory and test whether it's actually an image file
285         // FIXME: To support remote video/whatever files, this needs reworking.
286         common_debug(sprintf('Downloading remote thumbnail for file id==%u with thumbnail URL: %s', $thumbnail->file_id, $url));
287         $imgData = HTTPClient::quickGet($url);
288         $info = @getimagesizefromstring($imgData);
289         if ($info === false) {
290             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $url);
291         } elseif (!$info[0] || !$info[1]) {
292             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
293         }
294
295         // We'll trust sha256 (File::FILEHASH_ALG) not to have collision issues any time soon :)
296         $filename = hash(File::FILEHASH_ALG, $imgData) . '.' . common_supported_mime_to_ext($info['mime']);
297         $fullpath = File_thumbnail::path($filename);
298         // Write the file to disk. Throw Exception on failure
299         if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
300             throw new ServerException(_('Could not write downloaded file to disk.'));
301         }
302         // Get rid of the file from memory
303         unset($imgData);
304
305         // Updated our database for the file record
306         $orig = clone($thumbnail);
307         $thumbnail->filename = $filename;
308         $thumbnail->width = $info[0];    // array indexes documented on php.net:
309         $thumbnail->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
310         // Throws exception on failure.
311         $thumbnail->updateWithKeys($orig, 'file_id');
312     }
313
314     public function onPluginVersion(array &$versions)
315     {
316         $versions[] = array('name' => 'Oembed',
317                             'version' => GNUSOCIAL_VERSION,
318                             'author' => 'Mikael Nordfeldth',
319                             'homepage' => 'http://gnu.io/',
320                             'description' =>
321                             // TRANS: Plugin description.
322                             _m('Plugin for using and representing Oembed data.'));
323         return true;
324     }
325 }