PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.0
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.0
V-3.3.0 3.2.2 3.2.1 3.2.0 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 V3.0.3 V3.0.2 -3.0.1 V_3.0.0 1.1.1 1.1.8 1.2 1.3 1.4 1.4.18 1.5.2 1.9 2.0 2.10.0 2.10.1 2.10.2 All 137 releases
bit-form / includes / Admin / Form / AdminFormHandler.php

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

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