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