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