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