PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / -3.0.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v-3.0.1
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 -3.0.1, at includes/Core/Form/FormManager.php

1,523 lines 56.7 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\WorkFlow\WorkFlow;
27 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
28 use stdClass;
29 use WP_Error;
30
31 class FormManager
32 {
33 // Cache for instances of FormManager by form_id
34 private static $formManagerCache = [];
35 protected static $form;
36 protected $formModel;
37 protected $form_id;
38 private $_has_upload;
39 private $_field_label;
40 private $_fields;
41 private $_repeaterFields;
42 private $_work_flows;
43 private $_conf_messages;
44 private $_atomic_class_map;
45 private $_saveFormAsDraft;
46
47 public function __construct($form_id)
48 {
49 $this->form_id = $form_id;
50 $this->formModel = new FormModel();
51
52 static::$form = $this->formModel->get(
53 [
54 'id',
55 'form_content',
56 'form_name',
57 'created_at',
58 'views',
59 'entries',
60 'status',
61 'builder_helper_state',
62 'atomic_class_map',
63 'generated_script_page_ids',
64 ],
65 [
66 'id' => $form_id,
67 ]
68 );
69 if (!is_wp_error(static::$form)) {
70 $this->_atomic_class_map = json_decode(static::$form[0]->atomic_class_map);
71 $bfMultipleFormsExists = FrontendHelpers::hasMultipleForms();
72 if ($bfMultipleFormsExists && isset($this->_atomic_class_map->atomic_class_map_with_form_id)) {
73 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map_with_form_id;
74 } elseif (isset($this->_atomic_class_map->atomic_class_map)) {
75 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map;
76 }
77 } else {
78 // Log the error if needed
79 Log::debug_log('Error fetching form: ' . "Form Id = ($form_id)" . static::$form->get_error_message());
80 }
81 }
82
83 // Static method to get the instance of FormManager
84 public static function getInstance($form_id)
85 {
86 // Check if an instance of FormManager is already cached
87 if (!isset(self::$formManagerCache[$form_id])) {
88 // Create and cache the FormManager instance if not found
89 self::$formManagerCache[$form_id] = new self($form_id);
90 }
91
92 // Return the cached instance
93 return self::$formManagerCache[$form_id];
94 }
95
96 public function isExist()
97 {
98 return (!static::$form || is_wp_error(static::$form)) ? false : true;
99 }
100
101 public function checkStatus()
102 {
103 return '1' === static::$form[0]->status ? true : false;
104 }
105
106 public function getFieldsContent()
107 {
108 return self::$form[0]->form_content;
109 }
110
111 public function getFont()
112 {
113 $atomicClassMap = $this->_atomic_class_map;
114 $font = isset($atomicClassMap->font) ? $atomicClassMap->font : '';
115 return $font;
116 }
117
118 public function getStyle()
119 {
120 $builerState = \json_decode(static::$form[0]->builder_helper_state);
121 $style = '';
122 $themeVars = $builerState->themeVars;
123 $themeColors = $builerState->themeColors;
124
125 if (!empty($themeVars)) {
126 $style .= ':root {';
127 foreach ($themeVars->lgLightThemeVars as $key => $value) {
128 $style .= "$key: $value; ";
129 }
130 $style .= '} ';
131 }
132 if (!empty($themeColors)) {
133 $style .= ' :root {';
134 foreach ($themeColors->lightThemeColors as $k => $v) {
135 $style .= "$k:$v; ";
136 }
137 $style .= '} ';
138 }
139
140 $field = $builerState->style->lgLightStyles->fields;
141 foreach ($field as $value) {
142 $classes = $value->classes;
143 foreach ($classes as $key => $value) {
144 $style .= "{$key} {";
145 foreach ($value as $k => $v) {
146 $style .= "$k:$v; ";
147 }
148 $style .= '} ';
149 }
150 }
151 return $style;
152 }
153
154 public function getCustomStyle()
155 {
156 $customCSSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.css";
157 return FileHandler::readFile($customCSSPath);
158 }
159
160 public function getCustomJS()
161 {
162 $customJsPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.js";
163 return FileHandler::readFile($customJsPath);
164 }
165
166 public function getFormContentWithValue($defaultValues = [])
167 {
168 $form_content = \json_decode(static::$form[0]->form_content);
169 // this filter just use private purpose
170 $form_content->fields = apply_filters('bitform_dynamic_field_filter', $form_content->fields);
171 if (!is_array($defaultValues) || 0 === count($defaultValues)) {
172 return $form_content;
173 }
174 foreach ($form_content->fields as $fieldKey => $fieldDetails) {
175 // $field_name = empty($fieldDetails->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $fieldDetails->lbl);
176 $fieldName = $fieldDetails->fieldName;
177 $defaultValue = isset($defaultValues[$fieldName]) ? $defaultValues[$fieldName] : null;
178 $defaultValue = isset($defaultValues[$fieldKey]) ? $defaultValues[$fieldKey] : $defaultValue;
179 if ((isset($fieldDetails->mul) || 'check' === $fieldDetails->typ) && isset($defaultValue)) {
180 // if (is_array($defaultValue)) {
181 // $fieldDetails->val =
182 // wp_json_encode(
183 // array_map('sanitize_text_field', $defaultValue)
184 // );
185 // } else {
186 // $fieldDetails->val = sanitize_text_field($defaultValue);
187 // }
188 if ((isset($fieldDetails->mul) && true === $fieldDetails->mul) || is_array($defaultValue)) {
189 $fieldDetails->val = wp_json_encode(array_map('sanitize_text_field', $defaultValue));
190 } elseif (!is_array($defaultValue)) {
191 $fieldDetails->val = sanitize_text_field($defaultValue);
192 }
193 } elseif (!is_null($defaultValue)) {
194 $fieldDetails->val = is_string($defaultValue) ?
195 sanitize_text_field($defaultValue) :
196 sanitize_text_field($defaultValue[count($defaultValue) - 1]);
197 }
198 }
199 return $form_content;
200 }
201
202 public function getFormContent()
203 {
204 $formContent = json_decode(static::$form[0]->form_content);
205 $types = ['check', 'radio', 'select'];
206 $filter = false;
207 foreach ($formContent->fields as $field) {
208 if (in_array($field->typ, $types) && property_exists($field, 'customType')) {
209 $filter = true;
210 break; // reduce unnecessary loop
211 }
212 }
213 if (true === $filter) {
214 $updateFields = apply_filters('bitform_dynamic_field_filter', $formContent->fields);
215 $formContent->fields = $updateFields;
216 }
217 return $formContent;
218 }
219
220 public function getFormInfo()
221 {
222 $formContent = json_decode(static::$form[0]->form_content);
223 $formInfo = isset($formContent->formInfo) ? $formContent->formInfo : null;
224 return $formInfo;
225 }
226
227 public function getFormPermission()
228 {
229 $formContent = json_decode(static::$form[0]->form_content);
230 $formPermission = isset($formContent->formPermissions) ? $formContent->formPermissions : null;
231 return $formPermission;
232 }
233
234 public function getFormHelperStates()
235 {
236 $formHelperStates = json_decode(static::$form[0]->builder_helper_state);
237 return $formHelperStates;
238 }
239
240 public function getAtomicClsMap()
241 {
242 return $this->_atomic_class_map;
243 }
244
245 private function is_json($str)
246 {
247 $json = json_decode($str);
248 return $json && $str !== $json;
249 }
250
251 public function getFormData($columnName = '')
252 {
253 if (empty($columnName)) {
254 return null;
255 }
256
257 $form = static::$form[0];
258 if (!isset($form->{$columnName})) {
259 return null;
260 }
261
262 $data = $form->{$columnName};
263 if ($this->is_json($data)) {
264 return json_decode($data);
265 }
266
267 return $data;
268 }
269
270 public function getFormName()
271 {
272 return static::$form[0]->form_name;
273 }
274
275 public function getFormLayout()
276 {
277 $formContent = $this->getFormContent();
278 return $formContent->layout;
279 }
280
281 public function getFormNestedLayout()
282 {
283 $formContent = $this->getFormContent();
284 return $formContent->nestedLayout;
285 }
286
287 private function mergeNestedLayout(&$layout, $nestedLayout)
288 {
289 foreach ($nestedLayout as $key => $brkpnts) {
290 foreach ($brkpnts as $brkpnt=>$nLayout) {
291 $layout->{$brkpnt} = array_merge($layout->{$brkpnt}, $nLayout);
292 }
293 }
294 }
295
296 public function flatMultistepFormLayout()
297 {
298 $formLayout = $this->getFormLayout();
299 $multistepLayout = new stdClass();
300 foreach ($formLayout as $stpLayout) {
301 $lyout = $stpLayout->layout;
302
303 foreach ($lyout as $brkpnt=>$fields) {
304 $multistepLayout->{$brkpnt} = array_merge($multistepLayout->{$brkpnt} ?? [], $fields);
305 }
306 }
307
308 return $multistepLayout;
309 }
310
311 public function getFlatenFormLayout()
312 {
313 $layout = $this->getFormLayout();
314 $nestedLayout = $this->getFormNestedLayout();
315 if ('array' === gettype($layout)) {
316 // multi step form layout
317 $layout = $this->flatMultistepFormLayout();
318 }
319 if (!empty((array) $nestedLayout)) {
320 $this->mergeNestedLayout($layout, $nestedLayout);
321 }
322
323 return $layout;
324 }
325
326 public function getFieldsBasedOnLayout()
327 {
328 $layout = $this->getFlatenFormLayout();
329
330 $fieldKeyOrderbasedOnLayout = array_map(function ($fld) {
331 return $fld->i;
332 }, $layout->lg);
333 $orderedFields = [];
334 $fields = $this->getFields();
335
336 foreach ($fieldKeyOrderbasedOnLayout as $key) {
337 if (array_key_exists($key, $fields)) {
338 $orderedFields[$key] = $fields[$key];
339 }
340 }
341
342 foreach ($fields as $k=>$v) {
343 if (!array_key_exists($k, $fieldKeyOrderbasedOnLayout)) {
344 $orderedFields[$k] = $fields[$k];
345 }
346 }
347
348 return $orderedFields;
349 }
350
351 public function getFields()
352 {
353 if (!is_null($this->_fields)) {
354 return $this->_fields;
355 }
356 $form_content = \json_decode(static::$form[0]->form_content);
357 $layout = $form_content->layout;
358 $fields = $form_content->fields;
359 $field_details = [];
360 foreach ($fields as $key => $field) {
361 if ('recaptcha' === $field->typ || 'hcaptcha' === $field->typ) {
362 continue;
363 }
364 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
365 $field_type = $field->typ;
366 $field_details[$key]['label'] = !empty($field->lbl) ? $field->lbl : (!empty($field->adminLbl) ? $field->adminLbl : (!empty($field->fieldName) ? $field->fieldName : null));
367 $field_details[$key]['type'] = $field_type;
368 $field_details[$key]['key'] = $key;
369 $field_details[$key]['name'] = isset($field->fieldName) ? $field->fieldName : '';
370 if (isset($field->customType)) {
371 $field_details[$key]['customType'] = $field->customType;
372 }
373 // fields with confirm field
374 if (isset($field->childFields)) {
375 $field_details[$key]['childFields'] = $field->childFields;
376 }
377 if (isset($field->parentFieldKey)) {
378 $field_details[$key]['parentFieldKey'] = $field->parentFieldKey;
379 if (isset($field->isDeactive)) {
380 $field_details[$key]['isDeactive'] = $field->isDeactive;
381 }
382 }
383 if (isset($field->err)) {
384 if (isset($field->err->entryUnique)) {
385 $field_details[$key]['entryUnique'] = $field->err->entryUnique;
386 }
387 if (isset($field->err->userUnique)) {
388 $field_details[$key]['userUnique'] = $field->err->userUnique;
389 }
390 }
391
392 if (isset($field->mul)) {
393 $field_details[$key]['mul'] = $field->mul;
394 }
395 if ('file-up' === $field_type && isset($field->exts)) {
396 $field_details[$key]['valid']['type'] = $field->exts;
397 }
398 if ('file-up' === $field_type && isset($field->mxUp)) {
399 $field_details[$key]['valid']['upload_size'] = (int) $field->mxUp;
400 }
401 if (isset($field->valid) && !is_null($field->valid)) {
402 if (isset($field->valid->req)) {
403 $field_details[$key]['valid']['req'] = $field->valid->req;
404 }
405 if (isset($field->valid->reqMsg)) {
406 $field_details[$key]['valid']['reqMsg'] = $field->valid->reqMsg;
407 }
408 if (isset($field->valid->typMsg)) {
409 $field_details[$key]['valid']['typMsg'] = $field->valid->typMsg;
410 }
411 if (isset($field->valid->hide)) {
412 $field_details[$key]['valid']['hide'] = $field->valid->hide;
413 }
414 }
415 if ($this->isRepeatedField($key)) {
416 $field_details[$key]['repeated'] = true;
417 }
418 }
419 if ($this->isGCLIDEnabled()) {
420 $field_details['GCLID']['name'] = 'GCLID';
421 $field_details['GCLID']['adminLbl'] = 'GCLID';
422 $field_details['GCLID']['key'] = 'GCLID';
423 $field_details['GCLID']['type'] = 'hidden';
424 }
425 $this->_fields = $field_details;
426 return $field_details;
427 }
428
429 public function getFieldsKey()
430 {
431 $form_content = \json_decode(static::$form[0]->form_content);
432 $fields = $form_content->fields;
433 $field_details = [];
434 foreach ($fields as $key => $field) {
435 if ('recaptcha' === $field->typ || 'hcaptcha' === $field->typ) {
436 continue;
437 }
438 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
439 $field_details[$key] = $key;
440 }
441 if ($this->isGCLIDEnabled()) {
442 $field_details['GCLID'] = 'GCLID';
443 }
444 return $field_details;
445 }
446
447 public function getFieldLabel($forQuery = false)
448 {
449 if (!is_null($this->_field_label)) {
450 return $this->_field_label;
451 }
452 $form_content = \json_decode(static::$form[0]->form_content);
453 $fields = $form_content->fields;
454 $field_details = [];
455 $fieldCounter = 0;
456 foreach ($fields as $key => $field) {
457 if ('recaptcha' === $field->typ || 'turnstile' === $field->typ || 'html' === $field->typ || 'button' === $field->typ) {
458 continue;
459 }
460 $field_details[$fieldCounter]['name'] = empty($field->lbl) ? null : $field->lbl;
461 $field_details[$fieldCounter]['adminLbl'] = empty($field->adminLbl) ? $field_details[$fieldCounter]['name'] : $field->adminLbl;
462 $field_details[$fieldCounter]['key'] = $key;
463 $field_details[$fieldCounter]['type'] = $field->typ;
464 $fieldCounter += 1;
465 }
466 if ($this->isGCLIDEnabled()) {
467 $field_details[$fieldCounter]['name'] = 'GCLID';
468 $field_details[$fieldCounter]['adminLbl'] = 'GCLID';
469 $field_details[$fieldCounter]['key'] = 'GCLID';
470 $field_details[$fieldCounter]['type'] = 'hidden';
471 $fieldCounter += 1;
472 }
473 if (!$forQuery) {
474 $field_details = (array) $this->addEntryInfo($field_details, $fieldCounter);
475 }
476 $this->_field_label = $field_details;
477 return $field_details;
478 }
479
480 public function getUploadFields()
481 {
482 if (!is_null($this->_has_upload)) {
483 return $this->_has_upload;
484 }
485 $upload_fields = [];
486 $form_field_details = $this->getFields();
487 foreach ($form_field_details as $field_name => $__field_detail) {
488 if (isset($__field_detail['type']) && ('file-up' === $__field_detail['type'] || 'advanced-file-up' === $__field_detail['type'])) {
489 $upload_fields[] = $field_name;
490 }
491 }
492 $this->_has_upload = $upload_fields;
493 return $upload_fields;
494 }
495
496 public function getSignatureFilePath($blobLink, $form_id, $fieldKey, $entry_id, $imgType)
497 {
498 $imgTypes = [
499 'image/png' => 'png',
500 'image/jpeg' => 'jpg',
501 'image/svg+xml' => 'svg',
502 ];
503 try {
504 if (!isset($imgTypes[$imgType])) {
505 throw new \InvalidArgumentException("Unsupported image type: $imgType");
506 }
507 $parts = explode(',', $blobLink, 2);
508 if (2 !== count($parts) || false === ($decoded_image = base64_decode($parts[1]))) {
509 throw new \RuntimeException('Invalid or corrupt signature data URI');
510 }
511
512 $_upload_dir = FileHandler::getEntriesFileUploadDir($form_id, $entry_id);
513 FileHandler::createIndexFile($_upload_dir);
514 $uniqueId = time() . '-' . bin2hex(\random_bytes(4));
515 $filename = "{$entry_id}-{$fieldKey}-{$uniqueId}.{$imgTypes[$imgType]}";
516 $fullPath = $_upload_dir . DIRECTORY_SEPARATOR . $filename;
517 if (false === file_put_contents($fullPath, $decoded_image)) {
518 throw new \RuntimeException("Failed to write image to $fullPath");
519 }
520 return $filename;
521 } catch (\Throwable $e) {
522 Log::debug_log("[Signature Error] Form: $form_id, Entry: $entry_id, Field: $fieldKey - " . $e->getMessage());
523 return 'signature-failed.png'; // or a default filename if appropriate
524 }
525 }
526
527 private function entryInsert($user_details)
528 {
529 $formEntryModel = new FormEntryModel();
530 $entryId = $formEntryModel->insert(
531 [
532 'form_id' => $this->form_id,
533 'user_id' => $user_details['id'],
534 'user_ip' => $user_details['ip'],
535 'user_device' => $user_details['device'],
536 'referer' => $user_details['page'],
537 'status' => $this->_saveFormAsDraft ? 9 : 1,
538 'created_at' => $user_details['time'],
539 ]
540 );
541 return $entryId;
542 }
543
544 public function submisionLog($user_details, $entry_id, $type)
545 {
546 $formEntryLogModel = new FormEntryLogModel();
547 $submissionLogData = [
548 'user_id' => $user_details['id'],
549 'action_type' => $type, // create, update
550 'log_type' => 'entry',
551 'ip' => $user_details['ip'],
552 'form_entry_id' => $entry_id,
553 'content' => ['user_device' => $user_details['device']],
554 'form_id' => $this->form_id,
555 'created_at' => $user_details['time'],
556 ];
557 $submissionLogData = apply_filters('bitform_filter_submission_log_data', $submissionLogData, $this->form_id, $type);
558 $logId = $formEntryLogModel->form_log_insert(
559 $submissionLogData
560 );
561 return $logId;
562 }
563
564 private function isArrayAllKeyInt($InputArray)
565 {
566 if (!is_array($InputArray)) {
567 return false;
568 }
569
570 if (count($InputArray) <= 0) {
571 return true;
572 }
573
574 return array_unique(array_map('is_int', array_keys($InputArray))) === [true];
575 }
576
577 public function formatSubmittedData($submitted_data)
578 {
579 $form_content = $this->getFormContent();
580 $form_fields = $form_content->fields;
581
582 foreach ($submitted_data as $key => $value) {
583 if (!isset($form_fields->{$key})) {
584 continue;
585 }
586 $field_data = $form_fields->{$key};
587 $field_type = $field_data->typ;
588 $normalizedParentValue = $this->normalizeSubmittedValue($value);
589 $parentFieldName = isset($field_data->fieldName) ? $field_data->fieldName : '';
590 if (!empty($field_data->childFields) && is_array($field_data->childFields)) {
591 foreach ($field_data->childFields as $childFieldRef) {
592 $childFieldKey = isset($childFieldRef->fldKey) ? $childFieldRef->fldKey : '';
593 if (empty($childFieldKey) || !isset($form_fields->{$childFieldKey})) {
594 continue;
595 }
596
597 $childFieldData = $form_fields->{$childFieldKey};
598 $childFieldName = isset($childFieldData->fieldName) ? $childFieldData->fieldName : '';
599 $childFieldName = str_replace(['[', ']', $parentFieldName], '', $childFieldName);
600 if (empty($childFieldName)) {
601 continue;
602 }
603
604 $childValue = $this->extractChildValueFromParentValue($normalizedParentValue, $childFieldName, $childFieldKey);
605 if (null !== $childValue) {
606 $submitted_data[$childFieldKey] = $childValue;
607 }
608 }
609 }
610
611 if ($this->isRepeatedField($key) && in_array($field_type, ['name', 'address'])) {
612 $submitted_data[$key] = $this->normalizeRepeatedCompositeFieldInput($normalizedParentValue);
613 }
614
615 if ('select' === $field_type && !empty($field_data->config->multipleSelect)) {
616 $valueArr = [];
617 if ($this->isRepeatedField($key) && is_array($normalizedParentValue)) {
618 foreach ($normalizedParentValue as $index => $v) {
619 $valueArr[$index] = explode(BITFORMS_BF_SEPARATOR, $v);
620 }
621 } else {
622 $valueArr = explode(BITFORMS_BF_SEPARATOR, (string) $value);
623 }
624 $submitted_data[$key] = $valueArr;
625 }
626 }
627 $submitted_data = apply_filters('bitform_filter_format_submitted_data', $submitted_data, $this->form_id);
628 return $submitted_data;
629 }
630
631 private function normalizeSubmittedValue($value)
632 {
633 if (!is_string($value)) {
634 return $value;
635 }
636
637 $decoded = json_decode($value, true);
638 return (JSON_ERROR_NONE === json_last_error()) ? $decoded : $value;
639 }
640
641 private function extractChildValueFromParentValue($parentValue, $childFieldName, $childFieldKey)
642 {
643 if (is_object($parentValue)) {
644 $parentValue = (array) $parentValue;
645 }
646
647 if (!is_array($parentValue)) {
648 return null;
649 }
650
651 if (array_key_exists($childFieldName, $parentValue)) {
652 return $parentValue[$childFieldName];
653 }
654
655 if (array_key_exists($childFieldKey, $parentValue)) {
656 return $parentValue[$childFieldKey];
657 }
658
659 return null;
660 }
661
662 private function addNewFilePathToFiles($form_id, $entry_id, $file_fields = [])
663 {
664 $common_file_path = Helpers::getFullPathWithEncryptedEntryId($form_id, $entry_id);
665 foreach ($_FILES as $field_key => $file_details) {
666 if (!($file_fields && in_array($field_key, $file_fields))) {
667 continue;
668 }
669
670 $isRepeaterFldKey = $this->isRepeatedField($field_key);
671 if ($isRepeaterFldKey && isset($file_details['new_name'])) {
672 // If 'new_name' is an array (i.e., for repeated fields)
673 foreach ($file_details['new_name'] as $slNo => $newFileNamesArray) {
674 if (is_array($newFileNamesArray)) {
675 foreach ($newFileNamesArray as $newFileName) {
676 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
677 $_FILES[$field_key]['file_path'][$slNo][] = $filePath;
678 }
679 } else {
680 // Generate the file path for each file
681 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileNamesArray;
682 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
683 }
684 }
685 } elseif (isset($file_details['new_name'])) {
686 // If 'new_name' is an array (i.e., for repeated fields)
687 if (is_array($file_details['new_name'])) {
688 foreach ($file_details['new_name'] as $slNo => $newFileName) {
689 // Generate the file path for each file
690 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
691 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
692 }
693 } else {
694 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $file_details['new_name'];
695 $_FILES[$field_key]['file_path'] = $filePath;
696 }
697 }
698 }
699 }
700
701 private function formatRepeateFieldData($submitted_data, $form_fields)
702 {
703 $repeaterFields = $this->getRepeaterFields();
704 foreach ($repeaterFields as $repeaterFldKey => $repeatedFields) {
705 $repeatIndexes = $submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"];
706 $repeatIndexes = explode(',', $repeatIndexes);
707 foreach ($repeatIndexes as $slNo => $repeatIndex) {
708 foreach ($repeatedFields as $repeatedField) {
709 if (!isset($submitted_data[$repeatedField][$repeatIndex])) {
710 continue;
711 }
712 if (!isset($submitted_data[$repeaterFldKey][$slNo])) {
713 $submitted_data[$repeaterFldKey][$slNo] = [];
714 }
715 if (!isset($submitted_data[$repeaterFldKey][$slNo][$repeatedField])) {
716 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = [];
717 }
718 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = $submitted_data[$repeatedField][$repeatIndex];
719 }
720 }
721 foreach ($repeatedFields as $repeatedField) {
722 unset($submitted_data[$repeatedField]);
723 }
724 unset($submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"]);
725 }
726
727 return $submitted_data;
728 }
729
730 private function saveEntryMeta($submitted_data, $entry_id)
731 {
732 $errorInEntryMetaInsert = false;
733 $entryMeta = new FormEntryMetaModel();
734 foreach ($submitted_data as $key => $value) {
735 $value = $submitted_data[$key];
736 if (is_string($value)) {
737 $value = wp_unslash($value);
738 } elseif ($this->isArrayAllKeyInt($value)) {
739 $value = wp_json_encode(array_values($value));
740 } else {
741 $value = wp_json_encode($value);
742 }
743 // Form entry meta insert; meta_key/meta_value required to store dynamic field data per entry.
744 $status = $entryMeta->insert(
745 [
746 'bitforms_form_entry_id' => $entry_id,
747 'meta_key' => $key,
748 'meta_value' => $value,
749 ]
750 );
751 if (is_wp_error($status)) {
752 $errorInEntryMetaInsert = true;
753 break;
754 }
755 }
756 return $errorInEntryMetaInsert;
757 }
758
759 public function setSaveFormAsDraft()
760 {
761 $this->_saveFormAsDraft = true;
762 }
763
764 public function saveFormEntry($submitted_data)
765 {
766 // CSRF verified upstream via FrontendFormManager::verifySubmissionNonce() before this method is invoked.
767 $submitted_data = $this->formatSubmittedData($submitted_data);
768 $submitted_data = apply_filters('bitform_filter_save_form_entry', $submitted_data, $this->form_id);
769 $form_content = \json_decode(static::$form[0]->form_content);
770 do_action('bitform_save_entry', $this, $submitted_data, $this->form_id);
771 $key = null;
772 $ipTool = new IpTool();
773 $fileHandler = new FileHandler();
774 $form_fields = $this->getFields();
775 $file_fields = $this->getUploadFields();
776
777 foreach ($_FILES as $file_name => $file_details) {
778 if ($file_fields && in_array($file_name, $file_fields)) {
779 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
780 if (!empty($validation['error_type']) && !empty($validation['message'])) {
781 return new WP_Error($validation['error_type'], esc_html($validation['message']));
782 }
783 }
784 }
785 $user_details = $ipTool->getUserDetail();
786 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
787 $user_details = apply_filters('bitform_filter_save_entry_user_details', $user_details, $this->form_id);
788
789 $form_fields = $this->getFields();
790 $submitted_data = $this->passwordEncrypted($submitted_data, $form_fields);
791 $submitted_data = $this->formatRepeateFieldData($submitted_data, $form_fields);
792 global $wpdb;
793 // Direct transaction control; no user input involved.
794 $wpdb->query('START TRANSACTION');
795 $entry_id = $this->entryInsert($user_details);
796 $log_id = null;
797
798 $GLOBALS['bitform_entry_id'] = $entry_id;
799
800 if (is_wp_error($entry_id)) {
801 return new WP_Error('insert_error', __('Sorry, Error occurred in saving form entry', 'bit-form'));
802 }
803 if ($entry_id) {
804 $log_id = $this->submisionLog($user_details, $entry_id, 'create', $key);
805 if (is_wp_error($log_id)) {
806 $wpdb->query('ROLLBACK');
807 return new WP_Error('error_entry_log', __('Sorry, error occurred in logging form entry', 'bit-form'));
808 }
809 }
810 if ($entry_id) {
811 $submitted_fields = $this->getFormContentWithValue($submitted_data)->fields;
812 $workFlowRunHelper = new WorkFlow($this->form_id);
813
814 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
815 'create',
816 $submitted_fields,
817 $submitted_data,
818 $entry_id,
819 $log_id
820 );
821
822 if (!empty($workFlowreturnedOnSubmit['fields'])) {
823 $submitted_data = $workFlowreturnedOnSubmit['fields'];
824 }
825
826 $file_fields = $this->getUploadFields();
827 $formFields = $this->getFields();
828 $submitted_data = FileHandler::tempDirToUploadDir($submitted_data, $formFields, $this->form_id, $entry_id);
829 $fileHandler = new FileHandler();
830 foreach ($_FILES as $field_key => $file_details) {
831 if ($file_fields && in_array($field_key, $file_fields)) {
832 $fileNames = [];
833 $repeaterFldKey = $this->isRepeatedField($field_key);
834 if ($repeaterFldKey) {
835 foreach ($file_details['name'] as $slNo => $fileName) {
836 $repeateFileDetails = [
837 'name' => $file_details['name'][$slNo],
838 'type' => $file_details['type'][$slNo],
839 'tmp_name' => $file_details['tmp_name'][$slNo],
840 'error' => $file_details['error'][$slNo],
841 'size' => $file_details['size'][$slNo],
842 ];
843 $fileNames = $fileHandler->moveUploadedFiles($repeateFileDetails, $this->form_id, $entry_id);
844 if (!empty($fileNames)) {
845 $submitted_data[$repeaterFldKey][$slNo - 1][$field_key] = $fileNames;
846 $_FILES[$field_key]['new_name'][$slNo - 1] = $fileNames;
847 }
848 }
849 } else {
850 $fileNames = $fileHandler->moveUploadedFiles($file_details, $this->form_id, $entry_id);
851 if (!empty($fileNames)) {
852 $submitted_data[$field_key] = $fileNames;
853 $_FILES[$field_key]['new_name'] = $fileNames;
854 }
855 }
856 }
857 }
858
859 // Get the common path for file storage
860 $this->addNewFilePathToFiles($this->form_id, $entry_id, $file_fields);
861
862 foreach ($form_content->fields as $key => $field) {
863 /* ======== for Signature field ===========*/
864 if ('signature' === $field->typ) {
865 if (isset($submitted_data[$key])) {
866 $fld_data = $submitted_data[$key];
867 $img_type = $field->config->imgTyp;
868 $submitted_data[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entry_id, $img_type);
869 }
870 }
871
872 // for Signature field inside reepater
873 if ('repeater' === $field->typ) {
874 $rptr_data = $submitted_data[$key];
875 $formFields = $form_content->fields;
876 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entry_id, $submitted_data);
877 }
878 }
879
880 if (!isset($form_content->additional->enabled->submission)) {
881 $errorInEntryMetaInsert = $this->saveEntryMeta($submitted_data, $entry_id);
882 if ($errorInEntryMetaInsert) {
883 do_action('bitform_save_entry_error', $this, $submitted_data, $this->form_id);
884 $wpdb->query('ROLLBACK');
885 return new WP_Error('insert_error', __('Sorry, Error occured in saving form entry data', 'bit-form'));
886 }
887 do_action('bitform_after_save_entry_success', $this, $submitted_data, $this->form_id, $entry_id);
888 } else {
889 $wpdb->query('ROLLBACK');
890 }
891 $wpdb->query('COMMIT');
892 $this->setSubmissionCount();
893 $workFlowreturnedOnSubmit['entry_id'] = $entry_id;
894 $workFlowreturnedOnSubmit['fields'] = $submitted_data;
895 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_submit_success', $workFlowreturnedOnSubmit, $this->form_id);
896
897 return $workFlowreturnedOnSubmit;
898 }
899 }
900
901 private function setSignatureFilePathInRepeater($repeaterData, $repeaterFieldKey, $formFields, $entry_id, &$submitted_data)
902 {
903 foreach ($repeaterData as $rptr_entry_index => $rptr_entries) {
904 foreach ($rptr_entries as $entry_key => $entry_value) {
905 $rptr_entry_info = $formFields->{$entry_key};
906
907 if ('signature' === $rptr_entry_info->typ) {
908 $imgType = $rptr_entry_info->config->imgTyp;
909 $signatureImage = $this->getSignatureFilePath($entry_value, $this->form_id, $repeaterFieldKey, $entry_id, $imgType);
910 $submitted_data[$repeaterFieldKey][$rptr_entry_index][$entry_key] = $signatureImage;
911 }
912 }
913 }
914 }
915
916 public function passwordEncrypted($updatedValue, $form_fields)
917 {
918 $integrationHandler = new IntegrationHandler($this->form_id);
919 $formIntegrations = $integrationHandler->getAllIntegration('wp_user_auth', 'wp_auth', 1);
920 if (!isset($formIntegrations->errors['result_empty'])) {
921 foreach ($form_fields as $field) {
922 if (array_key_exists($field['key'], $updatedValue) && 'password' === $field['type']) {
923 $updatedValue[$field['key']] = '**** (encrypted)';
924 }
925 }
926 }
927 return $updatedValue;
928 }
929
930 public function updateFormEntry($updatedValue, $formID, $entryID)
931 {
932 // CSRF / entry-token verified upstream via FrontendFormManager::handleUpdateEntry() before this method is invoked.
933 $updatedValue = $this->formatSubmittedData($updatedValue);
934 $updatedValue = apply_filters('bitform_filter_update_form_entry', $updatedValue, $this->form_id);
935 do_action('bitform_update_entry', $this, $updatedValue, $formID, $entryID);
936 $form_content = $this->getFormContent();
937 if (isset($form_content->additional->enabled->submission)) {
938 // Run workflow but skip DB/meta update
939 $workFlowRunHelper = new WorkFlow($formID);
940 $fieldsWithValue = $this->getFormContentWithValue($updatedValue)->fields;
941 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
942 'edit',
943 $fieldsWithValue,
944 $updatedValue,
945 $entryID,
946 0
947 );
948 if (empty($workFlowreturnedOnSubmit['message'])) {
949 $workFlowreturnedOnSubmit['message'] = __('Entry update skipped due to submission restriction.', 'bit-form');
950 }
951 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
952 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
953 return $workFlowreturnedOnSubmit;
954 }
955
956 $formEntryModel = new FormEntryModel();
957 $formEntryLogModel = new FormEntryLogModel();
958 $formOldData = $formEntryLogModel->get_form_value($entryID);
959 $key = null;
960 $entryMeta = new FormEntryMetaModel();
961 $ipTool = new IpTool();
962 $user_details = $ipTool->getUserDetail();
963 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
964 $user_details = apply_filters('bitform_filter_update_entry_user_details', $user_details, $this->form_id);
965
966 $form_fields = $this->getFields();
967
968 $updatedValue = $this->passwordEncrypted($updatedValue, $form_fields);
969 $updatedValue = $this->formatRepeateFieldData($updatedValue, $form_fields);
970 $field_map = [];
971 foreach ($formOldData as $index => $data) {
972 foreach ($form_fields as $field_key => $field) {
973 if ($data->meta_key === $field['key']) {
974 $field_map[$field_key] = $field['key'];
975 }
976 }
977 }
978 $geResult = $formEntryModel->get('status', ['id' => $entryID]);
979 if (is_wp_error($geResult) || empty($geResult)) {
980 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
981 }
982 $oldEntry = $geResult[0];
983 $formEntry = $formEntryModel->update(
984 [
985 'status' => ('9' === $oldEntry->status && !$this->_saveFormAsDraft) ? 1 : $oldEntry->status,
986 'updated_at' => $user_details['time'],
987 ],
988 [
989 'form_id' => $formID,
990 'id' => $entryID,
991 ]
992 );
993 $log_id = null;
994 if ($formEntry) {
995 $log_id = $this->submisionLog($user_details, $entryID, 'update');
996 }
997
998 if (is_wp_error($formEntry) || !$formEntry) {
999 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
1000 }
1001 $formFields = $this->getFields();
1002 $updatedValue = FileHandler::tempDirToUploadDir($updatedValue, $formFields, $this->form_id, $entryID);
1003 $file_fields = $this->getUploadFields();
1004 if (count($file_fields) > 0) {
1005 $fileHandler = new FileHandler();
1006 foreach ($_FILES as $file_name => $file_details) {
1007 if ($file_fields && in_array($file_name, $file_fields)) {
1008 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
1009 if (!empty($validation['error_type']) && !empty($validation['message'])) {
1010 return new WP_Error($validation['error_type'], esc_html($validation['message']));
1011 }
1012 }
1013 }
1014 if (is_object($updatedValue)) {
1015 $updatedValue = (array) $updatedValue;
1016 }
1017 foreach ($file_fields as $field_key) {
1018 $repeaterFldKey = $this->isRepeatedField($field_key);
1019 if (isset($updatedValue[$field_key . '_old'])) {
1020 // Handle file deletion for repeater fields
1021 if ($repeaterFldKey) {
1022 // Form entry meta lookup; meta_key/meta_value query required to retrieve repeater field data by entry.
1023 $repeaterExistData = $entryMeta->get(
1024 'meta_value',
1025 [
1026 'bitforms_form_entry_id' => $entryID,
1027 'meta_key' => $repeaterFldKey,
1028 ]
1029 );
1030 if (!is_wp_error($repeaterExistData)) {
1031 // restructor json
1032 $repeaterExistData = json_decode($repeaterExistData[0]->meta_value, true);
1033 $repeaterExistFiles = [];
1034 $repeaterDeleted_files = [];
1035 $repeaterFiles_old = [];
1036 foreach ($repeaterExistData as $index => $repeaterRow) {
1037 $repeaterExistFiles[$index] = [];
1038 if (isset($repeaterRow[$field_key]) && !empty($repeaterRow[$field_key])) {
1039 $repeaterExistFiles[$index] = json_decode($repeaterRow[$field_key], true);
1040 }
1041 $repeaterFiles_old[$index] = empty($updatedValue[$field_key . '_old'][$index]) ? [] : explode(',', $updatedValue[$field_key . '_old'][$index]);
1042 $repeaterDeleted_files[$index] = array_diff($repeaterExistFiles[$index], $repeaterFiles_old[$index]);
1043 $fileHandler->deleteFiles($formID, $entryID, $repeaterDeleted_files[$index]);
1044 }
1045 }
1046 } else {
1047 // Handle file deletion for non-repeater fields; meta_key/meta_value lookup required to identify stored file paths per entry.
1048 $file_exists = $entryMeta->get(
1049 'meta_value',
1050 [
1051 'bitforms_form_entry_id' => $entryID,
1052 'meta_key' => $field_key,
1053 ]
1054 );
1055 if (!is_wp_error($file_exists) && count($file_exists) > 0) {
1056 $files_in_db = json_decode($file_exists[0]->meta_value);
1057 $files_old = empty($updatedValue[$field_key . '_old']) ? [] : explode(',', $updatedValue[$field_key . '_old']);
1058 $deleted_file = array_diff($files_in_db, $files_old);
1059 if (count($deleted_file) > 0) {
1060 $fileHandler->deleteFiles($formID, $entryID, $deleted_file);
1061 }
1062 $updatedValue[$field_key] = wp_json_encode($files_old);
1063 }
1064 }
1065 }
1066 if (!empty($_FILES[$field_key]['name'])) {
1067 if ($repeaterFldKey) {
1068 // Handle repeater field files
1069 $file_details = $_FILES[$field_key];
1070 foreach ($file_details['name'] as $index => $file) {
1071 // Retrieve existing old files for this specific repeater index
1072 if (isset($repeaterFiles_old[$index - 1]) && count($repeaterFiles_old[$index - 1]) > 0) {
1073 $old_meta_value = empty($repeaterFiles_old[$index - 1]) ? [] : $repeaterFiles_old[$index - 1];
1074 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1075 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($old_meta_value);
1076 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $old_meta_value;
1077 }
1078 $repeateFileDetails = [
1079 'name' => $file_details['name'][$index],
1080 'type' => $file_details['type'][$index],
1081 'tmp_name' => $file_details['tmp_name'][$index],
1082 'error' => $file_details['error'][$index],
1083 'size' => $file_details['size'][$index],
1084 ];
1085 $meta_value = $fileHandler->moveUploadedFiles($repeateFileDetails, $formID, $entryID, $index);
1086 if (!empty($meta_value)) {
1087 $mergedMetaValueWithOld = isset($old_meta_value) ? array_merge($old_meta_value, (array) $meta_value) : (array) $meta_value;
1088 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1089 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($mergedMetaValueWithOld);
1090 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $mergedMetaValueWithOld;
1091
1092 $_FILES[$field_key]['new_name'][$index - 1] = $mergedMetaValueWithOld;
1093 // $_FILES[$field_key]['file_path'][$index - 1] = $common_file_path . DIRECTORY_SEPARATOR . $meta_value;
1094 }
1095 }
1096 } else {
1097 // Handle non-repeater field files
1098 $meta_value = $fileHandler->moveUploadedFiles($_FILES[$field_key], $formID, $entryID);
1099 if (!empty($meta_value)) {
1100 $_FILES[$field_key]['new_name'] = $meta_value;
1101 if (isset($updatedValue[$field_key . '_old']) && !is_wp_error($file_exists) && count($file_exists) > 0) {
1102 $meta_value = empty($files_old) ? $meta_value : array_merge($meta_value, $files_old);
1103 $updatedValue[$field_key] = $meta_value;
1104 } else {
1105 $updatedValue[$field_key] = $meta_value;
1106 }
1107 }
1108 }
1109 }
1110 }
1111
1112 // Get the common file path to avoid repetitive calculation
1113 $this->addNewFilePathToFiles($formID, $entryID, $file_fields);
1114 }
1115
1116 if (is_object($updatedValue)) {
1117 $updatedValue = (array) $updatedValue;
1118 }
1119 if (isset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']) && sanitize_text_field(wp_unslash($_REQUEST['g-recaptcha-response']))) {
1120 unset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']);
1121 }
1122
1123 $toUpdateValues = [];
1124 foreach ($form_fields as $field) {
1125 if (isset($updatedValue[$field['key']])) {
1126 $toUpdateValues[$field['key']] = $updatedValue[$field['key']];
1127 }
1128 }
1129 $form_content = \json_decode(static::$form[0]->form_content);
1130
1131 foreach ($form_content->fields as $key => $field) {
1132 if ('signature' === $field->typ) {
1133 $fld_data = $updatedValue[$key];
1134 $img_type = $field->config->imgTyp;
1135 $toUpdateValues[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entryID, $img_type);
1136 }
1137
1138 // for Signature field inside reepater
1139 if ('repeater' === $field->typ) {
1140 $rptr_data = $updatedValue[$key];
1141 $formFields = $form_content->fields;
1142 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entryID, $toUpdateValues);
1143 }
1144 }
1145
1146 $workFlowRunHelper = new WorkFlow($formID);
1147 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
1148 'edit',
1149 $this->getFormContentWithValue($toUpdateValues)->fields,
1150 $toUpdateValues,
1151 $entryID,
1152 $log_id
1153 );
1154
1155 if (!empty($workFlowreturnedOnSubmit['fields'])) {
1156 $updatedValue = $workFlowreturnedOnSubmit['fields'];
1157 }
1158
1159 $formEntryMetaUpdateStatus = $entryMeta->update(
1160 $toUpdateValues,
1161 [
1162 'bitforms_form_entry_id' => $entryID,
1163 ]
1164 );
1165 if (is_wp_error($formEntryMetaUpdateStatus) || isset($newFileInsertStatus) && is_wp_error($newFileInsertStatus)) {
1166 do_action('bitform_update_entry_error', $this, $toUpdateValues, $formEntryMetaUpdateStatus, $this->form_id);
1167 return $formEntryMetaUpdateStatus;
1168 }
1169 $toUpdateValues = array_merge($formEntryMetaUpdateStatus, ['entry_id' => $entryID]);
1170 do_action('bitform_after_update_entry_success', $this, $toUpdateValues, $formID, $entryID);
1171 if (empty($workFlowreturnedOnSubmit['message'])) {
1172 $workFlowreturnedOnSubmit['message'] = __('Entry Updated Successfully', 'bit-form');
1173 }
1174 $customFieldHandler = new CustomFieldHandler();
1175 $toUpdateValues = $customFieldHandler->updatedData($form_fields, $toUpdateValues);
1176
1177 $workFlowreturnedOnSubmit['updatedData'] = $toUpdateValues;
1178 $counter = 0;
1179 for ($i = 0; $i < count($formOldData); $i++) {
1180 if (array_key_exists($formOldData[$i]->meta_key . '_old', $toUpdateValues)) {
1181 unset($toUpdateValues[$formOldData[$i]->meta_key . '_old']);
1182 }
1183 if (in_array($formOldData[$i]->meta_key, $file_fields)) {
1184 if (
1185 empty($_FILES[$formOldData[$i]->meta_key]['name'])
1186 || (is_array($_FILES[$formOldData[$i]->meta_key]['name'])
1187 && 1 === count($_FILES[$formOldData[$i]->meta_key]['name'])
1188 && empty($_FILES[$formOldData[$i]->meta_key]['name'][0]))
1189 ) {
1190 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1191 continue;
1192 }
1193 if (is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1194 $sanitized_names = array_map('sanitize_file_name', array_map('wp_unslash', (array) $_FILES[$formOldData[$i]->meta_key]['name']));
1195 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . wp_json_encode($sanitized_names);
1196 } elseif (!is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1197 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . sanitize_file_name(wp_unslash($_FILES[$formOldData[$i]->meta_key]['name']));
1198 }
1199 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1200 } elseif (isset($toUpdateValues[$formOldData[$i]->meta_key])) {
1201 if (is_array($toUpdateValues[$formOldData[$i]->meta_key])) {
1202 if (json_decode($formOldData[$i]->meta_value) !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1203 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated From ' . implode(',', json_decode($formOldData[$i]->meta_value)) . ' To ' . implode(',', $toUpdateValues[$formOldData[$i]->meta_key]);
1204 }
1205 } elseif (is_string($toUpdateValues[$formOldData[$i]->meta_key]) && !FieldValueHandler::isEmpty($toUpdateValues[$formOldData[$i]->meta_key])) {
1206 if ($formOldData[$i]->meta_value !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1207 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated' . ($formOldData[$i]->meta_value ? ' From ' . $formOldData[$i]->meta_value : '') . ' To ' . $toUpdateValues[$formOldData[$i]->meta_key];
1208 }
1209 }
1210 }
1211 $counter++;
1212 }
1213
1214 $newField = array_keys(array_diff_key($formEntryMetaUpdateStatus, $field_map));
1215 for ($i = 0; $i < count($newField); $i++) {
1216 if (is_array($toUpdateValues[$newField[$i]]) && !empty($toUpdateValues[$newField[$i]])) {
1217 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . implode(',', $toUpdateValues[$newField[$i]]);
1218 } elseif (is_string($newField[$i]) && !FieldValueHandler::isEmpty($toUpdateValues[$newField[$i]])) {
1219 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . $toUpdateValues[$newField[$i]];
1220 }
1221 }
1222 if (null !== $key) {
1223 $logUpdate = implode('b::f', (array) $key);
1224 $formEntryLogUpdate = $formEntryLogModel->logUpdate($logUpdate, $log_id);
1225 }
1226 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
1227 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
1228
1229 return $workFlowreturnedOnSubmit;
1230 }
1231
1232 public function getRepeaterFields()
1233 {
1234 if (!is_null($this->_repeaterFields)) {
1235 return $this->_repeaterFields;
1236 }
1237 $repeaterFields = [];
1238 $form_content = \json_decode(static::$form[0]->form_content);
1239 $fields = $form_content->fields;
1240 $nestedLayouts = !empty($form_content->nestedLayout) ? $form_content->nestedLayout : [];
1241 foreach ($nestedLayouts as $fieldKey => $repeatLayout) {
1242 if ('repeater' !== $fields->{$fieldKey}->typ) {
1243 continue;
1244 }
1245 $repeaterFields[$fieldKey] = [];
1246 foreach ($repeatLayout->lg as $fieldLayoutData) {
1247 $repeaterFields[$fieldKey][] = $fieldLayoutData->i;
1248 }
1249 }
1250 $this->_repeaterFields = $repeaterFields;
1251 return $repeaterFields;
1252 }
1253
1254 public function isRepeatedField($fieldKey)
1255 {
1256 $repeatedFields = $this->getRepeaterFields();
1257 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1258 if (in_array($fieldKey, $repeaterFields)) {
1259 return $repeaterKey;
1260 }
1261 }
1262 return false;
1263 }
1264
1265 public function getParentRepeaterField($fieldKey)
1266 {
1267 $repeatedFields = $this->getRepeaterFields();
1268 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1269 if (in_array($fieldKey, $repeaterFields)) {
1270 return $repeaterKey;
1271 }
1272 }
1273 return null;
1274 }
1275
1276 public function isRepeaterField($fieldKey)
1277 {
1278 $repeatedFields = $this->getRepeaterFields();
1279 if (array_key_exists($fieldKey, $repeatedFields)) {
1280 return true;
1281 }
1282 return false;
1283 }
1284
1285 public function fieldNameReplaceOfPost()
1286 {
1287 // CSRF verified upstream before this method is called; $_POST/$_FILES are being normalized (field key remapping), not reading new user input.
1288 $fields = $this->getFields();
1289 foreach ($fields as $fieldKey => $fieldData) {
1290 if (array_key_exists('name', $fieldData)) {
1291 $fldName = $fieldData['name'];
1292 $catchChildFldNamePattern = '/\[(.*?)\]/';
1293 // catching the child field name for confirm field, name field's child
1294 // preg_match_all($catchChildFldNamePattern, $fldName, $matches);
1295 $fldName = preg_replace($catchChildFldNamePattern, '', $fldName);
1296 $fldName = str_replace(['.', ' '], '_', $fldName);
1297 if (!empty($fldName)) {
1298 if (array_key_exists($fldName, $_POST)) {
1299 $temp = $this->sanitize_text_recursive($_POST[$fldName]);
1300 unset($_POST[$fldName]);
1301 $_POST[$fieldKey] = $temp;
1302 } elseif (array_key_exists($fldName, $_FILES)) {
1303 $temp = $this->sanitize_text_recursive($_FILES[$fldName], false);
1304 unset($_FILES[$fldName]);
1305 $_FILES[$fieldKey] = $temp;
1306 }
1307 // Convert _session_id suffix (used by email-otp and similar fields)
1308 if (array_key_exists($fldName . '_session_id', $_POST)) {
1309 $temp = sanitize_text_field(wp_unslash($_POST[$fldName . '_session_id']));
1310 unset($_POST[$fldName . '_session_id']);
1311 $_POST[$fieldKey . '_session_id'] = $temp;
1312 }
1313 }
1314 }
1315 }
1316 }
1317
1318 private function sanitize_text_recursive($input, $unslash = true)
1319 {
1320 if (is_array($input)) {
1321 return array_map(fn ($item) => $this->sanitize_text_recursive($item, $unslash), $input);
1322 }
1323
1324 return sanitize_text_field($unslash ? wp_unslash($input) : $input);
1325 }
1326
1327 private function normalizeRepeatedCompositeFieldInput($value)
1328 {
1329 if (!is_array($value) || empty($value)) {
1330 return $value;
1331 }
1332
1333 $hasNestedArray = false;
1334 foreach ($value as $childValues) {
1335 if (!is_array($childValues)) {
1336 return $value;
1337 }
1338 $hasNestedArray = true;
1339 }
1340
1341 if (!$hasNestedArray) {
1342 return $value;
1343 }
1344
1345 $formattedValue = [];
1346 foreach ($value as $childKey => $childValues) {
1347 foreach ($childValues as $repeatIndex => $repeatValue) {
1348 if (!isset($formattedValue[$repeatIndex]) || !is_array($formattedValue[$repeatIndex])) {
1349 $formattedValue[$repeatIndex] = [];
1350 }
1351 $formattedValue[$repeatIndex][$childKey] = $repeatValue;
1352 }
1353 }
1354
1355 return $formattedValue;
1356 }
1357
1358 public function setSubmissionCount($countStep = 1)
1359 {
1360 $update_status = $this->formModel->update(
1361 [
1362 'entries' => intval(static::$form[0]->entries) + $countStep,
1363 ],
1364 [
1365 'id' => $this->form_id,
1366 ]
1367 );
1368 }
1369
1370 public function resetSubmissionCount($countStep)
1371 {
1372 $update_status = $this->formModel->update(
1373 [
1374 'entries' => intval($countStep),
1375 ],
1376 [
1377 'id' => $this->form_id,
1378 ]
1379 );
1380 }
1381
1382 public function getCaptchaSettings()
1383 {
1384 $formContents = $this->getFormContent();
1385 $fieldStr = wp_json_encode($formContents->fields);
1386 if (false !== strpos($fieldStr, '"typ":"recaptcha"')) {
1387 return true;
1388 }
1389 }
1390
1391 public function getTurnstileSettings()
1392 {
1393 $formContents = $this->getFormContent();
1394 $fieldStr = wp_json_encode($formContents->fields);
1395 if (false !== strpos($fieldStr, '"typ":"turnstile"')) {
1396 return true;
1397 }
1398 }
1399
1400 public function isFieldTypeExist($fieldType)
1401 {
1402 $formContents = $this->getFormContent();
1403 $fieldStr = wp_json_encode($formContents->fields);
1404 if (false !== strpos($fieldStr, '"typ":"' . $fieldType . '"')) {
1405 return true;
1406 }
1407 }
1408
1409 public function getCaptchaV3Settings()
1410 {
1411 $formContents = $this->getFormContent();
1412 if (!empty($formContents->additional->enabled) && !empty($formContents->additional->enabled->recaptchav3)) {
1413 return $formContents->additional->settings->recaptchav3;
1414 }
1415 return false;
1416 }
1417
1418 // public function getSuccessMessageMarkups() {
1419 // if (is_null($this->_work_flows)) {
1420 // $workFlowManager = new WorkFlowHandler($this->form_id);
1421 // $this->_work_flows = $workFlowManager->getAllworkFlow();
1422 // }
1423
1424 // $ids = [];
1425 // foreach ($this->_work_flows as $msgItem) {
1426 // foreach ($msgItem['conditions'] as $condition) {
1427 // if (isset($condition->actions->success)) {
1428 // foreach ($condition->actions->success as $msg) {
1429 // if ('successMsg' === $msg->type && isset($msg->details->id)) {
1430 // $msgDetailsId = $msg->details->id;
1431 // $idObj = json_decode(stripslashes($msgDetailsId));
1432 // if (is_object($idObj) && !empty($idObj->id)) {
1433 // array_push($ids, $idObj->id);
1434 // }
1435 // }
1436 // }
1437 // }
1438 // if (isset($condition->actions->failure)) {
1439 // $idObj = json_decode(stripslashes($condition->actions->failure));
1440 // if (is_object($idObj) && !empty($idObj->id)) {
1441 // array_push($ids, $idObj->id);
1442 // }
1443 // }
1444 // }
1445 // }
1446 // $ids = array_unique($ids);
1447 // if (is_null($this->_conf_messages)) {
1448 // $successMsgHandler = new SuccessMessageHandler($this->form_id);
1449 // $this->_conf_messages = $successMsgHandler->getMessages($ids);
1450 // }
1451
1452 // $messageMarkups = '';
1453 // if (is_wp_error($this->_conf_messages)) {
1454 // return $messageMarkups;
1455 // }
1456
1457 // foreach ($this->_conf_messages as $key => $msgItem) {
1458 // $messageMarkups .= $this->messageMarkup($msgItem->id);
1459 // }
1460
1461 // return $messageMarkups;
1462 // }
1463
1464 // private function messageMarkup($msgId) {
1465 // return <<<SUCCESSMSG
1466 // <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive2 test">
1467 // <div role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
1468 // <div class="bf-notification-message {$this->getAtomicCls("msg-content-{$msgId}")}">
1469 // <button class="{$this->getAtomicCls("close-{$msgId}")} bf-msg-close" type="button">
1470 // <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
1471 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
1472 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
1473 // </svg>
1474 // </button>
1475 // <div class="msg-content"></div>
1476 // </div>
1477 // </div>
1478 // </div>
1479 // SUCCESSMSG;
1480 // }
1481
1482 public function getAtomicCls($element)
1483 {
1484 $atomicClassMap = $this->getAtomicClsMap();
1485 if (is_object($atomicClassMap) && property_exists($atomicClassMap, ".$element")) {
1486 $getAtomicCls = $atomicClassMap->{".$element"};
1487 return implode(' ', $getAtomicCls) . " $element";
1488 }
1489 return $element;
1490 }
1491
1492 public function isGCLIDEnabled()
1493 {
1494 $formContents = $this->getFormContent();
1495 if (isset($formContents->additional->enabled->captureGCLID) && $formContents->additional->enabled->captureGCLID) {
1496 return true;
1497 }
1498 return false;
1499 }
1500
1501 protected function addEntryInfo($field_details, $counter)
1502 {
1503 $infos = [
1504 '__user_id' => __('User', 'bit-form'),
1505 '__entry_status' => __('Status', 'bit-form'),
1506 //'__user_location' => __(''),
1507 '__referer' => __('Refer URL', 'bit-form'),
1508 '__user_device' => __('Device', 'bit-form'),
1509 '__user_ip' => __('IP address', 'bit-form'),
1510 '__created_at' => __('Created Time', 'bit-form'),
1511 '__updated_at' => __('Modified Time', 'bit-form'),
1512 ];
1513 foreach ($infos as $key => $value) {
1514 $field_details[$counter]['name'] = $value;
1515 $field_details[$counter]['key'] = $key;
1516 $field_details[$counter]['type'] = 'sys';
1517 $counter = $counter + 1;
1518 }
1519
1520 return $field_details;
1521 }
1522 }
1523