Jake Vanderwerf
2026-03-03 772462eeca3002a1d52508aeba485aab2b4742ad
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<?php
namespace JVBase\meta;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
/**
 * Handles meta value sanitization
 */
class Sanitizer
{
 
    public static function sanitize(mixed $value, array $field_config): mixed
    {
        $callback = static::getCallback($field_config);
 
        if (is_array($callback)) {
            return call_user_func([static::class, $callback[1]], $value, $field_config);
        }
        if (method_exists(static::class, $callback)) {
            return static::$callback($value, $field_config);
        }
 
        return call_user_func($callback, $value);
    }
 
    public static function getCallback(array $field_config):mixed
    {
        return $field_config['sanitize'] ??
           MetaTypeManager::getSanitizeCallback($field_config['type']);
    }
 
    protected static function sanitizeTaxonomy(array|string $values, array $field_config):string
    {
        if (!is_array($values)) {
            $values = explode(',', $values);
        }
 
        // Ensure taxonomy starts with BASE
        $taxonomy = (str_starts_with($field_config['taxonomy'], BASE))
            ? $field_config['taxonomy']
            : BASE . $field_config['taxonomy'];
 
        $values = array_filter($values, fn($value) => term_exists((int)$value, $taxonomy));
 
        return implode(',', $values);
    }
 
    protected static function sanitizeUser(array|string $values, array $field_config):string
    {
        if (!is_array($values)) {
            $values = explode(',', $values);
        }
 
        $values = array_filter($values, fn($value) => (bool)get_userdata((int)$value));
 
        return implode(',', $values);
    }
 
    protected static function sanitizeTagList(array $values, array $field_config): array
    {
        if (empty(array_filter($values, fn($value) => !empty($value)))) {
            return [];
        }
 
        if (!isset($field_config['fields']) || !is_array($field_config['fields'])) {
            return [];
        }
 
        $sanitized = [];
 
        foreach ($values as $row) {
            if (!is_array($row)) {
                continue;
            }
 
            // Clean up field names (remove prefixes like "fieldname:0:email")
            $temp = [];
            foreach ($row as $key => $value) {
                $key_parts = explode(':', $key);
                $clean_key = $key_parts[array_key_last($key_parts)];
                $temp[$clean_key] = $value;
            }
            $row = $temp;
 
            // Sanitize each field
            $clean_row = [];
            foreach ($field_config['fields'] as $key => $subfield_config) {
                if (!array_key_exists($key, $row)) {
                    continue;
                }
 
                $subfield_config['name'] = $key; // For backwards compatibility
                $clean_row[$key] = static::sanitize($row[$key], $subfield_config);
            }
 
            // Only add row if it has at least one non-empty value
            if (!empty(array_filter($clean_row))) {
                $sanitized[] = $clean_row;
            }
        }
 
        return $sanitized;
    }
 
    protected static function sanitizeRepeater(array $values, array $field_config):array
    {
        if (empty(array_filter($values, fn($value) => !empty($value)))) {
            return [];
        }
 
 
        $sanitized = [];
        foreach ($values as $row) {
            if (!is_array($row)) {
                continue;
            }
            $temp = [];
            foreach ($row as $key => $value) {
                $key = explode(':', $key);
                $temp[$key[array_key_last($key)]] = $value;
            }
            $row = $temp;
 
            $clean_row = [];
            foreach ($field_config['fields'] as $key => $subfield_config) {
                if (!array_key_exists($key, $row)) {
                    continue;
                }
                $subfield_config['name'] = $key;//For backwards compatability
                $clean_row[$key] = static::sanitize($row[$key], $subfield_config);
            }
            $sanitized[] = $clean_row;
        }
 
        return $sanitized;
    }
 
    protected static function sanitizeGroup(array|string $values, array $field_config):array
    {
        if (!is_array($values)) {
            return [];
        }
 
        if (!isset($field_config['fields']) || !is_array($field_config['fields'])) {
            return [];
        }
 
        // Remove group: prefix from keys if present
        $clean_values = [];
        foreach ($values as $key => $value) {
            $key_parts = explode(':', $key);
            $clean_key = $key_parts[array_key_last($key_parts)];
            $clean_values[$clean_key] = $value;
        }
 
        $sanitized = [];
        foreach ($field_config['fields'] as $key => $subfield_config) {
            if (!array_key_exists($key, $clean_values)) {
                // Use default value if not provided
                $default = MetaTypeManager::getType($subfield_config['type'])['default'] ?? '';
                $sanitized[$key] = $default;
                continue;
            }
 
            $subfield_config['name'] = $key; // For backwards compatibility
            $sanitized[$key] = static::sanitize($clean_values[$key], $subfield_config);
        }
 
        return $sanitized;
    }
 
