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

1,957 lines 84.1 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 WP_Error;
11 use BitCode\BitForm\Core\Util\IpTool;
12 use BitCode\BitForm\Core\Util\FileHandler;
13 use BitCode\BitForm\Core\Database\FormModel;
14 use BitCode\BitForm\Core\Database\ReportsModel;
15 use BitCode\BitForm\Admin\Form\AdminFormManager;
16 use BitCode\BitForm\Core\Database\WorkFlowModel;
17 use BitCode\BitForm\Core\Database\FormEntryModel;
18 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
19 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
20 use BitCode\BitForm\Core\Database\IntegrationModel;
21 use BitCode\BitForm\Core\Database\FormEntryLogModel;
22 use BitCode\BitForm\Core\WorkFlow\WorkFlowRunHelper;
23 use BitCode\BitForm\Core\Database\EmailTemplateModel;
24 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
25 use BitCode\BitForm\Core\Database\SuccessMessageModel;
26 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
27 use BitCode\BitForm\Core\Integration\IntegrationHandler;
28 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
29 use BitCode\BitForm\Admin\Form\Template\TemplateProvider;
30 use BitCode\BitForm\Admin\Form\CustomFieldHandler;
31
32 class AdminFormHandler
33 {
34 private static $formModel;
35 private static $ipTool;
36 public function __construct()
37 {
38 static::$formModel = new FormModel();
39 static::$ipTool = new IpTool();
40 }
41 public function getTemplate($Request, $post)
42 {
43 $templateName = null;
44 $newFormId = null;
45 if (isset($post->template)) {
46 $templateName = $post->template;
47 $newFormId = $post->newFormId;
48 }
49
50 $templateProvider = new TemplateProvider();
51 $form_content_raw = $templateProvider->getTemplate($templateName, $newFormId);
52 if (!$form_content_raw) {
53 return new WP_Error("template_empty", __("Template not found, by this name: ", "bit-form") . $templateName);
54 } else {
55 return \json_encode(
56 array(
57 'id' => 0,
58 'form_content' => $form_content_raw,
59 )
60 );
61 }
62 }
63
64 public function saveStyleSheet($styles, $sheetName)
65 {
66 $this->createFormStylesDirIfNotExists();
67
68 if (
69 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
70 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
71 ) {
72 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
73 fwrite($createStyleFile, $styles);
74 fclose($createStyleFile);
75 return true;
76 }
77 return false;
78 }
79
80 public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43)
81 {
82 $md_width = 600;
83 $sm_width = 400;
84 $lg_styles = '';
85 $md_styles = '';
86 $sm_styles = '';
87 for ($i = 0; $i < count($layout->lg); $i++) {
88 $fld = $layout->lg[$i];
89
90 $class = $fld->i;
91 $lg_g_r_s = $fld->y + 1;
92 $lg_g_c_s = $fld->x + 1;
93 $lg_g_r_e = $fld->y !== 1 ? $fld->h + ($fld->y + 1) : 1;
94 $lg_g_c_e = ($fld->x + 1) + $fld->w;
95 $lg_g_r_span = $lg_g_r_e - $lg_g_r_s;
96 $lg_g_c_span = $lg_g_c_e - $lg_g_c_s;
97 $lg_min_height = $fld->h * $lay_row_height . "px;";
98
99 $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; }";
100
101 $fld = $layout->md[$i];
102
103 $class = $fld->i;
104 $md_g_r_s = $fld->y + 1;
105 $md_g_c_s = $fld->x + 1;
106 $md_g_r_e = $fld->y !== 1 ? $fld->h + ($fld->y + 1) : 1;
107 $md_g_c_e = ($fld->x + 1) + $fld->w;
108 $md_g_r_span = $lg_g_r_e - $md_g_r_s;
109 $md_g_c_span = $lg_g_c_e - $md_g_c_s;
110 $md_min_height = $fld->h * $lay_row_height . "px;";
111
112 $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; }";
113
114 $fld = $layout->sm[$i];
115
116 $class = $fld->i;
117 $sm_g_r_s = $fld->y + 1;
118 $sm_g_c_s = $fld->x + 1;
119 $sm_g_r_e = $fld->y !== 1 ? $fld->h + ($fld->y + 1) : 1;
120 $sm_g_c_e = ($fld->x + 1) + $fld->w;
121 $sm_g_r_span = $sm_g_r_e - $sm_g_r_s;
122 $sm_g_c_span = $sm_g_c_e - $sm_g_c_s;
123 $sm_min_height = $fld->h * $lay_row_height . "px;";
124
125 $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; }";
126 }
127 $formStyle = "._frm-g{
128 display: grid;
129 display: -ms-grid;
130 grid-template-columns: repeat( 6 , minmax( 30px , 1fr ));
131 -ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr );
132 }
133 {$lg_styles}
134 @media only screen and (max-width:{$md_width}px) {
135 ._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 );}
136 {$md_styles}
137 }
138 @media only screen and (max-width:{$sm_width}px) {
139 ._frm-g {grid-template-columns: repeat( 2 , minmax( 30px , 1fr ));-ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr );}
140 {$sm_styles}
141 }";
142
143 $this->createFormStylesDirIfNotExists();
144
145 if (
146 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
147 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
148 ) {
149 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
150 fwrite($createStyleFile, $formStyle);
151 fclose($createStyleFile);
152 return true;
153 }
154 return false;
155 }
156
157 public function createFormStylesDirIfNotExists()
158 {
159 if (!file_exists(BITFORMS_UPLOAD_DIR)) {
160 wp_mkdir_p(BITFORMS_UPLOAD_DIR);
161 }
162 if (!file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')) {
163 wp_mkdir_p(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles');
164 }
165 }
166
167 public function createNewForm($Request, $post)
168 {
169 if (!isset($post->form_id) || $post->form_id == '') {
170 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
171 }
172
173 $formManager = new AdminFormManager($post->form_id);
174 if ($formManager->isExist()) {
175 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
176 }
177
178 if (!class_exists("BitCode\\BitFormPro\\Plugin")) {
179 if (!empty($workFlows) && count($workFlows) > 2) {
180 return new WP_Error(
181 'free_limit',
182 __('You are allowed to add maximum 2 workflows ', 'bit-form')
183 );
184 }
185 }
186
187 if (isset($post->formStyle) && $post->formStyle) {
188 $sheetName = 'bitform-' . $post->form_id . '.css';
189 $this->saveStyleSheet($post->formStyle, $sheetName);
190 }
191
192 if (isset($post->layoutChanged) && $post->layoutChanged) {
193 $sheetName = 'bitform-layout-' . $post->form_id . '.css';
194 $rowHeight = (int)$post->rowHeight;
195 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
196 }
197
198 $fields = wp_unslash($post->fields);
199 $layout = wp_unslash($post->layout);
200 $form_name = wp_unslash($post->form_name);
201 $formSettings = (object) wp_unslash($post->formSettings);
202 $workFlows = wp_unslash($post->workFlows);
203 $additional = wp_unslash($post->additional);
204 $reports = !empty($post->reports) ? $post->reports : (object) [];
205
206 $mailTem = $formSettings->mailTem;
207 $integrations = $formSettings->integrations;
208
209 $user_details = static::$ipTool->getUserDetail();
210 // var_dump($fields);
211 if (empty($fields) || empty($layout)) {
212 return new WP_Error(
213 'empty_form',
214 __('Can not save empty form.', 'bit-form')
215 );
216 }
217 if (strlen($form_name) > 50) {
218 return new WP_Error(
219 'empty_form',
220 __('Form Name Should Be Within 50 Characters', 'bit-form')
221 );
222 }
223 $form_content = array(
224 'fields' => $fields,
225 'layout' => $layout,
226 );
227
228 /* if (!empty($formSettings->submitBtn)) {
229 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
230 } */
231 if (!empty($formSettings->theme)) {
232 $form_content = array_merge($form_content, array('theme' => $formSettings->theme));
233 }
234
235 if (!empty($additional)) {
236 $form_content = array_merge($form_content, array('additional' => $additional));
237 }
238 if (!empty($workFlows)) {
239 $workFlowsStr = is_string($workFlows) ? $workFlows : json_encode($workFlows);
240 $workFlowExist = [];
241 if (\strpos($workFlowsStr, 'onload')) {
242 $workFlowExist['onload'] = true;
243 }
244 if (\strpos($workFlowsStr, 'oninput')) {
245 $workFlowExist['oninput'] = true;
246 }
247 $form_content = array_merge($form_content, array('workFlowExist' => $workFlowExist));
248 }
249 $form_content = \wp_json_encode($form_content);
250
251 $fdata = array(
252 "id" => $post->form_id,
253 "form_content" => $form_content,
254 "user_id" => $user_details['id'],
255 "user_ip" => $user_details['ip'],
256 "user_device" => $user_details['device'],
257 "status" => 1,
258 "form_name" => $form_name,
259 "created_at" => $user_details['time'],
260 "updated_at" => $user_details['time'],
261 );
262 $save_status = static::$formModel->insert($fdata);
263
264 if (is_wp_error($save_status)) {
265 return $save_status;
266 } elseif (!$save_status) {
267 return false;
268 } else {
269 wp_mkdir_p(BITFORMS_UPLOAD_DIR . "/$save_status");
270 $formID = $save_status;
271 $integartionIDForWorkflow = array();
272 // Confiramtion Message [start]
273 if (!empty($formSettings->confirmation->type->successMsg)) {
274 $successMessages = $formSettings->confirmation->type->successMsg;
275 $successMessageHandler
276 = new SuccessMessageHandler($formID, $user_details);
277 foreach ($successMessages as $messageKey => $messageDetail) {
278 $savedID = $successMessageHandler->saveMessage($messageDetail);
279 if ($savedID) {
280 $msgIdx = empty($messageDetail->id) ? $messageKey : \json_encode(["id" => $messageDetail->id]);
281 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
282 }
283 }
284 unset($formSettings->confirmation->type->successMsg);
285 }
286 // return $formSettings;
287 // Confiramtion Message [end] */
288 // Email Template [start]
289 if (!empty($mailTem)) {
290 $emailTemplateHandler
291 = new EmailTemplateHandler($formID, $user_details);
292 foreach ($mailTem as $templateKey => $templateDetail) {
293 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
294 if ($savedID) {
295 $tempIdx = empty($templateDetail->id) ? $templateKey : \json_encode(["id" => $templateDetail->id]);
296 $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
297 }
298 }
299 }
300 // Email Template [end] */
301 //Integration [start] */
302 $integrationHandler = new IntegrationHandler($formID, $user_details);
303 if (!empty($formSettings->confirmation->type)) {
304 $allIntegrations = $formSettings->confirmation->type;
305 foreach ($allIntegrations as $integrationType => $integrationGroup) {
306 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
307 if (empty($singleIntegrationDetail->details)) {
308 $integrationName = $singleIntegrationDetail->title;
309 unset($singleIntegrationDetail->title);
310 unset($singleIntegrationDetail->id);
311 $integrationDetails = !is_string($singleIntegrationDetail) ?
312 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
313 } else {
314 $integrationName = $singleIntegrationDetail->title;
315 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
316 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
317 }
318 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
319 $integIdx = empty($singleIntegrationDetail->id) ? $savedID : \json_encode(["id" => $singleIntegrationDetail->id]);
320 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
321 }
322 }
323 }
324 if (!empty($integrations)) {
325 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
326 $integrationName = $singleIntegrationDetail->name;
327 unset($singleIntegrationDetail->name);
328 $integrationType = $singleIntegrationDetail->type;
329 unset($singleIntegrationDetail->type);
330 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
331 unset($singleIntegrationDetail->id);
332 if (empty($singleIntegrationDetail->details)) {
333 $integrationDetails = !is_string($singleIntegrationDetail) ?
334 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
335 } else {
336 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
337 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
338 }
339 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
340 $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : \json_encode(["id" => $singleIntegrationDetailID]);
341 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
342 }
343 }
344 //Integrations [end]
345 if (!empty($workFlows)) {
346 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
347 $workflowCount = count($workFlows);
348 while ($workflowCount) {
349 $workFlow = $workFlows[--$workflowCount];
350 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow);
351 $newData['workflow'] = 1;
352 }
353 }
354 //wrokFlows [end]
355 if (!empty($reports)) {
356 $reportsModel = new ReportsModel();
357 foreach ($reports as $reportIndex => $report) {
358 $reportsModel->insert(
359 array(
360 "type" => 'table',
361 "category" => 'form',
362 "context" => $formID,
363 "details" => is_string($report->details) ? $report->details : wp_json_encode($report->details),
364 "isDefault" => 1,
365 "user_id" => $user_details['id'],
366 "user_ip" => $user_details['ip'],
367 "user_device" => $user_details['device'],
368 "created_at" => $user_details['time'],
369 "updated_at" => $user_details['time'],
370 )
371 );
372 $newData['reports'] = 1;
373 }
374 }
375 $updated_data = $this->getAForm(array('id' => $save_status), null);
376 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
377
378 return $updated_data;
379 }
380 }
381
382 public function updateForm($Request, $post)
383 {
384 if ($post->formStyle) {
385 $sheetName = 'bitform-' . $post->id . '.css';
386 $this->saveStyleSheet($post->formStyle, $sheetName);
387 }
388
389 if ($post->layoutChanged) {
390 $sheetName = 'bitform-layout-' . $post->id . '.css';
391 $rowHeight = (int)$post->rowHeight;
392 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
393 }
394
395 if (property_exists($post, 'fields') && $post->fields !== null && property_exists($post, 'layout') && $post->layout) {
396 $fields = wp_unslash($post->fields);
397 $layout = wp_unslash($post->layout);
398 $formID = wp_unslash($post->id);
399 $form_name = wp_unslash($post->form_name);
400 $formSettings = wp_unslash($post->formSettings);
401 $workFlows = wp_unslash($post->workFlows);
402 $additional = wp_unslash($post->additional);
403 $reports = wp_unslash($post->reports);
404 }
405
406 $mailTem = $formSettings->mailTem;
407 $integrations = $formSettings->integrations;
408
409 $user_details = static::$ipTool->getUserDetail();
410 if (empty($fields) || empty($layout) || is_null($formID)) {
411 return new WP_Error('empty_form', 'Can not update empty form.');
412 }
413
414 if (!class_exists("BitCode\\BitFormPro\\Plugin")) {
415 if (count($workFlows) > 2) {
416 return new WP_Error(
417 'free_limit',
418 __('You are allowed to add maximum 2 workflows ', 'bit-form')
419 );
420 }
421 }
422 $form_content = array(
423 'fields' => $fields,
424 'layout' => $layout,
425 );
426 /* if (!empty($formSettings->submitBtn)) {
427 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
428 } */
429 if (!empty($formSettings->theme)) {
430 $form_content = array_merge($form_content, array('theme' => $formSettings->theme));
431 }
432 if (!empty($additional)) {
433 $form_content = array_merge($form_content, array('additional' => $additional));
434 }
435 $integartionIDForWorkflow = array();
436 $newData['settingConfiramation'] = 0;
437 $newData['integation'] = 0;
438 $newData['mailTemplate'] = 0;
439 $newData['workflow'] = 0;
440 $newData['reports'] = 0;
441 // Confiramtion Message [start]
442 if (!empty($formSettings->confirmation->type->successMsg)) {
443 $successMessages = $formSettings->confirmation->type->successMsg;
444 $successMessageHandler
445 = new SuccessMessageHandler($formID, $user_details);
446 foreach ($successMessages as $messageKey => $messageDetail) {
447 if (empty($messageDetail->id)) {
448 $savedID = $successMessageHandler->saveMessage($messageDetail);
449 if ($savedID) {
450 $newData['settingConfiramation'] = 1;
451 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
452 }
453 } else {
454 $successMessageHandler->updateMessage($messageDetail);
455 }
456 }
457 unset($formSettings->confirmation->type->successMsg);
458 }
459 // return $formSettings;
460 // Confiramtion Message [end] */
461 // Email Template [start]
462 if (!empty($mailTem)) {
463 $emailTemplateHandler
464 = new EmailTemplateHandler($formID, $user_details);
465 foreach ($mailTem as $templateKey => $templateDetail) {
466 if (empty($templateDetail->id)) {
467 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
468 if (is_wp_error($savedID) && $savedID->get_error_code() === 'result_empty') {
469 $newData['mailTemplate'] = 2;
470 } else {
471 $newData['mailTemplate'] = 1;
472 $integartionIDForWorkflow['mailTem'][$templateKey] = $savedID;
473 }
474 } else {
475 $emailTemplateHandler->updateTemplate($templateDetail);
476 }
477 }
478 }
479 // return $formSettings;
480 // Email Template [end] */
481 //Integration [start] */
482 $integrationHandler = new IntegrationHandler($formID, $user_details);
483 if (!empty($formSettings->confirmation->type)) {
484 $allIntegrations = $formSettings->confirmation->type;
485 foreach ($allIntegrations as $integrationType => $integrationGroup) {
486 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
487 if (empty($singleIntegrationDetail->details)) {
488 $integrationName = $singleIntegrationDetail->title;
489 unset($singleIntegrationDetail->title);
490 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
491 unset($singleIntegrationDetail->id);
492 $integrationDetails = !is_string($singleIntegrationDetail) ?
493 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
494 } else {
495 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
496 unset($singleIntegrationDetail->id);
497 $integrationName = $singleIntegrationDetail->title;
498 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
499 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
500 }
501 if (empty($singleIntegrationDetailID)) {
502 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
503 $newData['settingConfiramation'] = 1;
504 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
505 } else {
506 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
507 }
508 }
509 }
510 }
511 if (!empty($integrations)) {
512 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
513 $integrationName = $singleIntegrationDetail->name;
514 unset($singleIntegrationDetail->name);
515 $integrationType = $singleIntegrationDetail->type;
516 unset($singleIntegrationDetail->type);
517 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
518 unset($singleIntegrationDetail->id);
519 if (empty($singleIntegrationDetail->details)) {
520 $integrationDetails = !is_string($singleIntegrationDetail) ?
521 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
522 } else {
523 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
524 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
525 }
526 if (empty($singleIntegrationDetailID)) {
527 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
528 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
529 if (is_wp_error($savedID) && $savedID->get_error_code() !== 'result_empty') {
530 $newData['integation'] = 2;
531 } else {
532 $newData['integation'] = 1;
533 }
534 } else {
535 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
536 }
537 }
538 }
539 //Integrations [end]
540 //workFlows [start] */
541 $workFlowExist = [];
542 if (!empty($workFlows)) {
543 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
544 // foreach ($workFlows as $workFlowIndex => $workFlow) {
545 $workflowCount = count($workFlows);
546 while ($workflowCount) {
547 $workFlow = $workFlows[--$workflowCount];
548 if ($workFlow->action_type === 'onload') {
549 $workFlowExist['onload'] = true;
550 }
551 if ($workFlow->action_type === 'oninput') {
552 $workFlowExist['oninput'] = true;
553 }
554 if (empty($workFlow->id)) {
555 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow);
556 if (is_wp_error($savedID) && $savedID->get_error_code() !== 'result_empty') {
557 $newData['workflow'] = 2;
558 } else {
559 $newData['workflow'] = 1;
560 }
561 } else {
562 $workFlowHandler->updateworkFlow($workFlow->id, $workFlow, $integartionIDForWorkflow);
563 }
564 }
565 }
566 $form_content = array_merge($form_content, array('workFlowExist' => $workFlowExist));
567 //wrokFlows [end]
568 //reports [start] */
569 if (!empty($reports)) {
570 $reportsModel = new ReportsModel();
571 $fieldNames = [];
572 foreach ($fields as $key => $field) {
573 if (!empty($field->lbl)) {
574 // $name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
575 $fieldNames["$key"] = $field->lbl;
576 }
577 }
578
579 $fieldNames['__user_id'] = __('User', 'bit-form');
580 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
581 // $fieldNames['__user_location'] = __('');
582 $fieldNames['__referer'] = __('Refer URL', 'bit-form');
583 $fieldNames['__user_device'] = __('Device', 'bit-form');
584 $fieldNames['__created_at'] = __('Created Time', 'bit-form');
585 $fieldNames['__updated_at'] = __('Modified Time', 'bit-form');
586 foreach ($reports as $reportIndex => $report) {
587 $reportDetails = $reportsModel->validateReportFields($report, $fieldNames);
588
589 if (empty($report->id)) {
590 $reportSaveStatus = $reportsModel->insert(
591 array(
592 "type" => 'table',
593 "category" => 'form',
594 "context" => $formID,
595 "details" => is_string($reportDetails) ? $reportDetails : wp_json_encode($reportDetails),
596 "isDefault" => 1,
597 "user_id" => $user_details['id'],
598 "user_ip" => $user_details['ip'],
599 "user_device" => $user_details['device'],
600 "created_at" => $user_details['time'],
601 "updated_at" => $user_details['time'],
602 )
603 );
604 if (is_wp_error($reportSaveStatus) && $reportSaveStatus->get_error_code() !== 'result_empty') {
605 $newData['reports'] = 2;
606 } else {
607 $newData['reports'] = 1;
608 }
609 } else {
610 $reportsModel->update(
611 array(
612 "type" => 'table',
613 "category" => 'form',
614 "context" => $formID,
615 "details" => is_string($reportDetails) ? $reportDetails : wp_json_encode($reportDetails),
616 "isDefault" => 1,
617 "user_id" => $user_details['id'],
618 "user_ip" => $user_details['ip'],
619 "user_device" => $user_details['device'],
620 "updated_at" => $user_details['time'],
621 ),
622 array(
623 'id' => $report->id,
624 )
625 );
626 }
627 }
628 }
629 //reports [end]
630 $form_content = wp_json_encode($form_content);
631 $update_status = static::$formModel->update(
632 array(
633 "form_name" => $form_name,
634 "form_content" => $form_content,
635 "user_id" => $user_details['id'],
636 "user_ip" => $user_details['ip'],
637 "user_device" => $user_details['device'],
638 "status" => 1,
639 "updated_at" => $user_details['time'],
640 ),
641 array(
642 "id" => $formID,
643 )
644 );
645 if (is_wp_error($update_status)) {
646 return $update_status;
647 } elseif (!$update_status) {
648 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
649 } else {
650 if (isset($post->deletedFldKey) && is_array($post->deletedFldKey)) {
651
652 $deletedMetaFlds = "'" . implode("','", $post->deletedFldKey) . "'";
653 global $wpdb;
654 $tablename = $wpdb->prefix . "bitforms_form_entrymeta";
655
656 $wpdb->query($wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN (%s)", " ", $deletedMetaFlds));
657 unset($post->deletedFldKey);
658 }
659
660 $updated_data = $this->getAForm(array('id' => $formID), null);
661 if ($newData['settingConfiramation'] === 0 && $newData['mailTemplate'] === 0 && $newData['integation'] === 0) {
662 unset($updated_data['formSettings']);
663 }
664 if ($newData['integation'] === 0) {
665 unset($updated_data['integrations']);
666 } elseif ($newData['integation'] === 2) {
667 $errorIN = '';
668 $errorIN .= empty($errorIN) ? 'integation' : ', integation';
669 }
670 if ($newData['mailTemplate'] === 0) {
671 unset($updated_data['mailTem']);
672 } elseif ($newData['mailTemplate'] === 2) {
673 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
674 }
675 if ($newData['workflow'] === 0) {
676 unset($updated_data['workFlows']);
677 } elseif ($newData['workflow'] === 2) {
678 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
679 }
680 if ($newData['reports'] === 2) {
681 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
682 }
683 if (!empty($errorIN)) {
684 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
685 return new WP_Error('Form update Error.', $updated_data);
686 }
687 $updated_data['message'] = __('Form updated successfully.', 'bit-form');
688 return $updated_data;
689 }
690 }
691 public function changeFormStatus($Request, $post)
692 {
693 if (isset($Request['status']) && $Request['id']) {
694 $status = wp_unslash($Request['status']);
695 $id = wp_unslash($Request['id']);
696 } else {
697 $status = wp_unslash($post->status);
698 $id = wp_unslash($post->id);
699 }
700 $user_details = static::$ipTool->getUserDetail();
701 // return $post->fields;
702 $status = $status === 'true' || $status === true ? true : false;
703 if (!is_bool($status) || is_null($id)) {
704 // echo $status;
705 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
706 }
707 $update_status = static::$formModel->update(
708 array(
709 "user_id" => $user_details['id'],
710 "user_ip" => $user_details['ip'],
711 "user_device" => $user_details['device'],
712 "status" => $status ? 1 : 0,
713 "updated_at" => $user_details['time'],
714 ),
715 array(
716 "id" => $id,
717 )
718 );
719 if (is_wp_error($update_status)) {
720 return $update_status;
721 } elseif (!$update_status) {
722 return false;
723 } else {
724 return __('Form status changed successfully', 'bit-form');
725 }
726 }
727 public function changeBulkFormStatus($Request, $post)
728 {
729 if (isset($Request['status']) && $Request['formID']) {
730 $status = wp_unslash($Request['status']);
731 $formID = wp_unslash($Request['formID']);
732 } else {
733 $status = wp_unslash($post->status);
734 $formID = wp_unslash($post->formID);
735 }
736 $user_details = static::$ipTool->getUserDetail();
737 // return $post->fields;
738 $status = $status === 'true' || $status === true ? true : false;
739 if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
740 // echo $status;
741 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
742 }
743 $update_status = static::$formModel->bulkUpdate(
744 array(
745 "user_id" => $user_details['id'],
746 "user_ip" => $user_details['ip'],
747 "user_device" => $user_details['device'],
748 "status" => $status ? 1 : 0,
749 "updated_at" => $user_details['time'],
750 ),
751 array(
752 "id" => $formID,
753 )
754 );
755 if (is_wp_error($update_status)) {
756 return $update_status;
757 } elseif (!$update_status) {
758 return false;
759 } else {
760 return __('Form status changed successfully', 'bit-form');
761 }
762 }
763 public function getAllForm()
764 {
765 global $wpdb;
766
767 $allForms = $wpdb->get_results("SELECT forms.id,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");
768
769 if (is_wp_error($allForms)) {
770 return $allForms;
771 } elseif (!$allForms) {
772 return [];
773 } else {
774 return $allForms;
775 }
776 }
777
778 public function getAForm($Request, $post)
779 {
780 if (isset($Request['id'])) {
781 $formID = wp_unslash($Request['id']);
782 } else {
783 $formID = wp_unslash($post->id);
784 }
785 // return $post->fields;
786 if (is_null($formID)) {
787 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
788 }
789 $formManager = new AdminFormManager($formID);
790 if (!$formManager->isExist()) {
791 return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
792 }
793 $form_content = $formManager->getFormContent();
794 if ($formManager->isExist()) {
795 $form_content_arr = array(
796 'layout' => $form_content->layout,
797 'fields' => $form_content->fields,
798 'form_name' => $formManager->getFormName(),
799 'workFlowExist' => $form_content->workFlowExist,
800 );
801 $successMessageHandler
802 = new SuccessMessageHandler($formID);
803 $successMessages = $successMessageHandler->getAllMessage();
804 if (!is_wp_error($successMessages)) {
805 foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
806 $allConfirmation['type']['successMsg'][$sucessMessagekey] =
807 array(
808 'id' => $sucessMessagevalue->id,
809 'title' => $sucessMessagevalue->message_title,
810 'msg' => $sucessMessagevalue->message_content,
811 );
812 }
813 }
814 $emailTemplateHandler
815 = new EmailTemplateHandler($formID);
816 $emailTemplates = $emailTemplateHandler->getAllTemplate();
817 if (!is_wp_error($emailTemplates)) {
818 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
819 $mailTem[] =
820 array(
821 'id' => $emailTemplatevalue->id,
822 'title' => $emailTemplatevalue->title,
823 'sub' => $emailTemplatevalue->sub,
824 'body' => $emailTemplatevalue->body,
825 );
826 }
827 }
828 $integrationHandler = new IntegrationHandler($formID);
829 $formIntegrations = $integrationHandler->getAllIntegration('form');
830 if (!is_wp_error($formIntegrations)) {
831 foreach ($formIntegrations as $integrationkey => $integrationValue) {
832 if ($integrationValue->integration_type === 'redirectPage' || $integrationValue->integration_type === 'webHooks') {
833 $integrationData = array(
834 'id' => $integrationValue->id,
835 'title' => $integrationValue->integration_name,
836 );
837 if (!empty($integrationValue->integration_details)) {
838 // var_dump(json_decode($integrationValue->integration_details));
839 $integration_details = (array) json_decode($integrationValue->integration_details);
840 $integrationData = array_merge($integration_details, $integrationData);
841 } else {
842 $integration_details = array(
843 'url' => '',
844 );
845 $integrationData = array_merge($integrationData, $integration_details);
846 }
847 $allConfirmation['type'][$integrationValue->integration_type][]
848 = $integrationData;
849 } else {
850 $integrationData = array(
851 'id' => $integrationValue->id,
852 'name' => $integrationValue->integration_name,
853 'type' => $integrationValue->integration_type,
854 );
855 $integrations[] = array_merge(
856 $integrationData,
857 is_string($integrationValue->integration_details) ?
858 (array) json_decode($integrationValue->integration_details) :
859 $integrationValue->integration_details
860 );
861 }
862 }
863 }
864 $settingsContent = array(
865 'formName' => $formManager->getFormName(),
866 'theme' => $form_content->theme,
867 // 'submitBtn' => $form_content->buttons,
868 );
869
870 if (!empty($allConfirmation)) {
871 $confirmation = array(
872 'confirmation' => $allConfirmation,
873 );
874 } else {
875 $confirmation = array(
876 'confirmation' => array('type' => []),
877 );
878 }
879 $settingsContent = array_merge($settingsContent, $confirmation);
880 if (!empty($integrations)) {
881 $settingsContent = array_merge(
882 $settingsContent,
883 array(
884 'integrations' => $integrations,
885 )
886 );
887 } else {
888 $settingsContent = array_merge(
889 $settingsContent,
890 array(
891 'integrations' => []
892 )
893 );
894 }
895 if (!empty($mailTem)) {
896 $settingsContent = array_merge(
897 $settingsContent,
898 array(
899 'mailTem' => $mailTem,
900 )
901 );
902 } else {
903 $settingsContent = array_merge(
904 $settingsContent,
905 array(
906 'mailTem' => []
907 )
908 );
909 }
910 $formSettings = array(
911 'formSettings' => $settingsContent,
912 );
913 $data = array(
914 "id" => $formID,
915 "form_name" => $formManager->getFormName(),
916 "form_content" => $form_content_arr,
917 "additional" => empty($form_content->additional) ? array(
918 "enabled" => array(
919 "blocked_ip" => false,
920 "restrict_form" => false,
921 ),
922 "settings" => array(
923 "restrict_form" => array(
924 'day' => [],
925 'date' => array(
926 'from' => null,
927 'to' => null,
928 ),
929 'time' => array(
930 'from' => null,
931 'to' => null,
932 ),
933 ),
934 "entry_limit" => null,
935 "blocked_ip" => [],
936 ),
937 "onePerIp" => false,
938 ) : $form_content->additional,
939 "created_at" => $formManager->getFormMetaData()['created_at'],
940 "views" => $formManager->getFormMetaData()['views'],
941 "entries" => $formManager->getFormMetaData()['entries'],
942 "status" => $formManager->getFormMetaData()['status'],
943 );
944 $data = array_merge($data, $formSettings);
945 $workFlowHandler = new WorkFlowHandler($formID);
946 $workFlows = array('workFlows' => $workFlowHandler->getAllworkFlow());
947 $data = array_merge($data, $workFlows);
948 $reportsModel = new ReportsModel();
949 $returnedReportData = $reportsModel->get(
950 array(
951 "id",
952 "details",
953 "isDefault",
954 "type",
955 ),
956 array(
957 "category" => 'form',
958 "context" => $formID,
959 )
960 );
961 if (!is_wp_error($returnedReportData)) {
962 $fieldNames = [];
963 foreach ($formManager->getFieldLabel() as $key => $field) {
964 $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
965 }
966 if ($formManager->isGCLIDEnabled()) {
967 $fieldNames["GCLID"] = "GCLID";
968 }
969 foreach ($returnedReportData as $reportKey => $reportData) {
970 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
971 if (!empty($reportDetails) && is_string($reportDetails)) {
972 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
973 } elseif (!empty($reportDetails)) {
974 $returnedReportData[$reportKey]->details = $reportDetails;
975 } else {
976 $returnedReportData[$reportKey]->details = [];
977 }
978 }
979 $reports = array('reports' => $returnedReportData);
980 $data = array_merge($data, $reports);
981 }
982
983 $formFields = $formManager->getFieldLabel();
984 $data = array_merge($data, array('Labels' => $formFields));
985
986 return $data;
987 }
988 }
989
990 public function deleteAForm($Request, $post)
991 {
992 if (isset($Request['id'])) {
993 $formID = wp_unslash($Request['id']);
994 } else {
995 $formID = wp_unslash($post->id);
996 }
997 if (is_null($formID)) {
998 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
999 }
1000 $delete_status = static::$formModel->delete(
1001 array(
1002 "id" => $formID,
1003 )
1004 );
1005
1006 $successMessageModel
1007 = new SuccessMessageModel();
1008 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1009
1010 $emailTemplateModel
1011 = new EmailTemplateModel();
1012 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1013
1014 $integrationModel = new IntegrationModel();
1015 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1016
1017 $workFlowModel = new WorkFlowModel();
1018 $deleteworkFlowStatus = $workFlowModel->delete(['form_id' => $formID]);
1019
1020 $reportsModel = new ReportsModel();
1021 $deleteReportStatus = $reportsModel->delete(['context' => $formID]);
1022
1023 $formEntryModel = new FormEntryModel();
1024 $returnedEntries = $formEntryModel->get("id", ["form_id" => $formID]);
1025 $entries = [];
1026
1027 if (!is_wp_error($returnedEntries)) {
1028 foreach ($returnedEntries as $entryKey => $entryInfo) {
1029 $entries[] = $entryInfo->id;
1030 }
1031 global $wpdb;
1032 $prefix = $wpdb->prefix;
1033 if (count($entries) > 0) {
1034 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1035 array(
1036 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1037 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1038 )
1039 );
1040 }
1041 }
1042
1043 $fileHandler = new FileHandler();
1044 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1045 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1046 }
1047 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1048 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1049 }
1050 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1051 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1052 }
1053 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1054 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1055 }
1056 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1057 }
1058 public function deleteBlukForm($Request, $post)
1059 {
1060 if (isset($Request['formID'])) {
1061 $formID = wp_unslash($Request['formID']);
1062 } else {
1063 $formID = wp_unslash($post->formID);
1064 }
1065 if (is_null($formID) || !is_array($formID)) {
1066 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1067 }
1068
1069 foreach ($formID as $id) {
1070 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $id . '.css');
1071 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $id . '.css');
1072 }
1073 $delete_status = static::$formModel->bulkDelete(
1074 array(
1075 "id" => $formID,
1076 )
1077 );
1078 $successMessageModel
1079 = new SuccessMessageModel();
1080 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1081
1082 $emailTemplateModel
1083 = new EmailTemplateModel();
1084 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1085
1086 $integrationModel = new IntegrationModel();
1087 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1088
1089 $workFlowModel = new WorkFlowModel();
1090 $deleteworkFlowStatus = $workFlowModel->bulkDelete(['form_id' => $formID]);
1091
1092 $reportsModel = new ReportsModel();
1093 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1094
1095 $formEntryModel = new FormEntryModel();
1096 $returnedEntries = $formEntryModel->get("id", ["form_id" => $formID]);
1097 $entries = [];
1098 foreach ($returnedEntries as $entryKey => $entryInfo) {
1099 $entries[] = $entryInfo->id;
1100 }
1101 global $wpdb;
1102 $prefix = $wpdb->prefix;
1103 if (count($entries) > 0) {
1104 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1105 array(
1106 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1107 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1108 )
1109 );
1110 }
1111
1112 $fileHandler = new FileHandler();
1113 foreach ($formID as $fId) {
1114 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1115 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1116 }
1117 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1118 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1119 }
1120
1121 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1122 }
1123
1124 public function genarateNewLayoutNField($layout, $fields, $oldId, $newId)
1125 {
1126 $newField = (object) [];
1127 foreach ($layout->lg as $ind => $itm) {
1128 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1129 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
1130 $layout->md[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->md[$ind]->i);
1131 $layout->sm[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->sm[$ind]->i);
1132 $newField->{$layout->lg[$ind]->i} = $fld_tmp;
1133 }
1134 return ['layout' => $layout, 'fields' => $newField];
1135 }
1136
1137 public function duplicateAForm($Request, $post)
1138 {
1139 $oldFormId = intval($post->id);
1140 $newFormId = intval($post->newFormId);
1141 if ($oldFormId < 1) {
1142 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1143 }
1144
1145 $formManager = new AdminFormManager($oldFormId);
1146 if (!$formManager->isExist()) {
1147 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1148 }
1149
1150 $duplicatedForm = $this->getAForm($Request, $post);
1151 $duplicatedForm['form_name'] = 'Duplicate of ' . $duplicatedForm['form_name'];
1152 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1153
1154
1155 /* echo wp_json_encode($formData);
1156 \wp_die(); */
1157 $duplicateResponse = $this->createNewForm(null, $formData);
1158
1159 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && $duplicateResponse->get_error_code() === 'result_empty')) {
1160 // duplicate stylesheet
1161 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1162 // layout style copy
1163 $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1164 $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1165 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1166 $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1167 fwrite($createStyleFile, $newStyle);
1168 fclose($createStyleFile);
1169 // style copy
1170 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1171 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1172 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1173 $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1174 fwrite($createStyleFile, $newStyle);
1175 fclose($createStyleFile);
1176 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1177 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1178 return $duplicatedForm;
1179 }
1180 return $duplicateResponse;
1181 }
1182
1183 public function importAForm($post)
1184 {
1185
1186 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1187 $newFormId = intval($post->newFormId);
1188 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1189 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1190 }
1191 $importtedForm = (array)$post->formDetail;
1192 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1193 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1194 unset($importtedForm['fields'], $importtedForm['layout']);
1195 $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1196
1197 if (!empty($importtedForm['rowHeight'])) {
1198 $formData->rowHeight = $importtedForm['rowHeight'];
1199 }
1200
1201 if (!empty($importtedForm['formStyle'])) {
1202 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $importtedForm['formStyle']);
1203 $formData->layoutChanged = '-';
1204 }
1205 $importResponse = $this->createNewForm(null, $formData);
1206
1207 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && $importResponse->get_error_code() === 'result_empty')) {
1208 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1209 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1210 return $responseData;
1211 }
1212 return $importResponse;
1213 }
1214
1215 public function exportAForm($Request)
1216 {
1217 $oldFormId = intval($Request['id']);
1218 if ($oldFormId < 1) {
1219 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1220 }
1221 $formManager = new AdminFormManager($oldFormId);
1222 if (!$formManager->isExist()) {
1223 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1224 }
1225
1226 $newFormId = $oldFormId;
1227 $duplicatedForm = $this->getAForm($Request, (object)["id" => $oldFormId]);
1228 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1229
1230 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1231 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1232 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1233
1234 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1235 $formData->layoutChanged = "-";
1236 $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1237
1238 $formJson = json_encode($formData);
1239 header("Content-Type: application/force-download");
1240 header("Content-Type: application/octet-stream");
1241 header("Content-Type: application/download");
1242 header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
1243 header('Content-Description: File Transfer');
1244 header('Expires: 0');
1245 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1246 header('Pragma: public');
1247 header('Content-Length: ' . strlen($formJson));
1248 header("Content-Transfer-Encoding: binary ");
1249 flush();
1250 echo $formJson;
1251 die();
1252 }
1253
1254 public function getFormEntryLabelAndCount($Request, $post)
1255 {
1256 if (isset($Request['id'])) {
1257 $id = wp_unslash($Request['id']);
1258 } else {
1259 $id = wp_unslash($post->id);
1260 }
1261 if (is_null($id)) {
1262 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1263 }
1264 $formManager = new AdminFormManager($id);
1265 if (!$formManager->isExist()) {
1266 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1267 }
1268 $formFields = $formManager->getFieldLabel();
1269 $formEntry = new FormEntryModel();
1270 $count = $formEntry->count(
1271 array(
1272 'form_id' => $id,
1273 )
1274 );
1275 $reportsModel = new ReportsModel();
1276 $returnedReportData = $reportsModel->get(
1277 array(
1278 "id",
1279 "details",
1280 "isDefault",
1281 "type",
1282 ),
1283 array(
1284 "category" => 'form',
1285 "context" => $id,
1286 )
1287 );
1288 $labels = [];
1289 if (!is_wp_error($returnedReportData)) {
1290 $fieldNames = [];
1291 foreach ($formFields as $field) {
1292 $fieldNames[$field['key']] = $field['name'];
1293 $labels[$field['key']] = $field;
1294 }
1295 foreach ($returnedReportData as $reportKey => $reportData) {
1296 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1297 if (!empty($reportDetails) && is_string($reportDetails)) {
1298 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1299 } elseif (!empty($reportDetails)) {
1300 $returnedReportData[$reportKey]->details = $reportDetails;
1301 }
1302 }
1303 $response['reports'] = empty($returnedReportData) ? [] : $returnedReportData;
1304 }
1305
1306 $response['count'] = intval($count[0]->count);
1307 $response['Labels'] = $formFields;
1308 $response['fieldDetails'] = $labels;
1309 return $response;
1310 }
1311 public function getFormEntry($Request, $post)
1312 {
1313 if (isset($Request['id'])) {
1314 $id = wp_unslash($Request['id']);
1315 $offset = isset($Request['offset']) ?
1316 wp_unslash($Request['offset']) : 0;
1317 $pageSize = isset($Request['pageSize']) ?
1318 wp_unslash($Request['pageSize']) : 10;
1319 } else {
1320 $id = wp_unslash($post->id);
1321 $offset = isset($post->offset) ? wp_unslash($post->offset) : 0;
1322 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1323 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1324 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1325 $pageSize = isset($post->pageSize) ?
1326 wp_unslash($post->pageSize) : 10;
1327 }
1328 if (is_null($id)) {
1329 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1330 }
1331 $formManager = new AdminFormManager($id);
1332 if (!$formManager->isExist()) {
1333 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1334 }
1335
1336 $formEntry = new FormEntryModel();
1337 $entries = $formEntry->get(
1338 'id',
1339 array(
1340 'form_id' => $id,
1341 ),
1342 null,
1343 null,
1344 'created_at',
1345 'DESC'
1346 );
1347 if (is_wp_error($entries)) {
1348 if ($entries->get_error_code() === 'result_empty') {
1349 return array(
1350 'count' => 0,
1351 'entries' => [],
1352 );
1353 }
1354 return $entries;
1355 }
1356 $filter['field'] = $filters;
1357 $filter['global'] = $globalFilter;
1358
1359 $formFields = $formManager->getFieldLabel(true);
1360 $fieldDetails = $formManager->getFields();
1361
1362 $entryMeta = new FormEntryMetaModel();
1363 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy);
1364 $customFieldHandler = new CustomFieldHandler();
1365 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1366 return $formEntries;
1367 }
1368
1369 public function getExportEntry($post)
1370 {
1371 $formId = wp_unslash($post->formId);
1372 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
1373 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1374 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1375 $formFields = json_decode($post->selectedField);
1376 if (is_null($formId)) {
1377 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1378 }
1379 $formManager = new AdminFormManager($formId);
1380 $fieldLabels = $formManager->getFieldLabel(true);
1381 if (!$formManager->isExist()) {
1382 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1383 }
1384
1385 $formEntry = new FormEntryModel();
1386 $entries = $formEntry->get(
1387 'id',
1388 array(
1389 'form_id' => $formId,
1390 ),
1391 null,
1392 null,
1393 'created_at',
1394 'DESC'
1395 );
1396 if (is_wp_error($entries)) {
1397 if ($entries->get_error_code() === 'result_empty') {
1398 return array(
1399 'count' => 0,
1400 'entries' => [],
1401 );
1402 }
1403 return $entries;
1404 }
1405 $entryMeta = new FormEntryMetaModel();
1406 $filter = [];
1407 $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
1408 return $formEntries;
1409 }
1410 public function deleteBlukFormEntries($Request, $post)
1411 {
1412 if (isset($Request['formID'])) {
1413 $formID = wp_unslash($Request['formID']);
1414 $entries = wp_unslash($Request['entries']);
1415 } else {
1416 $formID = wp_unslash($post->formID);
1417 $entries = wp_unslash($post->entries);
1418 }
1419 if (is_null($formID) || !is_array($entries) || count($entries) === 0) {
1420 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1421 }
1422 $formManager = new AdminFormManager($formID);
1423 if (!$formManager->isExist()) {
1424 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1425 }
1426 $workFlowRunHelper = new WorkFlowRunHelper($formID);
1427 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1428 $formManager,
1429 $formID,
1430 $entries
1431 );
1432 if (isset($workFlowreturnedOnDelete['entries'])) {
1433 if (count($workFlowreturnedOnDelete['entries']) === 0) {
1434 return ["message" => __('Entry Deletetion prevented by workflow', 'bit-form')];
1435 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1436 $message = __('Entry Deleted successfully', 'bit-form');
1437 } else {
1438 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
1439 $entries = $workFlowreturnedOnDelete['entries'];
1440 $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
1441 }
1442 } else {
1443 $message = __('Entry Deleted successfully', 'bit-form');
1444 }
1445 global $wpdb;
1446 $prefix = $wpdb->prefix;
1447 $formEntryModel = new FormEntryModel();
1448 $delete_status = $formEntryModel->bulkDelete(
1449 array(
1450 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1451 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1452 )
1453 );
1454 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1455 $fileHandler = new FileHandler();
1456 foreach ($entries as $enrtyKey => $entryID) {
1457 $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
1458 if (file_exists($fileEntries)) {
1459 $fileHandler->rmrf($fileEntries);
1460 }
1461 }
1462 }
1463 $count = $formEntryModel->count(
1464 array(
1465 'form_id' => $formID,
1466 )
1467 );
1468 $formManager->resetSubmissionCount(intval($count[0]->count));
1469 if (is_wp_error($delete_status)) {
1470 return new WP_Error('entry_not_exists', __("Form entry deletion failed.", "bit-form"));
1471 }
1472 $result['message'] = $message;
1473 return $result;
1474 }
1475 public function duplicateFormEntry($Request, $post)
1476 {
1477 if (isset($Request['formID'])) {
1478 $formID = wp_unslash($Request['formID']);
1479 $entries = wp_unslash($Request['entries']);
1480 } else {
1481 $formID = wp_unslash($post->formID);
1482 $entries = wp_unslash($post->entries);
1483 }
1484 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1485 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1486 }
1487
1488 $formManager = new AdminFormManager($formID);
1489 if (!$formManager->isExist()) {
1490 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1491 }
1492 $formEntryModel = new FormEntryModel();
1493 $entryMeta = new FormEntryMetaModel();
1494 $user_details = static::$ipTool->getUserDetail();
1495 $total_entries = count($entries);
1496 $duplicate_count = 0;
1497 $test = '';
1498 $fileHandler = new FileHandler();
1499 $result = array();
1500 foreach ($entries as $entryIndex => $entryID) {
1501 $duplicatedEntryId = $formEntryModel->insert(
1502 array(
1503 'form_id' => $formID,
1504 'user_id' => $user_details['id'],
1505 'user_ip' => $user_details['ip'],
1506 'user_device' => $user_details['device'],
1507 'referer' => 'duplicate of #' . $entryID,
1508 'status' => 0,
1509 'created_at' => $user_details['time'],
1510 )
1511 );
1512 if ($duplicatedEntryId) {
1513 $duplicate_status = $entryMeta->duplicateEntryMeta(
1514 array(
1515 'duplicateID' => $duplicatedEntryId,
1516 'entryID' => $entryID,
1517 )
1518 );
1519 if ($duplicate_status) {
1520 $result['details'][$entryID] = $duplicatedEntryId;
1521 $duplicate_count = $duplicate_count + 1;
1522 if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
1523 $fileHandler->cpyr(
1524 BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1525 BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
1526 );
1527 }
1528 }
1529 }
1530 }
1531
1532 $count = $formEntryModel->count(
1533 array(
1534 'form_id' => $formID,
1535 )
1536 );
1537 $formManager->resetSubmissionCount(intval($count[0]->count));
1538 $result['message'] = count($entries) === 1 ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
1539 return ($total_entries === $duplicate_count) ? $result : false;
1540 }
1541 public function editFormEntry($Request, $post)
1542 {
1543 if (isset($Request['formID'])) {
1544 $formID = wp_unslash($Request['formID']);
1545 $entryID = wp_unslash($Request['entryID']);
1546 } else {
1547 $formID = wp_unslash($post->formID);
1548 $entryID = wp_unslash($post->entryID);
1549 }
1550 if (is_null($formID) || is_null($entryID)) {
1551 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1552 }
1553
1554 $formManager = new AdminFormManager($formID);
1555 if (!$formManager->isExist()) {
1556 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1557 }
1558 $formEntryModel = new FormEntryModel();
1559 $entryMeta = new FormEntryMetaModel();
1560
1561 $formEntry = $formEntryModel->get(
1562 "*",
1563 array(
1564 'form_id' => $formID,
1565 'id' => $entryID,
1566 )
1567 );
1568
1569 if (!$formEntry) {
1570 return new WP_Error('empty_form', __('Form entries does not exist.', 'bit-form'));
1571 }
1572 $formEntryMeta = $entryMeta->get(
1573 array(
1574 'meta_key',
1575 'meta_value',
1576 ),
1577 array(
1578 'bitforms_form_entry_id' => $entryID,
1579 )
1580 );
1581 $entries = array();
1582 foreach ($formEntryMeta as $key => $value) {
1583 $entries[$value->meta_key] = $value->meta_value;
1584 }
1585 $formContent = $formManager->getFormContent();
1586 $fieldsKey = $formManager->getFieldsKey();
1587 $form_fields = $formContent->fields;
1588 $layout = $formContent->layout;
1589 foreach ($form_fields as $key => $value) {
1590 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
1591 if (isset($entries[$key])) {
1592 $form_fields->{$key}->val = $entries[$key];
1593 $form_fields->{$key}->name = $key;
1594 }
1595 }
1596 $workFlowRunHelper = new WorkFlowRunHelper($formID);
1597 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
1598 'edit',
1599 $form_fields
1600 );
1601 $workFlowreturnedOnUserInput = $workFlowRunHelper->executeOnUserInput(
1602 'edit',
1603 $form_fields
1604 );
1605 // var_dump($workFlowreturned);
1606 if (!empty($workFlowreturnedOnLoad['fields'])) {
1607 $form_fields = $workFlowreturnedOnLoad['fields'];
1608 }
1609 $formData = array(
1610 'layout' => $layout,
1611 'fields' => $form_fields,
1612 'conditional' => !empty($workFlowreturnedOnUserInput['conditional']) ? $workFlowreturnedOnUserInput['conditional'] : false,
1613 'fieldToCheck' => !empty($workFlowreturnedOnUserInput['fieldToCheck']) ? $workFlowreturnedOnUserInput['fieldToCheck'] : false,
1614 'fieldToChange' => !empty($workFlowreturnedOnUserInput['fieldToChange']) ? $workFlowreturnedOnUserInput['fieldToChange'] : false,
1615 'fieldsKey' => $fieldsKey,
1616 );
1617 return $formData;
1618 }
1619 public function updateFormEntry($Request, $post)
1620 {
1621 if (isset($Request['formID']) && isset($Request['entryID'])) {
1622 $formID = wp_unslash($Request['formID']);
1623 $entryID = wp_unslash($Request['entryID']);
1624 unset($Request['action']);
1625 unset($Request['formID']);
1626 unset($Request['entryID']);
1627 $updatedValue = wp_unslash($post);
1628 }
1629
1630 if (is_null($updatedValue) || !is_array($updatedValue)) {
1631 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1632 }
1633
1634 if (is_null($formID) || is_null($entryID)) {
1635 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
1636 }
1637
1638 $formManager = new AdminFormManager($formID);
1639 if (!$formManager->isExist()) {
1640 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
1641 }
1642 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
1643 }
1644
1645 public function getLogHistory($Request, $post)
1646 {
1647 if (isset($Request['formID'])) {
1648 $formID = wp_unslash($Request['formID']);
1649 $entryID = wp_unslash($Request['entryID']);
1650 } else {
1651 $formID = wp_unslash($post->formID);
1652 $entryID = wp_unslash($post->entryID);
1653 }
1654
1655 if (is_null($formID) || is_null($entryID)) {
1656 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1657 }
1658
1659 $formManager = new AdminFormManager($formID);
1660 if (!$formManager->isExist()) {
1661 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1662 }
1663 $formLogModel = new FormEntryLogModel();
1664
1665 $log_history = $formLogModel->geLogHistory($formID, $entryID);
1666 return $log_history;
1667 }
1668
1669 public function importDataStore($Request, $post)
1670 {
1671 if (isset($Request['formID'])) {
1672 $formID = wp_unslash($Request['formID']);
1673 } else {
1674 $formID = wp_unslash($post->formID);
1675 }
1676 if (is_null($formID)) {
1677 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
1678 }
1679 }
1680
1681 public function getAllWPPages($Request, $post)
1682 {
1683 $pages = get_pages(array('post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc'));
1684 $allPages = array();
1685 foreach ($pages as $pageKey => $pageDetails) {
1686 $allPages[$pageKey]['title'] = $pageDetails->post_title;
1687 $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
1688 }
1689 return $allPages;
1690 }
1691 public function deleteAIntegration($Request, $post)
1692 {
1693 if (isset($Request['formID']) && $Request['id']) {
1694 $formID = json_decode(wp_unslash($Request['formID']));
1695 $id = wp_unslash($Request['id']);
1696 } else {
1697 $formID = wp_unslash($post->formID);
1698 $id = wp_unslash($post->id);
1699 }
1700 if ($formID < 0 || empty($id)) {
1701 return new WP_Error('empty_form', 'Invalid Form ID or Integration ID.');
1702 }
1703
1704 $integrationHandler = new IntegrationHandler($formID);
1705 $delete_status = $integrationHandler->deleteIntegration($id);
1706 if (is_wp_error($delete_status)) {
1707 return $delete_status;
1708 }
1709
1710 return array(
1711 'message' => __('Integration deleted', 'bit-form'),
1712 );
1713 }
1714
1715 public function deleteSuccessMessage($Request, $post)
1716 {
1717 if (isset($Request['formID']) && $Request['id']) {
1718 $formID = json_decode(wp_unslash($Request['formID']));
1719 $id = wp_unslash($Request['id']);
1720 } else {
1721 $formID = wp_unslash($post->formID);
1722 $id = wp_unslash($post->id);
1723 }
1724 if (empty($formID) || empty($id)) {
1725 return new WP_Error('empty_form', 'Invalid Form ID or Message ID.');
1726 }
1727 $successMessageHandler
1728 = new SuccessMessageHandler($formID);
1729 $delete_status = $successMessageHandler->deleteMessage($id);
1730 if (is_wp_error($delete_status)) {
1731 return $delete_status;
1732 }
1733 return array(
1734 'message' => __('Message deleted', 'bit-form'),
1735 );
1736 }
1737
1738 public function deleteAWorkflow($Request, $post)
1739 {
1740 if (isset($Request['formID']) && $Request['id']) {
1741 $formID = json_decode(wp_unslash($Request['formID']));
1742 $id = wp_unslash($Request['id']);
1743 } else {
1744 $formID = wp_unslash($post->formID);
1745 $id = wp_unslash($post->id);
1746 }
1747 if (empty($formID) || empty($id)) {
1748 return new WP_Error('empty_form', 'Invalid Form ID or Workflow ID.');
1749 }
1750 $workFlowHandler = new WorkFlowHandler($formID);
1751 $delete_status = $workFlowHandler->deleteworkFlow($id);
1752 if (is_wp_error($delete_status)) {
1753 return $delete_status;
1754 }
1755 return array(
1756 'message' => __('workflow deleted', 'bit-form'),
1757 );
1758 }
1759 public function deleteAMailTemplate($Request, $post)
1760 {
1761 if (isset($Request['formID']) && $Request['id']) {
1762 $formID = json_decode(wp_unslash($Request['formID']));
1763 $id = wp_unslash($Request['id']);
1764 } else {
1765 $formID = wp_unslash($post->formID);
1766 $id = wp_unslash($post->id);
1767 }
1768 if (empty($formID) || empty($id)) {
1769 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
1770 }
1771 $emailTemplateHandler = new EmailTemplateHandler($formID);
1772 $delete_status = $emailTemplateHandler->deleteTemplate($id);
1773 if (is_wp_error($delete_status)) {
1774 return $delete_status;
1775 }
1776 return array(
1777 'message' => __('Email Template deleted', 'bit-form'),
1778 );
1779 }
1780 public function duplicateAMailTemplate($Request, $post)
1781 {
1782 if (isset($Request['formID']) && $Request['id']) {
1783 $formID = json_decode(wp_unslash($Request['formID']));
1784 $id = wp_unslash($Request['id']);
1785 } else {
1786 $formID = wp_unslash($post->formID);
1787 $id = wp_unslash($post->id);
1788 }
1789 if (empty($formID) || empty($id)) {
1790 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
1791 }
1792 $emailTemplateHandler = new EmailTemplateHandler($formID);
1793 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
1794 if (is_wp_error($duplicate_status)) {
1795 return $duplicate_status;
1796 }
1797 return array(
1798 'message' => __('Email Template duplicated', 'bit-form'),
1799 );
1800 }
1801 public function setAllFormsReport($Request, $post)
1802 {
1803 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
1804 if (empty($reports)) {
1805 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
1806 }
1807 if (!empty($reports)) {
1808 $reportsModel = new ReportsModel();
1809 $user_details = static::$ipTool->getUserDetail();
1810 foreach ($reports as $reportIndex => $report) {
1811 if (empty($report->id)) {
1812 $reportSaveSatus = $reportsModel->insert(
1813 array(
1814 "type" => 'table',
1815 "category" => 'app',
1816 "context" => 'allForm',
1817 "details" => is_string($report->details) ? $report->details : wp_json_encode($report->details),
1818 "isDefault" => 1,
1819 "user_id" => $user_details['id'],
1820 "user_ip" => $user_details['ip'],
1821 "user_device" => $user_details['device'],
1822 "created_at" => $user_details['time'],
1823 "updated_at" => $user_details['time'],
1824 )
1825 );
1826 $newData['reports'] = 1;
1827 } else {
1828 $reportSaveSatus = $reportsModel->update(
1829 array(
1830 "type" => 'table',
1831 "category" => 'app',
1832 "context" => 'allForm',
1833 "details" => is_string($report->details) ? $report->details : wp_json_encode($report->details),
1834 "isDefault" => 1,
1835 "user_id" => $user_details['id'],
1836 "user_ip" => $user_details['ip'],
1837 "user_device" => $user_details['device'],
1838 "updated_at" => $user_details['time'],
1839 ),
1840 array(
1841 'id' => $report->id,
1842 )
1843 );
1844 }
1845 }
1846 }
1847 if (is_wp_error($reportSaveSatus)) {
1848 if ($reportSaveSatus->get_error_code() === 'result_empty') {
1849 return new WP_Error('empty_report_prefs', 'Nothing to save or update');
1850 }
1851 return new WP_Error('error_report_prefs', 'Error occured in saving reports');
1852 }
1853 $returnedReportData = $reportsModel->get(
1854 array(
1855 "id",
1856 "details",
1857 "isDefault",
1858 "category",
1859 "context",
1860 ),
1861 array(
1862 "category" => 'app',
1863 "context" => 'allForm',
1864 )
1865 );
1866 if (!is_wp_error($returnedReportData)) {
1867 foreach ($returnedReportData as $reportKey => $reportData) {
1868 if (isset($reportData->details) && is_string($reportData->details)) {
1869 $returnedReportData[$reportKey]->details = json_decode($reportData->details);
1870 }
1871 }
1872 $reports = $returnedReportData;
1873 }
1874 return array(
1875 'message' => __('Report preferrences saved successfully', 'bit-form'),
1876 'reports' => empty($reports) ? [] : $reports,
1877 );
1878 }
1879
1880 public function savegReCaptcha($Request, $post)
1881 {
1882 $reCaptcha = $post->reCaptcha;
1883
1884 if (is_null($reCaptcha)) {
1885 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
1886 }
1887 if (is_string($reCaptcha) && !empty(json_decode($reCaptcha)->id)) {
1888 $reCaptcha = json_decode($reCaptcha);
1889 $integrationID = $reCaptcha->id;
1890 unset($reCaptcha->id);
1891 } else {
1892 $integrationID = $reCaptcha->id;
1893 unset($reCaptcha->id);
1894 }
1895 $reCaptcha = json_encode($reCaptcha);
1896 $integrationName = 'google reCaptcha';
1897 $integrationType = $post->version === 'v2' ? 'gReCaptcha' : 'gReCaptchaV3';
1898 $integrationDetails = $reCaptcha;
1899 $user_details = static::$ipTool->getUserDetail();
1900 $integrationHandler = new IntegrationHandler(0, $user_details);
1901 $response = array();
1902 if (empty($integrationID)) {
1903 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
1904 $response['id'] = $captchaSaveStatus;
1905 $response['message'] = __('g-reCAPTCHA saved successfully', 'bit-form');
1906 } else {
1907 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
1908 $response['message'] = __('g-reCAPTCHA updated successfully', 'bit-form');
1909 }
1910
1911 if (is_wp_error($captchaSaveStatus)) {
1912 return $captchaSaveStatus;
1913 }
1914 return $response;
1915 }
1916
1917 public function savePaymentSetting($Request, $post)
1918 {
1919 if (isset($post->paySetting)) {
1920 $paySetting = $post->paySetting;
1921 } else {
1922 $paySetting = $post->paySetting;
1923 }
1924 if (is_null($paySetting)) {
1925 return new WP_Error('empty_gcaptchdetails', __('Setting details is empty', 'bit-form'));
1926 }
1927 if (is_string($paySetting) && !empty(json_decode($paySetting)->id)) {
1928 $paySetting = json_decode($paySetting);
1929 $integrationID = $paySetting->id;
1930 unset($paySetting->id);
1931 } else {
1932 $integrationID = $paySetting->id;
1933 unset($paySetting->id);
1934 }
1935 $integrationName = $paySetting->name;
1936 $integrationType = 'payments';
1937 $paySetting = json_encode($paySetting);
1938 $integrationDetails = $paySetting;
1939 $user_details = static::$ipTool->getUserDetail();
1940 $integrationHandler = new IntegrationHandler(0, $user_details);
1941 $response = array();
1942 if (empty($integrationID)) {
1943 $paymentSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
1944 $response['id'] = $paymentSaveStatus;
1945 $response['message'] = __('Payment setting saved successfully', 'bit-form');
1946 } else {
1947 $paymentSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
1948 $response['message'] = __('Payment setting updated successfully', 'bit-form');
1949 }
1950
1951 if (is_wp_error($paymentSaveStatus)) {
1952 return $paymentSaveStatus;
1953 }
1954 return $response;
1955 }
1956 }
1957