]> jfr.im git - uguu.git/blame - src/Classes/Upload.php
fixes
[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
GJ
149 // Continue
150 case !$this->Connector->CONFIG['LOG_IP']:
cec6349e 151 $this->fingerPrintInfo['ip'] = null;
f0b5e51c
GJ
152 // Continue
153 }
154 if (!is_dir($this->Connector->CONFIG['FILES_ROOT'])) {
155 throw new Exception('File storage path not accessible.', 500);
156 }
157 if (
158 !move_uploaded_file(
159 $this->FILE_INFO['TEMP_NAME'],
160 $this->Connector->CONFIG['FILES_ROOT'] .
161 $this->FILE_INFO['NEW_NAME'],
162 )
163 ) {
164 throw new Exception('Failed to move file to destination', 500);
165 }
166 if (!chmod($this->Connector->CONFIG['FILES_ROOT'] . $this->FILE_INFO['NEW_NAME'], 0644)) {
167 throw new Exception('Failed to change file permissions', 500);
168 }
169
170
171
172 $this->Connector->newIntoDB($this->FILE_INFO, $this->fingerPrintInfo);
173 return [
174 'hash' => $this->FILE_INFO['SHA1'],
175 'name' => $this->FILE_INFO['NAME'],
176 'url' => $this->Connector->CONFIG['FILES_URL'] . '/' . $this->FILE_INFO['NEW_NAME'],
177 'size' => $this->FILE_INFO['SIZE'],
178 ];
179 }
180
181 /**
182 * Takes the amount of files that are being uploaded, and creates a fingerprint of the user's IP address,
183 * user agent, and the amount of files being
184 * uploaded
185 *
186 * @param $files_amount int The amount of files that are being uploaded.
187 *
188 * @throws \Exception
189 */
190 public function fingerPrint(int $files_amount): void
191 {
192 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
193 $USER_AGENT = filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_ENCODED);
194 $this->fingerPrintInfo = [
195 'timestamp' => time(),
196 'useragent' => $USER_AGENT,
197 'ip' => $_SERVER['REMOTE_ADDR'],
198 'ip_hash' => hash('sha1', $_SERVER['REMOTE_ADDR'] . $USER_AGENT),
199 'files_amount' => $files_amount,
cec6349e 200 ];
f0b5e51c
GJ
201 } else {
202 throw new Exception('Invalid user agent.', 500);
e480c0e5 203 }
f0b5e51c
GJ
204 }
205
206 /**
207 * Returns the MIME type of a file
208 *
209 * @param $file array The file to be checked.
210 *
211 * @return string The MIME type of the file.
212 */
213 public function fileMIME(array $file): string
214 {
215 $FILE_INFO = finfo_open(FILEINFO_MIME_TYPE);
216 return finfo_file($FILE_INFO, $file['tmp_name']);
217 }
218
219 /**
220 * It takes an array of strings, and returns the last two strings joined by a dot,
221 * unless the last two strings are in the array of strings in the
222 * `DOUBLE_DOTS_EXTENSIONS` config variable, in which case it returns the last string
223 *
224 * @param $extension array The extension of the file.
225 *
226 * @return string The last two elements of the array are joined together and returned.
227 */
228 public function doubleDotExtension(array $extension): string
229 {
230 $doubleDotArray = array_slice($extension, -2, 2);
231 $doubleDot = strtolower(preg_replace('/[^a-zA-Z.]/', '', join('.', $doubleDotArray)));
232 if (in_array($doubleDot, $this->Connector->CONFIG['DOUBLE_DOTS_EXTENSIONS'])) {
233 return $doubleDot;
234 } else {
235 return end($extension);
e480c0e5 236 }
f0b5e51c
GJ
237 }
238
239 /**
240 * Takes a file and returns the file extension
241 *
242 * @param $file array The file you want to get the extension from.
243 *
244 * @return string The file extension of the file.
245 */
246 public function fileExtension(array $file): string
247 {
248 $extension = explode('.', $file['name']);
249 $dotCount = substr_count($file['name'], '.');
250 return match ($dotCount) {
251 0 => null,
252 1 => end($extension),
253 2 => $this->doubleDotExtension($extension)
254 };
255 }
256
257 /**
258 * > Check if the file's MIME type is in the blacklist
259 *
260 * @throws \Exception
261 */
262 public function checkMimeBlacklist(): void
263 {
264 if (in_array($this->FILE_INFO['MIME'], $this->Connector->CONFIG['BLOCKED_MIME'])) {
265 throw new Exception('Filetype not allowed.', 415);
e480c0e5 266 }
f0b5e51c
GJ
267 }
268
269 /**
270 * > Check if the file extension is in the blacklist
271 *
272 * @throws \Exception
273 */
274 public function checkExtensionBlacklist(): void
275 {
276 if (in_array($this->FILE_INFO['EXTENSION'], $this->Connector->CONFIG['BLOCKED_EXTENSIONS'])) {
277 throw new Exception('Filetype not allowed.', 415);
e480c0e5 278 }
f0b5e51c
GJ
279 }
280
281 /**
282 * Generates a random string of characters, checks if it exists in the database,
283 * and if it does, it generates another one
284 *
285 * @param $extension string The file extension.
f0b5e51c
GJ
286 *
287 * @return string A string
288 * @throws \Exception
289 */
290 public function generateName(string $extension): string
291 {
292 do {
293 if ($this->Connector->CONFIG['FILES_RETRIES'] === 0) {
294 throw new Exception('Gave up trying to find an unused name!', 500);
cec6349e 295 }
f0b5e51c
GJ
296 $NEW_NAME = '';
297 $count = strlen($this->Connector->CONFIG['ID_CHARSET']);
298 while ($this->Connector->CONFIG['NAME_LENGTH']--) {
299 $NEW_NAME .= $this->Connector->CONFIG['ID_CHARSET'][mt_rand(0, $count - 1)];
cec6349e 300 }
f0b5e51c
GJ
301 if (!empty($extension)) {
302 $NEW_NAME .= '.' . $extension;
cec6349e 303 }
24383942 304 } while ($this->Connector->dbCheckNameExists($NEW_NAME));
f0b5e51c 305 return $NEW_NAME;
e480c0e5 306 }
f0b5e51c 307}