]> jfr.im git - uguu.git/blob - src/Classes/Upload.php
79d7ab437b660277738fc51939808dce8a53ded0
[uguu.git] / src / Classes / Upload.php
1 <?php
2
3 /**
4 * Uguu
5 *
6 * @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 namespace Pomf\Uguu\Classes;
23
24 use Exception;
25
26 class Upload extends Response
27 {
28 public array $FILE_INFO;
29 public array $fingerPrintInfo;
30 private mixed $Connector;
31
32 /**
33 * Takes an array of files, and returns an array of arrays containing the file's temporary name,
34 * name, size, SHA1 hash, extension, and MIME type
35 *
36 * @param $files array The files array from the $_FILES superglobal.
37 *
38 * @return array An array of arrays.
39 * @throws \Exception
40 */
41 public function reFiles(array $files): array
42 {
43 $this->Connector = new Connector();
44 $this->Connector->setDB($this->Connector->DB);
45 $result = [];
46 $files = $this->diverseArray($files);
47 foreach ($files as $file) {
48 $hash = sha1_file($file['tmp_name']);
49 $this->FILE_INFO = [
50 'TEMP_NAME' => $file['tmp_name'],
51 'NAME' => strip_tags($file['name']),
52 'SIZE' => $file['size'],
53 'SHA1' => $hash,
54 'EXTENSION' => $this->fileExtension($file),
55 'MIME' => $this->fileMIME($file),
56 ];
57
58 if ($this->Connector->CONFIG['ANTI_DUPE']) {
59 $dupeResult = $this->Connector->antiDupe($hash);
60 if ($dupeResult['result']) {
61 $this->FILE_INFO['NEW_NAME'] = $dupeResult['name'];
62 }
63 }
64
65 if (!isset($this->FILE_INFO['NEW_NAME'])) {
66 $this->FILE_INFO['NEW_NAME'] = $this->generateName($this->FILE_INFO['EXTENSION']);
67 }
68
69 $result[] = [
70 $this->FILE_INFO['TEMP_NAME'],
71 $this->FILE_INFO['NAME'],
72 $this->FILE_INFO['SIZE'],
73 $this->FILE_INFO['SHA1'],
74 $this->FILE_INFO['EXTENSION'],
75 $this->FILE_INFO['MIME'],
76 ];
77 }
78 return $result;
79 }
80
81 /**
82 * Takes an array of arrays and returns an array of arrays with the keys and values swapped
83 *
84 * @param $files array an array of arrays
85 *
86 * @return array ```
87 * array:2 [▼
88 * 0 => array:2 [▼
89 * 'TEMP_NAME' => 'example'
90 * 'NAME' => 'example'
91 * 'SIZE' => 'example'
92 * 'SHA1' => 'example'
93 * 'EXTENSION' => 'example'
94 * 'MIME' => 'example'
95 *
96 * ]
97 * 1 => array:2 [▼
98 * 'TEMP_NAME' => 'example'
99 * 'NAME' => 'example'
100 * 'SIZE' => 'example'
101 * 'SHA1' => 'example'
102 * 'EXTENSION' => 'example'
103 * 'MIME' => 'example'
104 * ]
105 * ]
106 * ```
107 */
108 public function diverseArray(array $files): array
109 {
110 $result = [];
111 foreach ($files as $key1 => $value1) {
112 foreach ($value1 as $key2 => $value2) {
113 $result[$key2][$key1] = $value2;
114 }
115 }
116 return $result;
117 }
118
119 /**
120 * Takes a file, checks if it's blacklisted, moves it to the file storage, and then logs it to the database
121 *
122 * @return array An array containing the hash, name, url, and size of the file.
123 * @throws \Exception
124 */
125 public function uploadFile(): array
126 {
127 switch (true) {
128 case $this->Connector->CONFIG['RATE_LIMIT']:
129 if (
130 $this->Connector->checkRateLimit(
131 $this->fingerPrintInfo,
132 (int) $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'],
133 (int) $this->Connector->CONFIG['RATE_LIMIT_FILES']
134 )
135 ) {
136 throw new Exception('Rate limit, please wait ' . $this->Connector->CONFIG['RATE_LIMIT_TIMEOUT'] .
137 ' seconds before uploading again.', 500);
138 }
139 // Continue
140 case $this->Connector->CONFIG['BLACKLIST_DB']:
141 $this->Connector->checkFileBlacklist($this->FILE_INFO);
142 // Continue
143 case $this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION']):
144 $this->checkMimeBlacklist();
145 // Continue
146 case $this->Connector->CONFIG['FILTER_MODE'] && !empty($this->FILE_INFO['EXTENSION']):
147 $this->checkMimeBlacklist();
148 $this->checkExtensionBlacklist();
149 // Continue
150 }
151 if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) {
152 throw new Exception('File storage path not accessible.', 500);
153 }
154 if (
155 !move_uploaded_file(
156 $this->FILE_INFO['TEMP_NAME'],
157 $this->Connector->CONFIG['FILES_ROOT'] .
158 $this->FILE_INFO['NEW_NAME'],
159 )
160 ) {
161 throw new Exception('Failed to move file to destination', 500);
162 }
163 if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['NEW_NAME'], 0644)) {
164 throw new Exception('Failed to change file permissions', 500);
165 }
166
167
168
169 $this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo);
170 return [
171 'hash' => $this->FILE_INFO['SHA1'],
172 'name' => $this->FILE_INFO['NAME'],
173 'url' => 'https://' . $this->Connector->CONFIG['FILE_DOMAIN'] . '/' . $this->FILE_INFO['NEW_NAME'],
174 'size' => $this->FILE_INFO['SIZE'],
175 ];
176 }
177
178 /**
179 * Takes the amount of files that are being uploaded, and creates a fingerprint of the user's IP address,
180 * user agent, and the amount of files being
181 * uploaded
182 *
183 * @param $files_amount int The amount of files that are being uploaded.
184 *
185 * @throws \Exception
186 */
187 public function fingerPrint(int $files_amount): void
188 {
189 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
190 $USER_AGENT = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_ENCODED);
191 $ip = null;
192 if ($this->Connector->CONFIG['LOG_IP']) {
193 $ip = $_SERVER['REMOTE_ADDR'];
194 }
195 $this->fingerPrintInfo = [
196 'timestamp' => time(),
197 'useragent' => $USER_AGENT,
198 'ip' => $ip,
199 'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $USER_AGENT),
200 'files_amount' => $files_amount,
201 ];
202 } else {
203 throw new Exception('Invalid user agent.', 500);
204 }
205 }
206
207 /**
208 * Returns the MIME type of a file
209 *
210 * @param $file array The file to be checked.
211 *
212 * @return string The MIME type of the file.
213 */
214 public function fileMIME(array $file): string
215 {
216 $FILE_INFO = finfo_open(FILEINFO_MIME_TYPE);
217 return finfo_file($FILE_INFO, $file['tmp_name']);
218 }
219
220 /**
221 * It takes an array of strings, and returns the last two strings joined by a dot,
222 * unless the last two strings are in the array of strings in the
223 * `DOUBLE_DOTS_EXTENSIONS` config variable, in which case it returns the last string
224 *
225 * @param $extension array The extension of the file.
226 *
227 * @return string The last two elements of the array are joined together and returned.
228 */
229 public function doubleDotExtension(array $extension): string
230 {
231 $doubleDotArray = array_slice($extension, -2, 2);
232 $doubleDot = strtolower(preg_replace('/[^a-zA-Z.]/', '', join('.', $doubleDotArray)));
233 if (in_array($doubleDot, $this->Connector->CONFIG['DOUBLE_DOTS_EXTENSIONS'])) {
234 return $doubleDot;
235 } else {
236 return end($extension);
237 }
238 }
239
240 /**
241 * Takes a file and returns the file extension
242 *
243 * @param $file array The file you want to get the extension from.
244 *
245 * @return string The file extension of the file.
246 */
247 public function fileExtension(array $file): string
248 {
249 $extension = explode('.', $file['name']);
250 $dotCount = substr_count($file['name'], '.');
251 return match ($dotCount) {
252 0 => null,
253 1 => end($extension),
254 2 => $this->doubleDotExtension($extension)
255 };
256 }
257
258 /**
259 * > Check if the file's MIME type is in the blacklist
260 *
261 * @throws \Exception
262 */
263 public function checkMimeBlacklist(): void
264 {
265 if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) {
266 throw new Exception('Filetype not allowed.', 415);
267 }
268 }
269
270 /**
271 * > Check if the file extension is in the blacklist
272 *
273 * @throws \Exception
274 */
275 public function checkExtensionBlacklist(): void
276 {
277 if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) {
278 throw new Exception('Filetype not allowed.', 415);
279 }
280 }
281
282 /**
283 * Generates a random string of characters, checks if it exists in the database,
284 * and if it does, it generates another one
285 *
286 * @param $extension string The file extension.
287 *
288 * @return string A string
289 * @throws \Exception
290 */
291 public function generateName(string $extension): string
292 {
293 do {
294 if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) {
295 throw new Exception('Gave up trying to find an unused name!', 500);
296 }
297 $NEW_NAME = '';
298 $count = strlen($this->Connector->CONFIG['ID_CHARSET']);
299 while ($this->Connector->CONFIG['NAME_LENGTH']--) {
300 $NEW_NAME .= $this->Connector->CONFIG['ID_CHARSET'][mt_rand(0, $count - 1)];
301 }
302 if (!empty($extension)) {
303 $NEW_NAME .= '.' . $extension;
304 }
305 } while ($this->Connector->dbCheckNameExists($NEW_NAME));
306 return $NEW_NAME;
307 }
308 }