PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.21.13
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.21.13
V-3.3.0 3.2.2 3.2.1 3.2.0 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 V3.0.3 V3.0.2 -3.0.1 V_3.0.0 1.1.1 1.1.8 1.2 1.3 1.4 1.4.18 1.5.2 1.9 2.0 2.10.0 2.10.1 2.10.2 All 137 releases
bit-form / includes / Core / Util / FieldValueHandler.php

FieldValueHandler.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.21.13, at includes/Core/Util/FieldValueHandler.php

990 lines 34.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace BitCode\BitForm\Core\Util;
4
5 use BitCode\BitForm\Admin\Form\Helpers;
6 use BitCode\BitForm\Core\Form\FormManager;
7
8 final class FieldValueHandler
9 {
10 public static function replaceFieldWithValue($stringToReplaceField, $fieldValues, $formID = null)
11 {
12 if (empty($stringToReplaceField)) {
13 return $stringToReplaceField;
14 }
15 if (!is_string($stringToReplaceField)) {
16 $stringToReplaceField = wp_json_encode($stringToReplaceField);
17 }
18 $fieldValues = $formID ? self::sortValueBasedOnLayout($formID, $fieldValues) : $fieldValues;
19
20 if ($formID) {
21 $stringToReplaceField = self::replaceValueOfBf_all_data($stringToReplaceField, $fieldValues, $formID);
22 $stringToReplaceField = self::replaceRepeaterFieldValue($stringToReplaceField, $fieldValues, $formID);
23 }
24
25 $stringToReplaceField = self::replaceSmartTagWithValue($stringToReplaceField);
26
27 $fieldPattern = '/\${\w[^ ${}]*}/';
28
29 preg_match_all($fieldPattern, $stringToReplaceField, $matchedField);
30 if (empty($matchedField)) {
31 return $stringToReplaceField;
32 }
33 $uniqueFieldsInStr = array_unique($matchedField[0]);
34 foreach ($uniqueFieldsInStr as $key => $value) {
35 $fieldName = substr($value, 2, strlen($value) - 3);
36 $fieldValue = null;
37 if (isset($fieldValues[$fieldName])) {
38 $targetFieldValue = isset($fieldValues[$fieldName]['value']) ? $fieldValues[$fieldName]['value'] : $fieldValues[$fieldName];
39 if ('array' === gettype($targetFieldValue) || 'object' === gettype($targetFieldValue)) {
40 foreach ((array) $targetFieldValue as $singleTargetVal) {
41 if (isset($fieldValue)) {
42 if (is_numeric($fieldValue) && is_numeric($singleTargetVal)) {
43 $fieldValue = $fieldValue + $singleTargetVal;
44 } else {
45 $fieldValue = "$fieldValue, $singleTargetVal";
46 }
47 } else {
48 $fieldValue = $singleTargetVal;
49 }
50 }
51 // $fieldValue = wp_json_encode($targetFieldValue);
52 } else {
53 $fieldValue = strval($targetFieldValue);
54 }
55 $stringToReplaceField = str_replace($value, $fieldValue, $stringToReplaceField);
56 } else {
57 $stringToReplaceField = str_replace($value, '', $stringToReplaceField);
58 }
59 }
60
61 // check if the string is a function like : "${_bf_calc(${b27-5}*10)}"
62 // TO DO: Implement the function properly
63 // if (self::isFunction($stringToReplaceField)) {
64 // $functionName = self::getFunctionName($stringToReplaceField);
65
66 // switch ($functionName) {
67 // case '_bf_calc':
68 // return self::getFunctionParameter($stringToReplaceField);
69 // case '_bf_count':
70 // return self::getCountValue($stringToReplaceField);
71 // default:
72 // return 0;
73 // }
74 // }
75 return $stringToReplaceField;
76 }
77
78 public static function replaceBackBtnWithPrevPageUrl($stringToReplaceField)
79 {
80 $prevPageUrl = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : home_url();
81 preg_match_all('/\$?\{back_to_view\}/', $stringToReplaceField, $matches);
82 $matched = $matches[0];
83
84 if (empty($matched) || !$prevPageUrl) {
85 return $stringToReplaceField;
86 }
87
88 foreach ($matched as $m) {
89 $stringToReplaceField = str_replace($m, $prevPageUrl, $stringToReplaceField);
90 }
91 return $stringToReplaceField;
92 }
93
94 /**
95 * Summary of getCountValue - get the count value from the function string "${_bf_count(item-1, item-2)}" => 2
96 *
97 * @param string $functionString
98 * @return int
99 */
100 private static function getCountValue(string $functionString): int
101 {
102 $options = self::getFunctionParameter($functionString);
103 $option = explode(',', $options);
104 return count($option);
105 }
106
107 /**
108 * Summary of getFunctionParameter - get the function parameter from the function string "${_bf_calc(2*10)}" => 2*10
109 *
110 * @param string $functionString
111 * @return string
112 */
113 private static function getFunctionParameter(string $functionString): string
114 {
115 $regexPattern = '/\(([^)]*)\)/';
116 preg_match($regexPattern, $functionString, $matches);
117 return $matches[1];
118 }
119
120 /**
121 * Summary of isFunction - check if the string is a function "${_bf_calc(${b27-5}*10)}" or not "${_bf_date}"
122 *
123 * @param string $functionString
124 * @return bool true if the string is a function else false
125 */
126 private static function isFunction(string $functionString): bool
127 {
128 $regexPattern = '/\([^)]*\)/';
129 return preg_match($regexPattern, $functionString);
130 }
131
132 /**
133 * Summary of getFunctionName - get the function name from the function string "${_bf_calc(${b27-5}*10)}" => _bf_calc
134 *
135 * @param string $functionString
136 * @return string
137 */
138 private static function getFunctionName(string $functionString): string
139 {
140 $regexPattern = '/\b([a-zA-Z_][a-zA-Z0-9_]*)\(/';
141 preg_match($regexPattern, $functionString, $matches);
142 return $matches[1];
143 }
144
145 public static function validateMailArry($emailAddresses, $fieldValues)
146 {
147 if (!is_array($emailAddresses)) {
148 return [FieldValueHandler::replaceFieldWithValue($emailAddresses, $fieldValues)];
149 }
150 foreach ($emailAddresses as $key => $email) {
151 if (!is_email($email)) {
152 $email = FieldValueHandler::replaceFieldWithValue($email, $fieldValues);
153 if (is_email($email)) {
154 $emailAddresses[$key] = $email;
155 }
156 }
157 }
158 return $emailAddresses;
159 }
160
161 public static function replaceSmartTagWithValue($contentWithSmartTag)
162 {
163 $fieldPattern = '/(\${_[^{]*?)(?=\})}/';
164 $matchPattern = preg_match_all($fieldPattern, $contentWithSmartTag, $matchedField);
165 if (!$matchPattern) {
166 return $contentWithSmartTag;
167 }
168
169 $ajaxRequest = false;
170 // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Called from nonce-verified admin/frontend contexts.
171 if (isset($_REQUEST['action']) && 'bitforms_trigger_workflow' === $_REQUEST['action']) {
172 $ajaxRequest = true;
173 }
174
175 foreach (array_unique($matchedField[0]) as $value) {
176 $fieldName = trim(substr($value, 2, strlen($value) - 3));
177
178 $matches = preg_match('/\("*([^\)]+"*)\)/', $value, $matchCustomFormat);
179
180 $customValue = '';
181 if ($matches) {
182 $removeQuote = ["'", '"'];
183 $customValue = str_replace($removeQuote, '', $matchCustomFormat[1]);
184 $fieldName = str_replace($matchCustomFormat[0], '', $fieldName);
185 }
186
187 $tagFieldValues = SmartTags::getSmartTagValue($fieldName, $ajaxRequest, $customValue);
188
189 $contentWithSmartTag = str_replace($value, $tagFieldValues, $contentWithSmartTag);
190 }
191 return $contentWithSmartTag;
192 }
193
194 public static function isEmpty($val)
195 {
196 if (empty($val) && !in_array($val, ['0', 0, 0.0], true)) {
197 return true;
198 }
199 return false;
200 }
201
202 public static function formatFieldValueForMail($fields, $fieldValues = [])
203 {
204 $formattedFldValues = $fieldValues;
205 $file_upload_types = Helpers::$file_upload_types;
206 $repeated_array_type_data_fields = Helpers::$repeated_array_type_data_fields;
207 foreach ($fields as $fldKey => $fldData) {
208 if (in_array($fldData->typ, $file_upload_types)) {
209 continue;
210 }
211 if (array_key_exists($fldKey, $fieldValues)) {
212 $value = $fieldValues[$fldKey];
213 // if (is_array($value)) {
214 // $formattedFldValues[$fldKey] = htmlspecialchars(implode(', ', $value));
215 // } else {
216 // $formattedFldValues[$fldKey] = htmlspecialchars($value);
217 // }
218
219 // TODO: this code are temporary commented, need to change and remove the comment
220
221 // if (is_array($value)) {
222 // $arrValue = '';
223 // foreach ($value as $v) {
224 // if (is_array($v)) {
225 // foreach ($v as $k1 => $v1) {
226 // if (array_key_exists($k1, $repeaterFieldKey)) {
227 // $oldValue = $repeaterFieldKey[$k1];
228 // if (is_array($v1) && in_array($fields->{$k1}->typ, $repeated_array_type_data_fields)) {
229 // $newValues = '[' . implode(', ', $v1) . '] ';
230 // if (!preg_match('/\[.*\]/', $oldValue)) {
231 // $oldValue = '[' . $oldValue . '] ';
232 // }
233 // } else {
234 // $newValues = $v1;
235 // }
236 // $repeaterFieldKey[$k1] = $oldValue . ', ' . $newValues;
237 // } else {
238 // if (!empty($v1) && is_array($v1)) {
239 // $repeaterFieldKey[$k1] = htmlspecialchars(implode(', ', $v1));
240 // } else {
241 // $repeaterFieldKey[$k1] = htmlspecialchars($v1);
242 // }
243 // }
244 // }
245 // } else {
246 // $arrValue .= $v . ', ';
247 // }
248 // }
249 // $formattedFldValues[$fldKey] = htmlspecialchars(rtrim($arrValue, ', '));
250 // $arrValue = '';
251 // } else {
252 // $formattedFldValues[$fldKey] = htmlspecialchars($value);
253 // }
254 if ('textarea' === $fldData->typ) {
255 $formattedFldValues[$fldKey] = nl2br(htmlspecialchars($value));
256 }
257 if ('date' === $fldData->typ && !empty($value)) {
258 $formattedFldValues[$fldKey] = date_i18n(get_option('date_format'), strtotime(htmlspecialchars($value)));
259 }
260 }
261 }
262
263 $merge_values = array_merge($fieldValues, $formattedFldValues);
264 // $merge_values = array_merge($merge_values, $repeaterFieldKey);
265
266 return $merge_values;
267 }
268
269 public static function changeHrefPathInHTMLString($html_body, $path)
270 {
271 if (empty($html_body) || empty($path)) {
272 return $html_body;
273 }
274
275 return preg_replace_callback(
276 '/<a\s+[^>]*href=[\'"]([^\'"]+)[\'"][^>]*>/i',
277 function ($matches) use ($path) {
278 $href = $matches[1];
279
280 if (filter_var($href, FILTER_VALIDATE_URL)) {
281 return $matches[0];
282 }
283
284 if (preg_match('/^(mailto:|tel:|javascript:|#)/i', $href)) {
285 return $matches[0];
286 }
287 if (preg_match('/\$?\{back_to_view\}/', $matches[0])) {
288 return $matches[0];
289 }
290
291 $fullPath = rtrim($path, '/') . '/' . ltrim($href, '/');
292
293 return str_replace(
294 $href,
295 htmlspecialchars($fullPath, ENT_QUOTES),
296 $matches[0]
297 );
298 },
299 $html_body
300 );
301 }
302
303 public static function changeImagePathInHTMLString($html_body, $path)
304 {
305 $allowedExtensions = ['jpg', 'jpeg', 'png', 'svg'];
306 if (empty($html_body) || empty($path)) {
307 return $html_body;
308 }
309
310 $allowedMimeTypes = [
311 'jpg' => ['image/jpeg', 'image/pjpeg'],
312 'jpeg' => ['image/jpeg', 'image/pjpeg'],
313 'png' => ['image/png'],
314 'svg' => ['image/svg+xml']
315 ];
316
317 return preg_replace_callback(
318 '/<img\s+[^>]*src=[\'"]([^\'"]*)[\'"][^>]*>/i',
319 function ($matches) use ($path, $allowedExtensions, $allowedMimeTypes) {
320 $src = $matches[1];
321
322 if (filter_var($src, FILTER_VALIDATE_URL)) {
323 return $matches[0];
324 }
325
326 if (!trim($src)) {
327 return '';
328 }
329
330 $fullPath = rtrim($path, '/') . '/' . ltrim($src, '/');
331
332 $extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
333
334 if (!preg_match('/^(http|https):\/\//', $fullPath)) {
335 if (!file_exists($fullPath) || !isset($allowedMimeTypes[$extension])) {
336 Log::debug_log([
337 'status' => 'error',
338 'code' => 'file_not_found',
339 'message' => "File not found or unsupported file type: $fullPath",
340 ]);
341 return '';
342 } else {
343 Log::debug_log([
344 'status' => 'success',
345 'code' => 'file_found',
346 'message' => "File Found => location: {$fullPath}"
347 ]);
348 }
349 $mimeType = mime_content_type($fullPath);
350 if (!in_array($mimeType, $allowedMimeTypes[$extension], true)) {
351 Log::debug_log([
352 'status' => 'error',
353 'code' => 'unsupported_file_type',
354 'message' => "Unsupported file type: $mimeType for file: $fullPath",
355 ]);
356 return '';
357 }
358 }
359
360 return str_replace($src, htmlspecialchars($fullPath, ENT_QUOTES), $matches[0]);
361 },
362 $html_body
363 );
364 }
365
366 public static function sortValueBasedOnLayout($formId, $fieldValues)
367 {
368 $formManager = FormManager::getInstance($formId);
369 $layout = $formManager->getFormLayout();
370 $formLayout = $formManager->getFlatenFormLayout(); // returns all layouts (lg, md, sm)
371 $fieldKeyOrderbasedOnLayout = array_map(function ($fld) {
372 return $fld->i;
373 }, $formLayout->lg);
374 $ordered = [];
375
376 foreach ($fieldKeyOrderbasedOnLayout as $key) {
377 if (array_key_exists($key, $fieldValues)) {
378 $ordered[$key] = $fieldValues[$key];
379 }
380 }
381
382 foreach ($fieldValues as $k=>$v) {
383 if (!array_key_exists($k, $fieldKeyOrderbasedOnLayout)) {
384 $ordered[$k] = $fieldValues[$k];
385 }
386 }
387 return $ordered;
388 }
389
390 public static function replaceValueOfBf_all_data($stringToReplaceField, $fieldValues, $formId)
391 {
392 // $pattern = '/\$\{bf_all_data\}/'; // Corrected escaping
393 $pattern = '/\$\{bf_all_data(?:\.onlyValues)?\}/'; // Corrected escaping
394
395 preg_match_all($pattern, $stringToReplaceField, $matches);
396 $matchesArray = $matches[0] ?? [];
397 if (count($matchesArray) > 0) {
398 $formManager = FormManager::getInstance($formId);
399 $formFields = $formManager->getFields();
400 $orderedFormFields = $formManager->getFieldsBasedOnLayout(); // ordered form fields based on layout(lg) order
401 foreach ($matchesArray as $match) {
402 switch ($match) {
403 case '${bf_all_data}':
404 $fieldValues = self::bindFormData($orderedFormFields, $fieldValues, $formId);
405 $table = self::generateTable($fieldValues, $orderedFormFields);
406 $stringToReplaceField = str_replace('${bf_all_data}', $table, $stringToReplaceField);
407 break;
408
409 case '${bf_all_data.onlyValues}':
410 $fieldValues = self::bindFormData($orderedFormFields, $fieldValues, $formId, true);
411 $table = self::generateTable($fieldValues, $orderedFormFields);
412 $stringToReplaceField = str_replace('${bf_all_data.onlyValues}', $table, $stringToReplaceField);
413 break;
414 default:
415 Log::debug_log([
416 'status' => 'error',
417 'code' => 'unknown_placeholder',
418 'message' => "Unknown placeholder: $match",
419 ]);
420 break;
421 }
422 }
423 }
424 return $stringToReplaceField;
425 }
426
427 /**
428 * Ensures an <img> tag with a style attribute exists in the input.
429 *
430 * Behavior:
431 * - If the input is just an image filename (e.g., "1.png"), returns a complete <img> tag with the default style.
432 * - If the input is HTML with <img> tags:
433 * - If any <img> has a style, returns the HTML as-is.
434 * - If <img> exists without style, adds the default style to the first one found.
435 * - If no <img> tag or image file is found, returns the input unchanged.
436 *
437 * @param string $input Image filename or HTML string.
438 * @param string $defaultStyle Optional. The CSS style to apply if missing. Default: 'max-width: 100%; height: auto;'.
439 *
440 * @return string Modified HTML string with styled <img> tag if needed.
441 */
442 private static function ensureImgWithStyle($input, $defaultStyle = 'max-width: 100%; height: auto;')
443 {
444 $imgTagWithStylePattern = '/<img\b[^>]*\bstyle\s*=\s*["\'][^"\']*["\'][^>]*>/i';
445 $imgTagPattern = '/<img\b[^>]*>/i';
446 $filePattern = '/\.(jpg|jpeg|png|gif|webp)$/i';
447
448 if (preg_match($filePattern, trim($input)) && !preg_match('/<img\b/i', $input)) {
449 return '<img src="' . htmlspecialchars(trim($input)) . '" style="' . $defaultStyle . '" />';
450 }
451
452 if (preg_match($imgTagWithStylePattern, $input)) {
453 // <img> already has style, return as is
454 return $input;
455 } elseif (preg_match($imgTagPattern, $input, $match)) {
456 // <img> without style, add style
457 $updatedImg = preg_replace('/<img\b(.*?)(\/?)>/i', '<img$1 style="' . $defaultStyle . '" $2>', $match[0]);
458 return str_replace($match[0], $updatedImg, $input);
459 } else {
460 // No <img> tag found, return input
461 return $input;
462 }
463 }
464
465 private static function orderRepeaterData($repeaterFldKey, $repeaterData, $formId)
466 {
467 if (!$formId) {
468 return $repeaterData;
469 }
470
471 $formManager = FormManager::getInstance($formId);
472 $nestedLayout = $formManager->getFormNestedLayout();
473 $repeaterLayout = $nestedLayout->{$repeaterFldKey}->lg;
474 $orderedFldKey = array_map(function ($fld) {
475 return $fld->i;
476 }, $repeaterLayout);
477
478 $orderedRepeaterData = [];
479 foreach ($repeaterData as $rptr) {
480 $orderedFlds = [];
481 foreach ($orderedFldKey as $k) {
482 if (array_key_exists($k, $rptr)) {
483 $orderedFlds[$k] = $rptr[$k];
484 }
485 }
486
487 foreach ($rptr as $ky => $v) {
488 if (!array_key_exists($ky, $orderedFldKey)) {
489 $orderedFlds[$ky] = $v;
490 }
491 }
492
493 $orderedRepeaterData[] = $orderedFlds;
494 }
495 return $orderedRepeaterData;
496 }
497
498 private static function bindFormData($formFields, $formData, $formId, $isOnlyValues = false)
499 {
500 $entryID = isset($formData['entry_id']) ? $formData['entry_id'] : null;
501 return array_reduce(array_keys($formFields), function ($filteredData, $key) use ($formFields, $formData, $isOnlyValues, $formId) {
502 $field = $formFields[$key];
503
504 $fieldNewData = $filteredData;
505
506 $ignoreFields = ['button', 'recaptcha', 'html', 'divider', 'spacer', 'section', 'turnstile', 'hcaptcha', 'image'];
507
508 $arrayValueFldType = ['check', 'select', 'image-select'];
509
510 if (in_array($field['type'], $ignoreFields)) {
511 return $fieldNewData;
512 }
513
514 // Skip processing for hidden or empty fields only when $isOnlyValues is true
515 if ($isOnlyValues) {
516 // Check if the value is strictly an empty string or null, but allow 0
517 if (!isset($formData[$key]) || '' === $formData[$key] || null === $formData[$key]) {
518 return $fieldNewData;
519 }
520
521 if (isset($field['valid']['hide']) && $field['valid']['hide']) {
522 return $fieldNewData;
523 }
524 }
525
526 if (isset($formData[$key])) {
527 if ('repeater' === $field['type']) {
528 $repeater_data = is_string($formData[$key]) ? json_decode($formData[$key], true) : $formData[$key];
529 // ordering repeater field according to nested repeater layout
530 $repeater_data = self::orderRepeaterData($key, $repeater_data, $formId);
531 if ($isOnlyValues) {
532 $repeater_data = array_filter($repeater_data, function ($sub) {
533 return array_filter($sub, fn ($value) => '' !== $value);
534 });
535 }
536 $fieldNewData[$key] = $repeater_data;
537 } elseif ('signature' === $field['type']) {
538 if ('signature-failed.png' !== $formData[$key]) {
539 $file_path = strpos($formData[$key], '/') ? $formData[$key] : $formData[$key];
540 $newPath = $file_path;
541 $fieldNewData[$key] = self::ensureImgWithStyle($newPath, 'max-width: 100%; height: auto;');
542 }
543 } elseif (in_array($field['type'], $arrayValueFldType)) {
544 $v = is_string($formData[$key]) ? json_decode($formData[$key], true) : $formData[$key];
545 $fieldNewData[$key] = $v && is_array($v) ? implode(', ', $v) : $formData[$key];
546 } else {
547 $fieldNewData[$key] = $formData[$key];
548 }
549 }
550
551 return $fieldNewData;
552 }, []);
553 }
554
555 private static function generateTable($fieldValues, $formFields)
556 {
557 if (empty($fieldValues)) {
558 Log::debug_log([
559 'status' => 'error',
560 'code' => 'no_fields_found',
561 'type' => 'bf_all_data',
562 'message' => 'No fields found for bf_all_data',
563 'fields' => $fieldValues,
564 'formFields' => $formFields,
565 ]);
566 return '<p>No data available.</p>';
567 }
568
569 $table = "<table style='font-family: arial, sans-serif; border-collapse: collapse; width: 100%;'>";
570
571 foreach ($fieldValues as $fk => $value) {
572 $value = self::decodeIfJson($value);
573 $fieldName = self::getLabel($formFields, $fk) ?? $fk;
574 $fieldType = $formFields[$fk]['type'];
575 $table .= "<tr>
576 <td style='border: 1px solid #dddddd; text-align: left; padding: 8px; font-weight: bold;'>{$fieldName}</td>
577 <td style='border: 1px solid #dddddd; text-align: left; padding: 8px;'>";
578
579 if (is_array($value)) {
580 if ('repeater' === $fieldType) {
581 $table .= "<table style='width: 100%; border-collapse: collapse;'>";
582
583 $table .= '<tr>';
584 foreach (array_keys($value[0]) as $subKey) {
585 $subLabel = self::getLabel($formFields, $subKey) ?? $subKey;
586 $table .= "<th style='border: 1px solid #dddddd; padding: 8px; background-color: #f2f2f2;'>" . $subLabel . '</th>';
587 }
588 $table .= '</tr>';
589
590 foreach ($value as $row) {
591 $table .= '<tr>';
592 foreach ($row as $subKey => $subValue) {
593 if (is_array($subValue)) {
594 $subValue = self::unorderedAnchorListMarkup($subValue);
595
596 // $subValue = implode(', ', array_map(function ($v) {
597 // if (self::isFileTypeValue($v)) {
598 // return self::anchorMarkup($v);
599 // // if (self::isImageTypeValue($v)) {
600 // // return "<img src='{$v}' alt='{$v}' width='250'/>";
601 // // } else {
602 // // return "<a href='{$v}' rel='noopener noreferrer' target='_blank' style='color:blue'>{$v}</a>";
603 // // }
604 // } else {
605 // return $v;
606 // }
607 // }, $subValue));
608 } else {
609 if (self::isFileTypeValue($subValue)) {
610 if ('signature' === self::getFldType($subKey, $formFields)) {
611 if ('signature-failed.png' === $subValue) {
612 $subValue = '';
613 } else {
614 $subValue = "<img src='{$subValue}' alt='{$subValue}' width='250'/>";
615 }
616 }
617 } else {
618 $subValue = $subValue;
619 }
620 }
621
622 $table .= "<td style='border: 1px solid #dddddd; padding: 8px;'>" . $subValue . '</td>';
623 }
624 $table .= '</tr>';
625 }
626 $table .= '</table>';
627 } elseif ('file-up' === $fieldType || 'advanced-file-up' === $fieldType) {
628 if (is_array($value)) {
629 $table .= self::unorderedAnchorListMarkup($value);
630 }
631 } elseif ('signature' === $fieldType) {
632 if ('signature-failed.png' === $subValue) {
633 $table .= '';
634 } else {
635 $table .= self::imgMarkup($value);
636 }
637 }
638 } else {
639 $table .= $value;
640 }
641
642 $table .= '</td></tr>';
643 }
644
645 $table .= '</table>';
646
647 return $table;
648 }
649
650 private static function unorderedAnchorListMarkup($list)
651 {
652 $ul = "<ul style='list-style-type: none; padding: 0; margin:0'>";
653 foreach ($list as $v) {
654 $ul .= '<li >' . self::anchorMarkup($v) . '</li>';
655 }
656 $ul .= '</ul>';
657 return $ul;
658 }
659
660 private static function imgMarkup($filename)
661 {
662 return "<img src='{$filename}' alt='{$filename}' width='250'/>";
663 }
664
665 private static function anchorMarkup($filename)
666 {
667 return "<a href='{$filename}' rel='noopener noreferrer' target='_blank' style='color:blue'>{$filename}</a>";
668 }
669
670 public static function replaceRepeaterFieldValue($stringToReplaceField, $fieldValues, $formID)
671 {
672 if (!is_string($stringToReplaceField) || empty($stringToReplaceField)) {
673 return $stringToReplaceField; // Return as-is if nothing to replace
674 }
675
676 $formManager = FormManager::getInstance($formID);
677 $formFields = $formManager->getFieldsBasedOnLayout(); // ordered form fields based on layout(lg) order
678
679 // Find all placeholders like ${field_key} example: ${b27-5}
680 preg_match_all('/\$\{(b\d+-\d+)\}/', $stringToReplaceField, $matches);
681
682 if (empty($matches[1])) {
683 return $stringToReplaceField;
684 }
685 // Clean field data
686 // $dataCleaning = self::removeEmptyValues($fieldValues);
687 $flatFieldData = self::restructureRepeaterData($fieldValues, $formManager);
688 // generate table for repeater fields
689 foreach ($matches[1] as $fk) {
690 $repeaterFieldKey = $fk;
691 $fieldType = isset($formFields[$repeaterFieldKey]['type']) && !empty($formFields[$repeaterFieldKey]['type']) ? $formFields[$repeaterFieldKey]['type'] : null;
692 if ('repeater' === $fieldType) {
693 $repeaterMarkup = self::repeaterFieldTable($fieldValues[$repeaterFieldKey] ?? [], $formFields, $repeaterFieldKey);
694 $stringToReplaceField = str_replace('${' . $fk . '}', $repeaterMarkup, $stringToReplaceField);
695 } else {
696 if ('signature' === $fieldType) {
697 $stringToReplaceField = self::replaceImgTagForRepeatedSignature($stringToReplaceField, $flatFieldData[$repeaterFieldKey], $repeaterFieldKey);
698 }
699
700 $repeaterFieldData = self::safeFlatString($flatFieldData[$repeaterFieldKey] ?? '', $fieldType);
701 $stringToReplaceField = str_replace('${' . $fk . '}', $repeaterFieldData, $stringToReplaceField);
702 }
703 }
704 return $stringToReplaceField;
705 }
706
707 private static function replaceImgTagForRepeatedSignature($stringToReplaceField, $repeaterValue, $fldKey)
708 {
709 $data = self::decodeIfJson($repeaterValue);
710 if (!is_string($stringToReplaceField) || empty($stringToReplaceField) || empty($fldKey)) {
711 return $stringToReplaceField;
712 }
713
714 $pattern = '/<img\s+[^>]*src=[\'"]([^\'"]*' . preg_quote($fldKey, '/') . '[^\'"]*)[\'"][^>]*>/i';
715
716 if (!preg_match($pattern, $stringToReplaceField)) {
717 return $stringToReplaceField;
718 }
719
720 $values = [];
721 $appendValue = function ($value) use (&$values) {
722 if (is_array($value)) {
723 foreach ($value as $item) {
724 if (is_string($item) && '' !== trim($item) && 'signature-failed.png' !== $item) {
725 $values[] = $item;
726 }
727 }
728 return;
729 }
730
731 if (is_string($value) && '' !== trim($value) && 'signature-failed.png' !== $value) {
732 $values[] = $value;
733 }
734 };
735
736 $appendValue($data);
737
738 if (empty($values)) {
739 return preg_replace($pattern, '', $stringToReplaceField);
740 }
741
742 return preg_replace_callback($pattern, function ($matches) use ($values) {
743 $imgTags = array_map(function ($value) use ($matches) {
744 $src = htmlspecialchars($value, ENT_QUOTES);
745 $alt = htmlspecialchars($value, ENT_QUOTES);
746
747 $tag = $matches[0];
748 $tag = preg_replace('/\bsrc\s*=\s*([\'"])(.*?)\1/i', 'src="' . $src . '"', $tag);
749
750 if (preg_match('/\balt\s*=\s*([\'"])(.*?)\1/i', $tag)) {
751 $tag = preg_replace('/\balt\s*=\s*([\'"])(.*?)\1/i', 'alt="' . $alt . '"', $tag);
752 } else {
753 $tag = preg_replace('/<img\b/i', '<img alt="' . $alt . '"', $tag, 1);
754 }
755
756 return $tag;
757 }, $values);
758
759 return implode('', $imgTags);
760 }, $stringToReplaceField);
761 }
762
763 /**
764 * Restructures repeater field data to maintain original structure while
765 * aggregating nested repeater values into top-level indexed arrays.
766 *
767 * @param array $data Original field data structure
768 * @return array Restructured data with aggregated arrays
769 */
770 public static function restructureRepeaterData(array $data, $formManagerInstance): array
771 {
772 $result = $data;
773 // topkey === field Key topValue === field value
774 foreach ($data as $topKey => $topValue) {
775 if ($formManagerInstance->isRepeaterField($topKey)) {
776 $topValue = self::decodeIfJson($topValue);
777 //assigning the converted value to repeater field
778 $result[$topKey] = $topValue;
779 // topvalue here is repeater field value;
780 // entryIndex repeater field key , entry == repeater field value
781 foreach ($topValue as $entryIndex => $entry) {
782 if (!is_array($entry)) {
783 continue;
784 }
785 foreach ($entry as $subKey => $subValue) {
786 if (!isset($result[$subKey]) || !is_array($result[$subKey])) {
787 $result[$subKey] = [];
788 }
789 // Handle nested arrays within entries
790 $result[$subKey][$entryIndex] = $subValue;
791 }
792 }
793 }
794 }
795 return $result;
796 }
797
798 /**
799 * Return decoded data if incoming data is stringified and if it's a plain string (e.g "John Doe") it returns the plain string
800 *
801 * @param mixed $data
802 * @return mixed
803 */
804 private static function decodeIfJson($data)
805 {
806 if (!is_string($data)) {
807 return $data;
808 }
809
810 $decoded = json_decode($data, true);
811
812 return (JSON_ERROR_NONE === json_last_error()) ? $decoded : $data;
813 }
814
815 /**
816 * Safely converts any type of form value(Specially Repeater Field Value) to string.
817 *
818 * @param mixed $data
819 * @param string $fldType
820 * @return string
821 */
822 public static function safeFlatString($data, $fldType): string
823 {
824 $newData = self::decodeIfJson($data);
825 if (is_array($newData)) {
826 return implode(', ', array_map(function ($item) use ($fldType) {
827 return is_array($item)
828 ? '[' . implode(', ', array_map(function ($itm) use ($fldType) {
829 if (in_array($fldType, ['advanced-file-up', 'file-up']) || self::isFileTypeValue($itm)) {
830 return self::anchorMarkup($itm);
831 // if (self::isImageTypeValue($itm)) {
832 // return "<img src='{$itm}' alt='{$itm}' width='250'/>";
833 // } else {
834 // return "<a href='{$itm}' rel='noopener noreferrer' target='_blank' style='color:blue'>{$itm}</a>";
835 // }
836 } else {
837 return $itm;
838 }
839 }, $item)) . ']'
840 : self::safeFlatString($item, $fldType);
841 }, $newData));
842 }
843
844 if (is_object($data)) {
845 return method_exists($data, '__toString') ? (string) $data : (json_encode($data) ?: '');
846 }
847
848 if (is_null($data)) {
849 return '';
850 }
851
852 if (self::isFileTypeValue($data)) {
853 if ('signature-failed.png' === $data) {
854 return '';
855 }
856 }
857
858 if (in_array($fldType, ['signature', 'file-up', 'advanced-file-up'])) {
859 return self::anchorMarkup($newData);
860 }
861
862 return (string) $data;
863 }
864
865 private static function removeEmptyValues($fieldData)
866 {
867 if (!is_array($fieldData)) {
868 return $fieldData;
869 }
870 // Remove empty values from the array
871 return array_filter($fieldData, function ($value) {
872 // Check if the value is 0
873 if (0 === $value) {
874 return '0';
875 }
876 return !empty($value);
877 });
878 }
879
880 /**
881 * Gets the field type by field key
882 *
883 * @param string $fldKey
884 * @param mixed $formField
885 * @return string
886 */
887 private static function getFldType($fldKey, $formFields)
888 {
889 if (array_key_exists($fldKey, $formFields)) {
890 return $formFields[$fldKey]['type'];
891 }
892 }
893
894 /**
895 * Return true is it's file type value by checking with extension
896 *
897 * @param string $filename
898 * @return boolean
899 */
900 private static function isFileTypeValue($fileName)
901 {
902 if (!is_string($fileName)) {
903 return false;
904 }
905 $ext = pathinfo($fileName, PATHINFO_EXTENSION);
906
907 if ('other' !== FileHandler::getFileTypeByExtension($ext)) {
908 return true;
909 }
910 }
911
912 /**
913 * Return true is it's image type value by checking with extension
914 *
915 * @param string $filename
916 * @return boolean
917 */
918 private static function isImageTypeValue($fileName)
919 {
920 if (!is_string($fileName)) {
921 return false;
922 }
923 $ext = pathinfo($fileName, PATHINFO_EXTENSION);
924
925 if ('image' === FileHandler::getFileTypeByExtension($ext)) {
926 return true;
927 }
928 }
929
930 private static function repeaterFieldTable($repeaterFieldData, $formFields, $repeaterFieldKey)
931 {
932 $repeaterFieldData = self::decodeIfJson($repeaterFieldData);
933
934 if (!is_array($repeaterFieldData) || !isset($repeaterFieldData[0]) || !is_array($repeaterFieldData[0])) {
935 return ''; // Safely return empty if not a valid repeater structure
936 }
937 $table = "<table style='font-family: arial, sans-serif; border-collapse: collapse; width: 100%;'>";
938 // $table .= '<tr>';
939 // $table .= '<th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">' . self::getLabel($formFields, $repeaterFieldKey) . '</th>';
940 // $table .= '</tr>';
941 // $table .= '<td style="border: 1px solid #dddddd; text-align: left; padding: 8px;">';
942 // $table .= '<table style="width: 100%; border-collapse: collapse;">';
943
944 $headers = array_keys($repeaterFieldData[0]);
945 $table .= '<tr>'; // open tr (for column header)
946 foreach ($headers as $fk) {
947 $table .= '<th style="border: 1px solid #dddddd; padding: 8px; ">' . self::getLabel($formFields, $fk) . '</th>';
948 }
949 $table .= '</tr>'; // close tr (for column header)
950
951 foreach ($repeaterFieldData as $row) {
952 $table .= '<tr>'; // open tr (for table data row)
953 foreach ($row as $k=>$value) {
954 $fldTyp = self::getFldType($k, $formFields);
955 if (is_array($value)) {
956 if (in_array($fldTyp, ['advanced-file-up', 'file-up'])) {
957 $newValue = self::unorderedAnchorListMarkup($value);
958 } else {
959 $newValue = implode(', ', $value);
960 }
961 } else {
962 if (self::isFileTypeValue($value)) {
963 $newValue = 'signature-failed.png' === $value
964 ? ''
965 : (self::isImageTypeValue($value)
966 ? "<img src='{$value}' alt='{$value}' width='250'/>"
967 : "<a href='{$value}' rel='noopener noreferrer' target='_blank' style='color:blue'>{$value}</a>");
968 } else {
969 $newValue = $value;
970 }
971 }
972
973 $table .= '<td style="border: 1px solid #dddddd; padding: 8px;">' . $newValue . '</td>';
974 }
975 $table .= '</tr>'; // close tr (for table data row)
976 }
977 // $table .= '</table>';
978
979 // $table .= '</td>';
980 $table .= '</table>';
981
982 return $table;
983 }
984
985 private static function getLabel($formFields, $key)
986 {
987 return $formFields[$key]['label'] ?? $key;
988 }
989 }
990