| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
/** |
| 8 |
* Validates uploaded import files before the importer reads CSV content. |
| 9 |
*/ |
| 10 |
class ABJ_404_Solution_ImportUploadValidator { |
| 11 |
|
| 12 |
/** |
| 13 |
* @param array<mixed> $file |
| 14 |
* @return string Empty on success, error message on failure. |
| 15 |
*/ |
| 16 |
function validate(array $file): string { |
| 17 |
$allowed_extensions = array('csv', 'txt'); |
| 18 |
$file_ext = strtolower(pathinfo($this->stringField($file, 'name'), PATHINFO_EXTENSION)); |
| 19 |
if (!in_array($file_ext, $allowed_extensions)) { |
| 20 |
return __('Error: Invalid file type. Only CSV/TXT files are allowed.', '404-solution'); |
| 21 |
} |
| 22 |
|
| 23 |
$max_file_size = 5 * 1024 * 1024; |
| 24 |
if ($this->intField($file, 'size') > $max_file_size) { |
| 25 |
return __('Error: File too large. Maximum size is 5MB.', '404-solution'); |
| 26 |
} |
| 27 |
|
| 28 |
$allowed_mime_types = array('text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values', 'application/vnd.ms-excel'); |
| 29 |
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
| 30 |
if ($finfo === false) { |
| 31 |
return __('Error: Unable to determine file type.', '404-solution'); |
| 32 |
} |
| 33 |
$mime_type = finfo_file($finfo, $this->tmpName($file)); |
| 34 |
if (!in_array($mime_type, $allowed_mime_types)) { |
| 35 |
return __('Error: Invalid file type. Only CSV files are allowed.', '404-solution'); |
| 36 |
} |
| 37 |
|
| 38 |
return ''; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* @param array<mixed> $file |
| 43 |
* @return string |
| 44 |
*/ |
| 45 |
function tmpName(array $file): string { |
| 46 |
return $this->stringField($file, 'tmp_name'); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* @param array<mixed> $file |
| 51 |
* @param string $key |
| 52 |
* @return string |
| 53 |
*/ |
| 54 |
private function stringField(array $file, string $key): string { |
| 55 |
$value = $file[$key] ?? ''; |
| 56 |
return is_scalar($value) ? (string)$value : ''; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* @param array<mixed> $file |
| 61 |
* @param string $key |
| 62 |
* @return int |
| 63 |
*/ |
| 64 |
private function intField(array $file, string $key): int { |
| 65 |
$value = $file[$key] ?? 0; |
| 66 |
return is_numeric($value) ? (int)$value : 0; |
| 67 |
} |
| 68 |
} |
| 69 |
|