    protected static function sanitizeUpload(array|string $value):string
    {
        if (empty($value)) {
            return '';
        }
 
        // Split value into array if it's a string
        $ids = is_array($value) ? $value : explode(',', $value);
 
        // Filter and validate each ID
        $valid_ids = array_filter($ids, function ($id) {
            $id = absint($id);
            // Verify this is a valid attachment
            return $id > 0 && wp_attachment_is_image($id);
        });
        return implode(',', $valid_ids);
    }
 
    protected static function sanitizeLocation(array $value, array $field_config):array
    {
        error_log('Location field to sanitize: '.print_r($value, true));
        return [
            'address' => sanitize_text_field($value['address'] ?? ''),
            'lat' => (float)($value['lat'] ?? 0),
            'lng' => (float)($value['lng'] ?? 0),
            // Address components
            'street' => sanitize_text_field($value['street'] ?? ''),
            'city' => sanitize_text_field($value['city'] ?? ''),
            'province' => sanitize_text_field($value['province'] ?? ''),
            'postal_code' => sanitize_text_field($value['postal_code'] ?? ''),
            'country' => sanitize_text_field($value['country'] ?? '')
        ];
    }
 
    protected static function sanitizeOptions(array|string $value, array $field_config):string
    {
        error_log('Sanitizing options: '.print_r($value, true));
        if (!isset($field_config['options'])) {
            return '';
        }
        if (!is_array($value)) {
            $value = array_map('trim', explode(',', $value));
        }
        return implode(',', array_intersect($value, array_keys($field_config['options'])));
    }
 
    protected static function sanitizeDate(string $value, array $field_config):string
    {
        $timestamp = strtotime($value);
        return $timestamp ? date('Y-m-d', $timestamp) : '';
    }
 
    protected static function sanitizeDateTime(string $value, array $field_config): string
    {
        if (empty($value)) {
            return '';
        }
 
        $timestamp = strtotime($value);
        if (!$timestamp) {
            return '';
        }
 
        // Return in MySQL datetime format
        return date('Y-m-d H:i:s', $timestamp);
    }
 
    protected static function sanitizeTime(string $value, array $field_config):string
    {
        // Remove any whitespace
        $value = trim($value);
 
        // Convert to lowercase for consistency
        $value = strtolower($value);
 
        // Pattern to match various time formats
        $patterns = [
            // 10am, 2pm, etc.
            '/^(\d{1,2})(am|pm)$/' => function ($matches) {
                $hour = (int)$matches[1];
                if ($matches[2] === 'pm' && $hour < 12) {
                    $hour += 12;
                } elseif ($matches[2] === 'am' && $hour === 12) {
                    $hour = 0;
                }
                return sprintf('%02d:00', $hour);
            },
 
            // 10:30am, 2:15pm, etc.
            '/^(\d{1,2}):(\d{2})(am|pm)$/' => function ($matches) {
                $hour = (int)$matches[1];
                $minute = (int)$matches[2];
                if ($matches[3] === 'pm' && $hour < 12) {
                    $hour += 12;
                } elseif ($matches[3] === 'am' && $hour === 12) {
                    $hour = 0;
                }
                return sprintf('%02d:%02d', $hour, $minute);
            },
 
            // 14:30, 09:45, etc. (24-hour format)
            '/^(\d{1,2}):(\d{2})$/' => function ($matches) {
                $hour = (int)$matches[1];
                $minute = (int)$matches[2];
                return sprintf('%02d:%02d', $hour, $minute);
            },
 
            // Just hours like "14", "9" (assuming 24-hour and whole hours)
            '/^(\d{1,2})$/' => function ($matches) {
                $hour = (int)$matches[1];
                return sprintf('%02d:00', $hour);
            }
        ];
 
        // Try each pattern
        foreach ($patterns as $pattern => $callback) {
            if (preg_match($pattern, $value, $matches)) {
                $time = $callback($matches);
 
                // Validate the resulting time
                $hour = (int)substr($time, 0, 2);
                $minute = (int)substr($time, 3, 2);
 
                if ($hour >= 0 && $hour <= 23 && $minute >= 0 && $minute <= 59) {
                    return $time; // Valid time in HH:MM format
                }
            }
        }
 
        // If no pattern matched or time was invalid
        return '';
    }
 
    public static function sanitizeFloat(string $value, array $config):float
    {
            if (is_numeric($value)) {
                return (float) $value;
            }
            return 0.0;
    }
 
    public static function sanitizePhone(string|int $value, array $config = []):string
    {
        $digits = preg_replace('/\D/', '', (string) $value);
 
        $length = strlen($digits);
 
        if ($length < 10 || $length > 13) { // 13 = 3-digit country code + 10
            return '';
        }
 
        $countryCode = $length > 10 ? substr($digits, 0, $length - 10) : null;
        $number = substr($digits, -10);
 
        $formatted = preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $number);
 
        return $countryCode ? '+' . $countryCode . '-' . $formatted : $formatted;
    }
}