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