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

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

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