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

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

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