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

AdminFormHandler.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.10.0, at includes/Admin/Form/AdminFormHandler.php

2,439 lines 91.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Handle Form Create,Update,delete Operation
5 *
6 */
7
8 namespace BitCode\BitForm\Admin\Form;
9
10 use BitCode\BitForm\Admin\Form\Template\TemplateProvider;
11 use BitCode\BitForm\Core\Database\EmailTemplateModel;
12 use BitCode\BitForm\Core\Database\FormEntryLogModel;
13 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
14 use BitCode\BitForm\Core\Database\FormEntryModel;
15 use BitCode\BitForm\Core\Database\FormModel;
16 use BitCode\BitForm\Core\Database\IntegrationModel;
17 use BitCode\BitForm\Core\Database\PdfTemplateModel;
18 use BitCode\BitForm\Core\Database\ReportsModel;
19 use BitCode\BitForm\Core\Database\SuccessMessageModel;
20 use BitCode\BitForm\Core\Database\WorkFlowModel;
21 use BitCode\BitForm\Core\Integration\IntegrationHandler;
22 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
23 use BitCode\BitForm\Core\Messages\PdfTemplateHandler;
24 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
25 use BitCode\BitForm\Core\Util\FileHandler;
26 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
27 use BitCode\BitForm\Core\Util\HttpHelper;
28 use BitCode\BitForm\Core\Util\IpTool;
29 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
30 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
31 use BitCode\BitFormPro\Admin\AppSetting\Pdf;
32 use WP_Error;
33
34 class AdminFormHandler
35 {
36 private static $formModel;
37 private static $ipTool;
38
39 public function __construct()
40 {
41 static::$formModel = new FormModel();
42 static::$ipTool = new IpTool();
43 }
44
45 public function getTemplate($Request, $post)
46 {
47 $templateName = null;
48 $newFormId = null;
49 if (isset($post->template)) {
50 $templateName = $post->template;
51 $newFormId = $post->newFormId;
52 }
53
54 $templateProvider = new TemplateProvider();
55 $form_content_raw = $templateProvider->getTemplate($templateName, $newFormId);
56 if (!$form_content_raw) {
57 return new WP_Error('template_empty', __('Template not found, by this name: ', 'bit-form') . $templateName);
58 } else {
59 return wp_json_encode(
60 [
61 'id' => 0,
62 'form_content' => $form_content_raw,
63 ]
64 );
65 }
66 }
67
68 public function saveStyleSheet($styles, $sheetName)
69 {
70 $this->createFormStylesDirIfNotExists();
71
72 if (
73 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
74 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
75 ) {
76 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
77 fwrite($createStyleFile, $styles);
78 fclose($createStyleFile);
79 return true;
80 }
81 return false;
82 }
83
84 public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43)
85 {
86 $md_width = 600;
87 $sm_width = 400;
88 $lg_styles = '';
89 $md_styles = '';
90 $sm_styles = '';
91 for ($i = 0; $i < count($layout->lg); $i++) {
92 $fld = $layout->lg[$i];
93
94 if ($fld->w < 10) {
95 $lay_row_height = 43;
96 } else {
97 $lay_row_height = 2;
98 }
99
100 $class = $fld->i;
101 $lg_g_r_s = $fld->y + 1;
102 $lg_g_c_s = $fld->x + 1;
103 $lg_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
104 $lg_g_c_e = ($fld->x + 1) + $fld->w;
105 $lg_g_r_span = $lg_g_r_e - $lg_g_r_s;
106 $lg_g_c_span = $lg_g_c_e - $lg_g_c_s;
107 $lg_min_height = $fld->h * $lay_row_height . 'px;';
108
109 $lg_styles .= ".$class { grid-area: $lg_g_r_s / $lg_g_c_s / $lg_g_r_e / $lg_g_c_e ; -ms-grid-row: $lg_g_r_s; -ms-grid-row-span: $lg_g_r_span; -ms-grid-column: $lg_g_c_s; -ms-grid-column-span: $lg_g_c_span; min-height: $lg_min_height; }";
110
111 $fld = $layout->md[$i];
112
113 $class = $fld->i;
114 $md_g_r_s = $fld->y + 1;
115 $md_g_c_s = $fld->x + 1;
116 $md_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
117 $md_g_c_e = ($fld->x + 1) + $fld->w;
118 $md_g_r_span = $lg_g_r_e - $md_g_r_s;
119 $md_g_c_span = $lg_g_c_e - $md_g_c_s;
120 $md_min_height = $fld->h * $lay_row_height . 'px;';
121
122 $md_styles .= ".$class { grid-area: $md_g_r_s / $md_g_c_s / $md_g_r_e / $md_g_c_e ; -ms-grid-row: $md_g_r_s; -ms-grid-row-span: $md_g_r_span; -ms-grid-column: $md_g_c_s; -ms-grid-column-span: $md_g_c_span; min-height: $md_min_height; }";
123
124 $fld = $layout->sm[$i];
125
126 $class = $fld->i;
127 $sm_g_r_s = $fld->y + 1;
128 $sm_g_c_s = $fld->x + 1;
129 $sm_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
130 $sm_g_c_e = ($fld->x + 1) + $fld->w;
131 $sm_g_r_span = $sm_g_r_e - $sm_g_r_s;
132 $sm_g_c_span = $sm_g_c_e - $sm_g_c_s;
133 $sm_min_height = $fld->h * $lay_row_height . 'px;';
134
135 $sm_styles .= ".$class { grid-area: $sm_g_r_s / $sm_g_c_s / $sm_g_r_e / $sm_g_c_e ; -ms-grid-row: $sm_g_r_s; -ms-grid-row-span: $sm_g_r_span; -ms-grid-column: $sm_g_c_s; -ms-grid-column-span: $sm_g_c_span; min-height: $sm_min_height; }";
136 }
137 $formStyle = "._frm-g{
138 display: grid;
139 display: -ms-grid;
140 grid-template-columns: repeat( 6 , minmax( 30px , 1fr ));
141 -ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr );
142 }
143 {$lg_styles}
144 @media only screen and (max-width:{$md_width}px) {
145 ._frm-g {grid-template-columns: repeat( 4 , minmax( 30px , 1fr ));-ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr );}
146 {$md_styles}
147 }
148 @media only screen and (max-width:{$sm_width}px) {
149 ._frm-g {grid-template-columns: repeat( 2 , minmax( 30px , 1fr ));-ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr );}
150 {$sm_styles}
151 }";
152
153 $this->createFormStylesDirIfNotExists();
154
155 if (
156 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
157 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
158 ) {
159 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
160 fwrite($createStyleFile, $formStyle);
161 fclose($createStyleFile);
162 return true;
163 }
164 return false;
165 }
166
167 public function createFormStylesDirIfNotExists()
168 {
169 if (!file_exists(BITFORMS_UPLOAD_DIR)) {
170 wp_mkdir_p(BITFORMS_UPLOAD_DIR);
171 }
172 if (!file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')) {
173 wp_mkdir_p(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles');
174 }
175 }
176
177 private function pdfFontDownload($fontName)
178 {
179 if (class_exists('\BitCode\BitFormPro\Admin\AppSetting\Pdf')) {
180 Pdf::getInstance()->fontsDownload($fontName);
181 }
182 return false;
183 }
184
185 public function createNewForm($Request, $post)
186 {
187 // wp_send_json_success($post);
188 // exit;
189 if (!isset($post->form_id) || '' === $post->form_id) {
190 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
191 }
192
193 $formManager = new AdminFormManager($post->form_id);
194 if ($formManager->isExist()) {
195 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
196 }
197
198 if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
199 if (!empty($workFlows) && count($workFlows) > 2) {
200 return new WP_Error(
201 'free_limit',
202 __('You are allowed to add maximum 2 workflows ', 'bit-form')
203 );
204 }
205 }
206
207 if (isset($post->formStyle) && $post->formStyle) {
208 $sheetName = 'bitform-' . $post->form_id . '.css';
209 $this->saveStyleSheet($post->formStyle, $sheetName);
210 }
211
212 if (isset($post->layoutChanged) && $post->layoutChanged) {
213 $sheetName = 'bitform-layout-' . $post->form_id . '.css';
214 $rowHeight = (int)$post->rowHeight;
215 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
216 }
217
218 $fields = wp_unslash($post->fields);
219 // $fields = $post->fields;
220 $layout = wp_unslash($post->layout);
221 $nestedLayout = isset($post->nestedLayout) ? wp_unslash($post->nestedLayout) : (object) [];
222 $formInfo = wp_unslash($post->formInfo);
223 $form_name = wp_unslash($post->form_name);
224 $formSettings = (object) wp_unslash($post->formSettings);
225 $atomic_class_map = isset($post->atomicClassMap) ? wp_unslash($post->atomicClassMap) : [];
226 $breakpointSize = wp_unslash($post->breakpointSize);
227 $style = $post->style;
228 $themeVars = $post->themeVars;
229 $themeColors = $post->themeColors;
230 $staticStyles = $post->staticStyles;
231 $workFlows = wp_unslash($post->workFlows);
232 $additional = wp_unslash($post->additional);
233 $reports = !empty($post->reports) ? $post->reports : (object) [];
234 $builderSettings = (object) isset($post->builderSettings) ? wp_unslash($post->builderSettings) : [];
235
236 $mailTem = $formSettings->mailTem;
237 $pdfTem = $formSettings->pdfTem;
238 $integrations = $formSettings->integrations;
239
240 $user_details = static::$ipTool->getUserDetail();
241 if (empty($fields) || empty($layout)) {
242 return new WP_Error(
243 'empty_form',
244 __('Can not save empty form.', 'bit-form')
245 );
246 }
247 if (strlen($form_name) > 50) {
248 return new WP_Error(
249 'empty_form',
250 __('Form Name Should Be Within 50 Characters', 'bit-form')
251 );
252 }
253 $form_content = [
254 'fields' => $fields,
255 'layout' => $layout,
256 'nestedLayout' => $nestedLayout,
257 'formInfo' => $formInfo,
258 ];
259
260 /* if (!empty($formSettings->submitBtn)) {
261 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
262 } */
263 if (!empty($formSettings->theme)) {
264 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
265 }
266
267 if (!empty($additional)) {
268 $form_content = array_merge($form_content, ['additional' => $additional]);
269 }
270 if (!empty($workFlows)) {
271 $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
272 $workFlowExist = [];
273 foreach ($workflows as $index => $workFlow) {
274 if (in_array($workFlow->action_type, ['always', 'onload'])) {
275 $workFlowExist['onload'] = true;
276 }
277 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
278 $workFlowExist['oninput'] = true;
279 }
280 }
281 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
282 }
283 $form_content = \wp_json_encode($form_content);
284
285 $builder_helper_state = (object) [
286 'style' => $style,
287 'staticStyles' => $staticStyles,
288 'breakpointSize' => $breakpointSize,
289 'themeVars' => $themeVars,
290 'themeColors' => $themeColors,
291 'builderSettings' => $builderSettings
292 ];
293 $atomic_class_map = \wp_json_encode($atomic_class_map);
294 $fdata = [
295 'id' => $post->form_id,
296 'form_content' => $form_content,
297 'builder_helper_state' => \wp_json_encode($builder_helper_state),
298 'atomic_class_map' => $atomic_class_map,
299 'generated_script_page_ids' => \wp_json_encode((object) []),
300 'user_id' => $user_details['id'],
301 'user_ip' => $user_details['ip'],
302 'user_device' => $user_details['device'],
303 'status' => 1,
304 'form_name' => $form_name,
305 'created_at' => $user_details['time'],
306 'updated_at' => $user_details['time'],
307 ];
308
309 $save_status = static::$formModel->insert($fdata);
310
311 if (is_wp_error($save_status)) {
312 return $save_status;
313 } elseif (!$save_status) {
314 return false;
315 } else {
316 wp_mkdir_p(BITFORMS_UPLOAD_DIR . "/$save_status");
317 $formID = $save_status;
318 $integartionIDForWorkflow = [];
319 // Confiramtion Message [start]
320 if (!empty($formSettings->confirmation->type->successMsg)) {
321 $successMessages = $formSettings->confirmation->type->successMsg;
322 $successMessageHandler = new SuccessMessageHandler($formID, $user_details);
323 foreach ($successMessages as $messageKey => $messageDetail) {
324 $savedID = $successMessageHandler->saveMessage($messageDetail);
325 if ($savedID) {
326 $msgIdx = empty($messageDetail->id) ? $messageKey : wp_json_encode(['id' => $messageDetail->id]);
327 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
328 $messageDetail->id = $savedID;
329 $style = $this->updateSuccessMessageClassName($style, $messageKey, $savedID);
330 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
331 }
332 }
333 $builder_helper_state = (object) [
334 'style' => $style,
335 'breakpointSize' => $breakpointSize,
336 'themeVars' => $themeVars,
337 'themeColors' => $themeColors,
338 'builderSettings' => $builderSettings
339 ];
340 $update_status = static::$formModel->update(
341 [
342 'builder_helper_state' => \wp_json_encode($builder_helper_state),
343 'atomic_class_map' => $atomic_class_map,
344 ],
345 [
346 'id' => $formID,
347 ]
348 );
349 if (is_wp_error($update_status)) {
350 return $update_status;
351 }
352 unset($formSettings->confirmation->type->successMsg);
353 }
354 // return $formSettings;
355 // Confiramtion Message [end] */
356 // Email Template [start]
357 if (!empty($mailTem)) {
358 $emailTemplateHandler
359 = new EmailTemplateHandler($formID, $user_details);
360 foreach ($mailTem as $templateKey => $templateDetail) {
361 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
362 if ($savedID) {
363 $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
364 $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
365 }
366 }
367 }
368 // Email Template [end] */
369 // if (!empty($pdfTem)) {
370 // $pdfTemplateHandler = new PdfTemplateHandler($formID);
371 // foreach ($pdfTem as $templateKey => $templateDetail) {
372 // $savedID = $pdfTemplateHandler->save($templateDetail);
373
374 // $pdfSetting = $templateDetail->setting;
375
376 // if( isset($pdfSetting->font->name) && !empty($pdfSetting->font->name)) {
377 // $this->pdfFontDownload($pdfSetting->font->name);
378 // }
379 // // if ($savedID) {
380 // // $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
381 // // $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
382 // // }
383 // }
384 // }
385 //Integration [start] */
386 $integrationHandler = new IntegrationHandler($formID, $user_details);
387 if (!empty($formSettings->confirmation->type)) {
388 $allIntegrations = $formSettings->confirmation->type;
389 foreach ($allIntegrations as $integrationType => $integrationGroup) {
390 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
391 if (empty($singleIntegrationDetail->details)) {
392 $integrationName = $singleIntegrationDetail->title;
393 unset($singleIntegrationDetail->title, $singleIntegrationDetail->id);
394
395 $integrationDetails = !is_string($singleIntegrationDetail) ?
396 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
397 } else {
398 $integrationName = $singleIntegrationDetail->title;
399 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
400 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
401 }
402 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
403 $integIdx = empty($singleIntegrationDetail->id) ? $savedID : wp_json_encode(['id' => $singleIntegrationDetail->id]);
404 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
405 }
406 }
407 }
408 if (!empty($integrations)) {
409 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
410 $integrationName = $singleIntegrationDetail->name;
411 unset($singleIntegrationDetail->name);
412 $integrationType = $singleIntegrationDetail->type;
413 unset($singleIntegrationDetail->type);
414 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
415 unset($singleIntegrationDetail->id);
416 if (empty($singleIntegrationDetail->details)) {
417 $integrationDetails = !is_string($singleIntegrationDetail) ?
418 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
419 } else {
420 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
421 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
422 }
423 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
424 $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : wp_json_encode(['id' => $singleIntegrationDetailID]);
425 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
426 }
427 }
428 //Integrations [end]
429 //wrokFlows [start]
430 if (!empty($workFlows)) {
431 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
432
433 foreach ($workFlows as $index => $workFlow) {
434 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
435 $newData['workflow'] = 1;
436 }
437
438 // $workflowCount = count($workFlows);
439 // while ($workflowCount) {
440 // $workFlow = $workFlows[--$workflowCount];
441 // $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow);
442 // $newData['workflow'] = 1;
443 // }
444 }
445 //wrokFlows [end]
446 $details = [
447 'report_name' => 'All Entries',
448 'hiddenColumns' => ['__user_id', '__user_ip', '__referer', '__user_device', '__created_at', '__updated_at'],
449 'pageSize' => 10,
450 'sortBy' => [],
451 'filters' => [],
452 'globalFilter' => '',
453 'order' => []
454 ];
455 $defaultReport = [
456 'type' => 'table',
457 'category' => 'form',
458 'context' => $formID,
459 'details' => wp_json_encode($details),
460 'isDefault' => (bool) 1,
461 'user_id' => $user_details['id'],
462 'user_ip' => $user_details['ip'],
463 'user_device' => $user_details['device'],
464 'created_at' => $user_details['time'],
465 'updated_at' => $user_details['time'],
466 ];
467 $reportsModel = new ReportsModel();
468 $saveReportId = $reportsModel->insert($defaultReport);
469
470 // }
471 $updated_data = $this->getAForm(['id' => $save_status], null);
472 if (!is_wp_error($saveReportId) && isset($updated_data['form_content'])) {
473 $updated_data['form_content']['report_id'] = $saveReportId;
474 $updated_data['form_content']['is_default'] = 1;
475 }
476 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
477
478 return $updated_data;
479 }
480 }
481
482 public function updateForm($Request, $post)
483 {
484 // return ['checked dta'=>$post];
485 $formId = $post->id;
486 // get the builder_helper_state from the form
487 $builder_helper_state = self::$formModel->get(['builder_helper_state'], ['id' => $formId]);
488 $builder_helper_state = (!is_wp_error($builder_helper_state) && 1 === count($builder_helper_state) && isset($builder_helper_state[0]->builder_helper_state)) ? $builder_helper_state[0]->builder_helper_state : '{}';
489 $builder_helper_state = json_decode($builder_helper_state);
490 if (property_exists($post, 'breakpointSize')) {
491 $builder_helper_state->breakpointSize = $post->breakpointSize;
492 }
493 if (property_exists($post, 'style')) {
494 $builder_helper_state->style = $post->style;
495 }
496 if (property_exists($post, 'staticStyles')) {
497 $builder_helper_state->staticStyles = $post->staticStyles;
498 }
499 if (property_exists($post, 'themeVars')) {
500 $builder_helper_state->themeVars = $post->themeVars;
501 }
502 if (property_exists($post, 'themeColors')) {
503 $builder_helper_state->themeColors = $post->themeColors;
504 }
505 if (property_exists($post, 'builderSettings')) {
506 $builder_helper_state->builderSettings = $post->builderSettings;
507 }
508 if (property_exists($post, 'atomicClassMap')) {
509 $atomic_class_map = \wp_json_encode((object)$post->atomicClassMap);
510 }
511
512 if (property_exists($post, 'fields') && null !== $post->fields && property_exists($post, 'layout') && $post->layout) {
513 $fields = wp_unslash($post->fields);
514 $layout = wp_unslash($post->layout);
515 $nestedLayout = wp_unslash($post->nestedLayouts);
516 $formInfo = wp_unslash($post->formInfo);
517 $formID = wp_unslash($post->id);
518 $form_name = wp_unslash($post->form_name);
519 $formSettings = wp_unslash($post->formSettings);
520 $workFlows = wp_unslash($post->workFlows);
521 $additional = wp_unslash($post->additional);
522 $reports = wp_unslash($post->currentReport);
523 }
524
525 $mailTem = $formSettings->mailTem;
526 $pdfTem = isset($formSettings->pdfTem) ? $formSettings->pdfTem : [];
527 $integrations = $formSettings->integrations;
528
529 $user_details = static::$ipTool->getUserDetail();
530
531 if (empty($fields) || empty($layout) || is_null($formID)) {
532 return new WP_Error('empty_form', 'Can not update empty form.');
533 }
534
535 if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
536 if (count($workFlows) > 2) {
537 return new WP_Error(
538 'free_limit',
539 __('You are allowed to add maximum 2 workflows ', 'bit-form')
540 );
541 }
542 }
543
544 $form_content = [
545 'fields' => $fields,
546 'layout' => $layout,
547 'nestedLayout' => $nestedLayout,
548 'formInfo' => $formInfo,
549 ];
550
551 if (isset($post->report_id)) {
552 $form_content['report_id'] = wp_unslash($post->report_id);
553 }
554
555 /* if (!empty($formSettings->submitBtn)) {
556 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
557 } */
558 if (!empty($formSettings->theme)) {
559 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
560 }
561 if (!empty($additional)) {
562 $form_content = array_merge($form_content, ['additional' => $additional]);
563 }
564 $integartionIDForWorkflow = [];
565 $newData['settingConfiramation'] = 0;
566 $newData['integation'] = 0;
567 $newData['mailTemplate'] = 0;
568 $newData['workflow'] = 0;
569 $newData['reports'] = 0;
570 // Confiramtion Message [start]
571 if (!empty($formSettings->confirmation->type->successMsg)) {
572 $successMessages = $formSettings->confirmation->type->successMsg;
573 $successMessageHandler
574 = new SuccessMessageHandler($formID, $user_details);
575 foreach ($successMessages as $messageKey => $messageDetail) {
576 if (empty($messageDetail->id)) {
577 $savedID = $successMessageHandler->saveMessage($messageDetail);
578 if ($savedID) {
579 $newData['settingConfiramation'] = 1;
580 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
581 $messageDetail->id = $savedID;
582 $builder_helper_state->style = $this->updateSuccessMessageClassName($builder_helper_state->style, $messageKey, $savedID);
583 if (isset($atomic_class_map)) {
584 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
585 }
586 }
587 } else {
588 $successMessageHandler->updateMessage($messageDetail);
589 }
590 }
591 unset($formSettings->confirmation->type->successMsg);
592 }
593 // return $formSettings;
594 // Confirmation Message [end] */
595 // Email Template [start]
596 if (!empty($mailTem)) {
597 $emailTemplateHandler
598 = new EmailTemplateHandler($formID, $user_details);
599 foreach ($mailTem as $templateKey => $templateDetail) {
600 if (empty($templateDetail->id)) {
601 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
602 if (is_wp_error($savedID) && 'result_empty' === $savedID->get_error_code()) {
603 $newData['mailTemplate'] = 2;
604 } else {
605 $newData['mailTemplate'] = 1;
606 $integartionIDForWorkflow['mailTem'][$templateKey] = $savedID;
607 }
608 } else {
609 $emailTemplateHandler->updateTemplate($templateDetail);
610 }
611 }
612 }
613 // return $formSettings;
614 // Email Template [end] */
615 if (!empty($pdfTem)) {
616 $pdfTemplateHandler = new PdfTemplateHandler($formID);
617
618 foreach ($pdfTem as $templateKey => $templateDetail) {
619 if (isset($templateDetail->setting->font->name)) {
620 $this->pdfFontDownload($templateDetail->setting->font->name);
621 }
622
623 $savedID = $pdfTemplateHandler->saveOrUpdate($templateDetail);
624 if (is_wp_error($savedID) && 'result_empty' === $savedID->get_error_code()) {
625 $newData['pdfTemplate'] = 2;
626 } else {
627 $newData['pdfTemplate'] = 1;
628 $integartionIDForWorkflow['pdfTem'][$templateKey] = $savedID;
629 }
630 }
631 }
632 //Integration [start] */
633 $integrationHandler = new IntegrationHandler($formID, $user_details);
634 if (!empty($formSettings->confirmation->type)) {
635 $allIntegrations = $formSettings->confirmation->type;
636 foreach ($allIntegrations as $integrationType => $integrationGroup) {
637 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
638 if (empty($singleIntegrationDetail->details)) {
639 $integrationName = $singleIntegrationDetail->title;
640 unset($singleIntegrationDetail->title);
641 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
642 unset($singleIntegrationDetail->id);
643 $integrationDetails = !is_string($singleIntegrationDetail) ?
644 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
645 } else {
646 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
647 unset($singleIntegrationDetail->id);
648 $integrationName = $singleIntegrationDetail->title;
649 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
650 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
651 }
652 if (empty($singleIntegrationDetailID)) {
653 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
654 $newData['settingConfiramation'] = 1;
655 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
656 } else {
657 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
658 }
659 }
660 }
661 }
662 if (!empty($integrations)) {
663 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
664 $integrationName = $singleIntegrationDetail->name;
665 unset($singleIntegrationDetail->name);
666 $integrationType = $singleIntegrationDetail->type;
667 unset($singleIntegrationDetail->type);
668 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
669 unset($singleIntegrationDetail->id);
670 if (empty($singleIntegrationDetail->details)) {
671 $integrationDetails = !is_string($singleIntegrationDetail) ?
672 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
673 } else {
674 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
675 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
676 }
677 if (empty($singleIntegrationDetailID)) {
678 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
679 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
680 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
681 $newData['integation'] = 2;
682 } else {
683 $newData['integation'] = 1;
684 }
685 } else {
686 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
687 }
688 }
689 }
690 //Integrations [end]
691 //workFlows [start] */
692 $workFlowExist = [];
693 if (!empty($workFlows)) {
694 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
695 // foreach ($workFlows as $workFlowIndex => $workFlow) {
696 $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
697
698 foreach ($workflows as $index => $workFlow) {
699 if (in_array($workFlow->action_type, ['always', 'onload'])) {
700 $workFlowExist['onload'] = true;
701 }
702 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
703 $workFlowExist['oninput'] = true;
704 }
705 if (empty($workFlow->id)) {
706 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
707 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
708 $newData['workflow'] = 2;
709 } else {
710 $newData['workflow'] = 1;
711 }
712 } else {
713 $newData = $workFlowHandler->updateworkFlow($workFlow->id, $workFlow, $integartionIDForWorkflow, $index, $newData);
714 }
715 }
716 }
717 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
718 //wrokFlows [end]
719 //reports [start] */
720 if (!empty($reports)) {
721 $reportsModel = new ReportsModel();
722 $fieldNames = [];
723 foreach ($fields as $key => $field) {
724 if (!empty($field->lbl)) {
725 // $name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
726 $fieldNames["$key"] = $field->lbl;
727 }
728 }
729
730 $fieldNames['__user_id'] = __('User', 'bit-form');
731 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
732 // $fieldNames['__user_location'] = __('');
733 $fieldNames['__referer'] = __('Refer URL');
734 $fieldNames['__user_device'] = __('Device');
735 $fieldNames['__created_at'] = __('Created Time');
736 $fieldNames['__updated_at'] = __('Modified Time');
737
738 $reportIsDefault = null;
739 if (isset($form_content['report_id'])) {
740 $validDateReport = $reportsModel->validateReportFields($reports, $fieldNames);
741 if (isset($reports->isDefault)) {
742 $reportIsDefault = $reports->isDefault;
743 } else {
744 $reportIsDefault = 0;
745 }
746
747 $reportsModel->update(
748 [
749 'type' => 'table',
750 'category' => 'form',
751 'context' => $formID,
752 'details' => is_string($validDateReport) ? $validDateReport : wp_json_encode($validDateReport),
753 'isDefault' => (int) $reportIsDefault,
754 'user_id' => $user_details['id'],
755 'user_ip' => $user_details['ip'],
756 'user_device' => $user_details['device'],
757 'updated_at' => $user_details['time'],
758 ],
759 [
760 'id' => $form_content['report_id'],
761 ]
762 );
763 }
764 }
765 //reports [end]
766 //form abandonment [start]
767 if (!empty($formSettings->formAbandonment)) {
768 $formAbandonment = $formSettings->formAbandonment;
769 // search for existing form abandonment in integration table
770 $abandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
771 if (!is_wp_error($abandonmentInteg) && !empty($abandonmentInteg)) {
772 $abandonmentInteg = $abandonmentInteg[0];
773 }
774 if (isset($abandonmentInteg->id)) {
775 $abandonmentIntegID = $abandonmentInteg->id;
776 $abandonmentIntegDetails = wp_json_encode($formAbandonment);
777 $integrationHandler->updateIntegration($abandonmentIntegID, 'formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
778 } else {
779 $abandonmentIntegDetails = wp_json_encode($formAbandonment);
780 $integrationHandler->saveIntegration('formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
781 }
782 }
783 //form abandonment [end]
784 $form_content = wp_json_encode($form_content);
785 $updateData = [
786 'form_name' => $form_name,
787 'form_content' => $form_content,
788 'user_id' => $user_details['id'],
789 'user_ip' => $user_details['ip'],
790 'builder_helper_state' => \wp_json_encode((object)$builder_helper_state),
791 'generated_script_page_ids' => \wp_json_encode((object) []),
792 'user_device' => $user_details['device'],
793 'updated_at' => $user_details['time'],
794 ];
795 if (isset($atomic_class_map)) {
796 $updateData['atomic_class_map'] = $atomic_class_map;
797 }
798 $formUpdateVersion = get_option('bit-form_form_update_version');
799 if (!$formUpdateVersion) {
800 $formUpdateVersion = 1;
801 } else {
802 $formUpdateVersion = (int) $formUpdateVersion + 1;
803 }
804 update_option('bit-form_form_update_version', $formUpdateVersion);
805
806 $update_status = static::$formModel->update(
807 $updateData,
808 [
809 'id' => $formID,
810 ]
811 );
812 if (is_wp_error($update_status)) {
813 return $update_status;
814 } elseif (!$update_status) {
815 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
816 } else {
817 if (isset($post->deletedFldKey) && is_array($post->deletedFldKey)) {
818 $this->setEmptyMetaValue($post->deletedFldKey);
819 unset($post->deletedFldKey);
820 }
821
822 $updated_data = $this->getAForm(['id' => $formID], null);
823
824 if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation']) {
825 unset($updated_data['formSettings']);
826 }
827 if (0 === $newData['integation']) {
828 unset($updated_data['integrations']);
829 } elseif (2 === $newData['integation']) {
830 $errorIN = '';
831 $errorIN .= empty($errorIN) ? 'integation' : ', integation';
832 }
833 if (0 === $newData['mailTemplate']) {
834 unset($updated_data['mailTem']);
835 } elseif (2 === $newData['mailTemplate']) {
836 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
837 }
838 // if (0 === $newData['pdfTemplate']) {
839 // unset($updated_data['pdfTem']);
840 // } elseif (2 === $newData['pdfTemplate']) {
841 // $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
842 // }
843 if (0 === $newData['workflow']) {
844 unset($updated_data['workFlows']);
845 } elseif (2 === $newData['workflow']) {
846 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
847 }
848 if (2 === $newData['reports']) {
849 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
850 }
851 if (!empty($errorIN)) {
852 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
853 return new WP_Error('Form update Error.', $updated_data);
854 }
855 if (null !== $reportIsDefault) {
856 $updated_data['form_content']['is_default'] = $reportIsDefault;
857 }
858 $updated_data['message'] = __('Form updated successfully.', 'bitform');
859 return $updated_data;
860 }
861 }
862
863 public function setEmptyMetaValue($fieldkeys)
864 {
865 $sqlEscaped = array_map(function ($fld) {
866 return "'" . esc_sql($fld) . "'";
867 }, $fieldkeys);
868 $deletedFldKey = implode(',', $sqlEscaped);
869 global $wpdb;
870 $tablename = $wpdb->prefix . 'bitforms_form_entrymeta';
871 $sql = $wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN ( " . $deletedFldKey . ')', '');
872 $wpdb->query($sql);
873 }
874
875 public function changeFormStatus($Request, $post)
876 {
877 if (isset($Request['status']) && $Request['id']) {
878 $status = wp_unslash($Request['status']);
879 $id = wp_unslash($Request['id']);
880 } else {
881 $status = wp_unslash($post->status);
882 $id = wp_unslash($post->id);
883 }
884 $user_details = static::$ipTool->getUserDetail();
885 // return $post->fields;
886 $status = 'true' === $status || true === $status ? true : false;
887 if (!is_bool($status) || is_null($id)) {
888 // echo $status;
889 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
890 }
891 $update_status = static::$formModel->update(
892 [
893 'user_id' => $user_details['id'],
894 'user_ip' => $user_details['ip'],
895 'user_device' => $user_details['device'],
896 'status' => $status ? 1 : 0,
897 'updated_at' => $user_details['time'],
898 ],
899 [
900 'id' => $id,
901 ]
902 );
903 if (is_wp_error($update_status)) {
904 return $update_status;
905 } elseif (!$update_status) {
906 return false;
907 } else {
908 return __('Form status changed successfully', 'bit-form');
909 }
910 }
911
912 public function changeBulkFormStatus($Request, $post)
913 {
914 if (isset($Request['status']) && $Request['formID']) {
915 $status = wp_unslash($Request['status']);
916 $formID = wp_unslash($Request['formID']);
917 } else {
918 $status = wp_unslash($post->status);
919 $formID = wp_unslash($post->formID);
920 }
921 $user_details = static::$ipTool->getUserDetail();
922 // return $post->fields;
923 $status = 'true' === $status || true === $status ? true : false;
924 if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
925 // echo $status;
926 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
927 }
928 $update_status = static::$formModel->bulkUpdate(
929 [
930 'user_id' => $user_details['id'],
931 'user_ip' => $user_details['ip'],
932 'user_device' => $user_details['device'],
933 'status' => $status ? 1 : 0,
934 'updated_at' => $user_details['time'],
935 ],
936 [
937 'id' => $formID,
938 ]
939 );
940 if (is_wp_error($update_status)) {
941 return $update_status;
942 } elseif (!$update_status) {
943 return false;
944 } else {
945 return __('Form status changed successfully', 'bit-form');
946 }
947 }
948
949 public function getAllForm()
950 {
951 global $wpdb;
952
953 $allForms = $wpdb->get_results("SELECT forms.id,forms.entries as fm_entries,forms.form_name,forms.status,forms.views,forms.created_at,COUNT(entries.id) as entries FROM `{$wpdb->prefix}bitforms_form` as forms LEFT JOIN `{$wpdb->prefix}bitforms_form_entries` as entries ON forms.id = entries.form_id GROUP BY forms.id");
954
955 if (is_wp_error($allForms)) {
956 return $allForms;
957 } elseif (!$allForms) {
958 return [];
959 } else {
960 return $allForms;
961 }
962 }
963
964 public function getAForm($Request, $post)
965 {
966 if (isset($Request['id'])) {
967 $formID = wp_unslash($Request['id']);
968 } else {
969 $formID = wp_unslash($post->id);
970 }
971 // return $post->fields;
972 if (is_null($formID)) {
973 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
974 }
975 $formManager = new AdminFormManager($formID);
976 if (!$formManager->isExist()) {
977 return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
978 }
979 $form_content = $formManager->getFormContent();
980 $helper_states = $formManager->getFormHelperStates();
981 if ($formManager->isExist()) {
982 $form_content_arr = [
983 'layout' => $form_content->layout,
984 'nestedLayout' => !empty($form_content->nestedLayout) ? $form_content->nestedLayout : (object) [],
985 'formInfo' => !empty($form_content->formInfo) ? $form_content->formInfo : (object) ['formName' => $formManager->getFormName()],
986 'fields' => $form_content->fields,
987 'form_name' => $formManager->getFormName(),
988 'workFlowExist' => $form_content->workFlowExist,
989 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
990 ];
991 $successMessageHandler
992 = new SuccessMessageHandler($formID);
993 $successMessages = $successMessageHandler->getAllMessage();
994 if (!is_wp_error($successMessages)) {
995 foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
996 $sucessMessagevalue->message_config = json_decode($sucessMessagevalue->message_config);
997 $allConfirmation['type']['successMsg'][$sucessMessagekey] =
998 [
999 'id' => $sucessMessagevalue->id,
1000 'title' => $sucessMessagevalue->message_title,
1001 'msg' => $sucessMessagevalue->message_content,
1002 'config' => $sucessMessagevalue->message_config,
1003 ];
1004 }
1005 }
1006 $emailTemplateHandler
1007 = new EmailTemplateHandler($formID);
1008 $emailTemplates = $emailTemplateHandler->getAllTemplate();
1009 if (!is_wp_error($emailTemplates)) {
1010 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1011 $mailTem[] =
1012 [
1013 'id' => $emailTemplatevalue->id,
1014 'title' => $emailTemplatevalue->title,
1015 'sub' => $emailTemplatevalue->sub,
1016 'body' => $emailTemplatevalue->body,
1017 ];
1018 }
1019 }
1020 // get all pdf template
1021 $pdfTemplateHandler = new PdfTemplateHandler($formID);
1022 $pdfTemplates = $pdfTemplateHandler->getAll();
1023
1024 if (!is_wp_error($pdfTemplates)) {
1025 foreach ($pdfTemplates as $value) {
1026 $pdfTem[] =
1027 [
1028 'id' => $value->id,
1029 'title' => $value->title,
1030 'setting' => json_decode($value->setting),
1031 'body' => $value->body,
1032 ];
1033 }
1034 }
1035
1036 $integrationHandler = new IntegrationHandler($formID);
1037 $formIntegrations = $integrationHandler->getAllIntegration('form');
1038 if (!is_wp_error($formIntegrations)) {
1039 foreach ($formIntegrations as $integrationkey => $integrationValue) {
1040 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1041 $integrationData = [
1042 'id' => $integrationValue->id,
1043 'title' => $integrationValue->integration_name,
1044 ];
1045 if (!empty($integrationValue->integration_details)) {
1046 $integration_details = (array) json_decode($integrationValue->integration_details);
1047 $integrationData = array_merge($integration_details, $integrationData);
1048 } else {
1049 $integration_details = [
1050 'url' => '',
1051 ];
1052 $integrationData = array_merge($integrationData, $integration_details);
1053 }
1054 $allConfirmation['type'][$integrationValue->integration_type][]
1055 = $integrationData;
1056 } else {
1057 $integrationData = [
1058 'id' => $integrationValue->id,
1059 'name' => $integrationValue->integration_name,
1060 'type' => $integrationValue->integration_type,
1061 ];
1062 $integrations[] = array_merge(
1063 $integrationData,
1064 is_string($integrationValue->integration_details) ?
1065 (array) json_decode($integrationValue->integration_details) :
1066 $integrationValue->integration_details
1067 );
1068 }
1069 }
1070 }
1071 $settingsContent = [
1072 'formName' => $formManager->getFormName(),
1073 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1074 // 'submitBtn' => $form_content->buttons,
1075 ];
1076
1077 if (!empty($allConfirmation)) {
1078 $confirmation = [
1079 'confirmation' => $allConfirmation,
1080 ];
1081 } else {
1082 $confirmation = [
1083 'confirmation' => ['type' => []],
1084 ];
1085 }
1086 $settingsContent = array_merge($settingsContent, $confirmation);
1087 if (!empty($integrations)) {
1088 $settingsContent = array_merge(
1089 $settingsContent,
1090 [
1091 'integrations' => $integrations,
1092 ]
1093 );
1094 } else {
1095 $settingsContent = array_merge(
1096 $settingsContent,
1097 [
1098 'integrations' => []
1099 ]
1100 );
1101 }
1102
1103 if (!empty($mailTem)) {
1104 $settingsContent = array_merge(
1105 $settingsContent,
1106 [
1107 'mailTem' => $mailTem,
1108 ]
1109 );
1110 } else {
1111 $settingsContent = array_merge(
1112 $settingsContent,
1113 [
1114 'mailTem' => []
1115 ]
1116 );
1117 }
1118
1119 if (!empty($pdfTem)) {
1120 $settingsContent = array_merge(
1121 $settingsContent,
1122 [
1123 'pdfTem' => $pdfTem,
1124 ]
1125 );
1126 } else {
1127 $settingsContent = array_merge(
1128 $settingsContent,
1129 [
1130 'pdfTem' => [],
1131 ]
1132 );
1133 }
1134 $formSettings = [
1135 'formSettings' => $settingsContent,
1136 ];
1137 $data = [
1138 'id' => $formID,
1139 'form_name' => $formManager->getFormName(),
1140 'form_content' => $form_content_arr,
1141 'breakpointSize' => $helper_states->breakpointSize,
1142 'style' => $helper_states->style,
1143 'themeVars' => $helper_states->themeVars,
1144 'themeColors' => $helper_states->themeColors,
1145 'builderSettings' => $helper_states->builderSettings,
1146 'additional' => empty($form_content->additional) ? [
1147 'enabled' => [
1148 'blocked_ip' => false,
1149 'restrict_form' => false,
1150 ],
1151 'settings' => [
1152 'restrict_form' => [
1153 'day' => [],
1154 'date' => [
1155 'from' => null,
1156 'to' => null,
1157 ],
1158 'time' => [
1159 'from' => null,
1160 'to' => null,
1161 ],
1162 ],
1163 'entry_limit' => null,
1164 'blocked_ip' => [],
1165 ],
1166 'onePerIp' => false,
1167 ] : $form_content->additional,
1168 'created_at' => $formManager->getFormMetaData()['created_at'],
1169 'views' => $formManager->getFormMetaData()['views'],
1170 'entries' => $formManager->getFormMetaData()['entries'],
1171 'status' => $formManager->getFormMetaData()['status'],
1172 ];
1173 $data = array_merge($data, $formSettings);
1174 $workFlowHandler = new WorkFlowHandler($formID);
1175 $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlow()];
1176 $data = array_merge($data, $workFlows);
1177 $reportsModel = new ReportsModel();
1178 $returnedReportData = $reportsModel->get(
1179 [
1180 'id',
1181 'details',
1182 'isDefault',
1183 'type',
1184 ],
1185 [
1186 'category' => 'form',
1187 'context' => $formID,
1188 ]
1189 );
1190
1191 if (!is_wp_error($returnedReportData)) {
1192 $fieldNames = [];
1193 foreach ($formManager->getFieldLabel() as $key => $field) {
1194 $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
1195 }
1196 if ($formManager->isGCLIDEnabled()) {
1197 $fieldNames['GCLID'] = 'GCLID';
1198 }
1199 foreach ($returnedReportData as $reportKey => $reportData) {
1200 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1201 if (!empty($reportDetails) && is_string($reportDetails)) {
1202 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1203 } elseif (!empty($reportDetails)) {
1204 $returnedReportData[$reportKey]->details = $reportDetails;
1205 } else {
1206 $returnedReportData[$reportKey]->details = [];
1207 }
1208 if ('1' === (string) $reportData->isDefault) {
1209 $returnedReportData[$reportKey]->details->report_name = 'All Entries';
1210 }
1211 }
1212 $reports = ['reports' => $returnedReportData];
1213 $data = array_merge($data, $reports);
1214 }
1215
1216 $formFields = $formManager->getFieldLabel();
1217 $data = array_merge($data, ['Labels' => $formFields]);
1218
1219 return $data;
1220 }
1221 }
1222
1223 public function deleteAForm($Request, $post)
1224 {
1225 if (isset($Request['id'])) {
1226 $formID = wp_unslash($Request['id']);
1227 } else {
1228 $formID = wp_unslash($post->id);
1229 }
1230 if (is_null($formID)) {
1231 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1232 }
1233 $delete_status = static::$formModel->delete(
1234 [
1235 'id' => $formID,
1236 ]
1237 );
1238
1239 $successMessageModel
1240 = new SuccessMessageModel();
1241 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1242
1243 $emailTemplateModel
1244 = new EmailTemplateModel();
1245 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1246
1247 $pdfTemplateModel = new PdfTemplateModel();
1248 $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
1249
1250 $integrationModel = new IntegrationModel();
1251 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1252
1253 $workFlowModel = new WorkFlowModel();
1254 $deleteworkFlowStatus = $workFlowModel->delete(['form_id' => $formID]);
1255
1256 $reportsModel = new ReportsModel();
1257 $deleteReportStatus = $reportsModel->delete(['context' => $formID]);
1258
1259 $formEntryModel = new FormEntryModel();
1260 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1261 $entries = [];
1262
1263 if (!is_wp_error($returnedEntries)) {
1264 foreach ($returnedEntries as $entryKey => $entryInfo) {
1265 $entries[] = $entryInfo->id;
1266 }
1267 global $wpdb;
1268 $prefix = $wpdb->prefix;
1269 if (count($entries) > 0) {
1270 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1271 [
1272 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1273 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1274 ]
1275 );
1276 }
1277 }
1278
1279 $fileHandler = new FileHandler();
1280 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1281 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1282 }
1283 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1284 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1285 }
1286 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1287 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1288 }
1289 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1290 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1291 }
1292 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css')) {
1293 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css');
1294 }
1295 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js')) {
1296 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js');
1297 }
1298 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css')) {
1299 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css');
1300 }
1301 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1302 }
1303
1304 public function deleteBlukForm($Request, $post)
1305 {
1306 if (isset($Request['formID'])) {
1307 $formID = wp_unslash($Request['formID']);
1308 } else {
1309 $formID = wp_unslash($post->formID);
1310 }
1311 if (is_null($formID) || !is_array($formID)) {
1312 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1313 }
1314 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1315 foreach ($formID as $id) {
1316 unlink($cssPath . 'bitform-' . $id . '.css');
1317 if (file_exists($cssPath . 'bitform-layout-' . $id . '.css')) {
1318 unlink($cssPath . 'bitform-layout-' . $id . '.css');
1319 }
1320 if (file_exists($cssPath . 'bitform-' . $id . '-formid' . '.css')) {
1321 unlink($cssPath . 'bitform-' . $id . '-formid' . '.css');
1322 }
1323 }
1324 $delete_status = static::$formModel->bulkDelete(
1325 [
1326 'id' => $formID,
1327 ]
1328 );
1329 $successMessageModel
1330 = new SuccessMessageModel();
1331 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1332
1333 $emailTemplateModel
1334 = new EmailTemplateModel();
1335 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1336
1337 $integrationModel = new IntegrationModel();
1338 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1339
1340 $workFlowModel = new WorkFlowModel();
1341 $deleteworkFlowStatus = $workFlowModel->bulkDelete(['form_id' => $formID]);
1342
1343 $reportsModel = new ReportsModel();
1344 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1345
1346 $formEntryModel = new FormEntryModel();
1347 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1348 $entries = [];
1349 foreach ($returnedEntries as $entryKey => $entryInfo) {
1350 if (!empty($entryInfo->id)) {
1351 $entries[] = $entryInfo->id;
1352 }
1353 }
1354 global $wpdb;
1355 $prefix = $wpdb->prefix;
1356 if (count($entries) > 0) {
1357 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1358 [
1359 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1360 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1361 ]
1362 );
1363 }
1364
1365 $fileHandler = new FileHandler();
1366 foreach ($formID as $fId) {
1367 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1368 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1369 }
1370
1371 // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1372 // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1373 }
1374
1375 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1376 }
1377
1378 public function genarateNewLayoutNField($layout, $fields, $oldId, $newId)
1379 {
1380 $newField = (object) [];
1381 foreach ($layout->lg as $ind => $itm) {
1382 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1383 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
1384 $layout->md[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->md[$ind]->i);
1385 $layout->sm[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->sm[$ind]->i);
1386 $newField->{$layout->lg[$ind]->i} = $fld_tmp;
1387 }
1388 return ['layout' => $layout, 'fields' => $newField];
1389 }
1390
1391 public function duplicateAForm($Request, $post)
1392 {
1393 $oldFormId = intval($post->id);
1394 $newFormId = intval($post->newFormId);
1395 if ($oldFormId < 1) {
1396 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1397 }
1398
1399 $formManager = new AdminFormManager($oldFormId);
1400 if (!$formManager->isExist()) {
1401 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1402 }
1403
1404 $duplicatedForm = $this->getAForm($Request, $post);
1405 $duplicatedForm['form_name'] = 'Duplicate of ' . $duplicatedForm['form_name'];
1406 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1407
1408 /* echo wp_json_encode($formData);
1409 \wp_die(); */
1410 $duplicateResponse = $this->createNewForm(null, $formData);
1411
1412 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1413 // duplicate stylesheet
1414 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1415 // layout style copy
1416 $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1417 $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1418 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1419 $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1420 fwrite($createStyleFile, $newStyle);
1421 fclose($createStyleFile);
1422 // style copy
1423 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1424 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1425 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1426 $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1427 fwrite($createStyleFile, $newStyle);
1428 fclose($createStyleFile);
1429 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1430 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1431 return $duplicatedForm;
1432 }
1433 return $duplicateResponse;
1434 }
1435
1436 public function importAForm($post)
1437 {
1438 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1439 $newFormId = intval($post->newFormId);
1440 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1441 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1442 }
1443 $importtedForm = (array)$post->formDetail;
1444 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1445 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1446 $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayout'];
1447 $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1448 unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1449 $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1450
1451 if (!empty($importtedForm['rowHeight'])) {
1452 $formData->rowHeight = $importtedForm['rowHeight'];
1453 }
1454
1455 if (!empty($importtedForm['formStyle'])) {
1456 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $importtedForm['formStyle']);
1457 $formData->layoutChanged = '-';
1458 }
1459 $importResponse = $this->createNewForm(null, $formData);
1460
1461 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1462 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1463 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1464 return $responseData;
1465 }
1466 return $importResponse;
1467 }
1468
1469 // public function exportAForm($Request) {
1470 // $oldFormId = intval($Request['id']);
1471 // if ($oldFormId < 1) {
1472 // return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1473 // }
1474 // $formManager = new AdminFormManager($oldFormId);
1475 // if (!$formManager->isExist()) {
1476 // return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1477 // }
1478
1479 // $newFormId = $oldFormId;
1480 // $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1481 // $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1482
1483 // $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1484 // $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1485 // $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1486
1487 // $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1488 // $formData->layoutChanged = '-';
1489 // $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1490
1491 // $formJson = wp_json_encode($formData);
1492 // header('Content-Type: application/force-download');
1493 // header('Content-Type: application/octet-stream');
1494 // header('Content-Type: application/download');
1495 // header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
1496 // header('Content-Description: File Transfer');
1497 // header('Expires: 0');
1498 // header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1499 // header('Pragma: public');
1500 // header('Content-Length: ' . strlen($formJson));
1501 // header('Content-Transfer-Encoding: binary ');
1502 // flush();
1503 // echo $formJson;
1504 // die();
1505 // }
1506
1507 public function exportAForm($Request, $post)
1508 {
1509 $oldFormId = intval($post->id);
1510 if ($oldFormId < 1) {
1511 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1512 }
1513 $formManager = new AdminFormManager($oldFormId);
1514 if (!$formManager->isExist()) {
1515 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1516 }
1517
1518 $newFormId = $oldFormId;
1519 $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1520 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1521 // for custom css
1522 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1523 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
1524 $customCssContain = Helpers::fileRead($cssPath);
1525 $formData->customCode = [];
1526 if ('' !== $customCssContain) {
1527 $formData->customCode['customCss'] = $customCssContain;
1528 }
1529 // for custom js
1530 $customJsPath = 'form-scripts/bitform-custom-' . $newFormId . '.js';
1531 $jsPath = Helpers::generatePathDirOrFile($customJsPath);
1532 $customJsContain = Helpers::fileRead($jsPath);
1533 if ('' !== $customJsContain) {
1534 $formData->customCode['customJs'] = $customJsContain;
1535 }
1536 return $formData;
1537 }
1538
1539 public function getFormEntryLabelAndCount($Request, $post)
1540 {
1541 if (isset($Request['id'])) {
1542 $id = wp_unslash($Request['id']);
1543 } else {
1544 $id = wp_unslash($post->id);
1545 }
1546 if (is_null($id)) {
1547 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1548 }
1549 $formManager = new AdminFormManager($id);
1550 if (!$formManager->isExist()) {
1551 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1552 }
1553 $formFields = $formManager->getFieldLabel();
1554 $formEntry = new FormEntryModel();
1555 $count = $formEntry->count(
1556 [
1557 'form_id' => $id,
1558 ]
1559 );
1560 $reportsModel = new ReportsModel();
1561 $returnedReportData = $reportsModel->get(
1562 [
1563 'id',
1564 'details',
1565 'isDefault',
1566 'type',
1567 ],
1568 [
1569 'category' => 'form',
1570 'context' => $id,
1571 ]
1572 );
1573 $labels = [];
1574 if (!is_wp_error($returnedReportData)) {
1575 $fieldNames = [];
1576 foreach ($formFields as $field) {
1577 $fieldNames[$field['key']] = $field['name'];
1578 $labels[$field['key']] = $field;
1579 }
1580 foreach ($returnedReportData as $reportKey => $reportData) {
1581 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1582 if (!empty($reportDetails) && is_string($reportDetails)) {
1583 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1584 } elseif (!empty($reportDetails)) {
1585 $returnedReportData[$reportKey]->details = $reportDetails;
1586 }
1587 }
1588 $response['reports'] = empty($returnedReportData) ? [] : $returnedReportData;
1589 }
1590
1591 $response['count'] = intval($count[0]->count);
1592 $response['Labels'] = $formFields;
1593 $response['fieldDetails'] = $labels;
1594 return $response;
1595 }
1596
1597 public function getFormEntry($Request, $post)
1598 {
1599 if (isset($Request['id'])) {
1600 $id = wp_unslash($Request['id']);
1601 $offset = isset($Request['offset']) ?
1602 wp_unslash($Request['offset']) : 0;
1603 $pageSize = isset($Request['pageSize']) ?
1604 wp_unslash($Request['pageSize']) : 10;
1605 } else {
1606 $id = wp_unslash($post->id);
1607 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1608 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1609 $offset = isset($post->offset) ? wp_unslash($post->offset) : 0;
1610 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1611 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1612 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1613 $pageSize = isset($post->pageSize) ?
1614 wp_unslash($post->pageSize) : 10;
1615 }
1616 if (is_null($id)) {
1617 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1618 }
1619 $formManager = new AdminFormManager($id);
1620 if (!$formManager->isExist()) {
1621 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1622 }
1623
1624 $formEntry = new FormEntryModel();
1625 $entries = $formEntry->get(
1626 'id',
1627 [
1628 'form_id' => $id,
1629 ],
1630 null,
1631 null,
1632 'created_at',
1633 'DESC'
1634 );
1635 if (is_wp_error($entries)) {
1636 if ('result_empty' === $entries->get_error_code()) {
1637 return [
1638 'count' => 0,
1639 'entries' => [],
1640 ];
1641 }
1642 return $entries;
1643 }
1644 $filter['field'] = $filters;
1645 $filter['global'] = $globalFilter;
1646
1647 $formFields = $formManager->getFieldLabel(true);
1648 $fieldDetails = $formManager->getFields();
1649
1650 $entryMeta = new FormEntryMetaModel();
1651 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1652 $customFieldHandler = new CustomFieldHandler();
1653 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1654 return $formEntries;
1655 }
1656
1657 public function getEntriesForReport($Request, $post)
1658 {
1659 if (isset($Request['id'])) {
1660 $id = wp_unslash($Request['id']);
1661 $offset = isset($Request['offset']) ?
1662 wp_unslash($Request['offset']) : null;
1663 $pageSize = isset($Request['pageSize']) ?
1664 wp_unslash($Request['pageSize']) : null;
1665 } else {
1666 $id = wp_unslash($post->id);
1667 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1668 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1669 $offset = isset($post->offset) ? wp_unslash($post->offset) : null;
1670 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1671 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1672 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1673 $pageSize = isset($post->pageSize) ?
1674 wp_unslash($post->pageSize) : null;
1675 }
1676 if (is_null($id)) {
1677 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1678 }
1679 $formManager = new AdminFormManager($id);
1680 if (!$formManager->isExist()) {
1681 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1682 }
1683
1684 $formEntry = new FormEntryModel();
1685 $entries = $formEntry->get(
1686 'id',
1687 [
1688 'form_id' => $id,
1689 ],
1690 null,
1691 null,
1692 'created_at',
1693 'DESC'
1694 );
1695 if (is_wp_error($entries)) {
1696 if ('result_empty' === $entries->get_error_code()) {
1697 return [
1698 'count' => 0,
1699 'entries' => [],
1700 ];
1701 }
1702 return $entries;
1703 }
1704 $filter['field'] = $filters;
1705 $filter['global'] = $globalFilter;
1706
1707 $formFields = $formManager->getFieldLabel(true);
1708 $fieldDetails = $formManager->getFields();
1709
1710 $entryMeta = new FormEntryMetaModel();
1711 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1712 $customFieldHandler = new CustomFieldHandler();
1713 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1714 $formEntries['entries'] = Helpers::filterNullEntries($formEntries['entries']);
1715 return $formEntries;
1716 }
1717
1718 public function getExportEntry($post)
1719 {
1720 $formId = wp_unslash($post->formId);
1721 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1722 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
1723 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1724 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1725 $formFields = json_decode($post->selectedField);
1726 if (is_null($formId)) {
1727 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1728 }
1729 $formManager = new AdminFormManager($formId);
1730 $fieldLabels = $formManager->getFieldLabel(true);
1731 if (!$formManager->isExist()) {
1732 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1733 }
1734
1735 $formEntry = new FormEntryModel();
1736 $entries = $formEntry->get(
1737 'id',
1738 [
1739 'form_id' => $formId,
1740 ],
1741 null,
1742 null,
1743 'created_at',
1744 'DESC'
1745 );
1746 if (is_wp_error($entries)) {
1747 if ('result_empty' === $entries->get_error_code()) {
1748 return [
1749 'count' => 0,
1750 'entries' => [],
1751 ];
1752 }
1753 return $entries;
1754 }
1755 $entryMeta = new FormEntryMetaModel();
1756 $filter = [];
1757 $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
1758 return $formEntries;
1759 }
1760
1761 public function deleteBlukFormEntries($Request, $post)
1762 {
1763 if (isset($Request['formID'])) {
1764 $formID = wp_unslash($Request['formID']);
1765 $entries = wp_unslash($Request['entries']);
1766 } else {
1767 $formID = wp_unslash($post->formID);
1768 $entries = wp_unslash($post->entries);
1769 }
1770 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1771 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1772 }
1773 $formManager = new AdminFormManager($formID);
1774 if (!$formManager->isExist()) {
1775 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1776 }
1777 $workFlowRunHelper = new WorkFlow($formID);
1778 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1779 $formManager,
1780 $formID,
1781 $entries
1782 );
1783 if (isset($workFlowreturnedOnDelete['entries'])) {
1784 if (0 === count($workFlowreturnedOnDelete['entries'])) {
1785 return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1786 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1787 $message = __('Entry Deleted successfully', 'bit-form');
1788 } else {
1789 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
1790 $entries = $workFlowreturnedOnDelete['entries'];
1791 $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
1792 }
1793 } else {
1794 $message = __('Entry Deleted successfully', 'bit-form');
1795 }
1796 global $wpdb;
1797 $prefix = $wpdb->prefix;
1798 $formEntryModel = new FormEntryModel();
1799 $delete_status = $formEntryModel->bulkDelete(
1800 [
1801 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1802 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1803 ]
1804 );
1805 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1806 $fileHandler = new FileHandler();
1807 foreach ($entries as $enrtyKey => $entryID) {
1808 $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
1809 if (file_exists($fileEntries)) {
1810 $fileHandler->rmrf($fileEntries);
1811 }
1812 }
1813 }
1814 $count = $formEntryModel->count(
1815 [
1816 'form_id' => $formID,
1817 ]
1818 );
1819 $formManager->resetSubmissionCount(intval($count[0]->count));
1820 if (is_wp_error($delete_status)) {
1821 return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
1822 }
1823 $result['message'] = $message;
1824 return $result;
1825 }
1826
1827 public function duplicateFormEntry($Request, $post)
1828 {
1829 if (isset($Request['formID'])) {
1830 $formID = wp_unslash($Request['formID']);
1831 $entries = wp_unslash($Request['entries']);
1832 } else {
1833 $formID = wp_unslash($post->formID);
1834 $entries = wp_unslash($post->entries);
1835 }
1836 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1837 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1838 }
1839
1840 $formManager = new AdminFormManager($formID);
1841 if (!$formManager->isExist()) {
1842 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1843 }
1844 $formEntryModel = new FormEntryModel();
1845 $entryMeta = new FormEntryMetaModel();
1846 $user_details = static::$ipTool->getUserDetail();
1847 $total_entries = count($entries);
1848 $duplicate_count = 0;
1849 $test = '';
1850 $fileHandler = new FileHandler();
1851 $result = [];
1852 foreach ($entries as $entryIndex => $entryID) {
1853 $duplicatedEntryId = $formEntryModel->insert(
1854 [
1855 'form_id' => $formID,
1856 'user_id' => $user_details['id'],
1857 'user_ip' => $user_details['ip'],
1858 'user_device' => $user_details['device'],
1859 'referer' => 'duplicate of #' . $entryID,
1860 'status' => 1,
1861 'created_at' => $user_details['time'],
1862 ]
1863 );
1864 if ($duplicatedEntryId) {
1865 $duplicate_status = $entryMeta->duplicateEntryMeta(
1866 [
1867 'duplicateID' => $duplicatedEntryId,
1868 'entryID' => $entryID,
1869 ]
1870 );
1871 if ($duplicate_status) {
1872 $result['details'][$entryID] = $duplicatedEntryId;
1873 $duplicate_count = $duplicate_count + 1;
1874 if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
1875 $fileHandler->cpyr(
1876 BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1877 BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
1878 );
1879 }
1880 }
1881 }
1882 }
1883
1884 $count = $formEntryModel->count(
1885 [
1886 'form_id' => $formID,
1887 ]
1888 );
1889 $formManager->resetSubmissionCount(intval($count[0]->count));
1890 $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
1891 return ($total_entries === $duplicate_count) ? $result : false;
1892 }
1893
1894 public function editFormEntry($Request, $post)
1895 {
1896 if (isset($Request['formID'])) {
1897 $formID = wp_unslash($Request['formID']);
1898 $entryID = wp_unslash($Request['entryID']);
1899 } else {
1900 $formID = wp_unslash($post->formID);
1901 $entryID = wp_unslash($post->entryID);
1902 }
1903 if (is_null($formID) || is_null($entryID)) {
1904 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1905 }
1906
1907 $formManager = new AdminFormManager($formID);
1908 if (!$formManager->isExist()) {
1909 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1910 }
1911 $formEntryModel = new FormEntryModel();
1912 $entryMeta = new FormEntryMetaModel();
1913
1914 $formEntry = $formEntryModel->get(
1915 '*',
1916 [
1917 'form_id' => $formID,
1918 'id' => $entryID,
1919 ]
1920 );
1921
1922 if (!$formEntry) {
1923 return new WP_Error('empty_form', __('Form entries does not exist.', 'bit-form'));
1924 }
1925 $formEntryMeta = $entryMeta->get(
1926 [
1927 'meta_key',
1928 'meta_value',
1929 ],
1930 [
1931 'bitforms_form_entry_id' => $entryID,
1932 ]
1933 );
1934 $entries = [];
1935 foreach ($formEntryMeta as $key => $value) {
1936 $entries[$value->meta_key] = $value->meta_value;
1937 }
1938 $formContent = $formManager->getFormContent();
1939 $fieldsKey = $formManager->getFieldsKey();
1940 $form_fields = $formContent->fields;
1941 $layout = $formContent->layout;
1942 foreach ($form_fields as $key => $value) {
1943 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
1944 if (isset($entries[$key])) {
1945 $form_fields->{$key}->val = $entries[$key];
1946 $form_fields->{$key}->name = $key;
1947 }
1948 }
1949 $workFlowRunHelper = new WorkFlow($formID);
1950 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
1951 'edit',
1952 $form_fields
1953 );
1954 $workFlowreturnedOnUserInput = $workFlowRunHelper->executeOnUserInput(
1955 'edit',
1956 $form_fields
1957 );
1958 if (!empty($workFlowreturnedOnLoad['fields'])) {
1959 $form_fields = $workFlowreturnedOnLoad['fields'];
1960 }
1961 $formData = [
1962 'layout' => $layout,
1963 'fields' => $form_fields,
1964 'conditional' => !empty($workFlowreturnedOnUserInput['conditional']) ? $workFlowreturnedOnUserInput['conditional'] : false,
1965 'fieldToCheck' => !empty($workFlowreturnedOnUserInput['fieldToCheck']) ? $workFlowreturnedOnUserInput['fieldToCheck'] : false,
1966 'fieldToChange' => !empty($workFlowreturnedOnUserInput['fieldToChange']) ? $workFlowreturnedOnUserInput['fieldToChange'] : false,
1967 'fieldsKey' => $fieldsKey,
1968 ];
1969 return $formData;
1970 }
1971
1972 public function updateFormEntry($Request, $post)
1973 {
1974 if (isset($Request['formID'], $Request['entryID'])) {
1975 $formID = wp_unslash($Request['formID']);
1976 $entryID = wp_unslash($Request['entryID']);
1977 unset($Request['action'], $Request['formID'], $Request['entryID']);
1978 }
1979 $formManager = new AdminFormManager($formID);
1980 $formManager->fieldNameReplaceOfPost();
1981 $updatedValue = wp_unslash($_POST);
1982
1983 if (is_null($updatedValue) || !is_array($updatedValue)) {
1984 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1985 }
1986
1987 if (is_null($formID) || is_null($entryID)) {
1988 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
1989 }
1990
1991 if (!$formManager->isExist()) {
1992 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
1993 }
1994 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
1995 }
1996
1997 public function getLogHistory($Request, $post)
1998 {
1999 if (isset($Request['formID'])) {
2000 $formID = wp_unslash($Request['formID']);
2001 $entryID = wp_unslash($Request['entryID']);
2002 } else {
2003 $formID = wp_unslash($post->formID);
2004 $entryID = wp_unslash($post->entryID);
2005 }
2006
2007 if (is_null($formID) || is_null($entryID)) {
2008 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
2009 }
2010
2011 $formManager = new AdminFormManager($formID);
2012 if (!$formManager->isExist()) {
2013 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
2014 }
2015 $formLogModel = new FormEntryLogModel();
2016
2017 $log_history = $formLogModel->geLogHistory($formID, $entryID);
2018 return $log_history;
2019 }
2020
2021 public function importDataStore($Request, $post)
2022 {
2023 if (isset($Request['formID'])) {
2024 $formID = wp_unslash($Request['formID']);
2025 } else {
2026 $formID = wp_unslash($post->formID);
2027 }
2028 if (is_null($formID)) {
2029 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
2030 }
2031 }
2032
2033 public function getAllWPPages($Request, $post)
2034 {
2035 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
2036 $allPages = [];
2037 foreach ($pages as $pageKey => $pageDetails) {
2038 $allPages[$pageKey]['title'] = $pageDetails->post_title;
2039 $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2040 }
2041 return $allPages;
2042 }
2043
2044 public function deleteAIntegration($Request, $post)
2045 {
2046 if (isset($Request['formID']) && $Request['id']) {
2047 $formID = json_decode(wp_unslash($Request['formID']));
2048 $id = wp_unslash($Request['id']);
2049 } else {
2050 $formID = wp_unslash($post->formID);
2051 $id = wp_unslash($post->id);
2052 }
2053 if ($formID < 0 || empty($id)) {
2054 return new WP_Error('empty_form', 'Invalid Form ID or Integration ID.');
2055 }
2056
2057 $integrationHandler = new IntegrationHandler($formID);
2058 $delete_status = $integrationHandler->deleteIntegration($id);
2059 if (is_wp_error($delete_status)) {
2060 return $delete_status;
2061 }
2062
2063 return [
2064 'message' => __('Integration deleted', 'bit-form'),
2065 ];
2066 }
2067
2068 public function deleteSuccessMessage($Request, $post)
2069 {
2070 if (isset($Request['formID']) && $Request['id']) {
2071 $formID = json_decode(wp_unslash($Request['formID']));
2072 $id = wp_unslash($Request['id']);
2073 } else {
2074 $formID = wp_unslash($post->formID);
2075 $id = wp_unslash($post->id);
2076 }
2077 if (empty($formID) || empty($id)) {
2078 return new WP_Error('empty_form', 'Invalid Form ID or Message ID.');
2079 }
2080 $successMessageHandler
2081 = new SuccessMessageHandler($formID);
2082 $delete_status = $successMessageHandler->deleteMessage($id);
2083 if (is_wp_error($delete_status)) {
2084 return $delete_status;
2085 }
2086 return [
2087 'message' => __('Message deleted', 'bit-form'),
2088 ];
2089 }
2090
2091 public function deleteAWorkflow($Request, $post)
2092 {
2093 if (isset($Request['formID']) && $Request['id']) {
2094 $formID = json_decode(wp_unslash($Request['formID']));
2095 $id = wp_unslash($Request['id']);
2096 } else {
2097 $formID = wp_unslash($post->formID);
2098 $id = wp_unslash($post->id);
2099 }
2100 if (empty($formID) || empty($id)) {
2101 return new WP_Error('empty_form', 'Invalid Form ID or Workflow ID.');
2102 }
2103 $workFlowHandler = new WorkFlowHandler($formID);
2104 $delete_status = $workFlowHandler->deleteworkFlow($id);
2105 if (is_wp_error($delete_status)) {
2106 return $delete_status;
2107 }
2108 return [
2109 'message' => __('workflow deleted', 'bit-form'),
2110 ];
2111 }
2112
2113 public function deleteAMailTemplate($Request, $post)
2114 {
2115 if (isset($Request['formID']) && $Request['id']) {
2116 $formID = json_decode(wp_unslash($Request['formID']));
2117 $id = wp_unslash($Request['id']);
2118 } else {
2119 $formID = wp_unslash($post->formID);
2120 $id = wp_unslash($post->id);
2121 }
2122 if (empty($formID) || empty($id)) {
2123 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2124 }
2125 $emailTemplateHandler = new EmailTemplateHandler($formID);
2126 $delete_status = $emailTemplateHandler->deleteTemplate($id);
2127 if (is_wp_error($delete_status)) {
2128 return $delete_status;
2129 }
2130 return [
2131 'message' => __('Email Template deleted', 'bit-form'),
2132 ];
2133 }
2134
2135 public function duplicateAMailTemplate($Request, $post)
2136 {
2137 if (isset($Request['formID']) && $Request['id']) {
2138 $formID = json_decode(wp_unslash($Request['formID']));
2139 $id = wp_unslash($Request['id']);
2140 } else {
2141 $formID = wp_unslash($post->formID);
2142 $id = wp_unslash($post->id);
2143 }
2144 if (empty($formID) || empty($id)) {
2145 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2146 }
2147 $emailTemplateHandler = new EmailTemplateHandler($formID);
2148 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
2149 if (is_wp_error($duplicate_status)) {
2150 return $duplicate_status;
2151 }
2152 return [
2153 'message' => __('Email Template duplicated', 'bit-form'),
2154 ];
2155 }
2156
2157 public function setAllFormsReport($Request, $post)
2158 {
2159 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
2160 if (empty($reports)) {
2161 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
2162 }
2163 if (!empty($reports)) {
2164 $reportsModel = new ReportsModel();
2165 $user_details = static::$ipTool->getUserDetail();
2166 foreach ($reports as $reportIndex => $report) {
2167 if (empty($report->id)) {
2168 $reportSaveSatus = $reportsModel->insert(
2169 [
2170 'type' => 'table',
2171 'category' => 'app',
2172 'context' => 'allForm',
2173 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2174 'isDefault' => 1,
2175 'user_id' => $user_details['id'],
2176 'user_ip' => $user_details['ip'],
2177 'user_device' => $user_details['device'],
2178 'created_at' => $user_details['time'],
2179 'updated_at' => $user_details['time'],
2180 ]
2181 );
2182 $newData['reports'] = 1;
2183 } else {
2184 $reportSaveSatus = $reportsModel->update(
2185 [
2186 'type' => 'table',
2187 'category' => 'app',
2188 'context' => 'allForm',
2189 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2190 'isDefault' => 1,
2191 'user_id' => $user_details['id'],
2192 'user_ip' => $user_details['ip'],
2193 'user_device' => $user_details['device'],
2194 'updated_at' => $user_details['time'],
2195 ],
2196 [
2197 'id' => $report->id,
2198 ]
2199 );
2200 }
2201 }
2202 }
2203 if (is_wp_error($reportSaveSatus)) {
2204 if ('result_empty' === $reportSaveSatus->get_error_code()) {
2205 return new WP_Error('empty_report_prefs', 'Nothing to save or update');
2206 }
2207 return new WP_Error('error_report_prefs', 'Error occured in saving reports');
2208 }
2209 $returnedReportData = $reportsModel->get(
2210 [
2211 'id',
2212 'details',
2213 'isDefault',
2214 'category',
2215 'context',
2216 ],
2217 [
2218 'category' => 'app',
2219 'context' => 'allForm',
2220 ]
2221 );
2222 if (!is_wp_error($returnedReportData)) {
2223 foreach ($returnedReportData as $reportKey => $reportData) {
2224 if (isset($reportData->details) && is_string($reportData->details)) {
2225 $returnedReportData[$reportKey]->details = json_decode($reportData->details);
2226 }
2227 }
2228 $reports = $returnedReportData;
2229 }
2230 return [
2231 'message' => __('Report preferrences saved successfully', 'bit-form'),
2232 'reports' => empty($reports) ? [] : $reports,
2233 ];
2234 }
2235
2236 public function savegReCaptcha($Request, $post)
2237 {
2238 $reCaptcha = $post->reCaptcha;
2239
2240 if (is_null($reCaptcha)) {
2241 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
2242 }
2243 if (is_string($reCaptcha) && !empty(json_decode($reCaptcha)->id)) {
2244 $reCaptcha = json_decode($reCaptcha);
2245 $integrationID = $reCaptcha->id;
2246 unset($reCaptcha->id);
2247 } else {
2248 $integrationID = $reCaptcha->id;
2249 unset($reCaptcha->id);
2250 }
2251 $reCaptcha = wp_json_encode($reCaptcha);
2252
2253 // $integrationName = 'google reCaptcha';
2254 $integrationName = $post->integrationName;
2255
2256 // $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
2257 $integrationType = $post->integrationType;
2258
2259 $integrationDetails = $reCaptcha;
2260 $user_details = static::$ipTool->getUserDetail();
2261 $integrationHandler = new IntegrationHandler(0, $user_details);
2262 $response = [];
2263 if (empty($integrationID)) {
2264 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2265 $response['id'] = $captchaSaveStatus;
2266 $response['message'] = __('reCAPTCHA saved successfully', 'bit-form');
2267 } else {
2268 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2269 $response['message'] = __('reCAPTCHA updated successfully', 'bit-form');
2270 }
2271
2272 if (is_wp_error($captchaSaveStatus)) {
2273 return $captchaSaveStatus;
2274 }
2275 return $response;
2276 }
2277
2278 public function savePaymentSetting($Request, $post)
2279 {
2280 if (isset($post->paySetting)) {
2281 $paySetting = $post->paySetting;
2282 }
2283 if (is_null($paySetting)) {
2284 return new WP_Error('empty_gcaptchdetails', __('Setting details is empty', 'bit-form'));
2285 }
2286 if (is_string($paySetting)) {
2287 $paySetting = json_decode($paySetting);
2288 }
2289 $canSave = null;
2290
2291 if ('PayPal' === $paySetting->type) {
2292 $canSave = $this->addWebhookToPaypal($paySetting);
2293 } elseif ('Razorpay' === $paySetting->type) {
2294 $canSave = true;
2295 } elseif ('Stripe' === $paySetting->type) {
2296 $canSave = $this->addWebhookToStripe($paySetting);
2297 }
2298 if (is_null($canSave)) {
2299 return new WP_Error('stripe', __('Please re-check your Client ID & Secret', 'bit-form'));
2300 }
2301 $integrationID = $paySetting->id;
2302 unset($paySetting->id);
2303 $integrationName = $paySetting->name;
2304 $integrationType = 'payments';
2305 $paySetting = wp_json_encode($paySetting);
2306 $integrationDetails = $paySetting;
2307 $user_details = static::$ipTool->getUserDetail();
2308 $integrationHandler = new IntegrationHandler(0, $user_details);
2309 $response = [];
2310 if (empty($integrationID)) {
2311 $paymentSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2312 $response['id'] = $paymentSaveStatus;
2313 $response['message'] = __('Payment setting saved successfully', 'bit-form');
2314 } else {
2315 $paymentSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2316 $response['message'] = __('Payment setting updated successfully', 'bit-form');
2317 }
2318
2319 if (is_wp_error($paymentSaveStatus)) {
2320 return $paymentSaveStatus;
2321 }
2322 return $response;
2323 }
2324
2325 private function addWebhookToPaypal($paySetting)
2326 {
2327 $transaction_mode = $paySetting->mode;
2328 $clientId = $paySetting->clientID;
2329 $clientSecret = $paySetting->clientSecret;
2330 $base_url = 'sandbox' === $transaction_mode ? 'https://api-m.sandbox.paypal.com' : 'https://api.paypal.com';
2331 // get all webhooks
2332 $webhooks_url = $base_url . '/v1/notifications/webhooks';
2333 $webhooks_headers = [
2334 'Content-Type' => 'application/json',
2335 'Authorization' => 'Basic ' . base64_encode($clientId . ':' . $clientSecret)
2336 ];
2337 $webhook_url = get_rest_url() . 'bitform/v1/payments/paypal';
2338 // adding webhook
2339 $data = [
2340 'url' => $webhook_url,
2341 'event_types' => [
2342 [
2343 'name' => 'CHECKOUT.ORDER.APPROVED'
2344 ]
2345 ]
2346 ];
2347 $webhook_response = HttpHelper::post($webhooks_url, wp_json_encode($data), $webhooks_headers);
2348 if (is_wp_error($webhook_response) || $webhook_response->error) {
2349 return null;
2350 }
2351 return true;
2352 }
2353
2354 private function addWebhookToStripe($paySetting)
2355 {
2356 $clientSecret = $paySetting->clientSecret;
2357
2358 $create_webhook_url = 'https://api.stripe.com/v1/webhook_endpoints';
2359 $headers = [
2360 'Content-Type' => 'application/x-www-form-urlencoded',
2361 'Authorization' => "Bearer $clientSecret",
2362 ];
2363
2364 $webhook_url = get_rest_url() . 'bitform/v1/payments/stripe';
2365
2366 $apiResponse = HttpHelper::get($create_webhook_url, '', $headers);
2367
2368 if (isset($apiResponse->error)) {
2369 return null;
2370 }
2371 $webhookList = $apiResponse->data;
2372 $webhook_already_exist = false;
2373
2374 foreach ($webhookList as $webhook) {
2375 if ($webhook->url === $webhook_url) {
2376 $webhook_already_exist = true;
2377 break;
2378 }
2379 }
2380
2381 $data = [
2382 'enabled_events[]' => 'payment_intent.succeeded',
2383 'url' => $webhook_url,
2384 ];
2385
2386 if (!$webhook_already_exist) {
2387 $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2388 if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2389 return null;
2390 }
2391 }
2392 return true;
2393 }
2394
2395 public function builerHelperState($formId)
2396 {
2397 $data = static::$formModel->get(
2398 ['id', 'builder_helper_state'],
2399 ['id' => $formId]
2400 );
2401
2402 if (!is_wp_error($data)) {
2403 foreach ($data as $key => $value) {
2404 if (isset($value->builder_helper_state) && is_string($value->builder_helper_state)) {
2405 $data[$key]->builder_helper_state = json_decode($value->builder_helper_state);
2406 }
2407 }
2408 }
2409
2410 return $data;
2411 }
2412
2413 public function updateGeneratedScriptPageIds()
2414 {
2415 $updateData = [
2416 'generated_script_page_ids' => \wp_json_encode((object) []),
2417 ];
2418 $update_status = static::$formModel->update(
2419 $updateData,
2420 [
2421 'status' => 1
2422 ]
2423 );
2424 if (is_wp_error($update_status)) {
2425 return $update_status;
2426 } elseif (!$update_status) {
2427 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
2428 } else {
2429 return true;
2430 }
2431 }
2432
2433 public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
2434 {
2435 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2436 return str_replace($TEMP_CONF_ID, $msgId, $str);
2437 }
2438 }
2439