PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / V-3.3.0
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder vV-3.3.0
3.3.1 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 All 138 releases
bit-form / includes / Core / Form / FormManager.php

FormManager.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder V-3.3.0, at includes/Core/Form/FormManager.php

2,094 lines 79.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Get set Form,fields
5 */
6
7 namespace BitCode\BitForm\Core\Form;
8
9 /**
10 * FrontendFormManager class
11 */
12
13 use BitCode\BitForm\Admin\Form\CustomFieldHandler;
14 use BitCode\BitForm\Admin\Form\Helpers;
15 use BitCode\BitForm\Core\Database\FormEntryLogModel;
16 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
17 use BitCode\BitForm\Core\Database\FormEntryModel;
18 use BitCode\BitForm\Core\Database\FormModel;
19 use BitCode\BitForm\Core\Integration\IntegrationHandler;
20 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
21 use BitCode\BitForm\Core\Util\FieldValueHandler;
22 use BitCode\BitForm\Core\Util\FileHandler;
23 use BitCode\BitForm\Core\Util\FrontendHelpers;
24 use BitCode\BitForm\Core\Util\IpTool;
25 use BitCode\BitForm\Core\Util\Log;
26 use BitCode\BitForm\Core\Util\Translation\FormContentTranslator;
27 use BitCode\BitForm\Core\Util\Utilities;
28 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
29 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
30 use BitCode\BitForm\enshrined\svgSanitize\Sanitizer;
31 use stdClass;
32 use WP_Error;
33
34 class FormManager
35 {
36 // Cache for instances of FormManager by form_id
37 private static $formManagerCache = [];
38
39 /**
40 * Object-cache group for translated form_content.
41 */
42 public const TRANSLATION_CACHE_GROUP = 'bitform_translation';
43
44 /**
45 * Request-scoped memo of translated form_content JSON, keyed "formId|lang".
46 * Static on purpose, unlike $form: the key carries the form id and the
47 * language, so an entry cannot be read back for the wrong form.
48 *
49 * @var array<string,string>
50 */
51 private static $translatedContentCache = [];
52
53 // Per-instance, never static: a static is shared with every subclass and overwritten by the
54 // last-constructed manager, so cached instances would read another form's row.
55 protected $form;
56 protected $formModel;
57 protected $form_id;
58 private $_has_upload;
59 private $_field_label;
60 private $_fields;
61 private $_repeaterFields;
62 private $_work_flows;
63 private $_conf_messages;
64 private $_atomic_class_map;
65 private $_saveFormAsDraft;
66
67 public function __construct($form_id)
68 {
69 $this->form_id = $form_id;
70 $this->formModel = new FormModel();
71
72 $this->form = $this->formModel->get(
73 [
74 'id',
75 'form_content',
76 'form_name',
77 'created_at',
78 'views',
79 'entries',
80 'status',
81 'builder_helper_state',
82 'atomic_class_map',
83 'generated_script_page_ids',
84 ],
85 [
86 'id' => $form_id,
87 ]
88 );
89 if (!is_wp_error($this->form)) {
90 $atomicClassMap = isset($this->form[0]->atomic_class_map) ? $this->form[0]->atomic_class_map : '';
91 $this->_atomic_class_map = json_decode((string) $atomicClassMap);
92 $bfMultipleFormsExists = FrontendHelpers::hasMultipleForms();
93 if ($bfMultipleFormsExists && isset($this->_atomic_class_map->atomic_class_map_with_form_id)) {
94 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map_with_form_id;
95 } elseif (isset($this->_atomic_class_map->atomic_class_map)) {
96 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map;
97 }
98 } else {
99 // Log the error if needed
100 Log::debug_log('Error fetching form: ' . "Form Id = ($form_id)" . $this->form->get_error_message());
101 }
102 }
103
104 /**
105 * Test hook: clears the request memo of translated form_content.
106 */
107 public static function resetTranslationMemoForTesting()
108 {
109 self::$translatedContentCache = [];
110 }
111
112 // Static method to get the instance of FormManager
113 public static function getInstance($form_id)
114 {
115 // Check if an instance of FormManager is already cached
116 if (!isset(self::$formManagerCache[$form_id])) {
117 // Create and cache the FormManager instance if not found
118 self::$formManagerCache[$form_id] = new self($form_id);
119 }
120
121 // Return the cached instance
122 return self::$formManagerCache[$form_id];
123 }
124
125 public function isExist()
126 {
127 return (!$this->form || is_wp_error($this->form)) ? false : true;
128 }
129
130 public function checkStatus()
131 {
132 // Fail closed for a missing form: $this->form is a WP_Error when the lookup
133 // found nothing, and the unauthenticated submit endpoints call this before
134 // isExist() — indexing it there fatals on any unknown form id.
135 if (!$this->isExist()) {
136 return false;
137 }
138 return '1' === $this->form[0]->status ? true : false;
139 }
140
141 public function getFieldsContent()
142 {
143 // Raw on purpose: FormFieldValidator's allowed-option lookup must compare
144 // against the source-language config whatever the request language is.
145 return $this->form[0]->form_content;
146 }
147
148 /**
149 * form_content JSON with display strings passed through
150 * `bitform_translate_form_string`; the raw string when nothing is hooked.
151 * Never persisted back to the row — stored form_content stays source-language.
152 * AdminFormManager overrides this to always return raw.
153 *
154 * @return string
155 */
156 protected function getEffectiveFormContentJson()
157 {
158 // $this->form is a WP_Error when the form was not found; indexing it here
159 // fataled for callers that pass an unknown or empty form id
160 $raw = $this->isExist() ? ($this->form[0]->form_content ?? '') : '';
161 $raw = is_string($raw) ? $raw : '';
162 if ('' === $raw || !has_filter('bitform_translate_form_string')) {
163 return $raw;
164 }
165
166 $rowId = isset($this->form[0]->id) ? (int) $this->form[0]->id : (int) $this->form_id;
167 $lang = (string) apply_filters('bitform_current_language', '', $rowId);
168 $memoKey = $rowId . '|' . $lang;
169 if (isset(self::$translatedContentCache[$memoKey])) {
170 return self::$translatedContentCache[$memoKey];
171 }
172
173 // Content-addressed, so a form save can never serve a stale entry. Edits on
174 // the translation side do not change the hash — the TTL bounds those.
175 $ttl = (int) apply_filters('bitform_translation_cache_ttl', HOUR_IN_SECONDS, $rowId, $lang);
176 $cacheKey = $ttl > 0 ? "form-{$rowId}-{$lang}-" . md5($raw) : '';
177
178 if ('' !== $cacheKey) {
179 $cached = wp_cache_get($cacheKey, self::TRANSLATION_CACHE_GROUP);
180 if (is_string($cached) && '' !== $cached) {
181 self::$translatedContentCache[$memoKey] = $cached;
182 return $cached;
183 }
184 }
185
186 $translated = $raw;
187 $decoded = Utilities::jsonObj($raw);
188 if ($decoded instanceof stdClass) {
189 FormContentTranslator::translate($decoded, $rowId);
190 $encoded = wp_json_encode($decoded);
191 $translated = is_string($encoded) ? $encoded : $raw;
192 }
193
194 if ('' !== $cacheKey) {
195 wp_cache_set($cacheKey, $translated, self::TRANSLATION_CACHE_GROUP, $ttl);
196 }
197 self::$translatedContentCache[$memoKey] = $translated;
198
199 return $translated;
200 }
201
202 public function getFont()
203 {
204 $atomicClassMap = $this->_atomic_class_map;
205 $font = isset($atomicClassMap->font) ? $atomicClassMap->font : '';
206 return $font;
207 }
208
209 public function getStyle()
210 {
211 $builerState = Utilities::jsonObj($this->isExist() ? ($this->form[0]->builder_helper_state ?? '') : '');
212 $style = '';
213 $themeVars = $builerState->themeVars ?? null;
214 $themeColors = $builerState->themeColors ?? null;
215
216 if (!empty($themeVars)) {
217 $style .= ':root {';
218 foreach ($themeVars->lgLightThemeVars as $key => $value) {
219 $style .= "$key: $value; ";
220 }
221 $style .= '} ';
222 }
223 if (!empty($themeColors)) {
224 $style .= ' :root {';
225 foreach ($themeColors->lightThemeColors as $k => $v) {
226 $style .= "$k:$v; ";
227 }
228 $style .= '} ';
229 }
230
231 $field = $builerState->style->lgLightStyles->fields;
232 foreach ($field as $value) {
233 $classes = $value->classes;
234 foreach ($classes as $key => $value) {
235 $style .= "{$key} {";
236 foreach ($value as $k => $v) {
237 $style .= "$k:$v; ";
238 }
239 $style .= '} ';
240 }
241 }
242 return $style;
243 }
244
245 public function getCustomStyle()
246 {
247 $customCSSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.css";
248 return FileHandler::readFile($customCSSPath);
249 }
250
251 public function getCustomJS()
252 {
253 $customJsPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.js";
254 return FileHandler::readFile($customJsPath);
255 }
256
257 public function getFormContentWithValue($defaultValues = [])
258 {
259 $form_content = Utilities::jsonObj($this->getEffectiveFormContentJson());
260 // this filter just use private purpose
261 if (isset($form_content->fields)) {
262 $form_content->fields = apply_filters('bitform_dynamic_field_filter', $form_content->fields);
263 }
264 if (!is_array($defaultValues) || 0 === count($defaultValues)) {
265 return $form_content;
266 }
267 foreach (($form_content->fields ?? []) as $fieldKey => $fieldDetails) {
268 // $field_name = empty($fieldDetails->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $fieldDetails->lbl);
269 $fieldName = $fieldDetails->fieldName;
270 $defaultValue = isset($defaultValues[$fieldName]) ? $defaultValues[$fieldName] : null;
271 $defaultValue = isset($defaultValues[$fieldKey]) ? $defaultValues[$fieldKey] : $defaultValue;
272 if ((isset($fieldDetails->mul) || 'check' === $fieldDetails->typ) && isset($defaultValue)) {
273 // if (is_array($defaultValue)) {
274 // $fieldDetails->val =
275 // wp_json_encode(
276 // array_map('sanitize_text_field', $defaultValue)
277 // );
278 // } else {
279 // $fieldDetails->val = sanitize_text_field($defaultValue);
280 // }
281 if ((isset($fieldDetails->mul) && true === $fieldDetails->mul) || is_array($defaultValue)) {
282 $fieldDetails->val = wp_json_encode(array_map('sanitize_text_field', $defaultValue));
283 } elseif (!is_array($defaultValue)) {
284 $fieldDetails->val = sanitize_text_field($defaultValue);
285 }
286 } elseif (!is_null($defaultValue)) {
287 $fieldDetails->val = self::sanitizeDefaultValue($defaultValue);
288 }
289 }
290 return $form_content;
291 }
292
293 /**
294 * Normalize a prefill value into the scalar `val` a field can hold.
295 *
296 * Composite fields (address, name, …) arrive as associative arrays, which a
297 * numeric last-index lookup cannot read.
298 *
299 * @param mixed $defaultValue
300 *
301 * @return string
302 */
303 private static function sanitizeDefaultValue($defaultValue)
304 {
305 if (is_string($defaultValue)) {
306 return sanitize_text_field($defaultValue);
307 }
308
309 if (is_scalar($defaultValue)) {
310 return sanitize_text_field((string) $defaultValue);
311 }
312
313 if (is_object($defaultValue)) {
314 $defaultValue = (array) $defaultValue;
315 }
316
317 if (!is_array($defaultValue) || 0 === count($defaultValue)) {
318 return '';
319 }
320
321 // A plain list is a repeated query param — keep the historic "last one wins".
322 if (array_keys($defaultValue) === range(0, count($defaultValue) - 1)) {
323 $last = end($defaultValue);
324 return is_scalar($last) ? sanitize_text_field((string) $last) : (string) wp_json_encode($last);
325 }
326
327 // Keyed (composite) value: keep the whole shape, same as the `mul` branch above.
328 return (string) wp_json_encode(map_deep($defaultValue, 'sanitize_text_field'));
329 }
330
331 public function getFormContent()
332 {
333 $formContent = Utilities::jsonObj($this->getEffectiveFormContentJson());
334 $types = ['check', 'radio', 'select'];
335 $filter = false;
336 foreach (($formContent->fields ?? []) as $field) {
337 if (in_array($field->typ, $types) && property_exists($field, 'customType')) {
338 $filter = true;
339 break; // reduce unnecessary loop
340 }
341 }
342 if (true === $filter) {
343 $updateFields = apply_filters('bitform_dynamic_field_filter', $formContent->fields);
344 $formContent->fields = $updateFields;
345 }
346 return $formContent;
347 }
348
349 public function getFormInfo()
350 {
351 $formContent = json_decode($this->getEffectiveFormContentJson());
352 $formInfo = isset($formContent->formInfo) ? $formContent->formInfo : null;
353 return $formInfo;
354 }
355
356 public function getFormPermission()
357 {
358 $formContent = json_decode($this->form[0]->form_content);
359 $formPermission = isset($formContent->formPermissions) ? $formContent->formPermissions : null;
360 return $formPermission;
361 }
362
363 public function getFormHelperStates()
364 {
365 $formHelperStates = json_decode($this->form[0]->builder_helper_state);
366 return $formHelperStates;
367 }
368
369 public function getAtomicClsMap()
370 {
371 return $this->_atomic_class_map;
372 }
373
374 private function is_json($str)
375 {
376 $json = json_decode($str);
377 return $json && $str !== $json;
378 }
379
380 public function getFormData($columnName = '')
381 {
382 if (empty($columnName)) {
383 return null;
384 }
385
386 $form = $this->form[0];
387 if (!isset($form->{$columnName})) {
388 return null;
389 }
390
391 $data = $form->{$columnName};
392 if ($this->is_json($data)) {
393 return json_decode($data);
394 }
395
396 return $data;
397 }
398
399 public function getFormName()
400 {
401 return $this->form[0]->form_name;
402 }
403
404 public function getFormLayout()
405 {
406 $formContent = $this->getFormContent();
407 return isset($formContent->layout) ? $formContent->layout : new stdClass();
408 }
409
410 public function getFormNestedLayout()
411 {
412 $formContent = $this->getFormContent();
413 return isset($formContent->nestedLayout) ? $formContent->nestedLayout : new stdClass();
414 }
415
416 private function mergeNestedLayout(&$layout, $nestedLayout)
417 {
418 foreach ($nestedLayout as $key => $brkpnts) {
419 foreach ($brkpnts as $brkpnt=>$nLayout) {
420 $layout->{$brkpnt} = array_merge(isset($layout->{$brkpnt}) ? (array) $layout->{$brkpnt} : [], (array) $nLayout);
421 }
422 }
423 }
424
425 public function flatMultistepFormLayout()
426 {
427 $formLayout = $this->getFormLayout();
428 $multistepLayout = new stdClass();
429 foreach ($formLayout as $stpLayout) {
430 $lyout = $stpLayout->layout;
431
432 foreach ($lyout as $brkpnt=>$fields) {
433 $multistepLayout->{$brkpnt} = array_merge($multistepLayout->{$brkpnt} ?? [], $fields);
434 }
435 }
436
437 return $multistepLayout;
438 }
439
440 public function getFlatenFormLayout()
441 {
442 $layout = $this->getFormLayout();
443 $nestedLayout = $this->getFormNestedLayout();
444 if ('array' === gettype($layout)) {
445 // multi step form layout
446 $layout = $this->flatMultistepFormLayout();
447 }
448 if (!empty((array) $nestedLayout)) {
449 $this->mergeNestedLayout($layout, $nestedLayout);
450 }
451
452 return $layout;
453 }
454
455 /**
456 * Union of field keys referenced by ANY breakpoint (lg/md/sm) of the root
457 * layout (all steps) plus nested layouts of RENDERED containers.
458 *
459 * Nested layout entries are gated by their parent key being in the root
460 * layout — the renderer (FormViewer) only renders nested children of
461 * containers present in the root layout, so a stale nestedLayout entry
462 * (parent removed) must not mark its children as rendered.
463 *
464 * Returns [] when the layout is missing or unparseable — callers MUST
465 * fail closed (validate all fields) on an empty result.
466 *
467 * @return string[]
468 */
469 public function getLayoutFieldKeys()
470 {
471 try {
472 $layout = $this->getFormLayout();
473 $nestedLayout = $this->getFormNestedLayout();
474 if ('array' === gettype($layout)) {
475 // multi step form layout
476 $layout = $this->flatMultistepFormLayout();
477 }
478 } catch (\Throwable $e) {
479 return [];
480 }
481 $rootKeys = self::collectLayoutKeys($layout);
482 if (empty($rootKeys)) {
483 return [];
484 }
485 $keys = array_fill_keys($rootKeys, true);
486 if (is_object($nestedLayout) || is_array($nestedLayout)) {
487 foreach ($nestedLayout as $parentKey => $nLay) {
488 if (!isset($keys[$parentKey])) {
489 continue; // stale entry: container no longer rendered
490 }
491 foreach (self::collectLayoutKeys($nLay) as $nestedKey) {
492 $keys[$nestedKey] = true;
493 }
494 }
495 }
496 return array_keys($keys);
497 }
498
499 /**
500 * Collect field keys from every breakpoint of a layout object.
501 *
502 * @param object $layout layout with ->lg/->md/->sm arrays of {i} items
503 *
504 * @return string[]
505 */
506 private static function collectLayoutKeys($layout)
507 {
508 if (!is_object($layout)) {
509 return [];
510 }
511 $keys = [];
512 foreach (['lg', 'md', 'sm'] as $brkpnt) {
513 if (!isset($layout->{$brkpnt}) || !is_array($layout->{$brkpnt})) {
514 continue;
515 }
516 foreach ($layout->{$brkpnt} as $item) {
517 if (is_object($item) && isset($item->i)) {
518 $keys[$item->i] = true;
519 }
520 }
521 }
522 return array_keys($keys);
523 }
524
525 /**
526 * Extract a child field key from a childFields[] entry (stdClass or array shape).
527 *
528 * @return string|null
529 */
530 private static function childFldKey($child)
531 {
532 if (is_object($child) && isset($child->fldKey)) {
533 return $child->fldKey;
534 }
535 if (is_array($child) && isset($child['fldKey'])) {
536 return $child['fldKey'];
537 }
538 return null;
539 }
540
541 /**
542 * Add childFields of every rendered parent into $renderedKeys (by ref).
543 *
544 * Several field types keep their children flat in `fields` and NEVER in
545 * any layout — Name (first/middle/last), Address (street/city/zip/...),
546 * Email and Password (confirm fields). A child is rendered iff its
547 * parent is, so each rendered parent's childFields[].fldKey must join
548 * the rendered set or their validation would be wrongly skipped.
549 *
550 * Runs to a fixpoint so expansion is safe regardless of field order or
551 * nesting depth.
552 *
553 * @param array $renderedKeys key => true map, mutated in place
554 * @param iterable $fields fields keyed by field key; each field may be
555 * a processed array (getFields()) or raw stdClass
556 */
557 protected static function expandChildFieldKeys(array &$renderedKeys, $fields)
558 {
559 do {
560 $grew = false;
561 foreach ($fields as $key => $field) {
562 if (!isset($renderedKeys[$key])) {
563 continue;
564 }
565 $childFields = null;
566 if (is_object($field) && isset($field->childFields)) {
567 $childFields = $field->childFields;
568 } elseif (is_array($field) && isset($field['childFields'])) {
569 $childFields = $field['childFields'];
570 }
571 if (empty($childFields) || !is_iterable($childFields)) {
572 continue;
573 }
574 foreach ($childFields as $child) {
575 $childKey = self::childFldKey($child);
576 if ($childKey && !isset($renderedKeys[$childKey])) {
577 $renderedKeys[$childKey] = true;
578 $grew = true;
579 }
580 }
581 }
582 } while ($grew);
583 }
584
585 /**
586 * getFields() narrowed to provably-rendered fields: key present in any
587 * breakpoint of any step/nested layout, OR a childField of a rendered
588 * parent (name/address/email/password children live outside layouts),
589 * OR the synthetic GCLID key.
590 *
591 * SECURITY: fail-closed — if the layout yields no keys, ALL fields are
592 * returned (current behavior). Derives exclusively from DB-stored
593 * form_content, never from POST, so submitters cannot influence which
594 * fields are validated.
595 */
596 public function getRenderedFields()
597 {
598 $fields = $this->getFields();
599 try {
600 $renderedKeys = self::renderedKeyMap($this->getFormLayout(), $this->getFormNestedLayout(), $fields);
601 } catch (\Throwable $e) {
602 return $fields; // fail-closed: unusable layout validates all fields
603 }
604 if (null === $renderedKeys) {
605 return $fields;
606 }
607 $rendered = [];
608 foreach ($fields as $key => $field) {
609 // renderedKeys already includes NON_LAYOUT_FIELD_KEYS (GCLID, ...)
610 if (isset($renderedKeys[$key])) {
611 $rendered[$key] = $field;
612 }
613 }
614 return $rendered;
615 }
616
617 /**
618 * Field keys that are legitimately part of a form yet never appear in any
619 * layout — synthetic/system fields the renderer always keeps. They must
620 * never be flagged as orphan (save guard) or dropped from validation
621 * (renderer). Extend this list as new non-layout system fields are added.
622 *
623 * @var string[]
624 */
625 protected const NON_LAYOUT_FIELD_KEYS = ['GCLID'];
626
627 /**
628 * True when $fields (object or array) holds $key.
629 *
630 * @param object|array $fields
631 * @param string $key
632 */
633 private static function fieldExists($fields, $key)
634 {
635 return is_object($fields) ? isset($fields->{$key}) : (is_array($fields) && isset($fields[$key]));
636 }
637
638 /**
639 * Flatten a raw layout into one object unioning lg/md/sm across all steps.
640 * Accepts a single layout object or an array of multi-step entries (each
641 * wrapping its layout in ->layout). Shared by the frontend renderer
642 * (getRenderedFields) and the admin save/import orphan guard
643 * (computeOrphanFieldKeys) so both flatten identically.
644 *
645 * @param array|object $layout
646 *
647 * @return object {lg,md,sm} arrays of {i} items
648 */
649 private static function flattenLayout($layout)
650 {
651 $flat = new stdClass();
652 $flat->lg = [];
653 $flat->md = [];
654 $flat->sm = [];
655 $addLayout = function ($lay) use ($flat) {
656 if (!is_object($lay)) {
657 return;
658 }
659 foreach (['lg', 'md', 'sm'] as $brkpnt) {
660 if (isset($lay->{$brkpnt}) && is_array($lay->{$brkpnt})) {
661 $flat->{$brkpnt} = array_merge($flat->{$brkpnt}, $lay->{$brkpnt});
662 }
663 }
664 };
665 if (is_array($layout)) {
666 // multi-step: each entry wraps its layout in ->layout
667 foreach ($layout as $step) {
668 $addLayout(isset($step->layout) ? $step->layout : $step);
669 }
670 } else {
671 $addLayout($layout);
672 }
673 return $flat;
674 }
675
676 /**
677 * SINGLE SOURCE OF TRUTH for "which field keys the renderer would show":
678 * unions all breakpoints across steps, adds nested-layout children of
679 * RENDERED containers only, then expands childFields of rendered parents
680 * (name/address/email/password children live outside layouts).
681 *
682 * Both getRenderedFields (frontend validation) and computeOrphanFieldKeys
683 * (admin save guard) route through this so the two can never diverge — a
684 * divergence would prune a real field or wrongly validate an orphan.
685 *
686 * @param array|object $layout single layout or array of steps
687 * @param object|null $nestedLayout keyed by parent field key
688 * @param object|array $fields form_content->fields
689 *
690 * @return array<string,true>|null key=>true map, or null when the layout is
691 * unusable (callers MUST fail closed)
692 */
693 protected static function renderedKeyMap($layout, $nestedLayout, $fields)
694 {
695 // Fail closed on a partial/unloaded multi-step layout: a step with no
696 // layout items at all almost always means the layout never finished
697 // loading/syncing (not a real "every field on this step was deleted").
698 // Treating it as usable would flag that step's real fields as orphan.
699 if (is_array($layout)) {
700 if (empty($layout)) {
701 return null;
702 }
703 foreach ($layout as $step) {
704 $stepLayout = is_object($step) && isset($step->layout) ? $step->layout : $step;
705 if (empty(self::collectLayoutKeys(self::flattenLayout($stepLayout)))) {
706 return null;
707 }
708 }
709 }
710 $flat = self::flattenLayout($layout);
711 $rootKeys = self::collectLayoutKeys($flat);
712 if (empty($rootKeys)) {
713 return null;
714 }
715 $renderedKeys = array_fill_keys($rootKeys, true);
716 // nested children count as rendered only when their container is —
717 // matches the renderer, which skips stale nestedLayout entries
718 if (is_object($nestedLayout) || is_array($nestedLayout)) {
719 foreach ($nestedLayout as $parentKey => $nLay) {
720 if (!isset($renderedKeys[$parentKey])) {
721 continue;
722 }
723 foreach (self::collectLayoutKeys($nLay) as $nestedKey) {
724 $renderedKeys[$nestedKey] = true;
725 }
726 }
727 }
728 self::expandChildFieldKeys($renderedKeys, $fields);
729 // synthetic/system fields (e.g. GCLID) live outside every layout; the
730 // renderer always keeps them, so they must never count as orphan
731 foreach (self::NON_LAYOUT_FIELD_KEYS as $sysKey) {
732 if (self::fieldExists($fields, $sysKey)) {
733 $renderedKeys[$sysKey] = true;
734 }
735 }
736 return $renderedKeys;
737 }
738
739 /**
740 * Pure variant of the orphan rule for the admin save/import guard: returns
741 * the keys of $fields absent from every layout (children of rendered
742 * parents excluded). Uses renderedKeyMap — the exact flattening the
743 * renderer uses — so the save guard and the renderer never diverge.
744 *
745 * @param array|object $layout single layout or array of steps ({layout} each)
746 * @param object|null $nestedLayout keyed by parent field key
747 * @param mixed $fields raw form_content->fields (decoded JSON: shape is not guaranteed, hence the runtime guard)
748 *
749 * @return string[]|null orphan keys to drop, or null when the layout is
750 * unusable (fail closed: drop nothing)
751 */
752 public static function computeOrphanFieldKeys($layout, $nestedLayout, $fields)
753 {
754 if (!is_object($fields) && !is_array($fields)) {
755 return null;
756 }
757 $renderedKeys = self::renderedKeyMap($layout, $nestedLayout, $fields);
758 if (null === $renderedKeys) {
759 return null; // unusable layout: fail closed, drop nothing
760 }
761 $orphans = [];
762 foreach ($fields as $key => $field) {
763 if (!isset($renderedKeys[$key])) {
764 $orphans[] = $key;
765 }
766 }
767 return $orphans;
768 }
769
770 public function getFieldsBasedOnLayout()
771 {
772 $layout = $this->getFlatenFormLayout();
773
774 $fieldKeyOrderbasedOnLayout = array_map(function ($fld) {
775 return $fld->i;
776 }, $layout->lg);
777 $orderedFields = [];
778 $fields = $this->getFields();
779
780 foreach ($fieldKeyOrderbasedOnLayout as $key) {
781 if (array_key_exists($key, $fields)) {
782 $orderedFields[$key] = $fields[$key];
783 }
784 }
785
786 foreach ($fields as $k=>$v) {
787 if (!array_key_exists($k, $fieldKeyOrderbasedOnLayout)) {
788 $orderedFields[$k] = $fields[$k];
789 }
790 }
791
792 return $orderedFields;
793 }
794
795 public function getFields()
796 {
797 if (!is_null($this->_fields)) {
798 return $this->_fields;
799 }
800 $form_content = \json_decode($this->form[0]->form_content);
801 $layout = $form_content->layout;
802 $fields = $form_content->fields;
803 $field_details = [];
804 foreach ($fields as $key => $field) {
805 if ('recaptcha' === $field->typ || 'hcaptcha' === $field->typ) {
806 continue;
807 }
808 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
809 $field_type = $field->typ;
810 $field_details[$key]['label'] = !empty($field->lbl) ? $field->lbl : (!empty($field->adminLbl) ? $field->adminLbl : (!empty($field->fieldName) ? $field->fieldName : null));
811 $field_details[$key]['type'] = $field_type;
812 $field_details[$key]['key'] = $key;
813 $field_details[$key]['name'] = isset($field->fieldName) ? $field->fieldName : '';
814 if (isset($field->customType)) {
815 $field_details[$key]['customType'] = $field->customType;
816 }
817 // fields with confirm field
818 if (isset($field->childFields)) {
819 $field_details[$key]['childFields'] = $field->childFields;
820 }
821 if (isset($field->parentFieldKey)) {
822 $field_details[$key]['parentFieldKey'] = $field->parentFieldKey;
823 if (isset($field->isDeactive)) {
824 $field_details[$key]['isDeactive'] = $field->isDeactive;
825 }
826 }
827 if (isset($field->err)) {
828 if (isset($field->err->entryUnique)) {
829 $field_details[$key]['entryUnique'] = $field->err->entryUnique;
830 }
831 if (isset($field->err->userUnique)) {
832 $field_details[$key]['userUnique'] = $field->err->userUnique;
833 }
834 }
835
836 if (isset($field->mul)) {
837 $field_details[$key]['mul'] = $field->mul;
838 }
839 if (in_array($field_type, ['name'])) {
840 $field_details[$key]['label'] = $field->adminLbl ?? $field->lbl;
841 }
842 if ('file-up' === $field_type && isset($field->exts)) {
843 $field_details[$key]['valid']['type'] = $field->exts;
844 }
845 if ('file-up' === $field_type && isset($field->mxUp)) {
846 $field_details[$key]['valid']['upload_size'] = (int) $field->mxUp;
847 }
848 if (isset($field->valid) && !is_null($field->valid)) {
849 if (isset($field->valid->req)) {
850 $field_details[$key]['valid']['req'] = $field->valid->req;
851 }
852 if (isset($field->valid->reqMsg)) {
853 $field_details[$key]['valid']['reqMsg'] = $field->valid->reqMsg;
854 }
855 if (isset($field->valid->typMsg)) {
856 $field_details[$key]['valid']['typMsg'] = $field->valid->typMsg;
857 }
858 if (isset($field->valid->hide)) {
859 $field_details[$key]['valid']['hide'] = $field->valid->hide;
860 }
861 }
862 if ($this->isRepeatedField($key)) {
863 $field_details[$key]['repeated'] = true;
864 }
865 }
866 if ($this->isGCLIDEnabled()) {
867 $field_details['GCLID']['name'] = 'GCLID';
868 $field_details['GCLID']['adminLbl'] = 'GCLID';
869 $field_details['GCLID']['key'] = 'GCLID';
870 $field_details['GCLID']['type'] = 'hidden';
871 }
872 $this->_fields = $field_details;
873 return $field_details;
874 }
875
876 public function getFieldsKey()
877 {
878 $form_content = \json_decode($this->form[0]->form_content);
879 $fields = $form_content->fields;
880 $field_details = [];
881 foreach ($fields as $key => $field) {
882 if ('recaptcha' === $field->typ || 'hcaptcha' === $field->typ) {
883 continue;
884 }
885 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
886 $field_details[$key] = $key;
887 }
888 if ($this->isGCLIDEnabled()) {
889 $field_details['GCLID'] = 'GCLID';
890 }
891 return $field_details;
892 }
893
894 public function getFieldLabel($forQuery = false)
895 {
896 if (!is_null($this->_field_label)) {
897 return $this->_field_label;
898 }
899 $form_content = \json_decode($this->form[0]->form_content);
900 $fields = $form_content->fields;
901 $field_details = [];
902 $fieldCounter = 0;
903 foreach ($fields as $key => $field) {
904 if ('recaptcha' === $field->typ || 'turnstile' === $field->typ || 'html' === $field->typ || 'button' === $field->typ) {
905 continue;
906 }
907 $field_details[$fieldCounter]['name'] = empty($field->lbl) ? null : $field->lbl;
908 $field_details[$fieldCounter]['adminLbl'] = empty($field->adminLbl) ? $field_details[$fieldCounter]['name'] : $field->adminLbl;
909 $field_details[$fieldCounter]['key'] = $key;
910 $field_details[$fieldCounter]['type'] = $field->typ;
911 $fieldCounter += 1;
912 }
913 if ($this->isGCLIDEnabled()) {
914 $field_details[$fieldCounter]['name'] = 'GCLID';
915 $field_details[$fieldCounter]['adminLbl'] = 'GCLID';
916 $field_details[$fieldCounter]['key'] = 'GCLID';
917 $field_details[$fieldCounter]['type'] = 'hidden';
918 $fieldCounter += 1;
919 }
920 if (!$forQuery) {
921 $field_details = (array) $this->addEntryInfo($field_details, $fieldCounter);
922 }
923 $this->_field_label = $field_details;
924 return $field_details;
925 }
926
927 public function getUploadFields()
928 {
929 if (!is_null($this->_has_upload)) {
930 return $this->_has_upload;
931 }
932 $upload_fields = [];
933 $form_field_details = $this->getFields();
934 foreach ($form_field_details as $field_name => $__field_detail) {
935 if (isset($__field_detail['type']) && ('file-up' === $__field_detail['type'] || 'advanced-file-up' === $__field_detail['type'])) {
936 $upload_fields[] = $field_name;
937 }
938 }
939 $this->_has_upload = $upload_fields;
940 return $upload_fields;
941 }
942
943 public function getSignatureFilePath($blobLink, $form_id, $fieldKey, $entry_id, $imgType)
944 {
945 $imgTypes = [
946 'image/png' => 'png',
947 'image/jpeg' => 'jpg',
948 'image/svg+xml' => 'svg',
949 ];
950 try {
951 if (!isset($imgTypes[$imgType])) {
952 throw new \InvalidArgumentException("Unsupported image type: $imgType");
953 }
954 $parts = explode(',', $blobLink, 2);
955 if (2 !== count($parts) || false === ($decoded_image = base64_decode($parts[1]))) {
956 throw new \RuntimeException('Invalid or corrupt signature data URI');
957 }
958
959 // An attacker-controlled SVG signature is written to a web-served path, so a raw write is a
960 // stored-XSS sink. Sanitize with the same enshrined library the upload path uses (FileHandler).
961 if ('svg' === $imgTypes[$imgType]) {
962 $clean = (new Sanitizer())->sanitize($decoded_image);
963 if (false === $clean) {
964 throw new \RuntimeException('Invalid or unsafe SVG signature data');
965 }
966 $decoded_image = $clean;
967 }
968
969 $_upload_dir = FileHandler::getEntriesFileUploadDir($form_id, $entry_id);
970 FileHandler::createIndexFile($_upload_dir);
971 $uniqueId = time() . '-' . bin2hex(\random_bytes(4));
972 $filename = "{$entry_id}-{$fieldKey}-{$uniqueId}.{$imgTypes[$imgType]}";
973 $fullPath = $_upload_dir . DIRECTORY_SEPARATOR . $filename;
974 if (false === file_put_contents($fullPath, $decoded_image)) {
975 throw new \RuntimeException("Failed to write image to $fullPath");
976 }
977 return $filename;
978 } catch (\Throwable $e) {
979 Log::debug_log("[Signature Error] Form: $form_id, Entry: $entry_id, Field: $fieldKey - " . $e->getMessage());
980 return 'signature-failed.png'; // or a default filename if appropriate
981 }
982 }
983
984 private function entryInsert($user_details)
985 {
986 $formEntryModel = new FormEntryModel();
987 $entryId = $formEntryModel->insert(
988 [
989 'form_id' => $this->form_id,
990 'user_id' => $user_details['id'],
991 'user_ip' => $user_details['ip'],
992 'user_device' => $user_details['device'],
993 'referer' => $user_details['page'],
994 'status' => $this->_saveFormAsDraft ? 9 : 1,
995 'created_at' => $user_details['time'],
996 ]
997 );
998 return $entryId;
999 }
1000
1001 public function submisionLog($user_details, $entry_id, $type)
1002 {
1003 $formEntryLogModel = new FormEntryLogModel();
1004 $submissionLogData = [
1005 'user_id' => $user_details['id'],
1006 'action_type' => $type, // create, update
1007 'log_type' => 'entry',
1008 'ip' => $user_details['ip'],
1009 'form_entry_id' => $entry_id,
1010 // encoded: wpdb cannot bind an array, so an array here silently stored an
1011 // empty string and every submission lost its device info
1012 'content' => wp_json_encode(['user_device' => $user_details['device']]),
1013 'form_id' => $this->form_id,
1014 'created_at' => $user_details['time'],
1015 ];
1016 $submissionLogData = apply_filters('bitform_filter_submission_log_data', $submissionLogData, $this->form_id, $type);
1017 $logId = $formEntryLogModel->form_log_insert(
1018 $submissionLogData
1019 );
1020 return $logId;
1021 }
1022
1023 private function isArrayAllKeyInt($InputArray)
1024 {
1025 if (!is_array($InputArray)) {
1026 return false;
1027 }
1028
1029 if (count($InputArray) <= 0) {
1030 return true;
1031 }
1032
1033 return array_unique(array_map('is_int', array_keys($InputArray))) === [true];
1034 }
1035
1036 public function formatSubmittedData($submitted_data)
1037 {
1038 $form_content = $this->getFormContent();
1039 $form_fields = $form_content->fields;
1040
1041 foreach ($submitted_data as $key => $value) {
1042 if (!isset($form_fields->{$key})) {
1043 continue;
1044 }
1045 $field_data = $form_fields->{$key};
1046 $field_type = $field_data->typ;
1047 $normalizedParentValue = $this->normalizeSubmittedValue($value);
1048 $parentFieldName = isset($field_data->fieldName) ? $field_data->fieldName : '';
1049 // Confirm child of a repeated email/password never persists — the non-repeated
1050 // path drops it too (the validator collapses the parent to its primary value).
1051 $isRepeatedConfirmComposite = in_array($field_type, ['email', 'password'], true) && $this->isRepeatedField($key);
1052 if (!$isRepeatedConfirmComposite && !empty($field_data->childFields) && is_array($field_data->childFields)) {
1053 foreach ($field_data->childFields as $childFieldRef) {
1054 $childFieldKey = isset($childFieldRef->fldKey) ? $childFieldRef->fldKey : '';
1055 if (empty($childFieldKey) || !isset($form_fields->{$childFieldKey})) {
1056 continue;
1057 }
1058
1059 $childFieldData = $form_fields->{$childFieldKey};
1060 $childFieldName = isset($childFieldData->fieldName) ? $childFieldData->fieldName : '';
1061 $childFieldName = FieldValueHandler::deriveChildName($childFieldName, $parentFieldName);
1062 if (empty($childFieldName)) {
1063 continue;
1064 }
1065
1066 $childValue = FieldValueHandler::extractChildValueFromParentValue($normalizedParentValue, $childFieldName, $childFieldKey);
1067 if (null !== $childValue) {
1068 $submitted_data[$childFieldKey] = $childValue;
1069 }
1070 }
1071 }
1072
1073 if ($this->isRepeatedField($key) && in_array($field_type, ['name', 'address', 'email', 'password'])) {
1074 $normalizedRows = $this->normalizeRepeatedCompositeFieldInput($normalizedParentValue);
1075 if ($isRepeatedConfirmComposite && is_array($normalizedRows)) {
1076 // Keep only the primary value per row, matching the non-repeated behavior
1077 // where a confirm-enabled field collapses to its primary value.
1078 foreach ($normalizedRows as $rowIndex => $rowValue) {
1079 if (is_array($rowValue) && array_key_exists('primary', $rowValue)) {
1080 $normalizedRows[$rowIndex] = $rowValue['primary'];
1081 }
1082 }
1083 }
1084 $submitted_data[$key] = $normalizedRows;
1085 }
1086
1087 if ('select' === $field_type && !empty($field_data->config->multipleSelect)) {
1088 $valueArr = [];
1089 if ($this->isRepeatedField($key) && is_array($normalizedParentValue)) {
1090 foreach ($normalizedParentValue as $index => $v) {
1091 $valueArr[$index] = explode(BITFORMS_BF_SEPARATOR, $v);
1092 }
1093 } else {
1094 $valueArr = explode(BITFORMS_BF_SEPARATOR, (string) $value);
1095 }
1096 $submitted_data[$key] = $valueArr;
1097 }
1098 }
1099 $submitted_data = apply_filters('bitform_filter_format_submitted_data', $submitted_data, $this->form_id);
1100 return $submitted_data;
1101 }
1102
1103 private function normalizeSubmittedValue($value)
1104 {
1105 if (!is_string($value)) {
1106 return $value;
1107 }
1108
1109 $decoded = json_decode($value, true);
1110 return (JSON_ERROR_NONE === json_last_error()) ? $decoded : $value;
1111 }
1112
1113 private function addNewFilePathToFiles($form_id, $entry_id, $file_fields = [])
1114 {
1115 $common_file_path = Helpers::getFullPathWithEncryptedEntryId($form_id, $entry_id);
1116 foreach ($_FILES as $field_key => $file_details) {
1117 if (!($file_fields && in_array($field_key, $file_fields))) {
1118 continue;
1119 }
1120
1121 $isRepeaterFldKey = $this->isRepeatedField($field_key);
1122 if ($isRepeaterFldKey && isset($file_details['new_name'])) {
1123 // If 'new_name' is an array (i.e., for repeated fields)
1124 foreach ($file_details['new_name'] as $slNo => $newFileNamesArray) {
1125 if (is_array($newFileNamesArray)) {
1126 foreach ($newFileNamesArray as $newFileName) {
1127 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
1128 $_FILES[$field_key]['file_path'][$slNo][] = $filePath;
1129 }
1130 } else {
1131 // Generate the file path for each file
1132 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileNamesArray;
1133 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
1134 }
1135 }
1136 } elseif (isset($file_details['new_name'])) {
1137 // If 'new_name' is an array (i.e., for repeated fields)
1138 if (is_array($file_details['new_name'])) {
1139 foreach ($file_details['new_name'] as $slNo => $newFileName) {
1140 // Generate the file path for each file
1141 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
1142 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
1143 }
1144 } else {
1145 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $file_details['new_name'];
1146 $_FILES[$field_key]['file_path'] = $filePath;
1147 }
1148 }
1149 }
1150 }
1151
1152 private function formatRepeateFieldData($submitted_data, $form_fields)
1153 {
1154 $repeaterFields = $this->getRepeaterFields();
1155 foreach ($repeaterFields as $repeaterFldKey => $repeatedFields) {
1156 $repeatIndexes = $submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"];
1157 $repeatIndexes = explode(',', $repeatIndexes);
1158 foreach ($repeatedFields as $repeatedField) {
1159 $oldFileKey = "{$repeatedField}_old";
1160 if (isset($submitted_data[$oldFileKey]) && is_array($submitted_data[$oldFileKey])) {
1161 $oldFileValues = $submitted_data[$oldFileKey];
1162 $oldFileKeys = array_map('strval', array_keys($oldFileValues));
1163 $repeatIndexKeys = array_map('strval', $repeatIndexes);
1164 $oldFilesUseRepeatIndexes = empty(array_diff($oldFileKeys, $repeatIndexKeys));
1165 $normalizedOldFileValues = [];
1166
1167 foreach ($repeatIndexes as $slNo => $repeatIndex) {
1168 $oldFileSourceIndex = $oldFilesUseRepeatIndexes ? $repeatIndex : $slNo;
1169 if (array_key_exists($oldFileSourceIndex, $oldFileValues)) {
1170 $normalizedOldFileValues[$slNo] = $oldFileValues[$oldFileSourceIndex];
1171 }
1172 }
1173
1174 $submitted_data[$oldFileKey] = $normalizedOldFileValues;
1175 }
1176 }
1177
1178 foreach ($repeatIndexes as $slNo => $repeatIndex) {
1179 foreach ($repeatedFields as $repeatedField) {
1180 if (!isset($submitted_data[$repeatedField][$repeatIndex])) {
1181 continue;
1182 }
1183 if (!isset($submitted_data[$repeaterFldKey][$slNo])) {
1184 $submitted_data[$repeaterFldKey][$slNo] = [];
1185 }
1186 if (!isset($submitted_data[$repeaterFldKey][$slNo][$repeatedField])) {
1187 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = [];
1188 }
1189 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = $submitted_data[$repeatedField][$repeatIndex];
1190 }
1191 }
1192 foreach ($repeatedFields as $repeatedField) {
1193 unset($submitted_data[$repeatedField]);
1194 }
1195 unset($submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"]);
1196 }
1197
1198 return $submitted_data;
1199 }
1200
1201 private function saveEntryMeta($submitted_data, $entry_id)
1202 {
1203 $errorInEntryMetaInsert = false;
1204 $entryMeta = new FormEntryMetaModel();
1205 foreach ($submitted_data as $key => $value) {
1206 $value = $submitted_data[$key];
1207 if (is_string($value)) {
1208 $value = wp_unslash($value);
1209 } elseif ($this->isArrayAllKeyInt($value)) {
1210 $value = wp_json_encode(array_values($value));
1211 } else {
1212 $value = wp_json_encode($value);
1213 }
1214 // Form entry meta insert; meta_key/meta_value required to store dynamic field data per entry.
1215 $status = $entryMeta->insert(
1216 [
1217 'bitforms_form_entry_id' => $entry_id,
1218 'meta_key' => $key,
1219 'meta_value' => $value,
1220 ]
1221 );
1222 if (is_wp_error($status)) {
1223 $errorInEntryMetaInsert = true;
1224 break;
1225 }
1226 }
1227 return $errorInEntryMetaInsert;
1228 }
1229
1230 public function setSaveFormAsDraft()
1231 {
1232 $this->_saveFormAsDraft = true;
1233 }
1234
1235 public function saveFormEntry($submitted_data)
1236 {
1237 // CSRF verified upstream via FrontendFormManager::verifySubmissionNonce() before this method is invoked.
1238 $submitted_data = $this->formatSubmittedData($submitted_data);
1239 $submitted_data = apply_filters('bitform_filter_save_form_entry', $submitted_data, $this->form_id);
1240 $form_content = \json_decode($this->form[0]->form_content);
1241 do_action('bitform_save_entry', $this, $submitted_data, $this->form_id);
1242 $key = null;
1243 $ipTool = new IpTool();
1244 $fileHandler = new FileHandler();
1245 $form_fields = $this->getFields();
1246 $file_fields = $this->getUploadFields();
1247
1248 foreach ($_FILES as $file_name => $file_details) {
1249 if ($file_fields && in_array($file_name, $file_fields)) {
1250 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
1251 if (!empty($validation['error_type']) && !empty($validation['message'])) {
1252 return new WP_Error($validation['error_type'], esc_html($validation['message']));
1253 }
1254 }
1255 }
1256 $user_details = $ipTool->getUserDetail();
1257 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
1258 $user_details = apply_filters('bitform_filter_save_entry_user_details', $user_details, $this->form_id);
1259
1260 $form_fields = $this->getFields();
1261 $submitted_data = $this->passwordEncrypted($submitted_data, $form_fields);
1262 $submitted_data = $this->formatRepeateFieldData($submitted_data, $form_fields);
1263 global $wpdb;
1264 // Direct transaction control; no user input involved.
1265 $wpdb->query('START TRANSACTION');
1266 $entry_id = $this->entryInsert($user_details);
1267 $log_id = null;
1268
1269 $GLOBALS['bitform_entry_id'] = $entry_id;
1270
1271 if (is_wp_error($entry_id)) {
1272 return new WP_Error('insert_error', __('Sorry, Error occurred in saving form entry', 'bit-form'));
1273 }
1274 if ($entry_id) {
1275 $log_id = $this->submisionLog($user_details, $entry_id, 'create', $key);
1276 if (is_wp_error($log_id)) {
1277 $wpdb->query('ROLLBACK');
1278 return new WP_Error('error_entry_log', __('Sorry, error occurred in logging form entry', 'bit-form'));
1279 }
1280 }
1281 if ($entry_id) {
1282 $submitted_fields = $this->getFormContentWithValue($submitted_data)->fields;
1283 $workFlowRunHelper = new WorkFlow($this->form_id);
1284
1285 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
1286 'create',
1287 $submitted_fields,
1288 $submitted_data,
1289 $entry_id,
1290 $log_id
1291 );
1292
1293 if (!empty($workFlowreturnedOnSubmit['fields'])) {
1294 $submitted_data = $workFlowreturnedOnSubmit['fields'];
1295 }
1296
1297 $file_fields = $this->getUploadFields();
1298 $formFields = $this->getFields();
1299 $submitted_data = FileHandler::tempDirToUploadDir($submitted_data, $formFields, $this->form_id, $entry_id);
1300 $fileHandler = new FileHandler();
1301 foreach ($_FILES as $field_key => $file_details) {
1302 if ($file_fields && in_array($field_key, $file_fields)) {
1303 $fileNames = [];
1304 $repeaterFldKey = $this->isRepeatedField($field_key);
1305 if ($repeaterFldKey) {
1306 foreach ($file_details['name'] as $slNo => $fileName) {
1307 $repeateFileDetails = [
1308 'name' => $file_details['name'][$slNo],
1309 'type' => $file_details['type'][$slNo],
1310 'tmp_name' => $file_details['tmp_name'][$slNo],
1311 'error' => $file_details['error'][$slNo],
1312 'size' => $file_details['size'][$slNo],
1313 ];
1314 $fileNames = $fileHandler->moveUploadedFiles($repeateFileDetails, $this->form_id, $entry_id);
1315 if (!empty($fileNames)) {
1316 $submitted_data[$repeaterFldKey][$slNo - 1][$field_key] = $fileNames;
1317 $_FILES[$field_key]['new_name'][$slNo - 1] = $fileNames;
1318 }
1319 }
1320 } else {
1321 $fileNames = $fileHandler->moveUploadedFiles($file_details, $this->form_id, $entry_id);
1322 if (!empty($fileNames)) {
1323 $submitted_data[$field_key] = $fileNames;
1324 $_FILES[$field_key]['new_name'] = $fileNames;
1325 }
1326 }
1327 }
1328 }
1329
1330 // Get the common path for file storage
1331 $this->addNewFilePathToFiles($this->form_id, $entry_id, $file_fields);
1332
1333 foreach ($form_content->fields as $key => $field) {
1334 /* ======== for Signature field ===========*/
1335 if ('signature' === $field->typ) {
1336 if (isset($submitted_data[$key])) {
1337 $fld_data = $submitted_data[$key];
1338 $img_type = $field->config->imgTyp;
1339 $submitted_data[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entry_id, $img_type);
1340 }
1341 }
1342
1343 // for Signature field inside reepater
1344 if ('repeater' === $field->typ) {
1345 $rptr_data = $submitted_data[$key];
1346 $formFields = $form_content->fields;
1347 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entry_id, $submitted_data);
1348 }
1349 }
1350
1351 if (!isset($form_content->additional->enabled->submission)) {
1352 $errorInEntryMetaInsert = $this->saveEntryMeta($submitted_data, $entry_id);
1353 if ($errorInEntryMetaInsert) {
1354 do_action('bitform_save_entry_error', $this, $submitted_data, $this->form_id);
1355 $wpdb->query('ROLLBACK');
1356 return new WP_Error('insert_error', __('Sorry, Error occured in saving form entry data', 'bit-form'));
1357 }
1358 do_action('bitform_after_save_entry_success', $this, $submitted_data, $this->form_id, $entry_id);
1359 } else {
1360 $wpdb->query('ROLLBACK');
1361 }
1362 $wpdb->query('COMMIT');
1363 $this->setSubmissionCount();
1364 $workFlowreturnedOnSubmit['entry_id'] = $entry_id;
1365 $workFlowreturnedOnSubmit['fields'] = $submitted_data;
1366 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_submit_success', $workFlowreturnedOnSubmit, $this->form_id);
1367
1368 return $workFlowreturnedOnSubmit;
1369 }
1370 }
1371
1372 /**
1373 * The signature file name an entry currently points at, '' when it has none.
1374 */
1375 private function getStoredSignatureFile($entryMeta, $entryID, $fieldKey)
1376 {
1377 $stored = $entryMeta->get(
1378 'meta_value',
1379 [
1380 'bitforms_form_entry_id' => $entryID,
1381 'meta_key' => $fieldKey,
1382 ]
1383 );
1384 if (is_wp_error($stored) || 0 === count($stored)) {
1385 return '';
1386 }
1387 $fileName = trim((string) $stored[0]->meta_value);
1388
1389 // signature-failed.png is a shared placeholder, not this entry's own file.
1390 return 'signature-failed.png' === $fileName ? '' : $fileName;
1391 }
1392
1393 private function setSignatureFilePathInRepeater($repeaterData, $repeaterFieldKey, $formFields, $entry_id, &$submitted_data)
1394 {
1395 foreach ($repeaterData as $rptr_entry_index => $rptr_entries) {
1396 foreach ($rptr_entries as $entry_key => $entry_value) {
1397 if (!isset($formFields->{$entry_key})) {
1398 continue;
1399 }
1400 $rptr_entry_info = $formFields->{$entry_key};
1401
1402 if ('signature' === $rptr_entry_info->typ) {
1403 $imgType = $rptr_entry_info->config->imgTyp;
1404 $signatureImage = $this->getSignatureFilePath($entry_value, $this->form_id, $repeaterFieldKey, $entry_id, $imgType);
1405 $submitted_data[$repeaterFieldKey][$rptr_entry_index][$entry_key] = $signatureImage;
1406 }
1407 }
1408 }
1409 }
1410
1411 public function passwordEncrypted($updatedValue, $form_fields)
1412 {
1413 $integrationHandler = new IntegrationHandler($this->form_id);
1414 $formIntegrations = $integrationHandler->getAllIntegration('wp_user_auth', 'wp_auth', 1);
1415 if (!isset($formIntegrations->errors['result_empty'])) {
1416 foreach ($form_fields as $field) {
1417 if (array_key_exists($field['key'], $updatedValue) && 'password' === $field['type']) {
1418 $updatedValue[$field['key']] = '**** (encrypted)';
1419 }
1420 }
1421 }
1422 return $updatedValue;
1423 }
1424
1425 private function normalizeOldFileValues($stored_files, $old_values)
1426 {
1427 $stored_files = is_array($stored_files) ? $stored_files : [];
1428 if (!is_array($old_values)) {
1429 $old_values_string = trim((string) $old_values);
1430 $decoded_old_values = json_decode($old_values_string, true);
1431 $old_values = is_array($decoded_old_values) ? $decoded_old_values : explode(',', $old_values_string);
1432 }
1433
1434 $normalized_values = [];
1435 foreach ($old_values as $value) {
1436 if (!is_string($value) && !is_numeric($value)) {
1437 continue;
1438 }
1439
1440 $trimmed_value = trim((string) $value);
1441 if ('' === $trimmed_value) {
1442 continue;
1443 }
1444
1445 if (in_array($trimmed_value, $stored_files, true)) {
1446 $normalized_values[] = $trimmed_value;
1447 }
1448 }
1449
1450 return array_values(array_unique($normalized_values));
1451 }
1452
1453 public function updateFormEntry($updatedValue, $formID, $entryID)
1454 {
1455 // CSRF / entry-token verified upstream via FrontendFormManager::handleUpdateEntry() before this method is invoked.
1456 $updatedValue = $this->formatSubmittedData($updatedValue);
1457 $updatedValue = apply_filters('bitform_filter_update_form_entry', $updatedValue, $this->form_id);
1458 do_action('bitform_update_entry', $this, $updatedValue, $formID, $entryID);
1459 $form_content = $this->getFormContent();
1460 if (isset($form_content->additional->enabled->submission)) {
1461 // Run workflow but skip DB/meta update
1462 $workFlowRunHelper = new WorkFlow($formID);
1463 $fieldsWithValue = $this->getFormContentWithValue($updatedValue)->fields;
1464 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
1465 'edit',
1466 $fieldsWithValue,
1467 $updatedValue,
1468 $entryID,
1469 0
1470 );
1471 if (empty($workFlowreturnedOnSubmit['message'])) {
1472 $workFlowreturnedOnSubmit['message'] = __('Entry update skipped due to submission restriction.', 'bit-form');
1473 }
1474 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
1475 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
1476 return $workFlowreturnedOnSubmit;
1477 }
1478
1479 $formEntryModel = new FormEntryModel();
1480 $formEntryLogModel = new FormEntryLogModel();
1481 $formOldData = $formEntryLogModel->get_form_value($entryID);
1482 $key = null;
1483 $entryMeta = new FormEntryMetaModel();
1484 $ipTool = new IpTool();
1485 $user_details = $ipTool->getUserDetail();
1486 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
1487 $user_details = apply_filters('bitform_filter_update_entry_user_details', $user_details, $this->form_id);
1488
1489 $form_fields = $this->getFields();
1490
1491 $updatedValue = $this->passwordEncrypted($updatedValue, $form_fields);
1492 $updatedValue = $this->formatRepeateFieldData($updatedValue, $form_fields);
1493 $field_map = [];
1494 foreach ($formOldData as $index => $data) {
1495 foreach ($form_fields as $field_key => $field) {
1496 if ($data->meta_key === $field['key']) {
1497 $field_map[$field_key] = $field['key'];
1498 }
1499 }
1500 }
1501
1502 $geResult = $formEntryModel->get('status', ['form_id' => $formID, 'id' => $entryID]);
1503 if (is_wp_error($geResult) || empty($geResult)) {
1504 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
1505 }
1506 $oldEntry = $geResult[0];
1507 $formEntry = $formEntryModel->update(
1508 [
1509 'status' => ('9' === $oldEntry->status && !$this->_saveFormAsDraft) ? 1 : $oldEntry->status,
1510 'updated_at' => $user_details['time'],
1511 ],
1512 [
1513 'form_id' => $formID,
1514 'id' => $entryID,
1515 ]
1516 );
1517
1518 if (is_wp_error($formEntry) && 'result_empty' !== $formEntry->get_error_code()) {
1519 return new WP_Error('entry_update_failed', __('Sorry, error occurred in updating form entry', 'bit-form'));
1520 }
1521
1522 $log_id = $this->submisionLog($user_details, $entryID, 'update');
1523 $formFields = $this->getFields();
1524 $updatedValue = FileHandler::tempDirToUploadDir($updatedValue, $formFields, $this->form_id, $entryID);
1525 $file_fields = $this->getUploadFields();
1526 if (count($file_fields) > 0) {
1527 $fileHandler = new FileHandler();
1528 foreach ($_FILES as $file_name => $file_details) {
1529 if ($file_fields && in_array($file_name, $file_fields)) {
1530 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
1531 if (!empty($validation['error_type']) && !empty($validation['message'])) {
1532 return new WP_Error($validation['error_type'], esc_html($validation['message']));
1533 }
1534 }
1535 }
1536 if (is_object($updatedValue)) {
1537 $updatedValue = (array) $updatedValue;
1538 }
1539 foreach ($file_fields as $field_key) {
1540 $repeaterFldKey = $this->isRepeatedField($field_key);
1541 if (isset($updatedValue[$field_key . '_old'])) {
1542 // Handle file deletion for repeater fields
1543 if ($repeaterFldKey) {
1544 // Form entry meta lookup; meta_key/meta_value query required to retrieve repeater field data by entry.
1545 $repeaterExistData = $entryMeta->get(
1546 'meta_value',
1547 [
1548 'bitforms_form_entry_id' => $entryID,
1549 'meta_key' => $repeaterFldKey,
1550 ]
1551 );
1552 if (!is_wp_error($repeaterExistData)) {
1553 // restructor json
1554 $repeaterExistData = json_decode($repeaterExistData[0]->meta_value, true);
1555 $repeaterExistFiles = [];
1556 $repeaterDeleted_files = [];
1557 $repeaterFiles_old = [];
1558 $submittedRepeaterOldFiles = is_array($updatedValue[$field_key . '_old']) ? $updatedValue[$field_key . '_old'] : [];
1559 foreach ($repeaterExistData as $index => $repeaterRow) {
1560 $repeaterExistFiles[$index] = [];
1561 if (isset($repeaterRow[$field_key]) && !empty($repeaterRow[$field_key]) && is_string($repeaterRow[$field_key])) {
1562 $repeaterExistFiles[$index] = json_decode($repeaterRow[$field_key], true);
1563 }
1564 if (isset($repeaterRow[$field_key]) && !empty($repeaterRow[$field_key]) && is_array($repeaterRow[$field_key])) {
1565 $repeaterExistFiles[$index] = $repeaterRow[$field_key];
1566 }
1567 if (!is_array($repeaterExistFiles[$index])) {
1568 $repeaterExistFiles[$index] = [];
1569 }
1570 $oldFileInputExists = array_key_exists($index, $submittedRepeaterOldFiles);
1571 $repeaterRowExists = $oldFileInputExists || (isset($updatedValue[$repeaterFldKey][$index]) && is_array($updatedValue[$repeaterFldKey][$index]));
1572 $oldFileValues = ($repeaterRowExists && $oldFileInputExists) ? $submittedRepeaterOldFiles[$index] : [];
1573 $repeaterFiles_old[$index] = $this->normalizeOldFileValues($repeaterExistFiles[$index], $oldFileValues);
1574 $repeaterDeleted_files[$index] = array_diff($repeaterExistFiles[$index], $repeaterFiles_old[$index]);
1575 $repeaterFiles_old[$index] = array_values(array_diff($repeaterFiles_old[$index], $repeaterDeleted_files[$index]));
1576 $fileHandler->deleteFiles($formID, $entryID, $repeaterDeleted_files[$index]);
1577 if ($repeaterRowExists) {
1578 if (!isset($updatedValue[$repeaterFldKey][$index]) || !is_array($updatedValue[$repeaterFldKey][$index])) {
1579 $updatedValue[$repeaterFldKey][$index] = [];
1580 }
1581 $updatedValue[$repeaterFldKey][$index][$field_key] = $repeaterFiles_old[$index];
1582 }
1583 }
1584 }
1585 } else {
1586 // Handle file deletion for non-repeater fields; meta_key/meta_value lookup required to identify stored file paths per entry.
1587 $file_exists = $entryMeta->get(
1588 'meta_value',
1589 [
1590 'bitforms_form_entry_id' => $entryID,
1591 'meta_key' => $field_key,
1592 ]
1593 );
1594 if (!is_wp_error($file_exists) && count($file_exists) > 0) {
1595 $files_in_db = json_decode($file_exists[0]->meta_value, true);
1596 if (!is_array($files_in_db)) {
1597 $files_in_db = [];
1598 }
1599 $retained_files = $this->normalizeOldFileValues($files_in_db, empty($updatedValue[$field_key . '_old']) ? [] : $updatedValue[$field_key . '_old']);
1600 $deleted_files = array_diff($files_in_db, $retained_files);
1601 $retained_files = array_values(array_diff($retained_files, $deleted_files));
1602 if (count($deleted_files) > 0) {
1603 $fileHandler->deleteFiles($formID, $entryID, $deleted_files);
1604 }
1605 $updatedValue[$field_key] = $retained_files;
1606 }
1607 }
1608 }
1609 if (!empty($_FILES[$field_key]['name'])) {
1610 if ($repeaterFldKey) {
1611 // Handle repeater field files
1612 $file_details = $_FILES[$field_key];
1613 foreach ($file_details['name'] as $index => $file) {
1614 $old_meta_value = [];
1615 // Retrieve existing old files for this specific repeater index
1616 if (isset($repeaterFiles_old[$index - 1]) && count($repeaterFiles_old[$index - 1]) > 0) {
1617 $old_meta_value = $repeaterFiles_old[$index - 1];
1618 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1619 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($old_meta_value);
1620 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $old_meta_value;
1621 }
1622 $repeateFileDetails = [
1623 'name' => $file_details['name'][$index],
1624 'type' => $file_details['type'][$index],
1625 'tmp_name' => $file_details['tmp_name'][$index],
1626 'error' => $file_details['error'][$index],
1627 'size' => $file_details['size'][$index],
1628 ];
1629 $meta_value = $fileHandler->moveUploadedFiles($repeateFileDetails, $formID, $entryID, $index);
1630 if (!empty($meta_value)) {
1631 $mergedMetaValueWithOld = array_merge($old_meta_value, (array) $meta_value);
1632 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1633 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($mergedMetaValueWithOld);
1634 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $mergedMetaValueWithOld;
1635
1636 $_FILES[$field_key]['new_name'][$index - 1] = $mergedMetaValueWithOld;
1637 // $_FILES[$field_key]['file_path'][$index - 1] = $common_file_path . DIRECTORY_SEPARATOR . $meta_value;
1638 }
1639 }
1640 } else {
1641 // Handle non-repeater field files
1642 $meta_value = $fileHandler->moveUploadedFiles($_FILES[$field_key], $formID, $entryID);
1643 if (!empty($meta_value)) {
1644 $_FILES[$field_key]['new_name'] = $meta_value;
1645 if (isset($updatedValue[$field_key . '_old']) && !is_wp_error($file_exists) && count($file_exists) > 0) {
1646 $meta_value = empty($retained_files) ? $meta_value : array_merge($meta_value, $retained_files);
1647 $updatedValue[$field_key] = $meta_value;
1648 } else {
1649 $updatedValue[$field_key] = $meta_value;
1650 }
1651 }
1652 }
1653 }
1654 }
1655
1656 // Get the common file path to avoid repetitive calculation
1657 $this->addNewFilePathToFiles($formID, $entryID, $file_fields);
1658 }
1659
1660 if (is_object($updatedValue)) {
1661 $updatedValue = (array) $updatedValue;
1662 }
1663 if (isset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']) && sanitize_text_field(wp_unslash($_REQUEST['g-recaptcha-response']))) {
1664 unset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']);
1665 }
1666
1667 $toUpdateValues = [];
1668 foreach ($form_fields as $field) {
1669 if (isset($updatedValue[$field['key']])) {
1670 $toUpdateValues[$field['key']] = $updatedValue[$field['key']];
1671 }
1672 }
1673 $form_content = \json_decode($this->form[0]->form_content);
1674
1675 $replacedSignatureFiles = [];
1676
1677 foreach ($form_content->fields as $key => $field) {
1678 if ('signature' === $field->typ) {
1679 $fld_data = isset($updatedValue[$key]) ? $updatedValue[$key] : '';
1680 $img_type = isset($field->config->imgTyp) ? $field->config->imgTyp : 'image/png';
1681 $storedSignature = $this->getStoredSignatureFile($entryMeta, $entryID, $key);
1682 if (is_string($fld_data) && 0 === strpos($fld_data, 'data:')) {
1683 $toUpdateValues[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entryID, $img_type);
1684 if ('' !== $storedSignature && $storedSignature !== $toUpdateValues[$key]) {
1685 $replacedSignatureFiles[] = $storedSignature;
1686 }
1687 } elseif (isset($updatedValue[$key . '_old'])) {
1688 // Nothing drawn: `_old` only confirms the stored file was kept, so write that back.
1689 $retained = FieldValueHandler::retainedOldValues($updatedValue, $key);
1690 $keepsStored = '' !== $storedSignature && in_array($storedSignature, $retained, true);
1691 $toUpdateValues[$key] = $keepsStored ? $storedSignature : '';
1692 if (!$keepsStored && '' !== $storedSignature) {
1693 $replacedSignatureFiles[] = $storedSignature;
1694 }
1695 } else {
1696 // No signature and no `_old` marker: leave what is stored alone.
1697 unset($toUpdateValues[$key]);
1698 }
1699 }
1700
1701 // for Signature field inside reepater
1702 if ('repeater' === $field->typ && isset($updatedValue[$key]) && is_array($updatedValue[$key])) {
1703 $rptr_data = $updatedValue[$key];
1704 $formFields = $form_content->fields;
1705 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entryID, $toUpdateValues);
1706 }
1707 }
1708
1709 $workFlowRunHelper = new WorkFlow($formID);
1710 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
1711 'edit',
1712 $this->getFormContentWithValue($toUpdateValues)->fields,
1713 $toUpdateValues,
1714 $entryID,
1715 $log_id
1716 );
1717
1718 if (!empty($workFlowreturnedOnSubmit['fields'])) {
1719 $updatedValue = $workFlowreturnedOnSubmit['fields'];
1720 }
1721
1722 $formEntryMetaUpdateStatus = $entryMeta->update(
1723 $toUpdateValues,
1724 [
1725 'bitforms_form_entry_id' => $entryID,
1726 ]
1727 );
1728 if (is_wp_error($formEntryMetaUpdateStatus) || isset($newFileInsertStatus) && is_wp_error($newFileInsertStatus)) {
1729 do_action('bitform_update_entry_error', $this, $toUpdateValues, $formEntryMetaUpdateStatus, $this->form_id);
1730 return $formEntryMetaUpdateStatus;
1731 }
1732 // Deleted only now the entry points elsewhere, so a failed update strands nothing.
1733 if (!empty($replacedSignatureFiles)) {
1734 (new FileHandler())->deleteFiles($formID, $entryID, $replacedSignatureFiles);
1735 }
1736 $toUpdateValues = array_merge($formEntryMetaUpdateStatus, ['entry_id' => $entryID]);
1737 do_action('bitform_after_update_entry_success', $this, $toUpdateValues, $formID, $entryID);
1738 if (empty($workFlowreturnedOnSubmit['message'])) {
1739 $workFlowreturnedOnSubmit['message'] = __('Entry Updated Successfully', 'bit-form');
1740 }
1741 $customFieldHandler = new CustomFieldHandler();
1742 $toUpdateValues = $customFieldHandler->updatedData($form_fields, $toUpdateValues);
1743
1744 $workFlowreturnedOnSubmit['updatedData'] = $toUpdateValues;
1745 $counter = 0;
1746 for ($i = 0; $i < count($formOldData); $i++) {
1747 if (array_key_exists($formOldData[$i]->meta_key . '_old', $toUpdateValues)) {
1748 unset($toUpdateValues[$formOldData[$i]->meta_key . '_old']);
1749 }
1750 if (in_array($formOldData[$i]->meta_key, $file_fields)) {
1751 if (
1752 empty($_FILES[$formOldData[$i]->meta_key]['name'])
1753 || (is_array($_FILES[$formOldData[$i]->meta_key]['name'])
1754 && 1 === count($_FILES[$formOldData[$i]->meta_key]['name'])
1755 && empty($_FILES[$formOldData[$i]->meta_key]['name'][0]))
1756 ) {
1757 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1758 continue;
1759 }
1760 if (is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1761 $sanitized_names = array_map('sanitize_file_name', array_map('wp_unslash', (array) $_FILES[$formOldData[$i]->meta_key]['name']));
1762 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . wp_json_encode($sanitized_names);
1763 } elseif (!is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1764 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . sanitize_file_name(wp_unslash($_FILES[$formOldData[$i]->meta_key]['name']));
1765 }
1766 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1767 } elseif (isset($toUpdateValues[$formOldData[$i]->meta_key])) {
1768 if (is_array($toUpdateValues[$formOldData[$i]->meta_key])) {
1769 if (json_decode($formOldData[$i]->meta_value) !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1770 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated From ' . implode(',', json_decode($formOldData[$i]->meta_value)) . ' To ' . implode(',', $toUpdateValues[$formOldData[$i]->meta_key]);
1771 }
1772 } elseif (is_string($toUpdateValues[$formOldData[$i]->meta_key]) && !FieldValueHandler::isEmpty($toUpdateValues[$formOldData[$i]->meta_key])) {
1773 if ($formOldData[$i]->meta_value !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1774 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated' . ($formOldData[$i]->meta_value ? ' From ' . $formOldData[$i]->meta_value : '') . ' To ' . $toUpdateValues[$formOldData[$i]->meta_key];
1775 }
1776 }
1777 }
1778 $counter++;
1779 }
1780
1781 $newField = array_keys(array_diff_key($formEntryMetaUpdateStatus, $field_map));
1782 for ($i = 0; $i < count($newField); $i++) {
1783 if (is_array($toUpdateValues[$newField[$i]]) && !empty($toUpdateValues[$newField[$i]])) {
1784 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . implode(',', $toUpdateValues[$newField[$i]]);
1785 } elseif (is_string($newField[$i]) && !FieldValueHandler::isEmpty($toUpdateValues[$newField[$i]])) {
1786 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . $toUpdateValues[$newField[$i]];
1787 }
1788 }
1789 if (null !== $key) {
1790 $logUpdate = implode('b::f', (array) $key);
1791 $formEntryLogUpdate = $formEntryLogModel->logUpdate($logUpdate, $log_id);
1792 }
1793 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
1794 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
1795
1796 return $workFlowreturnedOnSubmit;
1797 }
1798
1799 public function getRepeaterFields()
1800 {
1801 if (!is_null($this->_repeaterFields)) {
1802 return $this->_repeaterFields;
1803 }
1804 $repeaterFields = [];
1805 $form_content = \json_decode($this->form[0]->form_content);
1806 $fields = $form_content->fields;
1807 $nestedLayouts = !empty($form_content->nestedLayout) ? $form_content->nestedLayout : [];
1808 foreach ($nestedLayouts as $fieldKey => $repeatLayout) {
1809 if ('repeater' !== $fields->{$fieldKey}->typ) {
1810 continue;
1811 }
1812 $repeaterFields[$fieldKey] = [];
1813 foreach ($repeatLayout->lg as $fieldLayoutData) {
1814 $repeaterFields[$fieldKey][] = $fieldLayoutData->i;
1815 }
1816 }
1817 $this->_repeaterFields = $repeaterFields;
1818 return $repeaterFields;
1819 }
1820
1821 public function isRepeatedField($fieldKey)
1822 {
1823 $repeatedFields = $this->getRepeaterFields();
1824 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1825 if (in_array($fieldKey, $repeaterFields)) {
1826 return $repeaterKey;
1827 }
1828 }
1829 return false;
1830 }
1831
1832 public function getParentRepeaterField($fieldKey)
1833 {
1834 $repeatedFields = $this->getRepeaterFields();
1835 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1836 if (in_array($fieldKey, $repeaterFields)) {
1837 return $repeaterKey;
1838 }
1839 }
1840 return null;
1841 }
1842
1843 public function isRepeaterField($fieldKey)
1844 {
1845 $repeatedFields = $this->getRepeaterFields();
1846 if (array_key_exists($fieldKey, $repeatedFields)) {
1847 return true;
1848 }
1849 return false;
1850 }
1851
1852 public function fieldNameReplaceOfPost()
1853 {
1854 // CSRF verified upstream before this method is called; $_POST/$_FILES are being normalized (field key remapping), not reading new user input.
1855 $fields = $this->getFields();
1856 foreach ($fields as $fieldKey => $fieldData) {
1857 if (array_key_exists('name', $fieldData)) {
1858 $fldName = $fieldData['name'];
1859 $catchChildFldNamePattern = '/\[(.*?)\]/';
1860 // catching the child field name for confirm field, name field's child
1861 // preg_match_all($catchChildFldNamePattern, $fldName, $matches);
1862 $fldName = preg_replace($catchChildFldNamePattern, '', $fldName);
1863 $fldName = str_replace(['.', ' '], '_', $fldName);
1864 if (!empty($fldName)) {
1865 if (array_key_exists($fldName, $_POST)) {
1866 $temp = $this->sanitize_text_recursive($_POST[$fldName]);
1867 unset($_POST[$fldName]);
1868 $_POST[$fieldKey] = $temp;
1869 } elseif (array_key_exists($fieldKey, $_POST)) {
1870 $_POST[$fieldKey] = $this->sanitize_text_recursive($_POST[$fieldKey]);
1871 } elseif (array_key_exists($fldName, $_FILES)) {
1872 $temp = $this->sanitize_text_recursive($_FILES[$fldName], false);
1873 unset($_FILES[$fldName]);
1874 $_FILES[$fieldKey] = $temp;
1875 } elseif (array_key_exists($fieldKey, $_FILES)) {
1876 $_FILES[$fieldKey] = $this->sanitize_text_recursive($_FILES[$fieldKey], false);
1877 }
1878 // Convert _session_id suffix (used by email-otp and similar fields)
1879 if (array_key_exists($fldName . '_session_id', $_POST)) {
1880 $temp = sanitize_text_field(wp_unslash($_POST[$fldName . '_session_id']));
1881 unset($_POST[$fldName . '_session_id']);
1882 $_POST[$fieldKey . '_session_id'] = $temp;
1883 }
1884 }
1885 }
1886 }
1887 }
1888
1889 private function sanitize_text_recursive($input, $unslash = true)
1890 {
1891 if (is_array($input)) {
1892 return array_map(fn ($item) => $this->sanitize_text_recursive($item, $unslash), $input);
1893 }
1894
1895 return sanitize_text_field($unslash ? wp_unslash($input) : $input);
1896 }
1897
1898 private function normalizeRepeatedCompositeFieldInput($value)
1899 {
1900 if (!is_array($value) || empty($value)) {
1901 return $value;
1902 }
1903
1904 $hasNestedArray = false;
1905 foreach ($value as $childValues) {
1906 if (!is_array($childValues)) {
1907 return $value;
1908 }
1909 $hasNestedArray = true;
1910 }
1911
1912 if (!$hasNestedArray) {
1913 return $value;
1914 }
1915
1916 $formattedValue = [];
1917 foreach ($value as $childKey => $childValues) {
1918 foreach ($childValues as $repeatIndex => $repeatValue) {
1919 if (!isset($formattedValue[$repeatIndex]) || !is_array($formattedValue[$repeatIndex])) {
1920 $formattedValue[$repeatIndex] = [];
1921 }
1922 $formattedValue[$repeatIndex][$childKey] = $repeatValue;
1923 }
1924 }
1925
1926 return $formattedValue;
1927 }
1928
1929 public function setSubmissionCount($countStep = 1)
1930 {
1931 $update_status = $this->formModel->update(
1932 [
1933 'entries' => intval($this->form[0]->entries) + $countStep,
1934 ],
1935 [
1936 'id' => $this->form_id,
1937 ]
1938 );
1939 }
1940
1941 public function resetSubmissionCount($countStep)
1942 {
1943 $update_status = $this->formModel->update(
1944 [
1945 'entries' => intval($countStep),
1946 ],
1947 [
1948 'id' => $this->form_id,
1949 ]
1950 );
1951 }
1952
1953 public function getCaptchaSettings()
1954 {
1955 $formContents = $this->getFormContent();
1956 $fieldStr = wp_json_encode($formContents->fields);
1957 if (false !== strpos($fieldStr, '"typ":"recaptcha"')) {
1958 return true;
1959 }
1960 }
1961
1962 public function getTurnstileSettings()
1963 {
1964 $formContents = $this->getFormContent();
1965 $fieldStr = wp_json_encode($formContents->fields);
1966 if (false !== strpos($fieldStr, '"typ":"turnstile"')) {
1967 return true;
1968 }
1969 }
1970
1971 public function isFieldTypeExist($fieldType)
1972 {
1973 $formContents = $this->getFormContent();
1974 $fieldStr = wp_json_encode($formContents->fields);
1975 if (false !== strpos($fieldStr, '"typ":"' . $fieldType . '"')) {
1976 return true;
1977 }
1978 }
1979
1980 public function getCaptchaV3Settings()
1981 {
1982 $formContents = $this->getFormContent();
1983 if (!empty($formContents->additional->enabled) && !empty($formContents->additional->enabled->recaptchav3)) {
1984 return $formContents->additional->settings->recaptchav3;
1985 }
1986 return false;
1987 }
1988
1989 // public function getSuccessMessageMarkups() {
1990 // if (is_null($this->_work_flows)) {
1991 // $workFlowManager = new WorkFlowHandler($this->form_id);
1992 // $this->_work_flows = $workFlowManager->getAllworkFlow();
1993 // }
1994
1995 // $ids = [];
1996 // foreach ($this->_work_flows as $msgItem) {
1997 // foreach ($msgItem['conditions'] as $condition) {
1998 // if (isset($condition->actions->success)) {
1999 // foreach ($condition->actions->success as $msg) {
2000 // if ('successMsg' === $msg->type && isset($msg->details->id)) {
2001 // $msgDetailsId = $msg->details->id;
2002 // $idObj = json_decode(stripslashes($msgDetailsId));
2003 // if (is_object($idObj) && !empty($idObj->id)) {
2004 // array_push($ids, $idObj->id);
2005 // }
2006 // }
2007 // }
2008 // }
2009 // if (isset($condition->actions->failure)) {
2010 // $idObj = json_decode(stripslashes($condition->actions->failure));
2011 // if (is_object($idObj) && !empty($idObj->id)) {
2012 // array_push($ids, $idObj->id);
2013 // }
2014 // }
2015 // }
2016 // }
2017 // $ids = array_unique($ids);
2018 // if (is_null($this->_conf_messages)) {
2019 // $successMsgHandler = new SuccessMessageHandler($this->form_id);
2020 // $this->_conf_messages = $successMsgHandler->getMessages($ids);
2021 // }
2022
2023 // $messageMarkups = '';
2024 // if (is_wp_error($this->_conf_messages)) {
2025 // return $messageMarkups;
2026 // }
2027
2028 // foreach ($this->_conf_messages as $key => $msgItem) {
2029 // $messageMarkups .= $this->messageMarkup($msgItem->id);
2030 // }
2031
2032 // return $messageMarkups;
2033 // }
2034
2035 // private function messageMarkup($msgId) {
2036 // return <<<SUCCESSMSG
2037 // <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive2 test">
2038 // <div role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
2039 // <div class="bf-notification-message {$this->getAtomicCls("msg-content-{$msgId}")}">
2040 // <button class="{$this->getAtomicCls("close-{$msgId}")} bf-msg-close" type="button">
2041 // <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
2042 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
2043 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
2044 // </svg>
2045 // </button>
2046 // <div class="msg-content"></div>
2047 // </div>
2048 // </div>
2049 // </div>
2050 // SUCCESSMSG;
2051 // }
2052
2053 public function getAtomicCls($element)
2054 {
2055 $atomicClassMap = $this->getAtomicClsMap();
2056 if (is_object($atomicClassMap) && property_exists($atomicClassMap, ".$element")) {
2057 $getAtomicCls = $atomicClassMap->{".$element"};
2058 return implode(' ', $getAtomicCls) . " $element";
2059 }
2060 return $element;
2061 }
2062
2063 public function isGCLIDEnabled()
2064 {
2065 $formContents = $this->getFormContent();
2066 if (isset($formContents->additional->enabled->captureGCLID) && $formContents->additional->enabled->captureGCLID) {
2067 return true;
2068 }
2069 return false;
2070 }
2071
2072 protected function addEntryInfo($field_details, $counter)
2073 {
2074 $infos = [
2075 '__user_id' => __('User', 'bit-form'),
2076 '__entry_status' => __('Status', 'bit-form'),
2077 //'__user_location' => __(''),
2078 '__referer' => __('Refer URL', 'bit-form'),
2079 '__user_device' => __('Device', 'bit-form'),
2080 '__user_ip' => __('IP address', 'bit-form'),
2081 '__created_at' => __('Created Time', 'bit-form'),
2082 '__updated_at' => __('Modified Time', 'bit-form'),
2083 ];
2084 foreach ($infos as $key => $value) {
2085 $field_details[$counter]['name'] = $value;
2086 $field_details[$counter]['key'] = $key;
2087 $field_details[$counter]['type'] = 'sys';
2088 $counter = $counter + 1;
2089 }
2090
2091 return $field_details;
2092 }
2093 }
2094