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

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