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

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

1,505 lines 56.4 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 (in_array($field_type, ['name'])) {
396 $field_details[$key]['label'] = $field->adminLbl ?? $field->lbl;
397 }
398 if ('file-up' === $field_type && isset($field->exts)) {
399 $field_details[$key]['valid']['type'] = $field->exts;
400 }
401 if ('file-up' === $field_type && isset($field->mxUp)) {
402 $field_details[$key]['valid']['upload_size'] = (int) $field->mxUp;
403 }
404 if (isset($field->valid) && !is_null($field->valid)) {
405 if (isset($field->valid->req)) {
406 $field_details[$key]['valid']['req'] = $field->valid->req;
407 }
408 if (isset($field->valid->reqMsg)) {
409 $field_details[$key]['valid']['reqMsg'] = $field->valid->reqMsg;
410 }
411 if (isset($field->valid->typMsg)) {
412 $field_details[$key]['valid']['typMsg'] = $field->valid->typMsg;
413 }
414 if (isset($field->valid->hide)) {
415 $field_details[$key]['valid']['hide'] = $field->valid->hide;
416 }
417 }
418 if ($this->isRepeatedField($key)) {
419 $field_details[$key]['repeated'] = true;
420 }
421 }
422 if ($this->isGCLIDEnabled()) {
423 $field_details['GCLID']['name'] = 'GCLID';
424 $field_details['GCLID']['adminLbl'] = 'GCLID';
425 $field_details['GCLID']['key'] = 'GCLID';
426 $field_details['GCLID']['type'] = 'hidden';
427 }
428 $this->_fields = $field_details;
429 return $field_details;
430 }
431
432 public function getFieldsKey()
433 {
434 $form_content = \json_decode(static::$form[0]->form_content);
435 $fields = $form_content->fields;
436 $field_details = [];
437 foreach ($fields as $key => $field) {
438 if ('recaptcha' === $field->typ || 'hcaptcha' === $field->typ) {
439 continue;
440 }
441 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
442 $field_details[$key] = $key;
443 }
444 if ($this->isGCLIDEnabled()) {
445 $field_details['GCLID'] = 'GCLID';
446 }
447 return $field_details;
448 }
449
450 public function getFieldLabel($forQuery = false)
451 {
452 if (!is_null($this->_field_label)) {
453 return $this->_field_label;
454 }
455 $form_content = \json_decode(static::$form[0]->form_content);
456 $fields = $form_content->fields;
457 $field_details = [];
458 $fieldCounter = 0;
459 foreach ($fields as $key => $field) {
460 if ('recaptcha' === $field->typ || 'turnstile' === $field->typ || 'html' === $field->typ || 'button' === $field->typ) {
461 continue;
462 }
463 $field_details[$fieldCounter]['name'] = empty($field->lbl) ? null : $field->lbl;
464 $field_details[$fieldCounter]['adminLbl'] = empty($field->adminLbl) ? $field_details[$fieldCounter]['name'] : $field->adminLbl;
465 $field_details[$fieldCounter]['key'] = $key;
466 $field_details[$fieldCounter]['type'] = $field->typ;
467 $fieldCounter += 1;
468 }
469 if ($this->isGCLIDEnabled()) {
470 $field_details[$fieldCounter]['name'] = 'GCLID';
471 $field_details[$fieldCounter]['adminLbl'] = 'GCLID';
472 $field_details[$fieldCounter]['key'] = 'GCLID';
473 $field_details[$fieldCounter]['type'] = 'hidden';
474 $fieldCounter += 1;
475 }
476 if (!$forQuery) {
477 $field_details = (array) $this->addEntryInfo($field_details, $fieldCounter);
478 }
479 $this->_field_label = $field_details;
480 return $field_details;
481 }
482
483 public function getUploadFields()
484 {
485 if (!is_null($this->_has_upload)) {
486 return $this->_has_upload;
487 }
488 $upload_fields = [];
489 $form_field_details = $this->getFields();
490 foreach ($form_field_details as $field_name => $__field_detail) {
491 if (isset($__field_detail['type']) && ('file-up' === $__field_detail['type'] || 'advanced-file-up' === $__field_detail['type'])) {
492 $upload_fields[] = $field_name;
493 }
494 }
495 $this->_has_upload = $upload_fields;
496 return $upload_fields;
497 }
498
499 public function getSignatureFilePath($blobLink, $form_id, $fieldKey, $entry_id, $imgType)
500 {
501 $imgTypes = [
502 'image/png' => 'png',
503 'image/jpeg' => 'jpg',
504 'image/svg+xml' => 'svg',
505 ];
506 try {
507 if (!isset($imgTypes[$imgType])) {
508 throw new \InvalidArgumentException("Unsupported image type: $imgType");
509 }
510 $parts = explode(',', $blobLink, 2);
511 if (2 !== count($parts) || false === ($decoded_image = base64_decode($parts[1]))) {
512 throw new \RuntimeException('Invalid or corrupt signature data URI');
513 }
514
515 $_upload_dir = FileHandler::getEntriesFileUploadDir($form_id, $entry_id);
516 FileHandler::createIndexFile($_upload_dir);
517 $uniqueId = time() . '-' . bin2hex(\random_bytes(4));
518 $filename = "{$entry_id}-{$fieldKey}-{$uniqueId}.{$imgTypes[$imgType]}";
519 $fullPath = $_upload_dir . DIRECTORY_SEPARATOR . $filename;
520 if (false === file_put_contents($fullPath, $decoded_image)) {
521 throw new \RuntimeException("Failed to write image to $fullPath");
522 }
523 return $filename;
524 } catch (\Throwable $e) {
525 Log::debug_log("[Signature Error] Form: $form_id, Entry: $entry_id, Field: $fieldKey - " . $e->getMessage());
526 return 'signature-failed.png'; // or a default filename if appropriate
527 }
528 }
529
530 private function entryInsert($user_details)
531 {
532 $formEntryModel = new FormEntryModel();
533 $entryId = $formEntryModel->insert(
534 [
535 'form_id' => $this->form_id,
536 'user_id' => $user_details['id'],
537 'user_ip' => $user_details['ip'],
538 'user_device' => $user_details['device'],
539 'referer' => $user_details['page'],
540 'status' => $this->_saveFormAsDraft ? 9 : 1,
541 'created_at' => $user_details['time'],
542 ]
543 );
544 return $entryId;
545 }
546
547 public function submisionLog($user_details, $entry_id, $type)
548 {
549 $formEntryLogModel = new FormEntryLogModel();
550 $submissionLogData = [
551 'user_id' => $user_details['id'],
552 'action_type' => $type, // create, update
553 'log_type' => 'entry',
554 'ip' => $user_details['ip'],
555 'form_entry_id' => $entry_id,
556 'content' => ['user_device' => $user_details['device']],
557 'form_id' => $this->form_id,
558 'created_at' => $user_details['time'],
559 ];
560 $submissionLogData = apply_filters('bitform_filter_submission_log_data', $submissionLogData, $this->form_id, $type);
561 $logId = $formEntryLogModel->form_log_insert(
562 $submissionLogData
563 );
564 return $logId;
565 }
566
567 private function isArrayAllKeyInt($InputArray)
568 {
569 if (!is_array($InputArray)) {
570 return false;
571 }
572
573 if (count($InputArray) <= 0) {
574 return true;
575 }
576
577 return array_unique(array_map('is_int', array_keys($InputArray))) === [true];
578 }
579
580 public function formatSubmittedData($submitted_data)
581 {
582 $form_content = $this->getFormContent();
583 $form_fields = $form_content->fields;
584
585 foreach ($submitted_data as $key => $value) {
586 if (!isset($form_fields->{$key})) {
587 continue;
588 }
589 $field_data = $form_fields->{$key};
590 $field_type = $field_data->typ;
591 $normalizedParentValue = $this->normalizeSubmittedValue($value);
592 $parentFieldName = isset($field_data->fieldName) ? $field_data->fieldName : '';
593 if (!empty($field_data->childFields) && is_array($field_data->childFields)) {
594 foreach ($field_data->childFields as $childFieldRef) {
595 $childFieldKey = isset($childFieldRef->fldKey) ? $childFieldRef->fldKey : '';
596 if (empty($childFieldKey) || !isset($form_fields->{$childFieldKey})) {
597 continue;
598 }
599
600 $childFieldData = $form_fields->{$childFieldKey};
601 $childFieldName = isset($childFieldData->fieldName) ? $childFieldData->fieldName : '';
602 $childFieldName = FieldValueHandler::deriveChildName($childFieldName, $parentFieldName);
603 if (empty($childFieldName)) {
604 continue;
605 }
606
607 $childValue = FieldValueHandler::extractChildValueFromParentValue($normalizedParentValue, $childFieldName, $childFieldKey);
608 if (null !== $childValue) {
609 $submitted_data[$childFieldKey] = $childValue;
610 }
611 }
612 }
613
614 if ($this->isRepeatedField($key) && in_array($field_type, ['name', 'address'])) {
615 $submitted_data[$key] = $this->normalizeRepeatedCompositeFieldInput($normalizedParentValue);
616 }
617
618 if ('select' === $field_type && !empty($field_data->config->multipleSelect)) {
619 $valueArr = [];
620 if ($this->isRepeatedField($key) && is_array($normalizedParentValue)) {
621 foreach ($normalizedParentValue as $index => $v) {
622 $valueArr[$index] = explode(BITFORMS_BF_SEPARATOR, $v);
623 }
624 } else {
625 $valueArr = explode(BITFORMS_BF_SEPARATOR, (string) $value);
626 }
627 $submitted_data[$key] = $valueArr;
628 }
629 }
630 $submitted_data = apply_filters('bitform_filter_format_submitted_data', $submitted_data, $this->form_id);
631 return $submitted_data;
632 }
633
634 private function normalizeSubmittedValue($value)
635 {
636 if (!is_string($value)) {
637 return $value;
638 }
639
640 $decoded = json_decode($value, true);
641 return (JSON_ERROR_NONE === json_last_error()) ? $decoded : $value;
642 }
643
644 private function addNewFilePathToFiles($form_id, $entry_id, $file_fields = [])
645 {
646 $common_file_path = Helpers::getFullPathWithEncryptedEntryId($form_id, $entry_id);
647 foreach ($_FILES as $field_key => $file_details) {
648 if (!($file_fields && in_array($field_key, $file_fields))) {
649 continue;
650 }
651
652 $isRepeaterFldKey = $this->isRepeatedField($field_key);
653 if ($isRepeaterFldKey && isset($file_details['new_name'])) {
654 // If 'new_name' is an array (i.e., for repeated fields)
655 foreach ($file_details['new_name'] as $slNo => $newFileNamesArray) {
656 if (is_array($newFileNamesArray)) {
657 foreach ($newFileNamesArray as $newFileName) {
658 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
659 $_FILES[$field_key]['file_path'][$slNo][] = $filePath;
660 }
661 } else {
662 // Generate the file path for each file
663 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileNamesArray;
664 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
665 }
666 }
667 } elseif (isset($file_details['new_name'])) {
668 // If 'new_name' is an array (i.e., for repeated fields)
669 if (is_array($file_details['new_name'])) {
670 foreach ($file_details['new_name'] as $slNo => $newFileName) {
671 // Generate the file path for each file
672 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $newFileName;
673 $_FILES[$field_key]['file_path'][$slNo] = $filePath;
674 }
675 } else {
676 $filePath = $common_file_path . DIRECTORY_SEPARATOR . $file_details['new_name'];
677 $_FILES[$field_key]['file_path'] = $filePath;
678 }
679 }
680 }
681 }
682
683 private function formatRepeateFieldData($submitted_data, $form_fields)
684 {
685 $repeaterFields = $this->getRepeaterFields();
686 foreach ($repeaterFields as $repeaterFldKey => $repeatedFields) {
687 $repeatIndexes = $submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"];
688 $repeatIndexes = explode(',', $repeatIndexes);
689 foreach ($repeatIndexes as $slNo => $repeatIndex) {
690 foreach ($repeatedFields as $repeatedField) {
691 if (!isset($submitted_data[$repeatedField][$repeatIndex])) {
692 continue;
693 }
694 if (!isset($submitted_data[$repeaterFldKey][$slNo])) {
695 $submitted_data[$repeaterFldKey][$slNo] = [];
696 }
697 if (!isset($submitted_data[$repeaterFldKey][$slNo][$repeatedField])) {
698 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = [];
699 }
700 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = $submitted_data[$repeatedField][$repeatIndex];
701 }
702 }
703 foreach ($repeatedFields as $repeatedField) {
704 unset($submitted_data[$repeatedField]);
705 }
706 unset($submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"]);
707 }
708
709 return $submitted_data;
710 }
711
712 private function saveEntryMeta($submitted_data, $entry_id)
713 {
714 $errorInEntryMetaInsert = false;
715 $entryMeta = new FormEntryMetaModel();
716 foreach ($submitted_data as $key => $value) {
717 $value = $submitted_data[$key];
718 if (is_string($value)) {
719 $value = wp_unslash($value);
720 } elseif ($this->isArrayAllKeyInt($value)) {
721 $value = wp_json_encode(array_values($value));
722 } else {
723 $value = wp_json_encode($value);
724 }
725 // Form entry meta insert; meta_key/meta_value required to store dynamic field data per entry.
726 $status = $entryMeta->insert(
727 [
728 'bitforms_form_entry_id' => $entry_id,
729 'meta_key' => $key,
730 'meta_value' => $value,
731 ]
732 );
733 if (is_wp_error($status)) {
734 $errorInEntryMetaInsert = true;
735 break;
736 }
737 }
738 return $errorInEntryMetaInsert;
739 }
740
741 public function setSaveFormAsDraft()
742 {
743 $this->_saveFormAsDraft = true;
744 }
745
746 public function saveFormEntry($submitted_data)
747 {
748 // CSRF verified upstream via FrontendFormManager::verifySubmissionNonce() before this method is invoked.
749 $submitted_data = $this->formatSubmittedData($submitted_data);
750 $submitted_data = apply_filters('bitform_filter_save_form_entry', $submitted_data, $this->form_id);
751 $form_content = \json_decode(static::$form[0]->form_content);
752 do_action('bitform_save_entry', $this, $submitted_data, $this->form_id);
753 $key = null;
754 $ipTool = new IpTool();
755 $fileHandler = new FileHandler();
756 $form_fields = $this->getFields();
757 $file_fields = $this->getUploadFields();
758
759 foreach ($_FILES as $file_name => $file_details) {
760 if ($file_fields && in_array($file_name, $file_fields)) {
761 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
762 if (!empty($validation['error_type']) && !empty($validation['message'])) {
763 return new WP_Error($validation['error_type'], esc_html($validation['message']));
764 }
765 }
766 }
767 $user_details = $ipTool->getUserDetail();
768 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
769 $user_details = apply_filters('bitform_filter_save_entry_user_details', $user_details, $this->form_id);
770
771 $form_fields = $this->getFields();
772 $submitted_data = $this->passwordEncrypted($submitted_data, $form_fields);
773 $submitted_data = $this->formatRepeateFieldData($submitted_data, $form_fields);
774 global $wpdb;
775 // Direct transaction control; no user input involved.
776 $wpdb->query('START TRANSACTION');
777 $entry_id = $this->entryInsert($user_details);
778 $log_id = null;
779
780 $GLOBALS['bitform_entry_id'] = $entry_id;
781
782 if (is_wp_error($entry_id)) {
783 return new WP_Error('insert_error', __('Sorry, Error occurred in saving form entry', 'bit-form'));
784 }
785 if ($entry_id) {
786 $log_id = $this->submisionLog($user_details, $entry_id, 'create', $key);
787 if (is_wp_error($log_id)) {
788 $wpdb->query('ROLLBACK');
789 return new WP_Error('error_entry_log', __('Sorry, error occurred in logging form entry', 'bit-form'));
790 }
791 }
792 if ($entry_id) {
793 $submitted_fields = $this->getFormContentWithValue($submitted_data)->fields;
794 $workFlowRunHelper = new WorkFlow($this->form_id);
795
796 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
797 'create',
798 $submitted_fields,
799 $submitted_data,
800 $entry_id,
801 $log_id
802 );
803
804 if (!empty($workFlowreturnedOnSubmit['fields'])) {
805 $submitted_data = $workFlowreturnedOnSubmit['fields'];
806 }
807
808 $file_fields = $this->getUploadFields();
809 $formFields = $this->getFields();
810 $submitted_data = FileHandler::tempDirToUploadDir($submitted_data, $formFields, $this->form_id, $entry_id);
811 $fileHandler = new FileHandler();
812 foreach ($_FILES as $field_key => $file_details) {
813 if ($file_fields && in_array($field_key, $file_fields)) {
814 $fileNames = [];
815 $repeaterFldKey = $this->isRepeatedField($field_key);
816 if ($repeaterFldKey) {
817 foreach ($file_details['name'] as $slNo => $fileName) {
818 $repeateFileDetails = [
819 'name' => $file_details['name'][$slNo],
820 'type' => $file_details['type'][$slNo],
821 'tmp_name' => $file_details['tmp_name'][$slNo],
822 'error' => $file_details['error'][$slNo],
823 'size' => $file_details['size'][$slNo],
824 ];
825 $fileNames = $fileHandler->moveUploadedFiles($repeateFileDetails, $this->form_id, $entry_id);
826 if (!empty($fileNames)) {
827 $submitted_data[$repeaterFldKey][$slNo - 1][$field_key] = $fileNames;
828 $_FILES[$field_key]['new_name'][$slNo - 1] = $fileNames;
829 }
830 }
831 } else {
832 $fileNames = $fileHandler->moveUploadedFiles($file_details, $this->form_id, $entry_id);
833 if (!empty($fileNames)) {
834 $submitted_data[$field_key] = $fileNames;
835 $_FILES[$field_key]['new_name'] = $fileNames;
836 }
837 }
838 }
839 }
840
841 // Get the common path for file storage
842 $this->addNewFilePathToFiles($this->form_id, $entry_id, $file_fields);
843
844 foreach ($form_content->fields as $key => $field) {
845 /* ======== for Signature field ===========*/
846 if ('signature' === $field->typ) {
847 if (isset($submitted_data[$key])) {
848 $fld_data = $submitted_data[$key];
849 $img_type = $field->config->imgTyp;
850 $submitted_data[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entry_id, $img_type);
851 }
852 }
853
854 // for Signature field inside reepater
855 if ('repeater' === $field->typ) {
856 $rptr_data = $submitted_data[$key];
857 $formFields = $form_content->fields;
858 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entry_id, $submitted_data);
859 }
860 }
861
862 if (!isset($form_content->additional->enabled->submission)) {
863 $errorInEntryMetaInsert = $this->saveEntryMeta($submitted_data, $entry_id);
864 if ($errorInEntryMetaInsert) {
865 do_action('bitform_save_entry_error', $this, $submitted_data, $this->form_id);
866 $wpdb->query('ROLLBACK');
867 return new WP_Error('insert_error', __('Sorry, Error occured in saving form entry data', 'bit-form'));
868 }
869 do_action('bitform_after_save_entry_success', $this, $submitted_data, $this->form_id, $entry_id);
870 } else {
871 $wpdb->query('ROLLBACK');
872 }
873 $wpdb->query('COMMIT');
874 $this->setSubmissionCount();
875 $workFlowreturnedOnSubmit['entry_id'] = $entry_id;
876 $workFlowreturnedOnSubmit['fields'] = $submitted_data;
877 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_submit_success', $workFlowreturnedOnSubmit, $this->form_id);
878
879 return $workFlowreturnedOnSubmit;
880 }
881 }
882
883 private function setSignatureFilePathInRepeater($repeaterData, $repeaterFieldKey, $formFields, $entry_id, &$submitted_data)
884 {
885 foreach ($repeaterData as $rptr_entry_index => $rptr_entries) {
886 foreach ($rptr_entries as $entry_key => $entry_value) {
887 $rptr_entry_info = $formFields->{$entry_key};
888
889 if ('signature' === $rptr_entry_info->typ) {
890 $imgType = $rptr_entry_info->config->imgTyp;
891 $signatureImage = $this->getSignatureFilePath($entry_value, $this->form_id, $repeaterFieldKey, $entry_id, $imgType);
892 $submitted_data[$repeaterFieldKey][$rptr_entry_index][$entry_key] = $signatureImage;
893 }
894 }
895 }
896 }
897
898 public function passwordEncrypted($updatedValue, $form_fields)
899 {
900 $integrationHandler = new IntegrationHandler($this->form_id);
901 $formIntegrations = $integrationHandler->getAllIntegration('wp_user_auth', 'wp_auth', 1);
902 if (!isset($formIntegrations->errors['result_empty'])) {
903 foreach ($form_fields as $field) {
904 if (array_key_exists($field['key'], $updatedValue) && 'password' === $field['type']) {
905 $updatedValue[$field['key']] = '**** (encrypted)';
906 }
907 }
908 }
909 return $updatedValue;
910 }
911
912 public function updateFormEntry($updatedValue, $formID, $entryID)
913 {
914 // CSRF / entry-token verified upstream via FrontendFormManager::handleUpdateEntry() before this method is invoked.
915 $updatedValue = $this->formatSubmittedData($updatedValue);
916 $updatedValue = apply_filters('bitform_filter_update_form_entry', $updatedValue, $this->form_id);
917 do_action('bitform_update_entry', $this, $updatedValue, $formID, $entryID);
918 $form_content = $this->getFormContent();
919 if (isset($form_content->additional->enabled->submission)) {
920 // Run workflow but skip DB/meta update
921 $workFlowRunHelper = new WorkFlow($formID);
922 $fieldsWithValue = $this->getFormContentWithValue($updatedValue)->fields;
923 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
924 'edit',
925 $fieldsWithValue,
926 $updatedValue,
927 $entryID,
928 0
929 );
930 if (empty($workFlowreturnedOnSubmit['message'])) {
931 $workFlowreturnedOnSubmit['message'] = __('Entry update skipped due to submission restriction.', 'bit-form');
932 }
933 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
934 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
935 return $workFlowreturnedOnSubmit;
936 }
937
938 $formEntryModel = new FormEntryModel();
939 $formEntryLogModel = new FormEntryLogModel();
940 $formOldData = $formEntryLogModel->get_form_value($entryID);
941 $key = null;
942 $entryMeta = new FormEntryMetaModel();
943 $ipTool = new IpTool();
944 $user_details = $ipTool->getUserDetail();
945 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
946 $user_details = apply_filters('bitform_filter_update_entry_user_details', $user_details, $this->form_id);
947
948 $form_fields = $this->getFields();
949
950 $updatedValue = $this->passwordEncrypted($updatedValue, $form_fields);
951 $updatedValue = $this->formatRepeateFieldData($updatedValue, $form_fields);
952 $field_map = [];
953 foreach ($formOldData as $index => $data) {
954 foreach ($form_fields as $field_key => $field) {
955 if ($data->meta_key === $field['key']) {
956 $field_map[$field_key] = $field['key'];
957 }
958 }
959 }
960 $geResult = $formEntryModel->get('status', ['id' => $entryID]);
961 if (is_wp_error($geResult) || empty($geResult)) {
962 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
963 }
964 $oldEntry = $geResult[0];
965 $formEntry = $formEntryModel->update(
966 [
967 'status' => ('9' === $oldEntry->status && !$this->_saveFormAsDraft) ? 1 : $oldEntry->status,
968 'updated_at' => $user_details['time'],
969 ],
970 [
971 'form_id' => $formID,
972 'id' => $entryID,
973 ]
974 );
975 $log_id = null;
976 if ($formEntry) {
977 $log_id = $this->submisionLog($user_details, $entryID, 'update');
978 }
979
980 if (is_wp_error($formEntry) || !$formEntry) {
981 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
982 }
983 $formFields = $this->getFields();
984 $updatedValue = FileHandler::tempDirToUploadDir($updatedValue, $formFields, $this->form_id, $entryID);
985 $file_fields = $this->getUploadFields();
986 if (count($file_fields) > 0) {
987 $fileHandler = new FileHandler();
988 foreach ($_FILES as $file_name => $file_details) {
989 if ($file_fields && in_array($file_name, $file_fields)) {
990 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
991 if (!empty($validation['error_type']) && !empty($validation['message'])) {
992 return new WP_Error($validation['error_type'], esc_html($validation['message']));
993 }
994 }
995 }
996 if (is_object($updatedValue)) {
997 $updatedValue = (array) $updatedValue;
998 }
999 foreach ($file_fields as $field_key) {
1000 $repeaterFldKey = $this->isRepeatedField($field_key);
1001 if (isset($updatedValue[$field_key . '_old'])) {
1002 // Handle file deletion for repeater fields
1003 if ($repeaterFldKey) {
1004 // Form entry meta lookup; meta_key/meta_value query required to retrieve repeater field data by entry.
1005 $repeaterExistData = $entryMeta->get(
1006 'meta_value',
1007 [
1008 'bitforms_form_entry_id' => $entryID,
1009 'meta_key' => $repeaterFldKey,
1010 ]
1011 );
1012 if (!is_wp_error($repeaterExistData)) {
1013 // restructor json
1014 $repeaterExistData = json_decode($repeaterExistData[0]->meta_value, true);
1015 $repeaterExistFiles = [];
1016 $repeaterDeleted_files = [];
1017 $repeaterFiles_old = [];
1018 foreach ($repeaterExistData as $index => $repeaterRow) {
1019 $repeaterExistFiles[$index] = [];
1020 if (isset($repeaterRow[$field_key]) && !empty($repeaterRow[$field_key])) {
1021 $repeaterExistFiles[$index] = json_decode($repeaterRow[$field_key], true);
1022 }
1023 $repeaterFiles_old[$index] = empty($updatedValue[$field_key . '_old'][$index]) ? [] : explode(',', $updatedValue[$field_key . '_old'][$index]);
1024 $repeaterDeleted_files[$index] = array_diff($repeaterExistFiles[$index], $repeaterFiles_old[$index]);
1025 $fileHandler->deleteFiles($formID, $entryID, $repeaterDeleted_files[$index]);
1026 }
1027 }
1028 } else {
1029 // Handle file deletion for non-repeater fields; meta_key/meta_value lookup required to identify stored file paths per entry.
1030 $file_exists = $entryMeta->get(
1031 'meta_value',
1032 [
1033 'bitforms_form_entry_id' => $entryID,
1034 'meta_key' => $field_key,
1035 ]
1036 );
1037 if (!is_wp_error($file_exists) && count($file_exists) > 0) {
1038 $files_in_db = json_decode($file_exists[0]->meta_value);
1039 $files_old = empty($updatedValue[$field_key . '_old']) ? [] : explode(',', $updatedValue[$field_key . '_old']);
1040 $deleted_file = array_diff($files_in_db, $files_old);
1041 if (count($deleted_file) > 0) {
1042 $fileHandler->deleteFiles($formID, $entryID, $deleted_file);
1043 }
1044 $updatedValue[$field_key] = wp_json_encode($files_old);
1045 }
1046 }
1047 }
1048 if (!empty($_FILES[$field_key]['name'])) {
1049 if ($repeaterFldKey) {
1050 // Handle repeater field files
1051 $file_details = $_FILES[$field_key];
1052 foreach ($file_details['name'] as $index => $file) {
1053 // Retrieve existing old files for this specific repeater index
1054 if (isset($repeaterFiles_old[$index - 1]) && count($repeaterFiles_old[$index - 1]) > 0) {
1055 $old_meta_value = empty($repeaterFiles_old[$index - 1]) ? [] : $repeaterFiles_old[$index - 1];
1056 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1057 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($old_meta_value);
1058 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $old_meta_value;
1059 }
1060 $repeateFileDetails = [
1061 'name' => $file_details['name'][$index],
1062 'type' => $file_details['type'][$index],
1063 'tmp_name' => $file_details['tmp_name'][$index],
1064 'error' => $file_details['error'][$index],
1065 'size' => $file_details['size'][$index],
1066 ];
1067 $meta_value = $fileHandler->moveUploadedFiles($repeateFileDetails, $formID, $entryID, $index);
1068 if (!empty($meta_value)) {
1069 $mergedMetaValueWithOld = isset($old_meta_value) ? array_merge($old_meta_value, (array) $meta_value) : (array) $meta_value;
1070 // json format causing issue with repeater file in mail attachment as it's sending broken url(for multistep and abandonment form)
1071 // $updatedValue[$repeaterFldKey][$index - 1][$field_key] = wp_json_encode($mergedMetaValueWithOld);
1072 $updatedValue[$repeaterFldKey][$index - 1][$field_key] = $mergedMetaValueWithOld;
1073
1074 $_FILES[$field_key]['new_name'][$index - 1] = $mergedMetaValueWithOld;
1075 // $_FILES[$field_key]['file_path'][$index - 1] = $common_file_path . DIRECTORY_SEPARATOR . $meta_value;
1076 }
1077 }
1078 } else {
1079 // Handle non-repeater field files
1080 $meta_value = $fileHandler->moveUploadedFiles($_FILES[$field_key], $formID, $entryID);
1081 if (!empty($meta_value)) {
1082 $_FILES[$field_key]['new_name'] = $meta_value;
1083 if (isset($updatedValue[$field_key . '_old']) && !is_wp_error($file_exists) && count($file_exists) > 0) {
1084 $meta_value = empty($files_old) ? $meta_value : array_merge($meta_value, $files_old);
1085 $updatedValue[$field_key] = $meta_value;
1086 } else {
1087 $updatedValue[$field_key] = $meta_value;
1088 }
1089 }
1090 }
1091 }
1092 }
1093
1094 // Get the common file path to avoid repetitive calculation
1095 $this->addNewFilePathToFiles($formID, $entryID, $file_fields);
1096 }
1097
1098 if (is_object($updatedValue)) {
1099 $updatedValue = (array) $updatedValue;
1100 }
1101 if (isset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']) && sanitize_text_field(wp_unslash($_REQUEST['g-recaptcha-response']))) {
1102 unset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']);
1103 }
1104
1105 $toUpdateValues = [];
1106 foreach ($form_fields as $field) {
1107 if (isset($updatedValue[$field['key']])) {
1108 $toUpdateValues[$field['key']] = $updatedValue[$field['key']];
1109 }
1110 }
1111 $form_content = \json_decode(static::$form[0]->form_content);
1112
1113 foreach ($form_content->fields as $key => $field) {
1114 if ('signature' === $field->typ) {
1115 $fld_data = $updatedValue[$key];
1116 $img_type = $field->config->imgTyp;
1117 $toUpdateValues[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entryID, $img_type);
1118 }
1119
1120 // for Signature field inside reepater
1121 if ('repeater' === $field->typ) {
1122 $rptr_data = $updatedValue[$key];
1123 $formFields = $form_content->fields;
1124 $this->setSignatureFilePathInRepeater($rptr_data, $key, $formFields, $entryID, $toUpdateValues);
1125 }
1126 }
1127
1128 $workFlowRunHelper = new WorkFlow($formID);
1129 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
1130 'edit',
1131 $this->getFormContentWithValue($toUpdateValues)->fields,
1132 $toUpdateValues,
1133 $entryID,
1134 $log_id
1135 );
1136
1137 if (!empty($workFlowreturnedOnSubmit['fields'])) {
1138 $updatedValue = $workFlowreturnedOnSubmit['fields'];
1139 }
1140
1141 $formEntryMetaUpdateStatus = $entryMeta->update(
1142 $toUpdateValues,
1143 [
1144 'bitforms_form_entry_id' => $entryID,
1145 ]
1146 );
1147 if (is_wp_error($formEntryMetaUpdateStatus) || isset($newFileInsertStatus) && is_wp_error($newFileInsertStatus)) {
1148 do_action('bitform_update_entry_error', $this, $toUpdateValues, $formEntryMetaUpdateStatus, $this->form_id);
1149 return $formEntryMetaUpdateStatus;
1150 }
1151 $toUpdateValues = array_merge($formEntryMetaUpdateStatus, ['entry_id' => $entryID]);
1152 do_action('bitform_after_update_entry_success', $this, $toUpdateValues, $formID, $entryID);
1153 if (empty($workFlowreturnedOnSubmit['message'])) {
1154 $workFlowreturnedOnSubmit['message'] = __('Entry Updated Successfully', 'bit-form');
1155 }
1156 $customFieldHandler = new CustomFieldHandler();
1157 $toUpdateValues = $customFieldHandler->updatedData($form_fields, $toUpdateValues);
1158
1159 $workFlowreturnedOnSubmit['updatedData'] = $toUpdateValues;
1160 $counter = 0;
1161 for ($i = 0; $i < count($formOldData); $i++) {
1162 if (array_key_exists($formOldData[$i]->meta_key . '_old', $toUpdateValues)) {
1163 unset($toUpdateValues[$formOldData[$i]->meta_key . '_old']);
1164 }
1165 if (in_array($formOldData[$i]->meta_key, $file_fields)) {
1166 if (
1167 empty($_FILES[$formOldData[$i]->meta_key]['name'])
1168 || (is_array($_FILES[$formOldData[$i]->meta_key]['name'])
1169 && 1 === count($_FILES[$formOldData[$i]->meta_key]['name'])
1170 && empty($_FILES[$formOldData[$i]->meta_key]['name'][0]))
1171 ) {
1172 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1173 continue;
1174 }
1175 if (is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1176 $sanitized_names = array_map('sanitize_file_name', array_map('wp_unslash', (array) $_FILES[$formOldData[$i]->meta_key]['name']));
1177 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . wp_json_encode($sanitized_names);
1178 } elseif (!is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
1179 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . sanitize_file_name(wp_unslash($_FILES[$formOldData[$i]->meta_key]['name']));
1180 }
1181 unset($toUpdateValues[$formOldData[$i]->meta_key]);
1182 } elseif (isset($toUpdateValues[$formOldData[$i]->meta_key])) {
1183 if (is_array($toUpdateValues[$formOldData[$i]->meta_key])) {
1184 if (json_decode($formOldData[$i]->meta_value) !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1185 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated From ' . implode(',', json_decode($formOldData[$i]->meta_value)) . ' To ' . implode(',', $toUpdateValues[$formOldData[$i]->meta_key]);
1186 }
1187 } elseif (is_string($toUpdateValues[$formOldData[$i]->meta_key]) && !FieldValueHandler::isEmpty($toUpdateValues[$formOldData[$i]->meta_key])) {
1188 if ($formOldData[$i]->meta_value !== $toUpdateValues[$formOldData[$i]->meta_key]) {
1189 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated' . ($formOldData[$i]->meta_value ? ' From ' . $formOldData[$i]->meta_value : '') . ' To ' . $toUpdateValues[$formOldData[$i]->meta_key];
1190 }
1191 }
1192 }
1193 $counter++;
1194 }
1195
1196 $newField = array_keys(array_diff_key($formEntryMetaUpdateStatus, $field_map));
1197 for ($i = 0; $i < count($newField); $i++) {
1198 if (is_array($toUpdateValues[$newField[$i]]) && !empty($toUpdateValues[$newField[$i]])) {
1199 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . implode(',', $toUpdateValues[$newField[$i]]);
1200 } elseif (is_string($newField[$i]) && !FieldValueHandler::isEmpty($toUpdateValues[$newField[$i]])) {
1201 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . $toUpdateValues[$newField[$i]];
1202 }
1203 }
1204 if (null !== $key) {
1205 $logUpdate = implode('b::f', (array) $key);
1206 $formEntryLogUpdate = $formEntryLogModel->logUpdate($logUpdate, $log_id);
1207 }
1208 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
1209 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
1210
1211 return $workFlowreturnedOnSubmit;
1212 }
1213
1214 public function getRepeaterFields()
1215 {
1216 if (!is_null($this->_repeaterFields)) {
1217 return $this->_repeaterFields;
1218 }
1219 $repeaterFields = [];
1220 $form_content = \json_decode(static::$form[0]->form_content);
1221 $fields = $form_content->fields;
1222 $nestedLayouts = !empty($form_content->nestedLayout) ? $form_content->nestedLayout : [];
1223 foreach ($nestedLayouts as $fieldKey => $repeatLayout) {
1224 if ('repeater' !== $fields->{$fieldKey}->typ) {
1225 continue;
1226 }
1227 $repeaterFields[$fieldKey] = [];
1228 foreach ($repeatLayout->lg as $fieldLayoutData) {
1229 $repeaterFields[$fieldKey][] = $fieldLayoutData->i;
1230 }
1231 }
1232 $this->_repeaterFields = $repeaterFields;
1233 return $repeaterFields;
1234 }
1235
1236 public function isRepeatedField($fieldKey)
1237 {
1238 $repeatedFields = $this->getRepeaterFields();
1239 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1240 if (in_array($fieldKey, $repeaterFields)) {
1241 return $repeaterKey;
1242 }
1243 }
1244 return false;
1245 }
1246
1247 public function getParentRepeaterField($fieldKey)
1248 {
1249 $repeatedFields = $this->getRepeaterFields();
1250 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
1251 if (in_array($fieldKey, $repeaterFields)) {
1252 return $repeaterKey;
1253 }
1254 }
1255 return null;
1256 }
1257
1258 public function isRepeaterField($fieldKey)
1259 {
1260 $repeatedFields = $this->getRepeaterFields();
1261 if (array_key_exists($fieldKey, $repeatedFields)) {
1262 return true;
1263 }
1264 return false;
1265 }
1266
1267 public function fieldNameReplaceOfPost()
1268 {
1269 // CSRF verified upstream before this method is called; $_POST/$_FILES are being normalized (field key remapping), not reading new user input.
1270 $fields = $this->getFields();
1271 foreach ($fields as $fieldKey => $fieldData) {
1272 if (array_key_exists('name', $fieldData)) {
1273 $fldName = $fieldData['name'];
1274 $catchChildFldNamePattern = '/\[(.*?)\]/';
1275 // catching the child field name for confirm field, name field's child
1276 // preg_match_all($catchChildFldNamePattern, $fldName, $matches);
1277 $fldName = preg_replace($catchChildFldNamePattern, '', $fldName);
1278 $fldName = str_replace(['.', ' '], '_', $fldName);
1279 if (!empty($fldName)) {
1280 if (array_key_exists($fldName, $_POST)) {
1281 $temp = $this->sanitize_text_recursive($_POST[$fldName]);
1282 unset($_POST[$fldName]);
1283 $_POST[$fieldKey] = $temp;
1284 } elseif (array_key_exists($fldName, $_FILES)) {
1285 $temp = $this->sanitize_text_recursive($_FILES[$fldName], false);
1286 unset($_FILES[$fldName]);
1287 $_FILES[$fieldKey] = $temp;
1288 }
1289 // Convert _session_id suffix (used by email-otp and similar fields)
1290 if (array_key_exists($fldName . '_session_id', $_POST)) {
1291 $temp = sanitize_text_field(wp_unslash($_POST[$fldName . '_session_id']));
1292 unset($_POST[$fldName . '_session_id']);
1293 $_POST[$fieldKey . '_session_id'] = $temp;
1294 }
1295 }
1296 }
1297 }
1298 }
1299
1300 private function sanitize_text_recursive($input, $unslash = true)
1301 {
1302 if (is_array($input)) {
1303 return array_map(fn ($item) => $this->sanitize_text_recursive($item, $unslash), $input);
1304 }
1305
1306 return sanitize_text_field($unslash ? wp_unslash($input) : $input);
1307 }
1308
1309 private function normalizeRepeatedCompositeFieldInput($value)
1310 {
1311 if (!is_array($value) || empty($value)) {
1312 return $value;
1313 }
1314
1315 $hasNestedArray = false;
1316 foreach ($value as $childValues) {
1317 if (!is_array($childValues)) {
1318 return $value;
1319 }
1320 $hasNestedArray = true;
1321 }
1322
1323 if (!$hasNestedArray) {
1324 return $value;
1325 }
1326
1327 $formattedValue = [];
1328 foreach ($value as $childKey => $childValues) {
1329 foreach ($childValues as $repeatIndex => $repeatValue) {
1330 if (!isset($formattedValue[$repeatIndex]) || !is_array($formattedValue[$repeatIndex])) {
1331 $formattedValue[$repeatIndex] = [];
1332 }
1333 $formattedValue[$repeatIndex][$childKey] = $repeatValue;
1334 }
1335 }
1336
1337 return $formattedValue;
1338 }
1339
1340 public function setSubmissionCount($countStep = 1)
1341 {
1342 $update_status = $this->formModel->update(
1343 [
1344 'entries' => intval(static::$form[0]->entries) + $countStep,
1345 ],
1346 [
1347 'id' => $this->form_id,
1348 ]
1349 );
1350 }
1351
1352 public function resetSubmissionCount($countStep)
1353 {
1354 $update_status = $this->formModel->update(
1355 [
1356 'entries' => intval($countStep),
1357 ],
1358 [
1359 'id' => $this->form_id,
1360 ]
1361 );
1362 }
1363
1364 public function getCaptchaSettings()
1365 {
1366 $formContents = $this->getFormContent();
1367 $fieldStr = wp_json_encode($formContents->fields);
1368 if (false !== strpos($fieldStr, '"typ":"recaptcha"')) {
1369 return true;
1370 }
1371 }
1372
1373 public function getTurnstileSettings()
1374 {
1375 $formContents = $this->getFormContent();
1376 $fieldStr = wp_json_encode($formContents->fields);
1377 if (false !== strpos($fieldStr, '"typ":"turnstile"')) {
1378 return true;
1379 }
1380 }
1381
1382 public function isFieldTypeExist($fieldType)
1383 {
1384 $formContents = $this->getFormContent();
1385 $fieldStr = wp_json_encode($formContents->fields);
1386 if (false !== strpos($fieldStr, '"typ":"' . $fieldType . '"')) {
1387 return true;
1388 }
1389 }
1390
1391 public function getCaptchaV3Settings()
1392 {
1393 $formContents = $this->getFormContent();
1394 if (!empty($formContents->additional->enabled) && !empty($formContents->additional->enabled->recaptchav3)) {
1395 return $formContents->additional->settings->recaptchav3;
1396 }
1397 return false;
1398 }
1399
1400 // public function getSuccessMessageMarkups() {
1401 // if (is_null($this->_work_flows)) {
1402 // $workFlowManager = new WorkFlowHandler($this->form_id);
1403 // $this->_work_flows = $workFlowManager->getAllworkFlow();
1404 // }
1405
1406 // $ids = [];
1407 // foreach ($this->_work_flows as $msgItem) {
1408 // foreach ($msgItem['conditions'] as $condition) {
1409 // if (isset($condition->actions->success)) {
1410 // foreach ($condition->actions->success as $msg) {
1411 // if ('successMsg' === $msg->type && isset($msg->details->id)) {
1412 // $msgDetailsId = $msg->details->id;
1413 // $idObj = json_decode(stripslashes($msgDetailsId));
1414 // if (is_object($idObj) && !empty($idObj->id)) {
1415 // array_push($ids, $idObj->id);
1416 // }
1417 // }
1418 // }
1419 // }
1420 // if (isset($condition->actions->failure)) {
1421 // $idObj = json_decode(stripslashes($condition->actions->failure));
1422 // if (is_object($idObj) && !empty($idObj->id)) {
1423 // array_push($ids, $idObj->id);
1424 // }
1425 // }
1426 // }
1427 // }
1428 // $ids = array_unique($ids);
1429 // if (is_null($this->_conf_messages)) {
1430 // $successMsgHandler = new SuccessMessageHandler($this->form_id);
1431 // $this->_conf_messages = $successMsgHandler->getMessages($ids);
1432 // }
1433
1434 // $messageMarkups = '';
1435 // if (is_wp_error($this->_conf_messages)) {
1436 // return $messageMarkups;
1437 // }
1438
1439 // foreach ($this->_conf_messages as $key => $msgItem) {
1440 // $messageMarkups .= $this->messageMarkup($msgItem->id);
1441 // }
1442
1443 // return $messageMarkups;
1444 // }
1445
1446 // private function messageMarkup($msgId) {
1447 // return <<<SUCCESSMSG
1448 // <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive2 test">
1449 // <div role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
1450 // <div class="bf-notification-message {$this->getAtomicCls("msg-content-{$msgId}")}">
1451 // <button class="{$this->getAtomicCls("close-{$msgId}")} bf-msg-close" type="button">
1452 // <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
1453 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
1454 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
1455 // </svg>
1456 // </button>
1457 // <div class="msg-content"></div>
1458 // </div>
1459 // </div>
1460 // </div>
1461 // SUCCESSMSG;
1462 // }
1463
1464 public function getAtomicCls($element)
1465 {
1466 $atomicClassMap = $this->getAtomicClsMap();
1467 if (is_object($atomicClassMap) && property_exists($atomicClassMap, ".$element")) {
1468 $getAtomicCls = $atomicClassMap->{".$element"};
1469 return implode(' ', $getAtomicCls) . " $element";
1470 }
1471 return $element;
1472 }
1473
1474 public function isGCLIDEnabled()
1475 {
1476 $formContents = $this->getFormContent();
1477 if (isset($formContents->additional->enabled->captureGCLID) && $formContents->additional->enabled->captureGCLID) {
1478 return true;
1479 }
1480 return false;
1481 }
1482
1483 protected function addEntryInfo($field_details, $counter)
1484 {
1485 $infos = [
1486 '__user_id' => __('User', 'bit-form'),
1487 '__entry_status' => __('Status', 'bit-form'),
1488 //'__user_location' => __(''),
1489 '__referer' => __('Refer URL', 'bit-form'),
1490 '__user_device' => __('Device', 'bit-form'),
1491 '__user_ip' => __('IP address', 'bit-form'),
1492 '__created_at' => __('Created Time', 'bit-form'),
1493 '__updated_at' => __('Modified Time', 'bit-form'),
1494 ];
1495 foreach ($infos as $key => $value) {
1496 $field_details[$counter]['name'] = $value;
1497 $field_details[$counter]['key'] = $key;
1498 $field_details[$counter]['type'] = 'sys';
1499 $counter = $counter + 1;
1500 }
1501
1502 return $field_details;
1503 }
1504 }
1505