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

1,097 lines 39.3 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\Core\Database\FormEntryLogModel;
15 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
16 use BitCode\BitForm\Core\Database\FormEntryModel;
17 use BitCode\BitForm\Core\Database\FormModel;
18 use BitCode\BitForm\Core\Integration\IntegrationHandler;
19 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
20 use BitCode\BitForm\Core\Util\FieldValueHandler;
21 use BitCode\BitForm\Core\Util\FileHandler;
22 use BitCode\BitForm\Core\Util\FrontendHelpers;
23 use BitCode\BitForm\Core\Util\IpTool;
24 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
25 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
26 use WP_Error;
27
28 class FormManager
29 {
30 protected static $form;
31 protected $formModel;
32 protected $form_id;
33 private $_has_upload;
34 private $_field_label;
35 private $_fields;
36 private $_repeaterFields;
37 private $_work_flows;
38 private $_conf_messages;
39 private $_atomic_class_map;
40 private $_saveFormAsDraft;
41
42 public function __construct($form_id)
43 {
44 $this->form_id = $form_id;
45 $this->formModel = new FormModel();
46
47 static::$form = $this->formModel->get(
48 [
49 'id',
50 'form_content',
51 'form_name',
52 'created_at',
53 'views',
54 'entries',
55 'status',
56 'builder_helper_state',
57 'atomic_class_map',
58 'generated_script_page_ids',
59 ],
60 [
61 'id' => $form_id,
62 ]
63 );
64 if (!is_wp_error(static::$form)) {
65 $this->_atomic_class_map = json_decode(static::$form[0]->atomic_class_map);
66 $bfMultipleFormsExists = FrontendHelpers::hasMultipleForms();
67 if ($bfMultipleFormsExists && isset($this->_atomic_class_map->atomic_class_map_with_form_id)) {
68 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map_with_form_id;
69 } elseif (isset($this->_atomic_class_map->atomic_class_map)) {
70 $this->_atomic_class_map = $this->_atomic_class_map->atomic_class_map;
71 }
72 }
73 }
74
75 public function isExist()
76 {
77 return (!static::$form || is_wp_error(static::$form)) ? false : true;
78 }
79
80 public function checkStatus()
81 {
82 return '1' === static::$form[0]->status ? true : false;
83 }
84
85 public function getFieldsContent()
86 {
87 return self::$form[0]->form_content;
88 }
89
90 public function getFont()
91 {
92 $atomicClassMap = $this->_atomic_class_map;
93 $font = isset($atomicClassMap->font) ? $atomicClassMap->font : '';
94 return $font;
95 }
96
97 public function getStyle()
98 {
99 $builerState = \json_decode(static::$form[0]->builder_helper_state);
100 $style = '';
101 $themeVars = $builerState->themeVars;
102 $themeColors = $builerState->themeColors;
103
104 if (!empty($themeVars)) {
105 $style .= ':root {';
106 foreach ($themeVars->lgLightThemeVars as $key => $value) {
107 $style .= "$key: $value; ";
108 }
109 $style .= '} ';
110 }
111 if (!empty($themeColors)) {
112 $style .= ' :root {';
113 foreach ($themeColors->lightThemeColors as $k => $v) {
114 $style .= "$k:$v; ";
115 }
116 $style .= '} ';
117 }
118
119 $field = $builerState->style->lgLightStyles->fields;
120 foreach ($field as $value) {
121 $classes = $value->classes;
122 foreach ($classes as $key => $value) {
123 $style .= "{$key} {";
124 foreach ($value as $k => $v) {
125 $style .= "$k:$v; ";
126 }
127 $style .= '} ';
128 }
129 }
130 return $style;
131 }
132
133 public function getCustomStyle()
134 {
135 $customCssCodes = '';
136 $customCSSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.css";
137
138 if (file_exists($customCSSPath)) {
139 $file = fopen($customCSSPath, 'r');
140 $customCssCodes = fread($file, filesize($customCSSPath));
141 fclose($file);
142 }
143
144 return $customCssCodes;
145 }
146
147 public function getCustomJS()
148 {
149 $customJSCodes = '';
150 $customJsPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . "bitform-custom-{$this->form_id}.js";
151 if (file_exists($customJsPath)) {
152 $file = fopen($customJsPath, 'r');
153 $customJSCodes = fread($file, filesize($customJsPath));
154 fclose($file);
155 }
156
157 return $customJSCodes;
158 }
159
160 public function getFormContentWithValue($defaultValues)
161 {
162 $form_content = \json_decode(static::$form[0]->form_content);
163 // this filter just use private purpose
164 $form_content->fields = apply_filters('bitform_dynamic_field_filter', $form_content->fields);
165 if (!is_array($defaultValues) || 0 === count($defaultValues)) {
166 return $form_content;
167 }
168 foreach ($form_content->fields as $fieldKey => $fieldDetails) {
169 // $field_name = empty($fieldDetails->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $fieldDetails->lbl);
170 $fieldName = $fieldDetails->fieldName;
171 $defaultValue = isset($defaultValues[$fieldName]) ? $defaultValues[$fieldName] : null;
172 $defaultValue = isset($defaultValues[$fieldKey]) ? $defaultValues[$fieldKey] : $defaultValue;
173 if ((isset($fieldDetails->mul) || 'check' === $fieldDetails->typ) && isset($defaultValue)) {
174 // if (is_array($defaultValue)) {
175 // $fieldDetails->val =
176 // wp_json_encode(
177 // array_map('sanitize_text_field', $defaultValue)
178 // );
179 // } else {
180 // $fieldDetails->val = sanitize_text_field($defaultValue);
181 // }
182 if ((isset($fieldDetails->mul) && true === $fieldDetails->mul) || is_array($defaultValue)) {
183 $fieldDetails->val = wp_json_encode(array_map('sanitize_text_field', $defaultValue));
184 } elseif (!is_array($defaultValue)) {
185 $fieldDetails->val = sanitize_text_field($defaultValue);
186 }
187 } elseif (!is_null($defaultValue)) {
188 $fieldDetails->val = is_string($defaultValue) ?
189 sanitize_text_field($defaultValue) :
190 sanitize_text_field($defaultValue[count($defaultValue) - 1]);
191 }
192 }
193 return $form_content;
194 }
195
196 public function getFormContent()
197 {
198 $formContent = json_decode(static::$form[0]->form_content);
199 $types = ['check', 'radio', 'select'];
200 $filter = false;
201 foreach ($formContent->fields as $field) {
202 if (in_array($field->typ, $types) && property_exists($field, 'customType')) {
203 $filter = true;
204 break; // reduce unnecessary loop
205 }
206 }
207 if (true === $filter) {
208 $updateFields = apply_filters('bitform_dynamic_field_filter', $formContent->fields);
209 $formContent->fields = $updateFields;
210 }
211 return $formContent;
212 }
213
214 public function getFormInfo()
215 {
216 $formContent = json_decode(static::$form[0]->form_content);
217 $formInfo = isset($formContent->formInfo) ? $formContent->formInfo : null;
218 return $formInfo;
219 }
220
221 public function getFormHelperStates()
222 {
223 $formHelperStates = json_decode(static::$form[0]->builder_helper_state);
224 return $formHelperStates;
225 }
226
227 public function getAtomicClsMap()
228 {
229 return $this->_atomic_class_map;
230 }
231
232 private function is_json($str)
233 {
234 $json = json_decode($str);
235 return $json && $str !== $json;
236 }
237
238 public function getFormData($columnName = '')
239 {
240 if (empty($columnName)) {
241 return null;
242 }
243
244 $form = static::$form[0];
245 if (!isset($form->{$columnName})) {
246 return null;
247 }
248
249 $data = $form->{$columnName};
250 if ($this->is_json($data)) {
251 return json_decode($data);
252 }
253
254 return $data;
255 }
256
257 public function getFormName()
258 {
259 return static::$form[0]->form_name;
260 }
261
262 public function getFields()
263 {
264 if (!is_null($this->_fields)) {
265 return $this->_fields;
266 }
267 $form_content = \json_decode(static::$form[0]->form_content);
268 $layout = $form_content->layout;
269 $fields = $form_content->fields;
270 $field_details = [];
271 foreach ($fields as $key => $field) {
272 if ('recaptcha' === $field->typ) {
273 continue;
274 }
275 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
276 $field_type = $field->typ;
277 $field_details[$key]['label'] = empty($field->lbl) ? null : $field->lbl;
278 $field_details[$key]['type'] = $field_type;
279 $field_details[$key]['key'] = $key;
280 $field_details[$key]['name'] = isset($field->fieldName) ? $field->fieldName : '';
281 if (isset($field->customType)) {
282 $field_details[$key]['customType'] = $field->customType;
283 }
284
285 if (isset($field->err)) {
286 if (isset($field->err->entryUnique)) {
287 $field_details[$key]['entryUnique'] = $field->err->entryUnique;
288 }
289 if (isset($field->err->userUnique)) {
290 $field_details[$key]['userUnique'] = $field->err->userUnique;
291 }
292 }
293
294 if (isset($field->mul)) {
295 $field_details[$key]['mul'] = $field->mul;
296 }
297 if ('file-up' === $field_type && isset($field->exts)) {
298 $field_details[$key]['valid']['type'] = $field->exts;
299 }
300 if ('file-up' === $field_type && isset($field->mxUp)) {
301 $field_details[$key]['valid']['upload_size'] = (int) $field->mxUp;
302 }
303 if (isset($field->valid) && !is_null($field->valid)) {
304 if (isset($field->valid->req)) {
305 $field_details[$key]['valid']['req'] = $field->valid->req;
306 }
307 if (isset($field->valid->reqMsg)) {
308 $field_details[$key]['valid']['reqMsg'] = $field->valid->reqMsg;
309 }
310 if (isset($field->valid->typMsg)) {
311 $field_details[$key]['valid']['typMsg'] = $field->valid->typMsg;
312 }
313 }
314 if ($this->isRepeatedField($key)) {
315 $field_details[$key]['repeated'] = true;
316 }
317 }
318 if ($this->isGCLIDEnabled()) {
319 $field_details['GCLID']['name'] = 'GCLID';
320 $field_details['GCLID']['adminLbl'] = 'GCLID';
321 $field_details['GCLID']['key'] = 'GCLID';
322 $field_details['GCLID']['type'] = 'hidden';
323 }
324 $this->_fields = $field_details;
325 return $field_details;
326 }
327
328 public function getFieldsKey()
329 {
330 $form_content = \json_decode(static::$form[0]->form_content);
331 $fields = $form_content->fields;
332 $field_details = [];
333 foreach ($fields as $key => $field) {
334 if ('recaptcha' === $field->typ) {
335 continue;
336 }
337 // $field_name = empty($field->lbl) ? null : \preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
338 $field_details[$key] = $key;
339 }
340 if ($this->isGCLIDEnabled()) {
341 $field_details['GCLID'] = 'GCLID';
342 }
343 return $field_details;
344 }
345
346 public function getFieldLabel($forQuery = false)
347 {
348 if (!is_null($this->_field_label)) {
349 return $this->_field_label;
350 }
351 $form_content = \json_decode(static::$form[0]->form_content);
352 $fields = $form_content->fields;
353 $field_details = [];
354 $fieldCounter = 0;
355 foreach ($fields as $key => $field) {
356 if ('recaptcha' === $field->typ || 'turnstile' === $field->typ || 'html' === $field->typ || 'button' === $field->typ) {
357 continue;
358 }
359 $field_details[$fieldCounter]['name'] = empty($field->lbl) ? null : $field->lbl;
360 $field_details[$fieldCounter]['adminLbl'] = empty($field->adminLbl) ? $field_details[$fieldCounter]['name'] : $field->adminLbl;
361 $field_details[$fieldCounter]['key'] = $key;
362 $field_details[$fieldCounter]['type'] = $field->typ;
363 $fieldCounter += 1;
364 }
365 if ($this->isGCLIDEnabled()) {
366 $field_details[$fieldCounter]['name'] = 'GCLID';
367 $field_details[$fieldCounter]['adminLbl'] = 'GCLID';
368 $field_details[$fieldCounter]['key'] = 'GCLID';
369 $field_details[$fieldCounter]['type'] = 'hidden';
370 $fieldCounter += 1;
371 }
372 if (!$forQuery) {
373 $field_details = (array) $this->addEntryInfo($field_details, $fieldCounter);
374 }
375 $this->_field_label = $field_details;
376 return $field_details;
377 }
378
379 public function getUploadFields()
380 {
381 if (!is_null($this->_has_upload)) {
382 return $this->_has_upload;
383 }
384 $upload_fields = [];
385 $form_field_details = $this->getFields();
386 foreach ($form_field_details as $field_name => $__field_detail) {
387 if (isset($__field_detail['type']) && ('file-up' === $__field_detail['type'] || 'advanced-file-up' === $__field_detail['type'])) {
388 $upload_fields[] = $field_name;
389 }
390 }
391 $this->_has_upload = $upload_fields;
392 return $upload_fields;
393 }
394
395 public function getSignatureFilePath($blobLink, $form_id, $entry_id, $imgType)
396 {
397 $imgTypes = [
398 'image/png' => 'png',
399 'image/jpeg' => 'jpg',
400 'image/svg+xml' => 'svg',
401 ];
402 $data_uri = $blobLink;
403 $encoded_image = explode(',', $data_uri)[1];
404 $decoded_image = base64_decode($encoded_image);
405 $_upload_dir = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $form_id . DIRECTORY_SEPARATOR . $entry_id;
406
407 wp_mkdir_p($_upload_dir);
408
409 $filename = "{$entry_id}-" . time() . ".{$imgTypes[$imgType]}";
410 $fullPath = $_upload_dir . DIRECTORY_SEPARATOR . $filename;
411 file_put_contents($fullPath, $decoded_image);
412
413 return $filename;
414 }
415
416 private function entryInsert($user_details)
417 {
418 $formEntryModel = new FormEntryModel();
419 $entryId = $formEntryModel->insert(
420 [
421 'form_id' => $this->form_id,
422 'user_id' => $user_details['id'],
423 'user_ip' => $user_details['ip'],
424 'user_device' => $user_details['device'],
425 'referer' => $user_details['page'],
426 'status' => $this->_saveFormAsDraft ? 9 : 1,
427 'created_at' => $user_details['time'],
428 ]
429 );
430 return $entryId;
431 }
432
433 private function submisionLog($user_details, $entry_id, $type)
434 {
435 $formEntryLogModel = new FormEntryLogModel();
436 $submissionLogData = [
437 'user_id' => $user_details['id'],
438 'action_type' => $type, // create, update
439 'log_type' => 'entry',
440 'ip' => $user_details['ip'],
441 'form_entry_id' => $entry_id,
442 'content' => null,
443 'form_id' => $this->form_id,
444 'created_at' => $user_details['time'],
445 ];
446 $submissionLogData = apply_filters('bitform_filter_submission_log_data', $submissionLogData, $this->form_id, $type);
447 $logId = $formEntryLogModel->form_log_insert(
448 $submissionLogData
449 );
450 return $logId;
451 }
452
453 private function isArrayAllKeyInt($InputArray)
454 {
455 if (!is_array($InputArray)) {
456 return false;
457 }
458
459 if (count($InputArray) <= 0) {
460 return true;
461 }
462
463 return array_unique(array_map('is_int', array_keys($InputArray))) === [true];
464 }
465
466 public function formatSubmittedData($submitted_data)
467 {
468 $form_content = $this->getFormContent();
469 $form_fields = $form_content->fields;
470
471 foreach ($submitted_data as $key => $value) {
472 if (!isset($form_fields->{$key})) {
473 continue;
474 }
475 $field_data = $form_fields->{$key};
476 $field_type = $field_data->typ;
477 if ('select' === $field_type && !empty($field_data->config->multipleSelect)) {
478 $valueArr = [];
479 if ($this->isRepeatedField($key)) {
480 foreach ($value as $index => $v) {
481 $valueArr[$index] = explode(BITFORMS_BF_SEPARATOR, $v);
482 }
483 } else {
484 $valueArr = explode(BITFORMS_BF_SEPARATOR, $value);
485 }
486 $submitted_data[$key] = $valueArr;
487 }
488 }
489 $submitted_data = apply_filters('bitform_filter_format_submitted_data', $submitted_data, $this->form_id);
490 return $submitted_data;
491 }
492
493 private function formatRepeateFieldData($submitted_data, $form_fields)
494 {
495 $repeaterFields = $this->getRepeaterFields();
496 foreach ($repeaterFields as $repeaterFldKey => $repeatedFields) {
497 $repeatIndexes = $submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"];
498 $repeatIndexes = explode(',', $repeatIndexes);
499 foreach ($repeatIndexes as $slNo => $repeatIndex) {
500 foreach ($repeatedFields as $repeatedField) {
501 if (!isset($submitted_data[$repeaterFldKey][$slNo])) {
502 $submitted_data[$repeaterFldKey][$slNo] = [];
503 }
504 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = $submitted_data[$repeatedField][$repeatIndex];
505 }
506 }
507 foreach ($repeatedFields as $repeatedField) {
508 unset($submitted_data[$repeatedField]);
509 }
510 unset($submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"]);
511 }
512
513 return $submitted_data;
514 }
515
516 private function saveEntryMeta($submitted_data, $entry_id)
517 {
518 $errorInEntryMetaInsert = false;
519 $entryMeta = new FormEntryMetaModel();
520 foreach ($submitted_data as $key => $value) {
521 $value = $submitted_data[$key];
522 if (is_string($value)) {
523 $value = wp_unslash($value);
524 } elseif ($this->isArrayAllKeyInt($value)) {
525 $value = wp_json_encode(array_values($value));
526 } else {
527 $value = wp_json_encode($value);
528 }
529 $status = $entryMeta->insert(
530 [
531 'bitforms_form_entry_id' => $entry_id,
532 'meta_key' => $key,
533 'meta_value' => $value,
534 ]
535 );
536 if (is_wp_error($status)) {
537 $errorInEntryMetaInsert = true;
538 break;
539 }
540 }
541 return $errorInEntryMetaInsert;
542 }
543
544 public function setSaveFormAsDraft()
545 {
546 $this->_saveFormAsDraft = true;
547 }
548
549 public function saveFormEntry($submitted_data)
550 {
551 $submitted_data = $this->formatSubmittedData($submitted_data);
552 $submitted_data = apply_filters('bitform_filter_save_form_entry', $submitted_data, $this->form_id);
553 $form_content = \json_decode(static::$form[0]->form_content);
554 do_action('bitform_save_entry', $this, $submitted_data, $this->form_id);
555 $key = null;
556 $ipTool = new IpTool();
557 $fileHandler = new FileHandler();
558 $form_fields = $this->getFields();
559 $file_fields = $this->getUploadFields();
560
561 foreach ($_FILES as $file_name => $file_details) {
562 if ($file_fields && in_array($file_name, $file_fields)) {
563 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
564 if (!empty($validation['error_type']) && !empty($validation['message'])) {
565 return new WP_Error($validation['error_type'], __($validation['message'], 'bit-form'));
566 }
567 }
568 }
569 $user_details = $ipTool->getUserDetail();
570 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
571 $user_details = apply_filters('bitform_filter_save_entry_user_details', $user_details, $this->form_id);
572
573 $form_fields = $this->getFields();
574 $submitted_data = $this->passwordEncrypted($submitted_data, $form_fields);
575 $submitted_data = $this->formatRepeateFieldData($submitted_data, $form_fields);
576 global $wpdb;
577 $wpdb->query('START TRANSACTION');
578 $entry_id = $this->entryInsert($user_details);
579 $log_id = null;
580 if (is_wp_error($entry_id)) {
581 return new WP_Error('insert_error', __('Sorry, Error occurred in saving form entry', 'bit-form'));
582 }
583 if ($entry_id) {
584 $log_id = $this->submisionLog($user_details, $entry_id, 'create', $key);
585 if (is_wp_error($log_id)) {
586 $wpdb->query('ROLLBACK');
587 return new WP_Error('error_entry_log', __('Sorry, error occurred in logging form entry', 'bit-form'));
588 }
589 }
590 if ($entry_id) {
591 $submitted_fields = $this->getFormContentWithValue($submitted_data)->fields;
592 $workFlowRunHelper = new WorkFlow($this->form_id);
593 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
594 'create',
595 $submitted_fields,
596 $submitted_data,
597 $entry_id,
598 $log_id
599 );
600 if (!empty($workFlowreturnedOnSubmit['fields'])) {
601 $submitted_data = $workFlowreturnedOnSubmit['fields'];
602 }
603
604 $file_fields = $this->getUploadFields();
605 $formFields = $this->getFields();
606 $submitted_data = FileHandler::tempDirToUploadDir($submitted_data, $formFields, $this->form_id, $entry_id);
607 $fileHandler = new FileHandler();
608 foreach ($_FILES as $file_name => $file_details) {
609 if ($file_fields && in_array($file_name, $file_fields)) {
610 $filePath = [];
611 $repeaterFldKey = $this->isRepeatedField($file_name);
612 if ($repeaterFldKey) {
613 foreach ($file_details['name'] as $slNo => $fileName) {
614 $repeateFileDetails = [
615 'name' => $file_details['name'][$slNo],
616 'type' => $file_details['type'][$slNo],
617 'tmp_name' => $file_details['tmp_name'][$slNo],
618 'error' => $file_details['error'][$slNo],
619 'size' => $file_details['size'][$slNo],
620 ];
621 $filePath = $fileHandler->moveUploadedFiles($repeateFileDetails, $this->form_id, $entry_id);
622 if (!empty($filePath)) {
623 $submitted_data[$repeaterFldKey][$slNo - 1][$file_name] = $filePath;
624 }
625 }
626 } else {
627 $filePath = $fileHandler->moveUploadedFiles($file_details, $this->form_id, $entry_id);
628 if (!empty($filePath)) {
629 $submitted_data[$file_name] = $filePath;
630 }
631 }
632 }
633 }
634
635 /* ======== for Signature field ===========*/
636 foreach ($form_content->fields as $key => $field) {
637 if ('signature' === $field->typ) {
638 $fld_data = $submitted_data[$key];
639 $img_type = $field->config->imgTyp;
640 $submitted_data[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $entry_id, $img_type);
641 break;
642 }
643 }
644
645 if (!isset($form_content->additional->enabled->submission)) {
646 $errorInEntryMetaInsert = $this->saveEntryMeta($submitted_data, $entry_id);
647 if ($errorInEntryMetaInsert) {
648 do_action('bitform_save_entry_error', $this, $submitted_data, $this->form_id);
649 $wpdb->query('ROLLBACK');
650 return new WP_Error('insert_error', __('Sorry, Error occured in saving form entry data', 'bit-form'));
651 }
652 do_action('bitform_after_save_entry_success', $this, $submitted_data, $entry_id);
653 } else {
654 $wpdb->query('ROLLBACK');
655 }
656 $wpdb->query('COMMIT');
657 $this->setSubmissionCount();
658 $workFlowreturnedOnSubmit['entry_id'] = $entry_id;
659 $workFlowreturnedOnSubmit['fields'] = $submitted_data;
660 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_submit_success', $workFlowreturnedOnSubmit, $this->form_id);
661
662 return $workFlowreturnedOnSubmit;
663 }
664 }
665
666 public function passwordEncrypted($updatedValue, $form_fields)
667 {
668 $integrationHandler = new IntegrationHandler($this->form_id);
669 $formIntegrations = $integrationHandler->getAllIntegration('wp_user_auth', 'wp_auth', 1);
670 if (!isset($formIntegrations->errors['result_empty'])) {
671 foreach ($form_fields as $field) {
672 if (array_key_exists($field['key'], $updatedValue) && 'password' === $field['type']) {
673 $updatedValue[$field['key']] = '**** (encrypted)';
674 }
675 }
676 }
677 return $updatedValue;
678 }
679
680 public function updateFormEntry($updatedValue, $formID, $entryID)
681 {
682 $updatedValue = $this->formatSubmittedData($updatedValue);
683 $updatedValue = apply_filters('bitform_filter_update_form_entry', $updatedValue, $this->form_id);
684 do_action('bitform_update_entry', $this, $updatedValue, $formID, $entryID);
685 $formEntryModel = new FormEntryModel();
686 $formEntryLogModel = new FormEntryLogModel();
687 $formOldData = $formEntryLogModel->get_form_value($entryID);
688 $key = null;
689 $entryMeta = new FormEntryMetaModel();
690 $ipTool = new IpTool();
691 $user_details = $ipTool->getUserDetail();
692 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
693 $user_details = apply_filters('bitform_filter_update_entry_user_details', $user_details, $this->form_id);
694
695 $form_fields = $this->getFields();
696
697 $updatedValue = $this->passwordEncrypted($updatedValue, $form_fields);
698 $updatedValue = $this->formatRepeateFieldData($updatedValue, $form_fields);
699 $field_map = [];
700 foreach ($formOldData as $index => $data) {
701 foreach ($form_fields as $field_key => $field) {
702 if ($data->meta_key === $field['key']) {
703 $field_map[$field_key] = $field['key'];
704 }
705 }
706 }
707 $oldEntry = $formEntryModel->get('status', ['id' => $entryID])[0];
708 $formEntry = $formEntryModel->update(
709 [
710 'user_id' => $user_details['id'],
711 'user_ip' => $user_details['ip'],
712 'user_device' => $user_details['device'],
713 'status' => ('9' === $oldEntry->status && !$this->_saveFormAsDraft) ? 1 : $oldEntry->status,
714 'updated_at' => $user_details['time'],
715 ],
716 [
717 'form_id' => $formID,
718 'id' => $entryID,
719 ]
720 );
721 $log_id = null;
722 if ($formEntry) {
723 $log_id = $this->submisionLog($user_details, $entryID, 'update');
724 }
725
726 if (is_wp_error($formEntry) || !$formEntry) {
727 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
728 }
729 $formFields = $this->getFields();
730 $updatedValue = FileHandler::tempDirToUploadDir($updatedValue, $formFields, $this->form_id, $entryID);
731 $file_fields = $this->getUploadFields();
732 if (count($file_fields) > 0) {
733 $fileHandler = new FileHandler();
734 foreach ($file_fields as $field_name) {
735 if (isset($updatedValue[$field_name . '_old'])) {
736 $file_exists = $entryMeta->get(
737 'meta_value',
738 [
739 'bitforms_form_entry_id' => $entryID,
740 'meta_key' => $field_name,
741 ]
742 );
743 if (!is_wp_error($file_exists) && count($file_exists) > 0) {
744 $files_in_db = json_decode($file_exists[0]->meta_value);
745 $files_old = empty($updatedValue[$field_name . '_old']) ? [] : explode(',', $updatedValue[$field_name . '_old']);
746 $deleted_file = array_diff($files_in_db, $files_old);
747 if (count($deleted_file) > 0) {
748 $fileHandler->deleteFiles($formID, $entryID, $deleted_file);
749 }
750 $updatedValue[$field_name] = wp_json_encode($files_old);
751 }
752 }
753 if (!empty($_FILES[$field_name]['name'])) {
754 $repeaterFldKey = $this->isRepeatedField($field_name);
755 if ($repeaterFldKey) {
756 $file_details = $_FILES[$field_name];
757 foreach ($file_details['name'] as $index => $file) {
758 $repeateFileDetails = [
759 'name' => $file_details['name'][$index],
760 'type' => $file_details['type'][$index],
761 'tmp_name' => $file_details['tmp_name'][$index],
762 'error' => $file_details['error'][$index],
763 'size' => $file_details['size'][$index],
764 ];
765 $meta_value = $fileHandler->moveUploadedFiles($repeateFileDetails, $formID, $entryID, $index);
766 if (!empty($meta_value)) {
767 $updatedValue[$repeaterFldKey][$index - 1][$field_name] = wp_json_encode($meta_value);
768 }
769 }
770 } else {
771 $meta_value = $fileHandler->moveUploadedFiles($_FILES[$field_name], $formID, $entryID);
772 if (!empty($meta_value)) {
773 if (isset($updatedValue[$field_name . '_old']) && !is_wp_error($file_exists) && count($file_exists) > 0) {
774 $meta_value = empty($files_old) ? $meta_value : array_merge($meta_value, $files_old);
775 $updatedValue[$field_name] = wp_json_encode($meta_value);
776 } else {
777 $updatedValue[$field_name] = wp_json_encode($meta_value);
778 }
779 }
780 }
781 }
782 }
783 }
784
785 unset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']);
786
787 $workFlowRunHelper = new WorkFlow($formID);
788 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
789 'edit',
790 $this->getFormContentWithValue($updatedValue)->fields,
791 $updatedValue,
792 $entryID,
793 $log_id
794 );
795 if (!empty($workFlowreturnedOnSubmit['fields'])) {
796 $updatedValue = $workFlowreturnedOnSubmit['fields'];
797 }
798
799 $toUpdateValues = [];
800 foreach ($form_fields as $field) {
801 if (isset($updatedValue[$field['key']])) {
802 $toUpdateValues[$field['key']] = $updatedValue[$field['key']];
803 }
804 }
805 $form_content = \json_decode(static::$form[0]->form_content);
806
807 foreach ($form_content->fields as $key => $field) {
808 if ('signature' === $field->typ) {
809 $fld_data = $updatedValue[$key];
810 $img_type = $field->config->imgTyp;
811 $toUpdateValues[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $entryID, $img_type);
812 break;
813 }
814 }
815
816 $formEntryMetaUpdateStatus = $entryMeta->update(
817 $toUpdateValues,
818 [
819 'bitforms_form_entry_id' => $entryID,
820 ]
821 );
822 if (is_wp_error($formEntryMetaUpdateStatus) || isset($newFileInsertStatus) && is_wp_error($newFileInsertStatus)) {
823 do_action('bitform_update_entry_error', $this, $toUpdateValues, $formEntryMetaUpdateStatus, $this->form_id);
824 return $formEntryMetaUpdateStatus;
825 }
826 $toUpdateValues = array_merge($formEntryMetaUpdateStatus, ['entry_id' => $entryID]);
827 do_action('bitform_after_update_entry_success', $this, $toUpdateValues, $formID, $entryID);
828 if (empty($workFlowreturnedOnSubmit['message'])) {
829 $workFlowreturnedOnSubmit['message'] = __('Entry Updated Successfully', 'bit-form');
830 }
831 $customFieldHandler = new CustomFieldHandler();
832 $toUpdateValues = $customFieldHandler->updatedData($form_fields, $toUpdateValues);
833
834 $workFlowreturnedOnSubmit['updatedData'] = $toUpdateValues;
835 $counter = 0;
836 for ($i = 0; $i < count($formOldData); $i++) {
837 if (array_key_exists($formOldData[$i]->meta_key . '_old', $toUpdateValues)) {
838 unset($toUpdateValues[$formOldData[$i]->meta_key . '_old']);
839 }
840 if (in_array($formOldData[$i]->meta_key, $file_fields)) {
841 if (
842 empty($_FILES[$formOldData[$i]->meta_key]['name'])
843 || (is_array($_FILES[$formOldData[$i]->meta_key]['name'])
844 && 1 === count($_FILES[$formOldData[$i]->meta_key]['name'])
845 && empty($_FILES[$formOldData[$i]->meta_key]['name'][0]))
846 ) {
847 unset($toUpdateValues[$formOldData[$i]->meta_key]);
848 continue;
849 }
850 if (is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
851 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . wp_json_encode($_FILES[$formOldData[$i]->meta_key]['name']);
852 } elseif (!is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
853 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . $_FILES[$formOldData[$i]->meta_key]['name'];
854 }
855 unset($toUpdateValues[$formOldData[$i]->meta_key]);
856 } elseif (isset($toUpdateValues[$formOldData[$i]->meta_key])) {
857 if (is_array($toUpdateValues[$formOldData[$i]->meta_key])) {
858 if (json_decode($formOldData[$i]->meta_value) !== $toUpdateValues[$formOldData[$i]->meta_key]) {
859 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated From ' . implode(',', json_decode($formOldData[$i]->meta_value)) . ' To ' . implode(',', $toUpdateValues[$formOldData[$i]->meta_key]);
860 }
861 } elseif (is_string($toUpdateValues[$formOldData[$i]->meta_key]) && !FieldValueHandler::isEmpty($toUpdateValues[$formOldData[$i]->meta_key])) {
862 if ($formOldData[$i]->meta_value !== $toUpdateValues[$formOldData[$i]->meta_key]) {
863 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated' . ($formOldData[$i]->meta_value ? ' From ' . $formOldData[$i]->meta_value : '') . ' To ' . $toUpdateValues[$formOldData[$i]->meta_key];
864 }
865 }
866 }
867 $counter++;
868 }
869
870 $newField = array_keys(array_diff_key($formEntryMetaUpdateStatus, $field_map));
871 for ($i = 0; $i < count($newField); $i++) {
872 if (is_array($toUpdateValues[$newField[$i]]) && !empty($toUpdateValues[$newField[$i]])) {
873 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . implode(',', $toUpdateValues[$newField[$i]]);
874 } elseif (is_string($newField[$i]) && !FieldValueHandler::isEmpty($toUpdateValues[$newField[$i]])) {
875 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . $toUpdateValues[$newField[$i]];
876 }
877 }
878 if (null !== $key) {
879 $logUpdate = implode('b::f', (array) $key);
880 $formEntryLogUpdate = $formEntryLogModel->logUpdate($logUpdate, $log_id);
881 }
882 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
883 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
884
885 return $workFlowreturnedOnSubmit;
886 }
887
888 public function getRepeaterFields()
889 {
890 if (!is_null($this->_repeaterFields)) {
891 return $this->_repeaterFields;
892 }
893 $repeaterFields = [];
894 $form_content = \json_decode(static::$form[0]->form_content);
895 $fields = $form_content->fields;
896 $nestedLayouts = !empty($form_content->nestedLayout) ? $form_content->nestedLayout : [];
897 foreach ($nestedLayouts as $fieldKey => $repeatLayout) {
898 if ('repeater' !== $fields->{$fieldKey}->typ) {
899 continue;
900 }
901 $repeaterFields[$fieldKey] = [];
902 foreach ($repeatLayout->lg as $fieldLayoutData) {
903 $repeaterFields[$fieldKey][] = $fieldLayoutData->i;
904 }
905 }
906 $this->_repeaterFields = $repeaterFields;
907 return $repeaterFields;
908 }
909
910 public function isRepeatedField($fieldKey)
911 {
912 $repeatedFields = $this->getRepeaterFields();
913 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
914 if (in_array($fieldKey, $repeaterFields)) {
915 return $repeaterKey;
916 }
917 }
918 return false;
919 }
920
921 public function fieldNameReplaceOfPost()
922 {
923 $fields = $this->getFields();
924 foreach ($fields as $fieldKey => $fieldData) {
925 if (array_key_exists('name', $fieldData)) {
926 $fldName = $fieldData['name'];
927 $fldName = str_replace(['.', ' '], '_', $fldName);
928 if (array_key_exists($fldName, $_POST)) {
929 $temp = $_POST[$fldName];
930 unset($_POST[$fldName]);
931 $_POST[$fieldKey] = $temp;
932 } elseif (array_key_exists($fldName, $_FILES)) {
933 $temp = $_FILES[$fldName];
934 unset($_FILES[$fldName]);
935 $_FILES[$fieldKey] = $temp;
936 }
937 }
938 }
939 }
940
941 public function setSubmissionCount($countStep = 1)
942 {
943 $update_status = $this->formModel->update(
944 [
945 'entries' => intval(static::$form[0]->entries) + $countStep,
946 ],
947 [
948 'id' => $this->form_id,
949 ]
950 );
951 }
952
953 public function resetSubmissionCount($countStep)
954 {
955 $update_status = $this->formModel->update(
956 [
957 'entries' => intval($countStep),
958 ],
959 [
960 'id' => $this->form_id,
961 ]
962 );
963 }
964
965 public function getCaptchaSettings()
966 {
967 $formContents = $this->getFormContent();
968 $fieldStr = wp_json_encode($formContents->fields);
969 if (false !== strpos($fieldStr, '"typ":"recaptcha"')) {
970 return true;
971 }
972 }
973
974 public function getTurnstileSettings()
975 {
976 $formContents = $this->getFormContent();
977 $fieldStr = wp_json_encode($formContents->fields);
978 if (false !== strpos($fieldStr, '"typ":"turnstile"')) {
979 return true;
980 }
981 }
982
983 public function getCaptchaV3Settings()
984 {
985 $formContents = $this->getFormContent();
986 if (!empty($formContents->additional->enabled) && !empty($formContents->additional->enabled->recaptchav3)) {
987 return $formContents->additional->settings->recaptchav3;
988 }
989 return false;
990 }
991
992 // public function getSuccessMessageMarkups() {
993 // if (is_null($this->_work_flows)) {
994 // $workFlowManager = new WorkFlowHandler($this->form_id);
995 // $this->_work_flows = $workFlowManager->getAllworkFlow();
996 // }
997
998 // $ids = [];
999 // foreach ($this->_work_flows as $msgItem) {
1000 // foreach ($msgItem['conditions'] as $condition) {
1001 // if (isset($condition->actions->success)) {
1002 // foreach ($condition->actions->success as $msg) {
1003 // if ('successMsg' === $msg->type && isset($msg->details->id)) {
1004 // $msgDetailsId = $msg->details->id;
1005 // $idObj = json_decode(stripslashes($msgDetailsId));
1006 // if (is_object($idObj) && !empty($idObj->id)) {
1007 // array_push($ids, $idObj->id);
1008 // }
1009 // }
1010 // }
1011 // }
1012 // if (isset($condition->actions->failure)) {
1013 // $idObj = json_decode(stripslashes($condition->actions->failure));
1014 // if (is_object($idObj) && !empty($idObj->id)) {
1015 // array_push($ids, $idObj->id);
1016 // }
1017 // }
1018 // }
1019 // }
1020 // $ids = array_unique($ids);
1021 // if (is_null($this->_conf_messages)) {
1022 // $successMsgHandler = new SuccessMessageHandler($this->form_id);
1023 // $this->_conf_messages = $successMsgHandler->getMessages($ids);
1024 // }
1025
1026 // $messageMarkups = '';
1027 // if (is_wp_error($this->_conf_messages)) {
1028 // return $messageMarkups;
1029 // }
1030
1031 // foreach ($this->_conf_messages as $key => $msgItem) {
1032 // $messageMarkups .= $this->messageMarkup($msgItem->id);
1033 // }
1034
1035 // return $messageMarkups;
1036 // }
1037
1038 // private function messageMarkup($msgId) {
1039 // return <<<SUCCESSMSG
1040 // <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive2 test">
1041 // <div role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
1042 // <div class="bf-notification-message {$this->getAtomicCls("msg-content-{$msgId}")}">
1043 // <button class="{$this->getAtomicCls("close-{$msgId}")} bf-msg-close" type="button">
1044 // <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
1045 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
1046 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
1047 // </svg>
1048 // </button>
1049 // <div class="msg-content"></div>
1050 // </div>
1051 // </div>
1052 // </div>
1053 // SUCCESSMSG;
1054 // }
1055
1056 public function getAtomicCls($element)
1057 {
1058 $atomicClassMap = $this->getAtomicClsMap();
1059 if (property_exists($atomicClassMap, ".$element")) {
1060 $getAtomicCls = $atomicClassMap->{".$element"};
1061 return implode(' ', $getAtomicCls) . " $element";
1062 }
1063 return $element;
1064 }
1065
1066 public function isGCLIDEnabled()
1067 {
1068 $formContents = $this->getFormContent();
1069 if (isset($formContents->additional->enabled->captureGCLID) && $formContents->additional->enabled->captureGCLID) {
1070 return true;
1071 }
1072 return false;
1073 }
1074
1075 protected function addEntryInfo($field_details, $counter)
1076 {
1077 $infos = [
1078 '__user_id' => __('User'),
1079 '__entry_status' => __('Status'),
1080 //'__user_location' => __(''),
1081 '__referer' => __('Refer URL'),
1082 '__user_device' => __('Device'),
1083 '__user_ip' => __('IP address'),
1084 '__created_at' => __('Created Time'),
1085 '__updated_at' => __('Modified Time'),
1086 ];
1087 foreach ($infos as $key => $value) {
1088 $field_details[$counter]['name'] = $value;
1089 $field_details[$counter]['key'] = $key;
1090 $field_details[$counter]['type'] = 'sys';
1091 $counter = $counter + 1;
1092 }
1093
1094 return $field_details;
1095 }
1096 }
1097