PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.9.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.9.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 2.10.2 All 137 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.9.1, at includes/Admin/Form/AdminFormHandler.php

2,428 lines 90.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\ReportsModel;
18 use BitCode\BitForm\Core\Database\SuccessMessageModel;
19 use BitCode\BitForm\Core\Database\WorkFlowModel;
20 use BitCode\BitForm\Core\Integration\IntegrationHandler;
21 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
22 use BitCode\BitForm\Core\Messages\PdfTemplateHandler;
23 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
24 use BitCode\BitForm\Core\Util\FileHandler;
25 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
26 use BitCode\BitForm\Core\Util\HttpHelper;
27 use BitCode\BitForm\Core\Util\IpTool;
28 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
29 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
30 use BitCode\BitFormPro\Admin\AppSetting\Pdf;
31 use WP_Error;
32
33 class AdminFormHandler
34 {
35 private static $formModel;
36 private static $ipTool;
37
38 public function __construct()
39 {
40 static::$formModel = new FormModel();
41 static::$ipTool = new IpTool();
42 }
43
44 public function getTemplate($Request, $post)
45 {
46 $templateName = null;
47 $newFormId = null;
48 if (isset($post->template)) {
49 $templateName = $post->template;
50 $newFormId = $post->newFormId;
51 }
52
53 $templateProvider = new TemplateProvider();
54 $form_content_raw = $templateProvider->getTemplate($templateName, $newFormId);
55 if (!$form_content_raw) {
56 return new WP_Error('template_empty', __('Template not found, by this name: ', 'bit-form') . $templateName);
57 } else {
58 return \json_encode(
59 [
60 'id' => 0,
61 'form_content' => $form_content_raw,
62 ]
63 );
64 }
65 }
66
67 public function saveStyleSheet($styles, $sheetName)
68 {
69 $this->createFormStylesDirIfNotExists();
70
71 if (
72 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
73 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
74 ) {
75 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
76 fwrite($createStyleFile, $styles);
77 fclose($createStyleFile);
78 return true;
79 }
80 return false;
81 }
82
83 public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43)
84 {
85 $md_width = 600;
86 $sm_width = 400;
87 $lg_styles = '';
88 $md_styles = '';
89 $sm_styles = '';
90 for ($i = 0; $i < count($layout->lg); $i++) {
91 $fld = $layout->lg[$i];
92
93 if ($fld->w < 10) {
94 $lay_row_height = 43;
95 } else {
96 $lay_row_height = 2;
97 }
98
99 $class = $fld->i;
100 $lg_g_r_s = $fld->y + 1;
101 $lg_g_c_s = $fld->x + 1;
102 $lg_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
103 $lg_g_c_e = ($fld->x + 1) + $fld->w;
104 $lg_g_r_span = $lg_g_r_e - $lg_g_r_s;
105 $lg_g_c_span = $lg_g_c_e - $lg_g_c_s;
106 $lg_min_height = $fld->h * $lay_row_height . 'px;';
107
108 $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; }";
109
110 $fld = $layout->md[$i];
111
112 $class = $fld->i;
113 $md_g_r_s = $fld->y + 1;
114 $md_g_c_s = $fld->x + 1;
115 $md_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
116 $md_g_c_e = ($fld->x + 1) + $fld->w;
117 $md_g_r_span = $lg_g_r_e - $md_g_r_s;
118 $md_g_c_span = $lg_g_c_e - $md_g_c_s;
119 $md_min_height = $fld->h * $lay_row_height . 'px;';
120
121 $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; }";
122
123 $fld = $layout->sm[$i];
124
125 $class = $fld->i;
126 $sm_g_r_s = $fld->y + 1;
127 $sm_g_c_s = $fld->x + 1;
128 $sm_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
129 $sm_g_c_e = ($fld->x + 1) + $fld->w;
130 $sm_g_r_span = $sm_g_r_e - $sm_g_r_s;
131 $sm_g_c_span = $sm_g_c_e - $sm_g_c_s;
132 $sm_min_height = $fld->h * $lay_row_height . 'px;';
133
134 $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; }";
135 }
136 $formStyle = "._frm-g{
137 display: grid;
138 display: -ms-grid;
139 grid-template-columns: repeat( 6 , minmax( 30px , 1fr ));
140 -ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr );
141 }
142 {$lg_styles}
143 @media only screen and (max-width:{$md_width}px) {
144 ._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 );}
145 {$md_styles}
146 }
147 @media only screen and (max-width:{$sm_width}px) {
148 ._frm-g {grid-template-columns: repeat( 2 , minmax( 30px , 1fr ));-ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr );}
149 {$sm_styles}
150 }";
151
152 $this->createFormStylesDirIfNotExists();
153
154 if (
155 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
156 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
157 ) {
158 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
159 fwrite($createStyleFile, $formStyle);
160 fclose($createStyleFile);
161 return true;
162 }
163 return false;
164 }
165
166 public function createFormStylesDirIfNotExists()
167 {
168 if (!file_exists(BITFORMS_UPLOAD_DIR)) {
169 wp_mkdir_p(BITFORMS_UPLOAD_DIR);
170 }
171 if (!file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')) {
172 wp_mkdir_p(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles');
173 }
174 }
175
176 private function pdfFontDownload($fontName)
177 {
178 if (class_exists('\BitCode\BitFormPro\Admin\AppSetting\Pdf')) {
179 $pdf = new Pdf();
180 $pdf->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 : \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 : \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 : \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 : \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 : \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' => [],
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 = $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 = json_encode($formAbandonment);
777 $integrationHandler->updateIntegration($abandonmentIntegID, 'formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
778 } else {
779 $abandonmentIntegDetails = 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 $integrationModel = new IntegrationModel();
1248 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1249
1250 $workFlowModel = new WorkFlowModel();
1251 $deleteworkFlowStatus = $workFlowModel->delete(['form_id' => $formID]);
1252
1253 $reportsModel = new ReportsModel();
1254 $deleteReportStatus = $reportsModel->delete(['context' => $formID]);
1255
1256 $formEntryModel = new FormEntryModel();
1257 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1258 $entries = [];
1259
1260 if (!is_wp_error($returnedEntries)) {
1261 foreach ($returnedEntries as $entryKey => $entryInfo) {
1262 $entries[] = $entryInfo->id;
1263 }
1264 global $wpdb;
1265 $prefix = $wpdb->prefix;
1266 if (count($entries) > 0) {
1267 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1268 [
1269 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1270 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1271 ]
1272 );
1273 }
1274 }
1275
1276 $fileHandler = new FileHandler();
1277 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1278 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1279 }
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_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1284 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1285 }
1286 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1287 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1288 }
1289 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1290 }
1291
1292 public function deleteBlukForm($Request, $post)
1293 {
1294 if (isset($Request['formID'])) {
1295 $formID = wp_unslash($Request['formID']);
1296 } else {
1297 $formID = wp_unslash($post->formID);
1298 }
1299 if (is_null($formID) || !is_array($formID)) {
1300 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1301 }
1302 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1303 foreach ($formID as $id) {
1304 unlink($cssPath . 'bitform-' . $id . '.css');
1305 if (file_exists($cssPath . 'bitform-layout-' . $id . '.css')) {
1306 unlink($cssPath . 'bitform-layout-' . $id . '.css');
1307 }
1308 if (file_exists($cssPath . 'bitform-' . $id . '-formid' . '.css')) {
1309 unlink($cssPath . 'bitform-' . $id . '-formid' . '.css');
1310 }
1311 }
1312 $delete_status = static::$formModel->bulkDelete(
1313 [
1314 'id' => $formID,
1315 ]
1316 );
1317 $successMessageModel
1318 = new SuccessMessageModel();
1319 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1320
1321 $emailTemplateModel
1322 = new EmailTemplateModel();
1323 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1324
1325 $integrationModel = new IntegrationModel();
1326 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1327
1328 $workFlowModel = new WorkFlowModel();
1329 $deleteworkFlowStatus = $workFlowModel->bulkDelete(['form_id' => $formID]);
1330
1331 $reportsModel = new ReportsModel();
1332 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1333
1334 $formEntryModel = new FormEntryModel();
1335 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1336 $entries = [];
1337 foreach ($returnedEntries as $entryKey => $entryInfo) {
1338 $entries[] = $entryInfo->id;
1339 }
1340 global $wpdb;
1341 $prefix = $wpdb->prefix;
1342 if (count($entries) > 0) {
1343 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1344 [
1345 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1346 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1347 ]
1348 );
1349 }
1350
1351 $fileHandler = new FileHandler();
1352 foreach ($formID as $fId) {
1353 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1354 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1355 }
1356
1357 // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1358 // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1359 }
1360
1361 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1362 }
1363
1364 public function genarateNewLayoutNField($layout, $fields, $oldId, $newId)
1365 {
1366 $newField = (object) [];
1367 foreach ($layout->lg as $ind => $itm) {
1368 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1369 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
1370 $layout->md[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->md[$ind]->i);
1371 $layout->sm[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->sm[$ind]->i);
1372 $newField->{$layout->lg[$ind]->i} = $fld_tmp;
1373 }
1374 return ['layout' => $layout, 'fields' => $newField];
1375 }
1376
1377 public function duplicateAForm($Request, $post)
1378 {
1379 $oldFormId = intval($post->id);
1380 $newFormId = intval($post->newFormId);
1381 if ($oldFormId < 1) {
1382 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1383 }
1384
1385 $formManager = new AdminFormManager($oldFormId);
1386 if (!$formManager->isExist()) {
1387 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1388 }
1389
1390 $duplicatedForm = $this->getAForm($Request, $post);
1391 $duplicatedForm['form_name'] = 'Duplicate of ' . $duplicatedForm['form_name'];
1392 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1393
1394 /* echo wp_json_encode($formData);
1395 \wp_die(); */
1396 $duplicateResponse = $this->createNewForm(null, $formData);
1397
1398 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1399 // duplicate stylesheet
1400 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1401 // layout style copy
1402 $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1403 $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1404 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1405 $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1406 fwrite($createStyleFile, $newStyle);
1407 fclose($createStyleFile);
1408 // style copy
1409 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1410 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1411 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1412 $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1413 fwrite($createStyleFile, $newStyle);
1414 fclose($createStyleFile);
1415 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1416 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1417 return $duplicatedForm;
1418 }
1419 return $duplicateResponse;
1420 }
1421
1422 public function importAForm($post)
1423 {
1424 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1425 $newFormId = intval($post->newFormId);
1426 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1427 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1428 }
1429 $importtedForm = (array)$post->formDetail;
1430 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1431 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1432 $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayout'];
1433 $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1434 unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1435 $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1436
1437 if (!empty($importtedForm['rowHeight'])) {
1438 $formData->rowHeight = $importtedForm['rowHeight'];
1439 }
1440
1441 if (!empty($importtedForm['formStyle'])) {
1442 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $importtedForm['formStyle']);
1443 $formData->layoutChanged = '-';
1444 }
1445 $importResponse = $this->createNewForm(null, $formData);
1446
1447 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1448 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1449 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1450 return $responseData;
1451 }
1452 return $importResponse;
1453 }
1454
1455 // public function exportAForm($Request) {
1456 // $oldFormId = intval($Request['id']);
1457 // if ($oldFormId < 1) {
1458 // return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1459 // }
1460 // $formManager = new AdminFormManager($oldFormId);
1461 // if (!$formManager->isExist()) {
1462 // return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1463 // }
1464
1465 // $newFormId = $oldFormId;
1466 // $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1467 // $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1468
1469 // $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1470 // $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1471 // $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1472
1473 // $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1474 // $formData->layoutChanged = '-';
1475 // $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1476
1477 // $formJson = json_encode($formData);
1478 // header('Content-Type: application/force-download');
1479 // header('Content-Type: application/octet-stream');
1480 // header('Content-Type: application/download');
1481 // header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
1482 // header('Content-Description: File Transfer');
1483 // header('Expires: 0');
1484 // header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1485 // header('Pragma: public');
1486 // header('Content-Length: ' . strlen($formJson));
1487 // header('Content-Transfer-Encoding: binary ');
1488 // flush();
1489 // echo $formJson;
1490 // die();
1491 // }
1492
1493 public function exportAForm($Request, $post)
1494 {
1495 $oldFormId = intval($post->id);
1496 if ($oldFormId < 1) {
1497 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1498 }
1499 $formManager = new AdminFormManager($oldFormId);
1500 if (!$formManager->isExist()) {
1501 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1502 }
1503
1504 $newFormId = $oldFormId;
1505 $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1506 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1507 // for custom css
1508 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1509 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
1510 $customCssContain = Helpers::fileRead($cssPath);
1511 $formData->customCode = [];
1512 if ('' !== $customCssContain) {
1513 $formData->customCode['customCss'] = $customCssContain;
1514 }
1515 // for custom js
1516 $customJsPath = 'form-scripts/bitform-custom-' . $newFormId . '.js';
1517 $jsPath = Helpers::generatePathDirOrFile($customJsPath);
1518 $customJsContain = Helpers::fileRead($jsPath);
1519 if ('' !== $customJsContain) {
1520 $formData->customCode['customJs'] = $customJsContain;
1521 }
1522 return $formData;
1523 }
1524
1525 public function getFormEntryLabelAndCount($Request, $post)
1526 {
1527 if (isset($Request['id'])) {
1528 $id = wp_unslash($Request['id']);
1529 } else {
1530 $id = wp_unslash($post->id);
1531 }
1532 if (is_null($id)) {
1533 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1534 }
1535 $formManager = new AdminFormManager($id);
1536 if (!$formManager->isExist()) {
1537 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1538 }
1539 $formFields = $formManager->getFieldLabel();
1540 $formEntry = new FormEntryModel();
1541 $count = $formEntry->count(
1542 [
1543 'form_id' => $id,
1544 ]
1545 );
1546 $reportsModel = new ReportsModel();
1547 $returnedReportData = $reportsModel->get(
1548 [
1549 'id',
1550 'details',
1551 'isDefault',
1552 'type',
1553 ],
1554 [
1555 'category' => 'form',
1556 'context' => $id,
1557 ]
1558 );
1559 $labels = [];
1560 if (!is_wp_error($returnedReportData)) {
1561 $fieldNames = [];
1562 foreach ($formFields as $field) {
1563 $fieldNames[$field['key']] = $field['name'];
1564 $labels[$field['key']] = $field;
1565 }
1566 foreach ($returnedReportData as $reportKey => $reportData) {
1567 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1568 if (!empty($reportDetails) && is_string($reportDetails)) {
1569 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1570 } elseif (!empty($reportDetails)) {
1571 $returnedReportData[$reportKey]->details = $reportDetails;
1572 }
1573 }
1574 $response['reports'] = empty($returnedReportData) ? [] : $returnedReportData;
1575 }
1576
1577 $response['count'] = intval($count[0]->count);
1578 $response['Labels'] = $formFields;
1579 $response['fieldDetails'] = $labels;
1580 return $response;
1581 }
1582
1583 public function getFormEntry($Request, $post)
1584 {
1585 if (isset($Request['id'])) {
1586 $id = wp_unslash($Request['id']);
1587 $offset = isset($Request['offset']) ?
1588 wp_unslash($Request['offset']) : 0;
1589 $pageSize = isset($Request['pageSize']) ?
1590 wp_unslash($Request['pageSize']) : 10;
1591 } else {
1592 $id = wp_unslash($post->id);
1593 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1594 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1595 $offset = isset($post->offset) ? wp_unslash($post->offset) : 0;
1596 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1597 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1598 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1599 $pageSize = isset($post->pageSize) ?
1600 wp_unslash($post->pageSize) : 10;
1601 }
1602 if (is_null($id)) {
1603 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1604 }
1605 $formManager = new AdminFormManager($id);
1606 if (!$formManager->isExist()) {
1607 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1608 }
1609
1610 $formEntry = new FormEntryModel();
1611 $entries = $formEntry->get(
1612 'id',
1613 [
1614 'form_id' => $id,
1615 ],
1616 null,
1617 null,
1618 'created_at',
1619 'DESC'
1620 );
1621 if (is_wp_error($entries)) {
1622 if ('result_empty' === $entries->get_error_code()) {
1623 return [
1624 'count' => 0,
1625 'entries' => [],
1626 ];
1627 }
1628 return $entries;
1629 }
1630 $filter['field'] = $filters;
1631 $filter['global'] = $globalFilter;
1632
1633 $formFields = $formManager->getFieldLabel(true);
1634 $fieldDetails = $formManager->getFields();
1635
1636 $entryMeta = new FormEntryMetaModel();
1637 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1638 $customFieldHandler = new CustomFieldHandler();
1639 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1640 return $formEntries;
1641 }
1642
1643 public function getEntriesForReport($Request, $post)
1644 {
1645 if (isset($Request['id'])) {
1646 $id = wp_unslash($Request['id']);
1647 $offset = isset($Request['offset']) ?
1648 wp_unslash($Request['offset']) : null;
1649 $pageSize = isset($Request['pageSize']) ?
1650 wp_unslash($Request['pageSize']) : null;
1651 } else {
1652 $id = wp_unslash($post->id);
1653 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1654 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1655 $offset = isset($post->offset) ? wp_unslash($post->offset) : null;
1656 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1657 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1658 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1659 $pageSize = isset($post->pageSize) ?
1660 wp_unslash($post->pageSize) : null;
1661 }
1662 if (is_null($id)) {
1663 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1664 }
1665 $formManager = new AdminFormManager($id);
1666 if (!$formManager->isExist()) {
1667 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1668 }
1669
1670 $formEntry = new FormEntryModel();
1671 $entries = $formEntry->get(
1672 'id',
1673 [
1674 'form_id' => $id,
1675 ],
1676 null,
1677 null,
1678 'created_at',
1679 'DESC'
1680 );
1681 if (is_wp_error($entries)) {
1682 if ('result_empty' === $entries->get_error_code()) {
1683 return [
1684 'count' => 0,
1685 'entries' => [],
1686 ];
1687 }
1688 return $entries;
1689 }
1690 $filter['field'] = $filters;
1691 $filter['global'] = $globalFilter;
1692
1693 $formFields = $formManager->getFieldLabel(true);
1694 $fieldDetails = $formManager->getFields();
1695
1696 $entryMeta = new FormEntryMetaModel();
1697 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1698 $customFieldHandler = new CustomFieldHandler();
1699 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1700 $formEntries['entries'] = Helpers::filterNullEntries($formEntries['entries']);
1701 return $formEntries;
1702 }
1703
1704 public function getExportEntry($post)
1705 {
1706 $formId = wp_unslash($post->formId);
1707 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1708 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
1709 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1710 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1711 $formFields = json_decode($post->selectedField);
1712 if (is_null($formId)) {
1713 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1714 }
1715 $formManager = new AdminFormManager($formId);
1716 $fieldLabels = $formManager->getFieldLabel(true);
1717 if (!$formManager->isExist()) {
1718 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1719 }
1720
1721 $formEntry = new FormEntryModel();
1722 $entries = $formEntry->get(
1723 'id',
1724 [
1725 'form_id' => $formId,
1726 ],
1727 null,
1728 null,
1729 'created_at',
1730 'DESC'
1731 );
1732 if (is_wp_error($entries)) {
1733 if ('result_empty' === $entries->get_error_code()) {
1734 return [
1735 'count' => 0,
1736 'entries' => [],
1737 ];
1738 }
1739 return $entries;
1740 }
1741 $entryMeta = new FormEntryMetaModel();
1742 $filter = [];
1743 $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
1744 return $formEntries;
1745 }
1746
1747 public function deleteBlukFormEntries($Request, $post)
1748 {
1749 if (isset($Request['formID'])) {
1750 $formID = wp_unslash($Request['formID']);
1751 $entries = wp_unslash($Request['entries']);
1752 } else {
1753 $formID = wp_unslash($post->formID);
1754 $entries = wp_unslash($post->entries);
1755 }
1756 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1757 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1758 }
1759 $formManager = new AdminFormManager($formID);
1760 if (!$formManager->isExist()) {
1761 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1762 }
1763 $workFlowRunHelper = new WorkFlow($formID);
1764 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1765 $formManager,
1766 $formID,
1767 $entries
1768 );
1769 if (isset($workFlowreturnedOnDelete['entries'])) {
1770 if (0 === count($workFlowreturnedOnDelete['entries'])) {
1771 return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1772 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1773 $message = __('Entry Deleted successfully', 'bit-form');
1774 } else {
1775 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
1776 $entries = $workFlowreturnedOnDelete['entries'];
1777 $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
1778 }
1779 } else {
1780 $message = __('Entry Deleted successfully', 'bit-form');
1781 }
1782 global $wpdb;
1783 $prefix = $wpdb->prefix;
1784 $formEntryModel = new FormEntryModel();
1785 $delete_status = $formEntryModel->bulkDelete(
1786 [
1787 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1788 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1789 ]
1790 );
1791 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1792 $fileHandler = new FileHandler();
1793 foreach ($entries as $enrtyKey => $entryID) {
1794 $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
1795 if (file_exists($fileEntries)) {
1796 $fileHandler->rmrf($fileEntries);
1797 }
1798 }
1799 }
1800 $count = $formEntryModel->count(
1801 [
1802 'form_id' => $formID,
1803 ]
1804 );
1805 $formManager->resetSubmissionCount(intval($count[0]->count));
1806 if (is_wp_error($delete_status)) {
1807 return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
1808 }
1809 $result['message'] = $message;
1810 return $result;
1811 }
1812
1813 public function duplicateFormEntry($Request, $post)
1814 {
1815 if (isset($Request['formID'])) {
1816 $formID = wp_unslash($Request['formID']);
1817 $entries = wp_unslash($Request['entries']);
1818 } else {
1819 $formID = wp_unslash($post->formID);
1820 $entries = wp_unslash($post->entries);
1821 }
1822 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1823 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1824 }
1825
1826 $formManager = new AdminFormManager($formID);
1827 if (!$formManager->isExist()) {
1828 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1829 }
1830 $formEntryModel = new FormEntryModel();
1831 $entryMeta = new FormEntryMetaModel();
1832 $user_details = static::$ipTool->getUserDetail();
1833 $total_entries = count($entries);
1834 $duplicate_count = 0;
1835 $test = '';
1836 $fileHandler = new FileHandler();
1837 $result = [];
1838 foreach ($entries as $entryIndex => $entryID) {
1839 $duplicatedEntryId = $formEntryModel->insert(
1840 [
1841 'form_id' => $formID,
1842 'user_id' => $user_details['id'],
1843 'user_ip' => $user_details['ip'],
1844 'user_device' => $user_details['device'],
1845 'referer' => 'duplicate of #' . $entryID,
1846 'status' => 1,
1847 'created_at' => $user_details['time'],
1848 ]
1849 );
1850 if ($duplicatedEntryId) {
1851 $duplicate_status = $entryMeta->duplicateEntryMeta(
1852 [
1853 'duplicateID' => $duplicatedEntryId,
1854 'entryID' => $entryID,
1855 ]
1856 );
1857 if ($duplicate_status) {
1858 $result['details'][$entryID] = $duplicatedEntryId;
1859 $duplicate_count = $duplicate_count + 1;
1860 if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
1861 $fileHandler->cpyr(
1862 BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1863 BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
1864 );
1865 }
1866 }
1867 }
1868 }
1869
1870 $count = $formEntryModel->count(
1871 [
1872 'form_id' => $formID,
1873 ]
1874 );
1875 $formManager->resetSubmissionCount(intval($count[0]->count));
1876 $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
1877 return ($total_entries === $duplicate_count) ? $result : false;
1878 }
1879
1880 public function editFormEntry($Request, $post)
1881 {
1882 if (isset($Request['formID'])) {
1883 $formID = wp_unslash($Request['formID']);
1884 $entryID = wp_unslash($Request['entryID']);
1885 } else {
1886 $formID = wp_unslash($post->formID);
1887 $entryID = wp_unslash($post->entryID);
1888 }
1889 if (is_null($formID) || is_null($entryID)) {
1890 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1891 }
1892
1893 $formManager = new AdminFormManager($formID);
1894 if (!$formManager->isExist()) {
1895 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1896 }
1897 $formEntryModel = new FormEntryModel();
1898 $entryMeta = new FormEntryMetaModel();
1899
1900 $formEntry = $formEntryModel->get(
1901 '*',
1902 [
1903 'form_id' => $formID,
1904 'id' => $entryID,
1905 ]
1906 );
1907
1908 if (!$formEntry) {
1909 return new WP_Error('empty_form', __('Form entries does not exist.', 'bit-form'));
1910 }
1911 $formEntryMeta = $entryMeta->get(
1912 [
1913 'meta_key',
1914 'meta_value',
1915 ],
1916 [
1917 'bitforms_form_entry_id' => $entryID,
1918 ]
1919 );
1920 $entries = [];
1921 foreach ($formEntryMeta as $key => $value) {
1922 $entries[$value->meta_key] = $value->meta_value;
1923 }
1924 $formContent = $formManager->getFormContent();
1925 $fieldsKey = $formManager->getFieldsKey();
1926 $form_fields = $formContent->fields;
1927 $layout = $formContent->layout;
1928 foreach ($form_fields as $key => $value) {
1929 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
1930 if (isset($entries[$key])) {
1931 $form_fields->{$key}->val = $entries[$key];
1932 $form_fields->{$key}->name = $key;
1933 }
1934 }
1935 $workFlowRunHelper = new WorkFlow($formID);
1936 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
1937 'edit',
1938 $form_fields
1939 );
1940 $workFlowreturnedOnUserInput = $workFlowRunHelper->executeOnUserInput(
1941 'edit',
1942 $form_fields
1943 );
1944 if (!empty($workFlowreturnedOnLoad['fields'])) {
1945 $form_fields = $workFlowreturnedOnLoad['fields'];
1946 }
1947 $formData = [
1948 'layout' => $layout,
1949 'fields' => $form_fields,
1950 'conditional' => !empty($workFlowreturnedOnUserInput['conditional']) ? $workFlowreturnedOnUserInput['conditional'] : false,
1951 'fieldToCheck' => !empty($workFlowreturnedOnUserInput['fieldToCheck']) ? $workFlowreturnedOnUserInput['fieldToCheck'] : false,
1952 'fieldToChange' => !empty($workFlowreturnedOnUserInput['fieldToChange']) ? $workFlowreturnedOnUserInput['fieldToChange'] : false,
1953 'fieldsKey' => $fieldsKey,
1954 ];
1955 return $formData;
1956 }
1957
1958 public function updateFormEntry($Request, $post)
1959 {
1960 if (isset($Request['formID'], $Request['entryID'])) {
1961 $formID = wp_unslash($Request['formID']);
1962 $entryID = wp_unslash($Request['entryID']);
1963 unset($Request['action'], $Request['formID'], $Request['entryID']);
1964 }
1965 $formManager = new AdminFormManager($formID);
1966 $formManager->fieldNameReplaceOfPost();
1967 $updatedValue = wp_unslash($_POST);
1968
1969 if (is_null($updatedValue) || !is_array($updatedValue)) {
1970 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1971 }
1972
1973 if (is_null($formID) || is_null($entryID)) {
1974 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
1975 }
1976
1977 if (!$formManager->isExist()) {
1978 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
1979 }
1980 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
1981 }
1982
1983 public function getLogHistory($Request, $post)
1984 {
1985 if (isset($Request['formID'])) {
1986 $formID = wp_unslash($Request['formID']);
1987 $entryID = wp_unslash($Request['entryID']);
1988 } else {
1989 $formID = wp_unslash($post->formID);
1990 $entryID = wp_unslash($post->entryID);
1991 }
1992
1993 if (is_null($formID) || is_null($entryID)) {
1994 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1995 }
1996
1997 $formManager = new AdminFormManager($formID);
1998 if (!$formManager->isExist()) {
1999 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
2000 }
2001 $formLogModel = new FormEntryLogModel();
2002
2003 $log_history = $formLogModel->geLogHistory($formID, $entryID);
2004 return $log_history;
2005 }
2006
2007 public function importDataStore($Request, $post)
2008 {
2009 if (isset($Request['formID'])) {
2010 $formID = wp_unslash($Request['formID']);
2011 } else {
2012 $formID = wp_unslash($post->formID);
2013 }
2014 if (is_null($formID)) {
2015 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
2016 }
2017 }
2018
2019 public function getAllWPPages($Request, $post)
2020 {
2021 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
2022 $allPages = [];
2023 foreach ($pages as $pageKey => $pageDetails) {
2024 $allPages[$pageKey]['title'] = $pageDetails->post_title;
2025 $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2026 }
2027 return $allPages;
2028 }
2029
2030 public function deleteAIntegration($Request, $post)
2031 {
2032 if (isset($Request['formID']) && $Request['id']) {
2033 $formID = json_decode(wp_unslash($Request['formID']));
2034 $id = wp_unslash($Request['id']);
2035 } else {
2036 $formID = wp_unslash($post->formID);
2037 $id = wp_unslash($post->id);
2038 }
2039 if ($formID < 0 || empty($id)) {
2040 return new WP_Error('empty_form', 'Invalid Form ID or Integration ID.');
2041 }
2042
2043 $integrationHandler = new IntegrationHandler($formID);
2044 $delete_status = $integrationHandler->deleteIntegration($id);
2045 if (is_wp_error($delete_status)) {
2046 return $delete_status;
2047 }
2048
2049 return [
2050 'message' => __('Integration deleted', 'bit-form'),
2051 ];
2052 }
2053
2054 public function deleteSuccessMessage($Request, $post)
2055 {
2056 if (isset($Request['formID']) && $Request['id']) {
2057 $formID = json_decode(wp_unslash($Request['formID']));
2058 $id = wp_unslash($Request['id']);
2059 } else {
2060 $formID = wp_unslash($post->formID);
2061 $id = wp_unslash($post->id);
2062 }
2063 if (empty($formID) || empty($id)) {
2064 return new WP_Error('empty_form', 'Invalid Form ID or Message ID.');
2065 }
2066 $successMessageHandler
2067 = new SuccessMessageHandler($formID);
2068 $delete_status = $successMessageHandler->deleteMessage($id);
2069 if (is_wp_error($delete_status)) {
2070 return $delete_status;
2071 }
2072 return [
2073 'message' => __('Message deleted', 'bit-form'),
2074 ];
2075 }
2076
2077 public function deleteAWorkflow($Request, $post)
2078 {
2079 if (isset($Request['formID']) && $Request['id']) {
2080 $formID = json_decode(wp_unslash($Request['formID']));
2081 $id = wp_unslash($Request['id']);
2082 } else {
2083 $formID = wp_unslash($post->formID);
2084 $id = wp_unslash($post->id);
2085 }
2086 if (empty($formID) || empty($id)) {
2087 return new WP_Error('empty_form', 'Invalid Form ID or Workflow ID.');
2088 }
2089 $workFlowHandler = new WorkFlowHandler($formID);
2090 $delete_status = $workFlowHandler->deleteworkFlow($id);
2091 if (is_wp_error($delete_status)) {
2092 return $delete_status;
2093 }
2094 return [
2095 'message' => __('workflow deleted', 'bit-form'),
2096 ];
2097 }
2098
2099 public function deleteAMailTemplate($Request, $post)
2100 {
2101 if (isset($Request['formID']) && $Request['id']) {
2102 $formID = json_decode(wp_unslash($Request['formID']));
2103 $id = wp_unslash($Request['id']);
2104 } else {
2105 $formID = wp_unslash($post->formID);
2106 $id = wp_unslash($post->id);
2107 }
2108 if (empty($formID) || empty($id)) {
2109 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2110 }
2111 $emailTemplateHandler = new EmailTemplateHandler($formID);
2112 $delete_status = $emailTemplateHandler->deleteTemplate($id);
2113 if (is_wp_error($delete_status)) {
2114 return $delete_status;
2115 }
2116 return [
2117 'message' => __('Email Template deleted', 'bit-form'),
2118 ];
2119 }
2120
2121 public function duplicateAMailTemplate($Request, $post)
2122 {
2123 if (isset($Request['formID']) && $Request['id']) {
2124 $formID = json_decode(wp_unslash($Request['formID']));
2125 $id = wp_unslash($Request['id']);
2126 } else {
2127 $formID = wp_unslash($post->formID);
2128 $id = wp_unslash($post->id);
2129 }
2130 if (empty($formID) || empty($id)) {
2131 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2132 }
2133 $emailTemplateHandler = new EmailTemplateHandler($formID);
2134 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
2135 if (is_wp_error($duplicate_status)) {
2136 return $duplicate_status;
2137 }
2138 return [
2139 'message' => __('Email Template duplicated', 'bit-form'),
2140 ];
2141 }
2142
2143 public function setAllFormsReport($Request, $post)
2144 {
2145 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
2146 if (empty($reports)) {
2147 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
2148 }
2149 if (!empty($reports)) {
2150 $reportsModel = new ReportsModel();
2151 $user_details = static::$ipTool->getUserDetail();
2152 foreach ($reports as $reportIndex => $report) {
2153 if (empty($report->id)) {
2154 $reportSaveSatus = $reportsModel->insert(
2155 [
2156 'type' => 'table',
2157 'category' => 'app',
2158 'context' => 'allForm',
2159 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2160 'isDefault' => 1,
2161 'user_id' => $user_details['id'],
2162 'user_ip' => $user_details['ip'],
2163 'user_device' => $user_details['device'],
2164 'created_at' => $user_details['time'],
2165 'updated_at' => $user_details['time'],
2166 ]
2167 );
2168 $newData['reports'] = 1;
2169 } else {
2170 $reportSaveSatus = $reportsModel->update(
2171 [
2172 'type' => 'table',
2173 'category' => 'app',
2174 'context' => 'allForm',
2175 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2176 'isDefault' => 1,
2177 'user_id' => $user_details['id'],
2178 'user_ip' => $user_details['ip'],
2179 'user_device' => $user_details['device'],
2180 'updated_at' => $user_details['time'],
2181 ],
2182 [
2183 'id' => $report->id,
2184 ]
2185 );
2186 }
2187 }
2188 }
2189 if (is_wp_error($reportSaveSatus)) {
2190 if ('result_empty' === $reportSaveSatus->get_error_code()) {
2191 return new WP_Error('empty_report_prefs', 'Nothing to save or update');
2192 }
2193 return new WP_Error('error_report_prefs', 'Error occured in saving reports');
2194 }
2195 $returnedReportData = $reportsModel->get(
2196 [
2197 'id',
2198 'details',
2199 'isDefault',
2200 'category',
2201 'context',
2202 ],
2203 [
2204 'category' => 'app',
2205 'context' => 'allForm',
2206 ]
2207 );
2208 if (!is_wp_error($returnedReportData)) {
2209 foreach ($returnedReportData as $reportKey => $reportData) {
2210 if (isset($reportData->details) && is_string($reportData->details)) {
2211 $returnedReportData[$reportKey]->details = json_decode($reportData->details);
2212 }
2213 }
2214 $reports = $returnedReportData;
2215 }
2216 return [
2217 'message' => __('Report preferrences saved successfully', 'bit-form'),
2218 'reports' => empty($reports) ? [] : $reports,
2219 ];
2220 }
2221
2222 public function savegReCaptcha($Request, $post)
2223 {
2224 $reCaptcha = $post->reCaptcha;
2225
2226 if (is_null($reCaptcha)) {
2227 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
2228 }
2229 if (is_string($reCaptcha) && !empty(json_decode($reCaptcha)->id)) {
2230 $reCaptcha = json_decode($reCaptcha);
2231 $integrationID = $reCaptcha->id;
2232 unset($reCaptcha->id);
2233 } else {
2234 $integrationID = $reCaptcha->id;
2235 unset($reCaptcha->id);
2236 }
2237 $reCaptcha = json_encode($reCaptcha);
2238
2239 // $integrationName = 'google reCaptcha';
2240 $integrationName = $post->integrationName;
2241
2242 // $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
2243 $integrationType = $post->integrationType;
2244
2245 $integrationDetails = $reCaptcha;
2246 $user_details = static::$ipTool->getUserDetail();
2247 $integrationHandler = new IntegrationHandler(0, $user_details);
2248 $response = [];
2249 if (empty($integrationID)) {
2250 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2251 $response['id'] = $captchaSaveStatus;
2252 $response['message'] = __('reCAPTCHA saved successfully', 'bit-form');
2253 } else {
2254 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2255 $response['message'] = __('reCAPTCHA updated successfully', 'bit-form');
2256 }
2257
2258 if (is_wp_error($captchaSaveStatus)) {
2259 return $captchaSaveStatus;
2260 }
2261 return $response;
2262 }
2263
2264 public function savePaymentSetting($Request, $post)
2265 {
2266 if (isset($post->paySetting)) {
2267 $paySetting = $post->paySetting;
2268 }
2269 if (is_null($paySetting)) {
2270 return new WP_Error('empty_gcaptchdetails', __('Setting details is empty', 'bit-form'));
2271 }
2272 if (is_string($paySetting)) {
2273 $paySetting = json_decode($paySetting);
2274 }
2275 $canSave = null;
2276 // $checkedCanSave = [
2277 // 'PayPal' => $this->addWebhookToPaypal($paySetting),
2278 // 'Razorpay' => true,
2279 // 'Stripe' => $this->addWebhookToStripe($paySetting),
2280 // ];
2281 // $canSave = $checkedCanSave[$paySetting->type];
2282 if ('PayPal' === $paySetting->type) {
2283 $canSave = $this->addWebhookToPaypal($paySetting);
2284 } elseif ('Razorpay' === $paySetting->type) {
2285 $canSave = true;
2286 } elseif ('Stripe' === $paySetting->type) {
2287 $canSave = $this->addWebhookToStripe($paySetting);
2288 }
2289 if (is_null($canSave)) {
2290 return ['message' => __('Please re-check your Client ID & Secret', 'bit-form')];
2291 }
2292 $integrationID = $paySetting->id;
2293 unset($paySetting->id);
2294 $integrationName = $paySetting->name;
2295 $integrationType = 'payments';
2296 $paySetting = json_encode($paySetting);
2297 $integrationDetails = $paySetting;
2298 $user_details = static::$ipTool->getUserDetail();
2299 $integrationHandler = new IntegrationHandler(0, $user_details);
2300 $response = [];
2301 if (empty($integrationID)) {
2302 $paymentSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2303 $response['id'] = $paymentSaveStatus;
2304 $response['message'] = __('Payment setting saved successfully', 'bit-form');
2305 } else {
2306 $paymentSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2307 $response['message'] = __('Payment setting updated successfully', 'bit-form');
2308 }
2309
2310 if (is_wp_error($paymentSaveStatus)) {
2311 return $paymentSaveStatus;
2312 }
2313 return $response;
2314 }
2315
2316 private function addWebhookToPaypal($paySetting)
2317 {
2318 $transaction_mode = $paySetting->mode;
2319 $clientId = $paySetting->clientID;
2320 $clientSecret = $paySetting->clientSecret;
2321 $base_url = 'sandbox' === $transaction_mode ? 'https://api-m.sandbox.paypal.com' : 'https://api.paypal.com';
2322 // get all webhooks
2323 $webhooks_url = $base_url . '/v1/notifications/webhooks';
2324 $webhooks_headers = [
2325 'Content-Type' => 'application/json',
2326 'Authorization' => 'Basic ' . base64_encode($clientId . ':' . $clientSecret)
2327 ];
2328 $webhook_url = get_rest_url() . 'bitform/v1/payments/paypal';
2329 // adding webhook
2330 $data = [
2331 'url' => $webhook_url,
2332 'event_types' => [
2333 [
2334 'name' => 'CHECKOUT.ORDER.APPROVED'
2335 ]
2336 ]
2337 ];
2338 $webhook_response = HttpHelper::post($webhooks_url, wp_json_encode($data), $webhooks_headers);
2339 if (is_wp_error($webhook_response) || $webhook_response->error) {
2340 return null;
2341 }
2342 return true;
2343 }
2344
2345 private function addWebhookToStripe($paySetting)
2346 {
2347 // $transaction_mode = $paySetting->mode;
2348 // $publishableKey = $paySetting->publishableKey;
2349 $clientSecret = $paySetting->clientSecret;
2350
2351 $create_webhook_url = 'https://api.stripe.com/v1/webhook_endpoints';
2352 $headers = [
2353 'Content-Type' => 'application/x-www-form-urlencoded',
2354 'Authorization' => "Bearer $clientSecret",
2355 ];
2356
2357 $webhook_url = get_rest_url() . 'bitform/v1/payments/stripe';
2358
2359 $apiResponse = HttpHelper::get($create_webhook_url, '', $headers);
2360 $webhookList = $apiResponse->data;
2361 $webhook_already_exist = false;
2362
2363 foreach ($webhookList as $webhook) {
2364 if ($webhook->url === $webhook_url) {
2365 $webhook_already_exist = true;
2366 break;
2367 }
2368 }
2369
2370 $data = [
2371 'enabled_events[]' => 'payment_intent.succeeded',
2372 'url' => $webhook_url,
2373 ];
2374
2375 if (!$webhook_already_exist) {
2376 $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2377 if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2378 return null;
2379 }
2380 }
2381 return true;
2382 }
2383
2384 public function builerHelperState($formId)
2385 {
2386 $data = static::$formModel->get(
2387 ['id', 'builder_helper_state'],
2388 ['id' => $formId]
2389 );
2390
2391 if (!is_wp_error($data)) {
2392 foreach ($data as $key => $value) {
2393 if (isset($value->builder_helper_state) && is_string($value->builder_helper_state)) {
2394 $data[$key]->builder_helper_state = json_decode($value->builder_helper_state);
2395 }
2396 }
2397 }
2398
2399 return $data;
2400 }
2401
2402 public function updateGeneratedScriptPageIds()
2403 {
2404 $updateData = [
2405 'generated_script_page_ids' => \wp_json_encode((object) []),
2406 ];
2407 $update_status = static::$formModel->update(
2408 $updateData,
2409 [
2410 'status' => 1
2411 ]
2412 );
2413 if (is_wp_error($update_status)) {
2414 return $update_status;
2415 } elseif (!$update_status) {
2416 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
2417 } else {
2418 return true;
2419 }
2420 }
2421
2422 public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
2423 {
2424 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2425 return str_replace($TEMP_CONF_ID, $msgId, $str);
2426 }
2427 }
2428