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