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

1,958 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 'updated_at' => $user_details['time'],
643 ],
644 [
645 'id' => $formID,
646 ]
647 );
648 if (is_wp_error($update_status)) {
649 return $update_status;
650 } elseif (!$update_status) {
651 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
652 } else {
653 if (isset($post->deletedFldKey) && is_array($post->deletedFldKey)) {
654 $this->setEmptyMetaValue($post->deletedFldKey);
655 unset($post->deletedFldKey);
656 }
657 $updated_data = $this->getAForm(['id' => $formID], null);
658 if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation']) {
659 unset($updated_data['formSettings']);
660 }
661 if (0 === $newData['integation']) {
662 unset($updated_data['integrations']);
663 } elseif (2 === $newData['integation']) {
664 $errorIN = '';
665 $errorIN .= empty($errorIN) ? 'integation' : ', integation';
666 }
667 if (0 === $newData['mailTemplate']) {
668 unset($updated_data['mailTem']);
669 } elseif (2 === $newData['mailTemplate']) {
670 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
671 }
672 if (0 === $newData['workflow']) {
673 unset($updated_data['workFlows']);
674 } elseif (2 === $newData['workflow']) {
675 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
676 }
677 if (2 === $newData['reports']) {
678 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
679 }
680 if (!empty($errorIN)) {
681 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
682 return new WP_Error('Form update Error.', $updated_data);
683 }
684 if (null !== $reportIsDefault) {
685 $updated_data['form_content']['is_default'] = $reportIsDefault;
686 }
687 $updated_data['message'] = __('Form updated successfully.', 'bitform');
688 return $updated_data;
689 }
690 }
691
692 public function setEmptyMetaValue($fieldkeys) {
693 $sqlEscaped = array_map(function ($fld) {
694 return "'" . esc_sql($fld) . "'";
695 }, $fieldkeys);
696 $deletedFldKey = implode(',', $sqlEscaped);
697 global $wpdb;
698 $tablename = $wpdb->prefix . 'bitforms_form_entrymeta';
699 $sql = $wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN ( " . $deletedFldKey . ')', '');
700 $wpdb->query($sql);
701 }
702
703 public function changeFormStatus($Request, $post) {
704 if (isset($Request['status']) && $Request['id']) {
705 $status = wp_unslash($Request['status']);
706 $id = wp_unslash($Request['id']);
707 } else {
708 $status = wp_unslash($post->status);
709 $id = wp_unslash($post->id);
710 }
711 $user_details = static::$ipTool->getUserDetail();
712 // return $post->fields;
713 $status = 'true' === $status || true === $status ? true : false;
714 if (!is_bool($status) || is_null($id)) {
715 // echo $status;
716 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
717 }
718 $update_status = static::$formModel->update(
719 [
720 'user_id' => $user_details['id'],
721 'user_ip' => $user_details['ip'],
722 'user_device' => $user_details['device'],
723 'status' => $status ? 1 : 0,
724 'updated_at' => $user_details['time'],
725 ],
726 [
727 'id' => $id,
728 ]
729 );
730 if (is_wp_error($update_status)) {
731 return $update_status;
732 } elseif (!$update_status) {
733 return false;
734 } else {
735 return __('Form status changed successfully', 'bit-form');
736 }
737 }
738
739 public function changeBulkFormStatus($Request, $post) {
740 if (isset($Request['status']) && $Request['formID']) {
741 $status = wp_unslash($Request['status']);
742 $formID = wp_unslash($Request['formID']);
743 } else {
744 $status = wp_unslash($post->status);
745 $formID = wp_unslash($post->formID);
746 }
747 $user_details = static::$ipTool->getUserDetail();
748 // return $post->fields;
749 $status = 'true' === $status || true === $status ? true : false;
750 if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
751 // echo $status;
752 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
753 }
754 $update_status = static::$formModel->bulkUpdate(
755 [
756 'user_id' => $user_details['id'],
757 'user_ip' => $user_details['ip'],
758 'user_device' => $user_details['device'],
759 'status' => $status ? 1 : 0,
760 'updated_at' => $user_details['time'],
761 ],
762 [
763 'id' => $formID,
764 ]
765 );
766 if (is_wp_error($update_status)) {
767 return $update_status;
768 } elseif (!$update_status) {
769 return false;
770 } else {
771 return __('Form status changed successfully', 'bit-form');
772 }
773 }
774
775 public function getAllForm() {
776 global $wpdb;
777
778 $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");
779
780 if (is_wp_error($allForms)) {
781 return $allForms;
782 } elseif (!$allForms) {
783 return [];
784 } else {
785 return $allForms;
786 }
787 }
788
789 public function getAForm($Request, $post) {
790 if (isset($Request['id'])) {
791 $formID = wp_unslash($Request['id']);
792 } else {
793 $formID = wp_unslash($post->id);
794 }
795 // return $post->fields;
796 if (is_null($formID)) {
797 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
798 }
799 $formManager = new AdminFormManager($formID);
800 if (!$formManager->isExist()) {
801 return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
802 }
803 $form_content = $formManager->getFormContent();
804 if ($formManager->isExist()) {
805 $form_content_arr = [
806 'layout' => $form_content->layout,
807 'fields' => $form_content->fields,
808 'form_name' => $formManager->getFormName(),
809 'workFlowExist' => $form_content->workFlowExist,
810 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
811 ];
812 $successMessageHandler
813 = new SuccessMessageHandler($formID);
814 $successMessages = $successMessageHandler->getAllMessage();
815 if (!is_wp_error($successMessages)) {
816 foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
817 $allConfirmation['type']['successMsg'][$sucessMessagekey] =
818 [
819 'id' => $sucessMessagevalue->id,
820 'title' => $sucessMessagevalue->message_title,
821 'msg' => $sucessMessagevalue->message_content,
822 ];
823 }
824 }
825 $emailTemplateHandler
826 = new EmailTemplateHandler($formID);
827 $emailTemplates = $emailTemplateHandler->getAllTemplate();
828 if (!is_wp_error($emailTemplates)) {
829 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
830 $mailTem[] =
831 [
832 'id' => $emailTemplatevalue->id,
833 'title' => $emailTemplatevalue->title,
834 'sub' => $emailTemplatevalue->sub,
835 'body' => $emailTemplatevalue->body,
836 ];
837 }
838 }
839 $integrationHandler = new IntegrationHandler($formID);
840 $formIntegrations = $integrationHandler->getAllIntegration('form');
841 if (!is_wp_error($formIntegrations)) {
842 foreach ($formIntegrations as $integrationkey => $integrationValue) {
843 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
844 $integrationData = [
845 'id' => $integrationValue->id,
846 'title' => $integrationValue->integration_name,
847 ];
848 if (!empty($integrationValue->integration_details)) {
849 // var_dump(json_decode($integrationValue->integration_details));
850 $integration_details = (array) json_decode($integrationValue->integration_details);
851 $integrationData = array_merge($integration_details, $integrationData);
852 } else {
853 $integration_details = [
854 'url' => '',
855 ];
856 $integrationData = array_merge($integrationData, $integration_details);
857 }
858 $allConfirmation['type'][$integrationValue->integration_type][]
859 = $integrationData;
860 } else {
861 $integrationData = [
862 'id' => $integrationValue->id,
863 'name' => $integrationValue->integration_name,
864 'type' => $integrationValue->integration_type,
865 ];
866 $integrations[] = array_merge(
867 $integrationData,
868 is_string($integrationValue->integration_details) ?
869 (array) json_decode($integrationValue->integration_details) :
870 $integrationValue->integration_details
871 );
872 }
873 }
874 }
875 $settingsContent = [
876 'formName' => $formManager->getFormName(),
877 'theme' => $form_content->theme,
878 // 'submitBtn' => $form_content->buttons,
879 ];
880
881 if (!empty($allConfirmation)) {
882 $confirmation = [
883 'confirmation' => $allConfirmation,
884 ];
885 } else {
886 $confirmation = [
887 'confirmation' => ['type' => []],
888 ];
889 }
890 $settingsContent = array_merge($settingsContent, $confirmation);
891 if (!empty($integrations)) {
892 $settingsContent = array_merge(
893 $settingsContent,
894 [
895 'integrations' => $integrations,
896 ]
897 );
898 } else {
899 $settingsContent = array_merge(
900 $settingsContent,
901 [
902 'integrations' => []
903 ]
904 );
905 }
906 if (!empty($mailTem)) {
907 $settingsContent = array_merge(
908 $settingsContent,
909 [
910 'mailTem' => $mailTem,
911 ]
912 );
913 } else {
914 $settingsContent = array_merge(
915 $settingsContent,
916 [
917 'mailTem' => []
918 ]
919 );
920 }
921 $formSettings = [
922 'formSettings' => $settingsContent,
923 ];
924 $data = [
925 'id' => $formID,
926 'form_name' => $formManager->getFormName(),
927 'form_content' => $form_content_arr,
928 'additional' => empty($form_content->additional) ? [
929 'enabled' => [
930 'blocked_ip' => false,
931 'restrict_form' => false,
932 ],
933 'settings' => [
934 'restrict_form' => [
935 'day' => [],
936 'date' => [
937 'from' => null,
938 'to' => null,
939 ],
940 'time' => [
941 'from' => null,
942 'to' => null,
943 ],
944 ],
945 'entry_limit' => null,
946 'blocked_ip' => [],
947 ],
948 'onePerIp' => false,
949 ] : $form_content->additional,
950 'created_at' => $formManager->getFormMetaData()['created_at'],
951 'views' => $formManager->getFormMetaData()['views'],
952 'entries' => $formManager->getFormMetaData()['entries'],
953 'status' => $formManager->getFormMetaData()['status'],
954 ];
955 $data = array_merge($data, $formSettings);
956 $workFlowHandler = new WorkFlowHandler($formID);
957 $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlow()];
958 $data = array_merge($data, $workFlows);
959 $reportsModel = new ReportsModel();
960 $returnedReportData = $reportsModel->get(
961 [
962 'id',
963 'details',
964 'isDefault',
965 'type',
966 ],
967 [
968 'category' => 'form',
969 'context' => $formID,
970 ]
971 );
972
973 if (!is_wp_error($returnedReportData)) {
974 $fieldNames = [];
975 foreach ($formManager->getFieldLabel() as $key => $field) {
976 $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
977 }
978 if ($formManager->isGCLIDEnabled()) {
979 $fieldNames['GCLID'] = 'GCLID';
980 }
981 foreach ($returnedReportData as $reportKey => $reportData) {
982 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
983 if (!empty($reportDetails) && is_string($reportDetails)) {
984 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
985 } elseif (!empty($reportDetails)) {
986 $returnedReportData[$reportKey]->details = $reportDetails;
987 } else {
988 $returnedReportData[$reportKey]->details = [];
989 }
990 if ('1' === (string) $reportData->isDefault) {
991 $returnedReportData[$reportKey]->details->report_name = 'All Entries';
992 }
993 }
994 $reports = ['reports' => $returnedReportData];
995 $data = array_merge($data, $reports);
996 }
997
998 $formFields = $formManager->getFieldLabel();
999 $data = array_merge($data, ['Labels' => $formFields]);
1000
1001 return $data;
1002 }
1003 }
1004
1005 public function deleteAForm($Request, $post) {
1006 if (isset($Request['id'])) {
1007 $formID = wp_unslash($Request['id']);
1008 } else {
1009 $formID = wp_unslash($post->id);
1010 }
1011 if (is_null($formID)) {
1012 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1013 }
1014 $delete_status = static::$formModel->delete(
1015 [
1016 'id' => $formID,
1017 ]
1018 );
1019
1020 $successMessageModel
1021 = new SuccessMessageModel();
1022 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1023
1024 $emailTemplateModel
1025 = new EmailTemplateModel();
1026 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1027
1028 $integrationModel = new IntegrationModel();
1029 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1030
1031 $workFlowModel = new WorkFlowModel();
1032 $deleteworkFlowStatus = $workFlowModel->delete(['form_id' => $formID]);
1033
1034 $reportsModel = new ReportsModel();
1035 $deleteReportStatus = $reportsModel->delete(['context' => $formID]);
1036
1037 $formEntryModel = new FormEntryModel();
1038 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1039 $entries = [];
1040
1041 if (!is_wp_error($returnedEntries)) {
1042 foreach ($returnedEntries as $entryKey => $entryInfo) {
1043 $entries[] = $entryInfo->id;
1044 }
1045 global $wpdb;
1046 $prefix = $wpdb->prefix;
1047 if (count($entries) > 0) {
1048 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1049 [
1050 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1051 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1052 ]
1053 );
1054 }
1055 }
1056
1057 $fileHandler = new FileHandler();
1058 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1059 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1060 }
1061 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1062 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1063 }
1064 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1065 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1066 }
1067 if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1068 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1069 }
1070 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1071 }
1072
1073 public function deleteBlukForm($Request, $post) {
1074 if (isset($Request['formID'])) {
1075 $formID = wp_unslash($Request['formID']);
1076 } else {
1077 $formID = wp_unslash($post->formID);
1078 }
1079 if (is_null($formID) || !is_array($formID)) {
1080 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1081 }
1082
1083 foreach ($formID as $id) {
1084 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $id . '.css');
1085 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $id . '.css');
1086 }
1087 $delete_status = static::$formModel->bulkDelete(
1088 [
1089 'id' => $formID,
1090 ]
1091 );
1092 $successMessageModel
1093 = new SuccessMessageModel();
1094 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1095
1096 $emailTemplateModel
1097 = new EmailTemplateModel();
1098 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1099
1100 $integrationModel = new IntegrationModel();
1101 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1102
1103 $workFlowModel = new WorkFlowModel();
1104 $deleteworkFlowStatus = $workFlowModel->bulkDelete(['form_id' => $formID]);
1105
1106 $reportsModel = new ReportsModel();
1107 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1108
1109 $formEntryModel = new FormEntryModel();
1110 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1111 $entries = [];
1112 foreach ($returnedEntries as $entryKey => $entryInfo) {
1113 $entries[] = $entryInfo->id;
1114 }
1115 global $wpdb;
1116 $prefix = $wpdb->prefix;
1117 if (count($entries) > 0) {
1118 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1119 [
1120 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1121 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1122 ]
1123 );
1124 }
1125
1126 $fileHandler = new FileHandler();
1127 foreach ($formID as $fId) {
1128 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1129 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1130 }
1131 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1132 unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1133 }
1134
1135 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1136 }
1137
1138 public function genarateNewLayoutNField($layout, $fields, $oldId, $newId) {
1139 $newField = (object) [];
1140 foreach ($layout->lg as $ind => $itm) {
1141 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1142 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
1143 $layout->md[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->md[$ind]->i);
1144 $layout->sm[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->sm[$ind]->i);
1145 $newField->{$layout->lg[$ind]->i} = $fld_tmp;
1146 }
1147 return ['layout' => $layout, 'fields' => $newField];
1148 }
1149
1150 public function duplicateAForm($Request, $post) {
1151 $oldFormId = intval($post->id);
1152 $newFormId = intval($post->newFormId);
1153 if ($oldFormId < 1) {
1154 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1155 }
1156
1157 $formManager = new AdminFormManager($oldFormId);
1158 if (!$formManager->isExist()) {
1159 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1160 }
1161
1162 $duplicatedForm = $this->getAForm($Request, $post);
1163 $duplicatedForm['form_name'] = 'Duplicate of ' . $duplicatedForm['form_name'];
1164 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1165
1166 /* echo wp_json_encode($formData);
1167 \wp_die(); */
1168 $duplicateResponse = $this->createNewForm(null, $formData);
1169
1170 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1171 // duplicate stylesheet
1172 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1173 // layout style copy
1174 $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1175 $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1176 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1177 $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1178 fwrite($createStyleFile, $newStyle);
1179 fclose($createStyleFile);
1180 // style copy
1181 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1182 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1183 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1184 $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1185 fwrite($createStyleFile, $newStyle);
1186 fclose($createStyleFile);
1187 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1188 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1189 return $duplicatedForm;
1190 }
1191 return $duplicateResponse;
1192 }
1193
1194 public function importAForm($post) {
1195 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1196 $newFormId = intval($post->newFormId);
1197 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1198 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1199 }
1200 $importtedForm = (array)$post->formDetail;
1201 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1202 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1203 unset($importtedForm['fields'], $importtedForm['layout']);
1204 $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1205
1206 if (!empty($importtedForm['rowHeight'])) {
1207 $formData->rowHeight = $importtedForm['rowHeight'];
1208 }
1209
1210 if (!empty($importtedForm['formStyle'])) {
1211 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $importtedForm['formStyle']);
1212 $formData->layoutChanged = '-';
1213 }
1214 $importResponse = $this->createNewForm(null, $formData);
1215
1216 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1217 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1218 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1219 return $responseData;
1220 }
1221 return $importResponse;
1222 }
1223
1224 public function exportAForm($Request) {
1225 $oldFormId = intval($Request['id']);
1226 if ($oldFormId < 1) {
1227 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1228 }
1229 $formManager = new AdminFormManager($oldFormId);
1230 if (!$formManager->isExist()) {
1231 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1232 }
1233
1234 $newFormId = $oldFormId;
1235 $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1236 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1237
1238 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1239 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1240 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1241
1242 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1243 $formData->layoutChanged = '-';
1244 $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1245
1246 $formJson = json_encode($formData);
1247 header('Content-Type: application/force-download');
1248 header('Content-Type: application/octet-stream');
1249 header('Content-Type: application/download');
1250 header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
1251 header('Content-Description: File Transfer');
1252 header('Expires: 0');
1253 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1254 header('Pragma: public');
1255 header('Content-Length: ' . strlen($formJson));
1256 header('Content-Transfer-Encoding: binary ');
1257 flush();
1258 echo $formJson;
1259 die();
1260 }
1261
1262 public function getFormEntryLabelAndCount($Request, $post) {
1263 if (isset($Request['id'])) {
1264 $id = wp_unslash($Request['id']);
1265 } else {
1266 $id = wp_unslash($post->id);
1267 }
1268 if (is_null($id)) {
1269 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1270 }
1271 $formManager = new AdminFormManager($id);
1272 if (!$formManager->isExist()) {
1273 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1274 }
1275 $formFields = $formManager->getFieldLabel();
1276 $formEntry = new FormEntryModel();
1277 $count = $formEntry->count(
1278 [
1279 'form_id' => $id,
1280 ]
1281 );
1282 $reportsModel = new ReportsModel();
1283 $returnedReportData = $reportsModel->get(
1284 [
1285 'id',
1286 'details',
1287 'isDefault',
1288 'type',
1289 ],
1290 [
1291 'category' => 'form',
1292 'context' => $id,
1293 ]
1294 );
1295 $labels = [];
1296 if (!is_wp_error($returnedReportData)) {
1297 $fieldNames = [];
1298 foreach ($formFields as $field) {
1299 $fieldNames[$field['key']] = $field['name'];
1300 $labels[$field['key']] = $field;
1301 }
1302 foreach ($returnedReportData as $reportKey => $reportData) {
1303 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1304 if (!empty($reportDetails) && is_string($reportDetails)) {
1305 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1306 } elseif (!empty($reportDetails)) {
1307 $returnedReportData[$reportKey]->details = $reportDetails;
1308 }
1309 }
1310 $response['reports'] = empty($returnedReportData) ? [] : $returnedReportData;
1311 }
1312
1313 $response['count'] = intval($count[0]->count);
1314 $response['Labels'] = $formFields;
1315 $response['fieldDetails'] = $labels;
1316 return $response;
1317 }
1318
1319 public function getFormEntry($Request, $post) {
1320 if (isset($Request['id'])) {
1321 $id = wp_unslash($Request['id']);
1322 $offset = isset($Request['offset']) ?
1323 wp_unslash($Request['offset']) : 0;
1324 $pageSize = isset($Request['pageSize']) ?
1325 wp_unslash($Request['pageSize']) : 10;
1326 } else {
1327 $id = wp_unslash($post->id);
1328 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1329 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1330 $offset = isset($post->offset) ? wp_unslash($post->offset) : 0;
1331 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1332 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1333 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1334 $pageSize = isset($post->pageSize) ?
1335 wp_unslash($post->pageSize) : 10;
1336 }
1337 if (is_null($id)) {
1338 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1339 }
1340 $formManager = new AdminFormManager($id);
1341 if (!$formManager->isExist()) {
1342 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1343 }
1344
1345 $formEntry = new FormEntryModel();
1346 $entries = $formEntry->get(
1347 'id',
1348 [
1349 'form_id' => $id,
1350 ],
1351 null,
1352 null,
1353 'created_at',
1354 'DESC'
1355 );
1356 if (is_wp_error($entries)) {
1357 if ('result_empty' === $entries->get_error_code()) {
1358 return [
1359 'count' => 0,
1360 'entries' => [],
1361 ];
1362 }
1363 return $entries;
1364 }
1365 $filter['field'] = $filters;
1366 $filter['global'] = $globalFilter;
1367
1368 $formFields = $formManager->getFieldLabel(true);
1369 $fieldDetails = $formManager->getFields();
1370
1371 $entryMeta = new FormEntryMetaModel();
1372 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1373 $customFieldHandler = new CustomFieldHandler();
1374 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1375 return $formEntries;
1376 }
1377
1378 public function getExportEntry($post) {
1379 $formId = wp_unslash($post->formId);
1380 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1381 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
1382 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1383 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1384 $formFields = json_decode($post->selectedField);
1385 if (is_null($formId)) {
1386 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1387 }
1388 $formManager = new AdminFormManager($formId);
1389 $fieldLabels = $formManager->getFieldLabel(true);
1390 if (!$formManager->isExist()) {
1391 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1392 }
1393
1394 $formEntry = new FormEntryModel();
1395 $entries = $formEntry->get(
1396 'id',
1397 [
1398 'form_id' => $formId,
1399 ],
1400 null,
1401 null,
1402 'created_at',
1403 'DESC'
1404 );
1405 if (is_wp_error($entries)) {
1406 if ('result_empty' === $entries->get_error_code()) {
1407 return [
1408 'count' => 0,
1409 'entries' => [],
1410 ];
1411 }
1412 return $entries;
1413 }
1414 $entryMeta = new FormEntryMetaModel();
1415 $filter = [];
1416 $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $fileFormate, $limit, $sortBy, $sortByField);
1417 return $formEntries;
1418 }
1419
1420 public function deleteBlukFormEntries($Request, $post) {
1421 if (isset($Request['formID'])) {
1422 $formID = wp_unslash($Request['formID']);
1423 $entries = wp_unslash($Request['entries']);
1424 } else {
1425 $formID = wp_unslash($post->formID);
1426 $entries = wp_unslash($post->entries);
1427 }
1428 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1429 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1430 }
1431 $formManager = new AdminFormManager($formID);
1432 if (!$formManager->isExist()) {
1433 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1434 }
1435 $workFlowRunHelper = new WorkFlowRunHelper($formID);
1436 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1437 $formManager,
1438 $formID,
1439 $entries
1440 );
1441 if (isset($workFlowreturnedOnDelete['entries'])) {
1442 if (0 === count($workFlowreturnedOnDelete['entries'])) {
1443 return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1444 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1445 $message = __('Entry Deleted successfully', 'bit-form');
1446 } else {
1447 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
1448 $entries = $workFlowreturnedOnDelete['entries'];
1449 $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
1450 }
1451 } else {
1452 $message = __('Entry Deleted successfully', 'bit-form');
1453 }
1454 global $wpdb;
1455 $prefix = $wpdb->prefix;
1456 $formEntryModel = new FormEntryModel();
1457 $delete_status = $formEntryModel->bulkDelete(
1458 [
1459 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1460 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1461 ]
1462 );
1463 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1464 $fileHandler = new FileHandler();
1465 foreach ($entries as $enrtyKey => $entryID) {
1466 $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
1467 if (file_exists($fileEntries)) {
1468 $fileHandler->rmrf($fileEntries);
1469 }
1470 }
1471 }
1472 $count = $formEntryModel->count(
1473 [
1474 'form_id' => $formID,
1475 ]
1476 );
1477 $formManager->resetSubmissionCount(intval($count[0]->count));
1478 if (is_wp_error($delete_status)) {
1479 return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
1480 }
1481 $result['message'] = $message;
1482 return $result;
1483 }
1484
1485 public function duplicateFormEntry($Request, $post) {
1486 if (isset($Request['formID'])) {
1487 $formID = wp_unslash($Request['formID']);
1488 $entries = wp_unslash($Request['entries']);
1489 } else {
1490 $formID = wp_unslash($post->formID);
1491 $entries = wp_unslash($post->entries);
1492 }
1493 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1494 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1495 }
1496
1497 $formManager = new AdminFormManager($formID);
1498 if (!$formManager->isExist()) {
1499 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1500 }
1501 $formEntryModel = new FormEntryModel();
1502 $entryMeta = new FormEntryMetaModel();
1503 $user_details = static::$ipTool->getUserDetail();
1504 $total_entries = count($entries);
1505 $duplicate_count = 0;
1506 $test = '';
1507 $fileHandler = new FileHandler();
1508 $result = [];
1509 foreach ($entries as $entryIndex => $entryID) {
1510 $duplicatedEntryId = $formEntryModel->insert(
1511 [
1512 'form_id' => $formID,
1513 'user_id' => $user_details['id'],
1514 'user_ip' => $user_details['ip'],
1515 'user_device' => $user_details['device'],
1516 'referer' => 'duplicate of #' . $entryID,
1517 'status' => 1,
1518 'created_at' => $user_details['time'],
1519 ]
1520 );
1521 if ($duplicatedEntryId) {
1522 $duplicate_status = $entryMeta->duplicateEntryMeta(
1523 [
1524 'duplicateID' => $duplicatedEntryId,
1525 'entryID' => $entryID,
1526 ]
1527 );
1528 if ($duplicate_status) {
1529 $result['details'][$entryID] = $duplicatedEntryId;
1530 $duplicate_count = $duplicate_count + 1;
1531 if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
1532 $fileHandler->cpyr(
1533 BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1534 BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
1535 );
1536 }
1537 }
1538 }
1539 }
1540
1541 $count = $formEntryModel->count(
1542 [
1543 'form_id' => $formID,
1544 ]
1545 );
1546 $formManager->resetSubmissionCount(intval($count[0]->count));
1547 $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
1548 return ($total_entries === $duplicate_count) ? $result : false;
1549 }
1550
1551 public function editFormEntry($Request, $post) {
1552 if (isset($Request['formID'])) {
1553 $formID = wp_unslash($Request['formID']);
1554 $entryID = wp_unslash($Request['entryID']);
1555 } else {
1556 $formID = wp_unslash($post->formID);
1557 $entryID = wp_unslash($post->entryID);
1558 }
1559 if (is_null($formID) || is_null($entryID)) {
1560 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1561 }
1562
1563 $formManager = new AdminFormManager($formID);
1564 if (!$formManager->isExist()) {
1565 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1566 }
1567 $formEntryModel = new FormEntryModel();
1568 $entryMeta = new FormEntryMetaModel();
1569
1570 $formEntry = $formEntryModel->get(
1571 '*',
1572 [
1573 'form_id' => $formID,
1574 'id' => $entryID,
1575 ]
1576 );
1577
1578 if (!$formEntry) {
1579 return new WP_Error('empty_form', __('Form entries does not exist.', 'bit-form'));
1580 }
1581 $formEntryMeta = $entryMeta->get(
1582 [
1583 'meta_key',
1584 'meta_value',
1585 ],
1586 [
1587 'bitforms_form_entry_id' => $entryID,
1588 ]
1589 );
1590 $entries = [];
1591 foreach ($formEntryMeta as $key => $value) {
1592 $entries[$value->meta_key] = $value->meta_value;
1593 }
1594 $formContent = $formManager->getFormContent();
1595 $fieldsKey = $formManager->getFieldsKey();
1596 $form_fields = $formContent->fields;
1597 $layout = $formContent->layout;
1598 foreach ($form_fields as $key => $value) {
1599 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
1600 if (isset($entries[$key])) {
1601 $form_fields->{$key}->val = $entries[$key];
1602 $form_fields->{$key}->name = $key;
1603 }
1604 }
1605 $workFlowRunHelper = new WorkFlowRunHelper($formID);
1606 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
1607 'edit',
1608 $form_fields
1609 );
1610 $workFlowreturnedOnUserInput = $workFlowRunHelper->executeOnUserInput(
1611 'edit',
1612 $form_fields
1613 );
1614 // var_dump($workFlowreturned);
1615 if (!empty($workFlowreturnedOnLoad['fields'])) {
1616 $form_fields = $workFlowreturnedOnLoad['fields'];
1617 }
1618 $formData = [
1619 'layout' => $layout,
1620 'fields' => $form_fields,
1621 'conditional' => !empty($workFlowreturnedOnUserInput['conditional']) ? $workFlowreturnedOnUserInput['conditional'] : false,
1622 'fieldToCheck' => !empty($workFlowreturnedOnUserInput['fieldToCheck']) ? $workFlowreturnedOnUserInput['fieldToCheck'] : false,
1623 'fieldToChange' => !empty($workFlowreturnedOnUserInput['fieldToChange']) ? $workFlowreturnedOnUserInput['fieldToChange'] : false,
1624 'fieldsKey' => $fieldsKey,
1625 ];
1626 return $formData;
1627 }
1628
1629 public function updateFormEntry($Request, $post) {
1630 if (isset($Request['formID'], $Request['entryID'])) {
1631 $formID = wp_unslash($Request['formID']);
1632 $entryID = wp_unslash($Request['entryID']);
1633 unset($Request['action'], $Request['formID'], $Request['entryID']);
1634
1635 $updatedValue = wp_unslash($post);
1636 }
1637
1638 if (is_null($updatedValue) || !is_array($updatedValue)) {
1639 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1640 }
1641
1642 if (is_null($formID) || is_null($entryID)) {
1643 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
1644 }
1645
1646 $formManager = new AdminFormManager($formID);
1647 if (!$formManager->isExist()) {
1648 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
1649 }
1650 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
1651 }
1652
1653 public function getLogHistory($Request, $post) {
1654 if (isset($Request['formID'])) {
1655 $formID = wp_unslash($Request['formID']);
1656 $entryID = wp_unslash($Request['entryID']);
1657 } else {
1658 $formID = wp_unslash($post->formID);
1659 $entryID = wp_unslash($post->entryID);
1660 }
1661
1662 if (is_null($formID) || is_null($entryID)) {
1663 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1664 }
1665
1666 $formManager = new AdminFormManager($formID);
1667 if (!$formManager->isExist()) {
1668 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1669 }
1670 $formLogModel = new FormEntryLogModel();
1671
1672 $log_history = $formLogModel->geLogHistory($formID, $entryID);
1673 return $log_history;
1674 }
1675
1676 public function importDataStore($Request, $post) {
1677 if (isset($Request['formID'])) {
1678 $formID = wp_unslash($Request['formID']);
1679 } else {
1680 $formID = wp_unslash($post->formID);
1681 }
1682 if (is_null($formID)) {
1683 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
1684 }
1685 }
1686
1687 public function getAllWPPages($Request, $post) {
1688 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
1689 $allPages = [];
1690 foreach ($pages as $pageKey => $pageDetails) {
1691 $allPages[$pageKey]['title'] = $pageDetails->post_title;
1692 $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
1693 }
1694 return $allPages;
1695 }
1696
1697 public function deleteAIntegration($Request, $post) {
1698 if (isset($Request['formID']) && $Request['id']) {
1699 $formID = json_decode(wp_unslash($Request['formID']));
1700 $id = wp_unslash($Request['id']);
1701 } else {
1702 $formID = wp_unslash($post->formID);
1703 $id = wp_unslash($post->id);
1704 }
1705 if ($formID < 0 || empty($id)) {
1706 return new WP_Error('empty_form', 'Invalid Form ID or Integration ID.');
1707 }
1708
1709 $integrationHandler = new IntegrationHandler($formID);
1710 $delete_status = $integrationHandler->deleteIntegration($id);
1711 if (is_wp_error($delete_status)) {
1712 return $delete_status;
1713 }
1714
1715 return [
1716 'message' => __('Integration deleted', 'bit-form'),
1717 ];
1718 }
1719
1720 public function deleteSuccessMessage($Request, $post) {
1721 if (isset($Request['formID']) && $Request['id']) {
1722 $formID = json_decode(wp_unslash($Request['formID']));
1723 $id = wp_unslash($Request['id']);
1724 } else {
1725 $formID = wp_unslash($post->formID);
1726 $id = wp_unslash($post->id);
1727 }
1728 if (empty($formID) || empty($id)) {
1729 return new WP_Error('empty_form', 'Invalid Form ID or Message ID.');
1730 }
1731 $successMessageHandler
1732 = new SuccessMessageHandler($formID);
1733 $delete_status = $successMessageHandler->deleteMessage($id);
1734 if (is_wp_error($delete_status)) {
1735 return $delete_status;
1736 }
1737 return [
1738 'message' => __('Message deleted', 'bit-form'),
1739 ];
1740 }
1741
1742 public function deleteAWorkflow($Request, $post) {
1743 if (isset($Request['formID']) && $Request['id']) {
1744 $formID = json_decode(wp_unslash($Request['formID']));
1745 $id = wp_unslash($Request['id']);
1746 } else {
1747 $formID = wp_unslash($post->formID);
1748 $id = wp_unslash($post->id);
1749 }
1750 if (empty($formID) || empty($id)) {
1751 return new WP_Error('empty_form', 'Invalid Form ID or Workflow ID.');
1752 }
1753 $workFlowHandler = new WorkFlowHandler($formID);
1754 $delete_status = $workFlowHandler->deleteworkFlow($id);
1755 if (is_wp_error($delete_status)) {
1756 return $delete_status;
1757 }
1758 return [
1759 'message' => __('workflow deleted', 'bit-form'),
1760 ];
1761 }
1762
1763 public function deleteAMailTemplate($Request, $post) {
1764 if (isset($Request['formID']) && $Request['id']) {
1765 $formID = json_decode(wp_unslash($Request['formID']));
1766 $id = wp_unslash($Request['id']);
1767 } else {
1768 $formID = wp_unslash($post->formID);
1769 $id = wp_unslash($post->id);
1770 }
1771 if (empty($formID) || empty($id)) {
1772 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
1773 }
1774 $emailTemplateHandler = new EmailTemplateHandler($formID);
1775 $delete_status = $emailTemplateHandler->deleteTemplate($id);
1776 if (is_wp_error($delete_status)) {
1777 return $delete_status;
1778 }
1779 return [
1780 'message' => __('Email Template deleted', 'bit-form'),
1781 ];
1782 }
1783
1784 public function duplicateAMailTemplate($Request, $post) {
1785 if (isset($Request['formID']) && $Request['id']) {
1786 $formID = json_decode(wp_unslash($Request['formID']));
1787 $id = wp_unslash($Request['id']);
1788 } else {
1789 $formID = wp_unslash($post->formID);
1790 $id = wp_unslash($post->id);
1791 }
1792 if (empty($formID) || empty($id)) {
1793 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
1794 }
1795 $emailTemplateHandler = new EmailTemplateHandler($formID);
1796 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
1797 if (is_wp_error($duplicate_status)) {
1798 return $duplicate_status;
1799 }
1800 return [
1801 'message' => __('Email Template duplicated', 'bit-form'),
1802 ];
1803 }
1804
1805 public function setAllFormsReport($Request, $post) {
1806 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
1807 if (empty($reports)) {
1808 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
1809 }
1810 if (!empty($reports)) {
1811 $reportsModel = new ReportsModel();
1812 $user_details = static::$ipTool->getUserDetail();
1813 foreach ($reports as $reportIndex => $report) {
1814 if (empty($report->id)) {
1815 $reportSaveSatus = $reportsModel->insert(
1816 [
1817 'type' => 'table',
1818 'category' => 'app',
1819 'context' => 'allForm',
1820 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
1821 'isDefault' => 1,
1822 'user_id' => $user_details['id'],
1823 'user_ip' => $user_details['ip'],
1824 'user_device' => $user_details['device'],
1825 'created_at' => $user_details['time'],
1826 'updated_at' => $user_details['time'],
1827 ]
1828 );
1829 $newData['reports'] = 1;
1830 } else {
1831 $reportSaveSatus = $reportsModel->update(
1832 [
1833 'type' => 'table',
1834 'category' => 'app',
1835 'context' => 'allForm',
1836 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
1837 'isDefault' => 1,
1838 'user_id' => $user_details['id'],
1839 'user_ip' => $user_details['ip'],
1840 'user_device' => $user_details['device'],
1841 'updated_at' => $user_details['time'],
1842 ],
1843 [
1844 'id' => $report->id,
1845 ]
1846 );
1847 }
1848 }
1849 }
1850 if (is_wp_error($reportSaveSatus)) {
1851 if ('result_empty' === $reportSaveSatus->get_error_code()) {
1852 return new WP_Error('empty_report_prefs', 'Nothing to save or update');
1853 }
1854 return new WP_Error('error_report_prefs', 'Error occured in saving reports');
1855 }
1856 $returnedReportData = $reportsModel->get(
1857 [
1858 'id',
1859 'details',
1860 'isDefault',
1861 'category',
1862 'context',
1863 ],
1864 [
1865 'category' => 'app',
1866 'context' => 'allForm',
1867 ]
1868 );
1869 if (!is_wp_error($returnedReportData)) {
1870 foreach ($returnedReportData as $reportKey => $reportData) {
1871 if (isset($reportData->details) && is_string($reportData->details)) {
1872 $returnedReportData[$reportKey]->details = json_decode($reportData->details);
1873 }
1874 }
1875 $reports = $returnedReportData;
1876 }
1877 return [
1878 'message' => __('Report preferrences saved successfully', 'bit-form'),
1879 'reports' => empty($reports) ? [] : $reports,
1880 ];
1881 }
1882
1883 public function savegReCaptcha($Request, $post) {
1884 $reCaptcha = $post->reCaptcha;
1885
1886 if (is_null($reCaptcha)) {
1887 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
1888 }
1889 if (is_string($reCaptcha) && !empty(json_decode($reCaptcha)->id)) {
1890 $reCaptcha = json_decode($reCaptcha);
1891 $integrationID = $reCaptcha->id;
1892 unset($reCaptcha->id);
1893 } else {
1894 $integrationID = $reCaptcha->id;
1895 unset($reCaptcha->id);
1896 }
1897 $reCaptcha = json_encode($reCaptcha);
1898 $integrationName = 'google reCaptcha';
1899 $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
1900 $integrationDetails = $reCaptcha;
1901 $user_details = static::$ipTool->getUserDetail();
1902 $integrationHandler = new IntegrationHandler(0, $user_details);
1903 $response = [];
1904 if (empty($integrationID)) {
1905 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
1906 $response['id'] = $captchaSaveStatus;
1907 $response['message'] = __('g-reCAPTCHA saved successfully', 'bit-form');
1908 } else {
1909 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
1910 $response['message'] = __('g-reCAPTCHA updated successfully', 'bit-form');
1911 }
1912
1913 if (is_wp_error($captchaSaveStatus)) {
1914 return $captchaSaveStatus;
1915 }
1916 return $response;
1917 }
1918
1919 public function savePaymentSetting($Request, $post) {
1920 if (isset($post->paySetting)) {
1921 $paySetting = $post->paySetting;
1922 } else {
1923 $paySetting = $post->paySetting;
1924 }
1925 if (is_null($paySetting)) {
1926 return new WP_Error('empty_gcaptchdetails', __('Setting details is empty', 'bit-form'));
1927 }
1928 if (is_string($paySetting) && !empty(json_decode($paySetting)->id)) {
1929 $paySetting = json_decode($paySetting);
1930 $integrationID = $paySetting->id;
1931 unset($paySetting->id);
1932 } else {
1933 $integrationID = $paySetting->id;
1934 unset($paySetting->id);
1935 }
1936 $integrationName = $paySetting->name;
1937 $integrationType = 'payments';
1938 $paySetting = json_encode($paySetting);
1939 $integrationDetails = $paySetting;
1940 $user_details = static::$ipTool->getUserDetail();
1941 $integrationHandler = new IntegrationHandler(0, $user_details);
1942 $response = [];
1943 if (empty($integrationID)) {
1944 $paymentSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
1945 $response['id'] = $paymentSaveStatus;
1946 $response['message'] = __('Payment setting saved successfully', 'bit-form');
1947 } else {
1948 $paymentSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
1949 $response['message'] = __('Payment setting updated successfully', 'bit-form');
1950 }
1951
1952 if (is_wp_error($paymentSaveStatus)) {
1953 return $paymentSaveStatus;
1954 }
1955 return $response;
1956 }
1957 }
1958