]> jfr.im git - uguu.git/blame - src/Classes/Upload.php
changes
[uguu.git] / src / Classes / Upload.php
CommitLineData
e480c0e5 1<?php
f0b5e51c 2
e480c0e5 3 /**
cec6349e 4 * Uguu
8f7f8840 5 *
cec6349e 6 * @copyright Copyright (c) 2022 Go Johansson (nokonoko) <neku@pomf.se>
8f7f8840 7 *
cec6349e
GJ
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.
8f7f8840 12 *
cec6349e
GJ
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.
8f7f8840 17 *
cec6349e
GJ
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/>.
8f7f8840 20 */
f0b5e51c 21
f059e2cf 22 namespace Pomf\Uguu\Classes;
f0b5e51c 23
cec6349e 24 use Exception;
f0b5e51c
GJ
25
26class 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
e480c0e5 42 {
f0b5e51c
GJ
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']);
cec6349e 67 }
f0b5e51c
GJ
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 ];
e480c0e5 77 }
f0b5e51c
GJ
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;
cec6349e 114 }
e480c0e5 115 }
f0b5e51c
GJ
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']:
24383942
GJ
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 }
f0b5e51c
GJ
139 // Continue
140 case $this->Connector->CONFIG['BLACKLIST_DB']:
cec6349e 141 $this->Connector->checkFileBlacklist($this->FILE_INFO);
f0b5e51c
GJ
142 // Continue
143 case $this->Connector->CONFIG['FILTER_MODE'] && empty($this->FILE_INFO['EXTENSION']):
cec6349e 144 $this->checkMimeBlacklist();
f0b5e51c
GJ
145 // Continue
146 case $this->Connector->CONFIG['FILTER_MODE'] && !empty($this->FILE_INFO['EXTENSION']):
cec6349e
GJ
147 $this->checkMimeBlacklist();
148 $this->checkExtensionBlacklist();
f0b5e51c 149 // Continue
f0b5e51c
GJ
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'],
f7f02b92 173 'url' => 'https://' . $this->Connector->CONFIG['FILE_DOMAIN'] . '/' . $this->FILE_INFO['NEW_NAME'],
f0b5e51c
GJ
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);
e2c8b572
GJ
191 $ip = null;
192 if ($this->Connector->CONFIG['LOG_IP']) {
193 $ip = $_SERVER['REMOTE_ADDR'];
194 }
f0b5e51c
GJ
195 $this->fingerPrintInfo = [
196 'timestamp' => time(),
197 'useragent' => $USER_AGENT,
e2c8b572 198 'ip' => $ip,
f0b5e51c
GJ
199 'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $USER_AGENT),
200 'files_amount' => $files_amount,
cec6349e 201 ];
f0b5e51c
GJ
202 } else {
203 throw new Exception('Invalid user agent.', 500);
e480c0e5 204 }
f0b5e51c
GJ
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);
e480c0e5 237 }
f0b5e51c
GJ
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);
e480c0e5 267 }
f0b5e51c
GJ
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);
e480c0e5 279 }
f0b5e51c
GJ
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.
f0b5e51c
GJ
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);
cec6349e 296 }
f0b5e51c
GJ
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)];
cec6349e 301 }
f0b5e51c
GJ
302 if (!empty($extension)) {
303 $NEW_NAME .= '.' . $extension;
cec6349e 304 }
24383942 305 } while ($this->Connector->dbCheckNameExists($NEW_NAME));
f0b5e51c 306 return $NEW_NAME;
e480c0e5 307 }
f0b5e51c 308}