]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/StoreRemoteMedia/StoreRemoteMediaPlugin.php
StoreRemoteMedia now checks remote filesize before downloading
[quix0rs-gnu-social.git] / plugins / StoreRemoteMedia / StoreRemoteMediaPlugin.php
1 <?php
2
3 if (!defined('GNUSOCIAL')) { exit(1); }
4
5 // FIXME: To support remote video/whatever files, this plugin needs reworking.
6
7 class StoreRemoteMediaPlugin extends Plugin
8 {
9     // settings which can be set in config.php with addPlugin('Oembed', array('param'=>'value', ...));
10     // WARNING, these are _regexps_ (slashes added later). Always escape your dots and end your strings
11     public $domain_whitelist = array(       // hostname => service provider
12                                     '^i\d*\.ytimg\.com$' => 'YouTube',
13                                     '^i\d*\.vimeocdn\.com$' => 'Vimeo',
14                                     );
15     public $append_whitelist = array(); // fill this array as domain_whitelist to add more trusted sources
16     public $check_whitelist  = false;    // security/abuse precaution
17
18     public $domain_blacklist = array();
19     public $check_blacklist = false;
20
21     protected $imgData = array();
22
23     // these should be declared protected everywhere
24     public function initialize()
25     {
26         parent::initialize();
27
28         $this->domain_whitelist = array_merge($this->domain_whitelist, $this->append_whitelist);
29     }
30
31     /**
32      * Save embedding information for a File, if applicable.
33      *
34      * Normally this event is called through File::saveNew()
35      *
36      * @param File   $file       The abount-to-be-inserted File object.
37      *
38      * @return boolean success
39      */
40     public function onStartFileSaveNew(File &$file)
41     {
42         // save given URL as title if it's a media file this plugin understands
43         // which will make it shown in the AttachmentList widgets
44
45         if (isset($file->title) && strlen($file->title)>0) {
46             // Title is already set
47             return true;
48         }
49         if (!isset($file->mimetype)) {
50             // Unknown mimetype, it's not our job to figure out what it is.
51             return true;
52         }
53         switch (common_get_mime_media($file->mimetype)) {
54         case 'image':
55             // Just to set something for now at least...
56             $file->title = $file->mimetype;
57             break;
58         }
59         
60         return true;
61     }
62
63     public function onCreateFileImageThumbnailSource(File $file, &$imgPath, $media=null)
64     {
65         // If we are on a private node, we won't do any remote calls (just as a precaution until
66         // we can configure this from config.php for the private nodes)
67         if (common_config('site', 'private')) {
68             return true;
69         }
70
71         if ($media !== 'image') {
72             return true;
73         }
74
75         // If there is a local filename, it is either a local file already or has already been downloaded.
76         if (!empty($file->filename)) {
77             return true;
78         }
79
80         $remoteUrl = $file->getUrl();
81
82         if (!$this->checkWhiteList($remoteUrl) ||
83             !$this->checkBlackList($remoteUrl)) {
84                     return true;
85         }
86
87         try {
88             /*
89             $http = new HTTPClient();
90             common_debug(sprintf('Performing HEAD request for remote file id==%u to avoid unnecessarily downloading too large files. URL: %s', $file->getID(), $remoteUrl));
91             $head = $http->head($remoteUrl);
92             $remoteUrl = $head->effectiveUrl;   // to avoid going through redirects again
93             if (!$this->checkBlackList($remoteUrl)) {
94                 common_log(LOG_WARN, sprintf('%s: Non-blacklisted URL %s redirected to blacklisted URL %s', __CLASS__, $file->getUrl(), $remoteUrl));
95                 return true;
96             }
97
98             $headers = $head->getHeader();
99             $filesize = isset($headers['content-length']) ? $headers['content-length'] : null;
100             */
101             $filesize = $file->getSize();
102             if (empty($filesize)) {
103                 // file size not specified on remote server
104                 common_debug(sprintf('%s: Ignoring remote media because we did not get a content length for file id==%u', __CLASS__, $file->getID()));
105                 return true;
106             } elseif ($filesize > common_config('attachments', 'file_quota')) {
107                 // file too big
108                 common_debug(sprintf('%s: Skipping remote media because content length (%u) is larger than file_quota (%u) for file id==%u', __CLASS__, intval($filesize), common_config('attachments', 'file_quota'), $file->getID()));
109                 return true;
110             }
111
112             $http = new HTTPClient();
113             // Then we download the file to memory and test whether it's actually an image file
114             common_debug(sprintf('Downloading remote file id==%u (should be size %u) with effective URL: %s', $file->getID(), $filesize, _ve($remoteUrl)));
115             $imgData = $http->get($remoteUrl);
116         } catch (HTTP_Request2_ConnectionException $e) {
117             common_log(LOG_ERR, __CLASS__.': quickGet on URL: '._ve($file->getUrl()).' threw exception: '.$e->getMessage());
118             return true;
119         }
120         $info = @getimagesizefromstring($imgData);
121         if ($info === false) {
122             throw new UnsupportedMediaException(_('Remote file format was not identified as an image.'), $remoteUrl);
123         } elseif (!$info[0] || !$info[1]) {
124             throw new UnsupportedMediaException(_('Image file had impossible geometry (0 width or height)'));
125         }
126
127         $filehash = hash(File::FILEHASH_ALG, $imgData);
128         try {
129             // Exception will be thrown before $file is set to anything, so old $file value will be kept
130             $file = File::getByHash($filehash);
131
132             //FIXME: Add some code so we don't have to store duplicate File rows for same hash files.
133         } catch (NoResultException $e) {
134             $filename = $filehash . '.' . common_supported_mime_to_ext($info['mime']);
135             $fullpath = File::path($filename);
136
137             // Write the file to disk if it doesn't exist yet. Throw Exception on failure.
138             if (!file_exists($fullpath) && file_put_contents($fullpath, $imgData) === false) {
139                 throw new ServerException(_('Could not write downloaded file to disk.'));
140             }
141
142             // Updated our database for the file record
143             $orig = clone($file);
144             $file->filehash = $filehash;
145             $file->filename = $filename;
146             $file->width = $info[0];    // array indexes documented on php.net:
147             $file->height = $info[1];   // https://php.net/manual/en/function.getimagesize.php
148             // Throws exception on failure.
149             $file->updateWithKeys($orig);
150         }
151         // Get rid of the file from memory
152         unset($imgData);
153
154         $imgPath = $file->getPath();
155
156         return false;
157     }
158
159     /**
160      * @return boolean          true if given url passes blacklist check
161      */
162     protected function checkBlackList($url)
163     {
164         if (!$this->check_blacklist) {
165             return true;
166         }
167         $host = parse_url($url, PHP_URL_HOST);
168         foreach ($this->domain_blacklist as $regex => $provider) {
169             if (preg_match("/$regex/", $host)) {
170                 return false;
171             }
172         }
173
174         return true;
175     }
176
177     /***
178      * @return boolean          true if given url passes whitelist check
179      */
180     protected function checkWhiteList($url)
181     {
182         if (!$this->check_whitelist) {
183             return true;
184         }
185         $host = parse_url($url, PHP_URL_HOST);
186         foreach ($this->domain_whitelist as $regex => $provider) {
187             if (preg_match("/$regex/", $host)) {
188                 return true;
189             }
190         }
191
192         return false;
193     }
194
195     public function onPluginVersion(array &$versions)
196     {
197         $versions[] = array('name' => 'StoreRemoteMedia',
198                             'version' => GNUSOCIAL_VERSION,
199                             'author' => 'Mikael Nordfeldth',
200                             'homepage' => 'https://gnu.io/',
201                             'description' =>
202                             // TRANS: Plugin description.
203                             _m('Plugin for downloading remotely attached files to local server.'));
204         return true;
205     }
206 }