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

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