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

1,107 lines 39.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\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, $fieldKey, $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 = FileHandler::getEntriesFileUploadDir($form_id, $entry_id);
406 FileHandler::createIndexFile($_upload_dir);
407
408 $filename = "{$entry_id}-{$fieldKey}.{$imgTypes[$imgType]}";
409 $fullPath = $_upload_dir . DIRECTORY_SEPARATOR . $filename;
410 file_put_contents($fullPath, $decoded_image);
411
412 return $filename;
413 }
414
415 private function entryInsert($user_details)
416 {
417 $formEntryModel = new FormEntryModel();
418 $entryId = $formEntryModel->insert(
419 [
420 'form_id' => $this->form_id,
421 'user_id' => $user_details['id'],
422 'user_ip' => $user_details['ip'],
423 'user_device' => $user_details['device'],
424 'referer' => $user_details['page'],
425 'status' => $this->_saveFormAsDraft ? 9 : 1,
426 'created_at' => $user_details['time'],
427 ]
428 );
429 return $entryId;
430 }
431
432 private function submisionLog($user_details, $entry_id, $type)
433 {
434 $formEntryLogModel = new FormEntryLogModel();
435 $submissionLogData = [
436 'user_id' => $user_details['id'],
437 'action_type' => $type, // create, update
438 'log_type' => 'entry',
439 'ip' => $user_details['ip'],
440 'form_entry_id' => $entry_id,
441 'content' => null,
442 'form_id' => $this->form_id,
443 'created_at' => $user_details['time'],
444 ];
445 $submissionLogData = apply_filters('bitform_filter_submission_log_data', $submissionLogData, $this->form_id, $type);
446 $logId = $formEntryLogModel->form_log_insert(
447 $submissionLogData
448 );
449 return $logId;
450 }
451
452 private function isArrayAllKeyInt($InputArray)
453 {
454 if (!is_array($InputArray)) {
455 return false;
456 }
457
458 if (count($InputArray) <= 0) {
459 return true;
460 }
461
462 return array_unique(array_map('is_int', array_keys($InputArray))) === [true];
463 }
464
465 public function formatSubmittedData($submitted_data)
466 {
467 $form_content = $this->getFormContent();
468 $form_fields = $form_content->fields;
469
470 foreach ($submitted_data as $key => $value) {
471 if (!isset($form_fields->{$key})) {
472 continue;
473 }
474 $field_data = $form_fields->{$key};
475 $field_type = $field_data->typ;
476 if ('select' === $field_type && !empty($field_data->config->multipleSelect)) {
477 $valueArr = [];
478 if ($this->isRepeatedField($key)) {
479 foreach ($value as $index => $v) {
480 $valueArr[$index] = explode(BITFORMS_BF_SEPARATOR, $v);
481 }
482 } else {
483 $valueArr = explode(BITFORMS_BF_SEPARATOR, $value);
484 }
485 $submitted_data[$key] = $valueArr;
486 }
487 }
488 $submitted_data = apply_filters('bitform_filter_format_submitted_data', $submitted_data, $this->form_id);
489 return $submitted_data;
490 }
491
492 private function formatRepeateFieldData($submitted_data, $form_fields)
493 {
494 $repeaterFields = $this->getRepeaterFields();
495 foreach ($repeaterFields as $repeaterFldKey => $repeatedFields) {
496 $repeatIndexes = $submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"];
497 $repeatIndexes = explode(',', $repeatIndexes);
498 foreach ($repeatIndexes as $slNo => $repeatIndex) {
499 foreach ($repeatedFields as $repeatedField) {
500 if (!isset($submitted_data[$repeaterFldKey][$slNo])) {
501 $submitted_data[$repeaterFldKey][$slNo] = [];
502 }
503 $submitted_data[$repeaterFldKey][$slNo][$repeatedField] = $submitted_data[$repeatedField][$repeatIndex];
504 }
505 }
506 foreach ($repeatedFields as $repeatedField) {
507 unset($submitted_data[$repeatedField]);
508 }
509 unset($submitted_data["{$form_fields[$repeaterFldKey]['name']}-repeat-index"]);
510 }
511
512 return $submitted_data;
513 }
514
515 private function saveEntryMeta($submitted_data, $entry_id)
516 {
517 $errorInEntryMetaInsert = false;
518 $entryMeta = new FormEntryMetaModel();
519 foreach ($submitted_data as $key => $value) {
520 $value = $submitted_data[$key];
521 if (is_string($value)) {
522 $value = wp_unslash($value);
523 } elseif ($this->isArrayAllKeyInt($value)) {
524 $value = wp_json_encode(array_values($value));
525 } else {
526 $value = wp_json_encode($value);
527 }
528 $status = $entryMeta->insert(
529 [
530 'bitforms_form_entry_id' => $entry_id,
531 'meta_key' => $key,
532 'meta_value' => $value,
533 ]
534 );
535 if (is_wp_error($status)) {
536 $errorInEntryMetaInsert = true;
537 break;
538 }
539 }
540 return $errorInEntryMetaInsert;
541 }
542
543 public function setSaveFormAsDraft()
544 {
545 $this->_saveFormAsDraft = true;
546 }
547
548 public function saveFormEntry($submitted_data)
549 {
550 $submitted_data = $this->formatSubmittedData($submitted_data);
551 $submitted_data = apply_filters('bitform_filter_save_form_entry', $submitted_data, $this->form_id);
552 $form_content = \json_decode(static::$form[0]->form_content);
553 do_action('bitform_save_entry', $this, $submitted_data, $this->form_id);
554 $key = null;
555 $ipTool = new IpTool();
556 $fileHandler = new FileHandler();
557 $form_fields = $this->getFields();
558 $file_fields = $this->getUploadFields();
559
560 foreach ($_FILES as $file_name => $file_details) {
561 if ($file_fields && in_array($file_name, $file_fields)) {
562 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
563 if (!empty($validation['error_type']) && !empty($validation['message'])) {
564 return new WP_Error($validation['error_type'], __($validation['message'], 'bit-form'));
565 }
566 }
567 }
568 $user_details = $ipTool->getUserDetail();
569 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
570 $user_details = apply_filters('bitform_filter_save_entry_user_details', $user_details, $this->form_id);
571
572 $form_fields = $this->getFields();
573 $submitted_data = $this->passwordEncrypted($submitted_data, $form_fields);
574 $submitted_data = $this->formatRepeateFieldData($submitted_data, $form_fields);
575 global $wpdb;
576 $wpdb->query('START TRANSACTION');
577 $entry_id = $this->entryInsert($user_details);
578 $log_id = null;
579
580 $GLOBALS['bf_entry_id'] = $entry_id;
581
582 if (is_wp_error($entry_id)) {
583 return new WP_Error('insert_error', __('Sorry, Error occurred in saving form entry', 'bit-form'));
584 }
585 if ($entry_id) {
586 $log_id = $this->submisionLog($user_details, $entry_id, 'create', $key);
587 if (is_wp_error($log_id)) {
588 $wpdb->query('ROLLBACK');
589 return new WP_Error('error_entry_log', __('Sorry, error occurred in logging form entry', 'bit-form'));
590 }
591 }
592 if ($entry_id) {
593 $submitted_fields = $this->getFormContentWithValue($submitted_data)->fields;
594 $workFlowRunHelper = new WorkFlow($this->form_id);
595
596 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
597 'create',
598 $submitted_fields,
599 $submitted_data,
600 $entry_id,
601 $log_id
602 );
603
604 if (!empty($workFlowreturnedOnSubmit['fields'])) {
605 $submitted_data = $workFlowreturnedOnSubmit['fields'];
606 }
607
608 $file_fields = $this->getUploadFields();
609 $formFields = $this->getFields();
610 $submitted_data = FileHandler::tempDirToUploadDir($submitted_data, $formFields, $this->form_id, $entry_id);
611 $fileHandler = new FileHandler();
612 foreach ($_FILES as $file_name => $file_details) {
613 if ($file_fields && in_array($file_name, $file_fields)) {
614 $filePath = [];
615 $repeaterFldKey = $this->isRepeatedField($file_name);
616 if ($repeaterFldKey) {
617 foreach ($file_details['name'] as $slNo => $fileName) {
618 $repeateFileDetails = [
619 'name' => $file_details['name'][$slNo],
620 'type' => $file_details['type'][$slNo],
621 'tmp_name' => $file_details['tmp_name'][$slNo],
622 'error' => $file_details['error'][$slNo],
623 'size' => $file_details['size'][$slNo],
624 ];
625 $filePath = $fileHandler->moveUploadedFiles($repeateFileDetails, $this->form_id, $entry_id);
626 if (!empty($filePath)) {
627 $submitted_data[$repeaterFldKey][$slNo - 1][$file_name] = $filePath;
628 }
629 }
630 } else {
631 $filePath = $fileHandler->moveUploadedFiles($file_details, $this->form_id, $entry_id);
632 if (!empty($filePath)) {
633 $submitted_data[$file_name] = $filePath;
634 }
635 }
636 }
637 }
638
639 /* ======== for Signature field ===========*/
640 foreach ($form_content->fields as $key => $field) {
641 if ('signature' === $field->typ) {
642 $fld_data = $submitted_data[$key];
643 $img_type = $field->config->imgTyp;
644 $submitted_data[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entry_id, $img_type);
645 }
646 }
647
648 if (!isset($form_content->additional->enabled->submission)) {
649 $errorInEntryMetaInsert = $this->saveEntryMeta($submitted_data, $entry_id);
650 if ($errorInEntryMetaInsert) {
651 do_action('bitform_save_entry_error', $this, $submitted_data, $this->form_id);
652 $wpdb->query('ROLLBACK');
653 return new WP_Error('insert_error', __('Sorry, Error occured in saving form entry data', 'bit-form'));
654 }
655 do_action('bitform_after_save_entry_success', $this, $submitted_data, $this->form_id, $entry_id);
656 } else {
657 $wpdb->query('ROLLBACK');
658 }
659 $wpdb->query('COMMIT');
660 $this->setSubmissionCount();
661 $workFlowreturnedOnSubmit['entry_id'] = $entry_id;
662 $workFlowreturnedOnSubmit['fields'] = $submitted_data;
663 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_submit_success', $workFlowreturnedOnSubmit, $this->form_id);
664
665 return $workFlowreturnedOnSubmit;
666 }
667 }
668
669 public function passwordEncrypted($updatedValue, $form_fields)
670 {
671 $integrationHandler = new IntegrationHandler($this->form_id);
672 $formIntegrations = $integrationHandler->getAllIntegration('wp_user_auth', 'wp_auth', 1);
673 if (!isset($formIntegrations->errors['result_empty'])) {
674 foreach ($form_fields as $field) {
675 if (array_key_exists($field['key'], $updatedValue) && 'password' === $field['type']) {
676 $updatedValue[$field['key']] = '**** (encrypted)';
677 }
678 }
679 }
680 return $updatedValue;
681 }
682
683 public function updateFormEntry($updatedValue, $formID, $entryID)
684 {
685 $updatedValue = $this->formatSubmittedData($updatedValue);
686 $updatedValue = apply_filters('bitform_filter_update_form_entry', $updatedValue, $this->form_id);
687 do_action('bitform_update_entry', $this, $updatedValue, $formID, $entryID);
688 $formEntryModel = new FormEntryModel();
689 $formEntryLogModel = new FormEntryLogModel();
690 $formOldData = $formEntryLogModel->get_form_value($entryID);
691 $key = null;
692 $entryMeta = new FormEntryMetaModel();
693 $ipTool = new IpTool();
694 $user_details = $ipTool->getUserDetail();
695 $user_details = apply_filters('bitform_filter_user_details', $user_details, $this->form_id);
696 $user_details = apply_filters('bitform_filter_update_entry_user_details', $user_details, $this->form_id);
697
698 $form_fields = $this->getFields();
699
700 $updatedValue = $this->passwordEncrypted($updatedValue, $form_fields);
701 $updatedValue = $this->formatRepeateFieldData($updatedValue, $form_fields);
702 $field_map = [];
703 foreach ($formOldData as $index => $data) {
704 foreach ($form_fields as $field_key => $field) {
705 if ($data->meta_key === $field['key']) {
706 $field_map[$field_key] = $field['key'];
707 }
708 }
709 }
710 $oldEntry = $formEntryModel->get('status', ['id' => $entryID])[0];
711 $formEntry = $formEntryModel->update(
712 [
713 'user_id' => $user_details['id'],
714 'user_ip' => $user_details['ip'],
715 'user_device' => $user_details['device'],
716 'status' => ('9' === $oldEntry->status && !$this->_saveFormAsDraft) ? 1 : $oldEntry->status,
717 'updated_at' => $user_details['time'],
718 ],
719 [
720 'form_id' => $formID,
721 'id' => $entryID,
722 ]
723 );
724 $log_id = null;
725 if ($formEntry) {
726 $log_id = $this->submisionLog($user_details, $entryID, 'update');
727 }
728
729 if (is_wp_error($formEntry) || !$formEntry) {
730 return new WP_Error('empty_form', __('provided form entries does not exists', 'bit-form'));
731 }
732 $formFields = $this->getFields();
733 $updatedValue = FileHandler::tempDirToUploadDir($updatedValue, $formFields, $this->form_id, $entryID);
734 $file_fields = $this->getUploadFields();
735 if (count($file_fields) > 0) {
736 $fileHandler = new FileHandler();
737 foreach ($_FILES as $file_name => $file_details) {
738 if ($file_fields && in_array($file_name, $file_fields)) {
739 $validation = $fileHandler->validation($file_name, $file_details, $this->form_id);
740 if (!empty($validation['error_type']) && !empty($validation['message'])) {
741 return new WP_Error($validation['error_type'], __($validation['message'], 'bit-form'));
742 }
743 }
744 }
745 foreach ($file_fields as $field_name) {
746 if (isset($updatedValue[$field_name . '_old'])) {
747 $file_exists = $entryMeta->get(
748 'meta_value',
749 [
750 'bitforms_form_entry_id' => $entryID,
751 'meta_key' => $field_name,
752 ]
753 );
754 if (!is_wp_error($file_exists) && count($file_exists) > 0) {
755 $files_in_db = json_decode($file_exists[0]->meta_value);
756 $files_old = empty($updatedValue[$field_name . '_old']) ? [] : explode(',', $updatedValue[$field_name . '_old']);
757 $deleted_file = array_diff($files_in_db, $files_old);
758 if (count($deleted_file) > 0) {
759 $fileHandler->deleteFiles($formID, $entryID, $deleted_file);
760 }
761 $updatedValue[$field_name] = wp_json_encode($files_old);
762 }
763 }
764 if (!empty($_FILES[$field_name]['name'])) {
765 $repeaterFldKey = $this->isRepeatedField($field_name);
766 if ($repeaterFldKey) {
767 $file_details = $_FILES[$field_name];
768 foreach ($file_details['name'] as $index => $file) {
769 $repeateFileDetails = [
770 'name' => $file_details['name'][$index],
771 'type' => $file_details['type'][$index],
772 'tmp_name' => $file_details['tmp_name'][$index],
773 'error' => $file_details['error'][$index],
774 'size' => $file_details['size'][$index],
775 ];
776 $meta_value = $fileHandler->moveUploadedFiles($repeateFileDetails, $formID, $entryID, $index);
777 if (!empty($meta_value)) {
778 $updatedValue[$repeaterFldKey][$index - 1][$field_name] = wp_json_encode($meta_value);
779 }
780 }
781 } else {
782 $meta_value = $fileHandler->moveUploadedFiles($_FILES[$field_name], $formID, $entryID);
783 if (!empty($meta_value)) {
784 if (isset($updatedValue[$field_name . '_old']) && !is_wp_error($file_exists) && count($file_exists) > 0) {
785 $meta_value = empty($files_old) ? $meta_value : array_merge($meta_value, $files_old);
786 $updatedValue[$field_name] = $meta_value;
787 } else {
788 $updatedValue[$field_name] = $meta_value;
789 }
790 }
791 }
792 }
793 }
794 }
795
796 unset($updatedValue['_ajax_nonce'], $_REQUEST['g-recaptcha-response']);
797
798 $workFlowRunHelper = new WorkFlow($formID);
799 $workFlowreturnedOnSubmit = $workFlowRunHelper->executeOnSubmit(
800 'edit',
801 $this->getFormContentWithValue($updatedValue)->fields,
802 $updatedValue,
803 $entryID,
804 $log_id
805 );
806 if (!empty($workFlowreturnedOnSubmit['fields'])) {
807 $updatedValue = $workFlowreturnedOnSubmit['fields'];
808 }
809
810 $toUpdateValues = [];
811 foreach ($form_fields as $field) {
812 if (isset($updatedValue[$field['key']])) {
813 $toUpdateValues[$field['key']] = $updatedValue[$field['key']];
814 }
815 }
816 $form_content = \json_decode(static::$form[0]->form_content);
817
818 foreach ($form_content->fields as $key => $field) {
819 if ('signature' === $field->typ) {
820 $fld_data = $updatedValue[$key];
821 $img_type = $field->config->imgTyp;
822 $toUpdateValues[$key] = $this->getSignatureFilePath($fld_data, $this->form_id, $key, $entryID, $img_type);
823 }
824 }
825
826 $formEntryMetaUpdateStatus = $entryMeta->update(
827 $toUpdateValues,
828 [
829 'bitforms_form_entry_id' => $entryID,
830 ]
831 );
832 if (is_wp_error($formEntryMetaUpdateStatus) || isset($newFileInsertStatus) && is_wp_error($newFileInsertStatus)) {
833 do_action('bitform_update_entry_error', $this, $toUpdateValues, $formEntryMetaUpdateStatus, $this->form_id);
834 return $formEntryMetaUpdateStatus;
835 }
836 $toUpdateValues = array_merge($formEntryMetaUpdateStatus, ['entry_id' => $entryID]);
837 do_action('bitform_after_update_entry_success', $this, $toUpdateValues, $formID, $entryID);
838 if (empty($workFlowreturnedOnSubmit['message'])) {
839 $workFlowreturnedOnSubmit['message'] = __('Entry Updated Successfully', 'bit-form');
840 }
841 $customFieldHandler = new CustomFieldHandler();
842 $toUpdateValues = $customFieldHandler->updatedData($form_fields, $toUpdateValues);
843
844 $workFlowreturnedOnSubmit['updatedData'] = $toUpdateValues;
845 $counter = 0;
846 for ($i = 0; $i < count($formOldData); $i++) {
847 if (array_key_exists($formOldData[$i]->meta_key . '_old', $toUpdateValues)) {
848 unset($toUpdateValues[$formOldData[$i]->meta_key . '_old']);
849 }
850 if (in_array($formOldData[$i]->meta_key, $file_fields)) {
851 if (
852 empty($_FILES[$formOldData[$i]->meta_key]['name'])
853 || (is_array($_FILES[$formOldData[$i]->meta_key]['name'])
854 && 1 === count($_FILES[$formOldData[$i]->meta_key]['name'])
855 && empty($_FILES[$formOldData[$i]->meta_key]['name'][0]))
856 ) {
857 unset($toUpdateValues[$formOldData[$i]->meta_key]);
858 continue;
859 }
860 if (is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
861 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . wp_json_encode($_FILES[$formOldData[$i]->meta_key]['name']);
862 } elseif (!is_array($_FILES[$formOldData[$i]->meta_key]['name']) && !in_array($_FILES[$formOldData[$i]->meta_key]['name'], json_decode($formOldData[$i]->meta_value))) {
863 $key[$i] = '${' . $formOldData[$i]->meta_key . '} file was Updated To ' . $_FILES[$formOldData[$i]->meta_key]['name'];
864 }
865 unset($toUpdateValues[$formOldData[$i]->meta_key]);
866 } elseif (isset($toUpdateValues[$formOldData[$i]->meta_key])) {
867 if (is_array($toUpdateValues[$formOldData[$i]->meta_key])) {
868 if (json_decode($formOldData[$i]->meta_value) !== $toUpdateValues[$formOldData[$i]->meta_key]) {
869 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated From ' . implode(',', json_decode($formOldData[$i]->meta_value)) . ' To ' . implode(',', $toUpdateValues[$formOldData[$i]->meta_key]);
870 }
871 } elseif (is_string($toUpdateValues[$formOldData[$i]->meta_key]) && !FieldValueHandler::isEmpty($toUpdateValues[$formOldData[$i]->meta_key])) {
872 if ($formOldData[$i]->meta_value !== $toUpdateValues[$formOldData[$i]->meta_key]) {
873 $key[$i] = '${' . $formOldData[$i]->meta_key . '} was Updated' . ($formOldData[$i]->meta_value ? ' From ' . $formOldData[$i]->meta_value : '') . ' To ' . $toUpdateValues[$formOldData[$i]->meta_key];
874 }
875 }
876 }
877 $counter++;
878 }
879
880 $newField = array_keys(array_diff_key($formEntryMetaUpdateStatus, $field_map));
881 for ($i = 0; $i < count($newField); $i++) {
882 if (is_array($toUpdateValues[$newField[$i]]) && !empty($toUpdateValues[$newField[$i]])) {
883 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . implode(',', $toUpdateValues[$newField[$i]]);
884 } elseif (is_string($newField[$i]) && !FieldValueHandler::isEmpty($toUpdateValues[$newField[$i]])) {
885 $key[$counter + $i] = '${' . $newField[$i] . '} Updated To ' . $toUpdateValues[$newField[$i]];
886 }
887 }
888 if (null !== $key) {
889 $logUpdate = implode('b::f', (array) $key);
890 $formEntryLogUpdate = $formEntryLogModel->logUpdate($logUpdate, $log_id);
891 }
892 $workFlowreturnedOnSubmit['entry_id'] = $entryID;
893 $workFlowreturnedOnSubmit = apply_filters('bitform_filter_return_edit_success', $workFlowreturnedOnSubmit, $this->form_id);
894
895 return $workFlowreturnedOnSubmit;
896 }
897
898 public function getRepeaterFields()
899 {
900 if (!is_null($this->_repeaterFields)) {
901 return $this->_repeaterFields;
902 }
903 $repeaterFields = [];
904 $form_content = \json_decode(static::$form[0]->form_content);
905 $fields = $form_content->fields;
906 $nestedLayouts = !empty($form_content->nestedLayout) ? $form_content->nestedLayout : [];
907 foreach ($nestedLayouts as $fieldKey => $repeatLayout) {
908 if ('repeater' !== $fields->{$fieldKey}->typ) {
909 continue;
910 }
911 $repeaterFields[$fieldKey] = [];
912 foreach ($repeatLayout->lg as $fieldLayoutData) {
913 $repeaterFields[$fieldKey][] = $fieldLayoutData->i;
914 }
915 }
916 $this->_repeaterFields = $repeaterFields;
917 return $repeaterFields;
918 }
919
920 public function isRepeatedField($fieldKey)
921 {
922 $repeatedFields = $this->getRepeaterFields();
923 foreach ($repeatedFields as $repeaterKey => $repeaterFields) {
924 if (in_array($fieldKey, $repeaterFields)) {
925 return $repeaterKey;
926 }
927 }
928 return false;
929 }
930
931 public function fieldNameReplaceOfPost()
932 {
933 $fields = $this->getFields();
934 foreach ($fields as $fieldKey => $fieldData) {
935 if (array_key_exists('name', $fieldData)) {
936 $fldName = $fieldData['name'];
937 $fldName = str_replace(['.', ' '], '_', $fldName);
938 if (array_key_exists($fldName, $_POST)) {
939 $temp = $_POST[$fldName];
940 unset($_POST[$fldName]);
941 $_POST[$fieldKey] = $temp;
942 } elseif (array_key_exists($fldName, $_FILES)) {
943 $temp = $_FILES[$fldName];
944 unset($_FILES[$fldName]);
945 $_FILES[$fieldKey] = $temp;
946 }
947 }
948 }
949 }
950
951 public function setSubmissionCount($countStep = 1)
952 {
953 $update_status = $this->formModel->update(
954 [
955 'entries' => intval(static::$form[0]->entries) + $countStep,
956 ],
957 [
958 'id' => $this->form_id,
959 ]
960 );
961 }
962
963 public function resetSubmissionCount($countStep)
964 {
965 $update_status = $this->formModel->update(
966 [
967 'entries' => intval($countStep),
968 ],
969 [
970 'id' => $this->form_id,
971 ]
972 );
973 }
974
975 public function getCaptchaSettings()
976 {
977 $formContents = $this->getFormContent();
978 $fieldStr = wp_json_encode($formContents->fields);
979 if (false !== strpos($fieldStr, '"typ":"recaptcha"')) {
980 return true;
981 }
982 }
983
984 public function getTurnstileSettings()
985 {
986 $formContents = $this->getFormContent();
987 $fieldStr = wp_json_encode($formContents->fields);
988 if (false !== strpos($fieldStr, '"typ":"turnstile"')) {
989 return true;
990 }
991 }
992
993 public function getCaptchaV3Settings()
994 {
995 $formContents = $this->getFormContent();
996 if (!empty($formContents->additional->enabled) && !empty($formContents->additional->enabled->recaptchav3)) {
997 return $formContents->additional->settings->recaptchav3;
998 }
999 return false;
1000 }
1001
1002 // public function getSuccessMessageMarkups() {
1003 // if (is_null($this->_work_flows)) {
1004 // $workFlowManager = new WorkFlowHandler($this->form_id);
1005 // $this->_work_flows = $workFlowManager->getAllworkFlow();
1006 // }
1007
1008 // $ids = [];
1009 // foreach ($this->_work_flows as $msgItem) {
1010 // foreach ($msgItem['conditions'] as $condition) {
1011 // if (isset($condition->actions->success)) {
1012 // foreach ($condition->actions->success as $msg) {
1013 // if ('successMsg' === $msg->type && isset($msg->details->id)) {
1014 // $msgDetailsId = $msg->details->id;
1015 // $idObj = json_decode(stripslashes($msgDetailsId));
1016 // if (is_object($idObj) && !empty($idObj->id)) {
1017 // array_push($ids, $idObj->id);
1018 // }
1019 // }
1020 // }
1021 // }
1022 // if (isset($condition->actions->failure)) {
1023 // $idObj = json_decode(stripslashes($condition->actions->failure));
1024 // if (is_object($idObj) && !empty($idObj->id)) {
1025 // array_push($ids, $idObj->id);
1026 // }
1027 // }
1028 // }
1029 // }
1030 // $ids = array_unique($ids);
1031 // if (is_null($this->_conf_messages)) {
1032 // $successMsgHandler = new SuccessMessageHandler($this->form_id);
1033 // $this->_conf_messages = $successMsgHandler->getMessages($ids);
1034 // }
1035
1036 // $messageMarkups = '';
1037 // if (is_wp_error($this->_conf_messages)) {
1038 // return $messageMarkups;
1039 // }
1040
1041 // foreach ($this->_conf_messages as $key => $msgItem) {
1042 // $messageMarkups .= $this->messageMarkup($msgItem->id);
1043 // }
1044
1045 // return $messageMarkups;
1046 // }
1047
1048 // private function messageMarkup($msgId) {
1049 // return <<<SUCCESSMSG
1050 // <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive2 test">
1051 // <div role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
1052 // <div class="bf-notification-message {$this->getAtomicCls("msg-content-{$msgId}")}">
1053 // <button class="{$this->getAtomicCls("close-{$msgId}")} bf-msg-close" type="button">
1054 // <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
1055 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
1056 // <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
1057 // </svg>
1058 // </button>
1059 // <div class="msg-content"></div>
1060 // </div>
1061 // </div>
1062 // </div>
1063 // SUCCESSMSG;
1064 // }
1065
1066 public function getAtomicCls($element)
1067 {
1068 $atomicClassMap = $this->getAtomicClsMap();
1069 if (is_object($atomicClassMap) && property_exists($atomicClassMap, ".$element")) {
1070 $getAtomicCls = $atomicClassMap->{".$element"};
1071 return implode(' ', $getAtomicCls) . " $element";
1072 }
1073 return $element;
1074 }
1075
1076 public function isGCLIDEnabled()
1077 {
1078 $formContents = $this->getFormContent();
1079 if (isset($formContents->additional->enabled->captureGCLID) && $formContents->additional->enabled->captureGCLID) {
1080 return true;
1081 }
1082 return false;
1083 }
1084
1085 protected function addEntryInfo($field_details, $counter)
1086 {
1087 $infos = [
1088 '__user_id' => __('User'),
1089 '__entry_status' => __('Status'),
1090 //'__user_location' => __(''),
1091 '__referer' => __('Refer URL'),
1092 '__user_device' => __('Device'),
1093 '__user_ip' => __('IP address'),
1094 '__created_at' => __('Created Time'),
1095 '__updated_at' => __('Modified Time'),
1096 ];
1097 foreach ($infos as $key => $value) {
1098 $field_details[$counter]['name'] = $value;
1099 $field_details[$counter]['key'] = $key;
1100 $field_details[$counter]['type'] = 'sys';
1101 $counter = $counter + 1;
1102 }
1103
1104 return $field_details;
1105 }
1106 }
1107