PluginProbe
404 Solution / 4.3.0
404 Solution v4.3.0
4.3.5 4.3.4 4.3.3 4.3.2 4.3.1 4.3.0 4.2.0 4.1.19 4.1.18 4.1.17 4.1.16 4.1.15 4.1.13 4.1.12 4.1.11 4.1.10 4.1.9 4.1.8 4.1.7 4.1.6 4.1.5 4.1.4 4.1.3 trunk 2.30.0 All 109 releases
404-solution / includes / services / ImportUploadValidator.php

ImportUploadValidator.php in 404 Solution 4.3.0, at includes/services/ImportUploadValidator.php

69 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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