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

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

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