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

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