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

2,878 lines 106.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 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\PdfTemplateModel;
18 use BitCode\BitForm\Core\Database\ReportsModel;
19 use BitCode\BitForm\Core\Database\SuccessMessageModel;
20 use BitCode\BitForm\Core\Database\WorkFlowModel;
21 use BitCode\BitForm\Core\Integration\IntegrationHandler;
22 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
23 use BitCode\BitForm\Core\Messages\PdfTemplateHandler;
24 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
25 use BitCode\BitForm\Core\Migration\MigrationHelper;
26 use BitCode\BitForm\Core\Util\FileHandler;
27 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
28 use BitCode\BitForm\Core\Util\HttpHelper;
29 use BitCode\BitForm\Core\Util\IpTool;
30 use BitCode\BitForm\Core\Util\Log;
31 use BitCode\BitForm\Core\Util\Utilities;
32 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
33 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
34 use WP_Error;
35
36 class AdminFormHandler
37 {
38 private static $formModel;
39 private static $ipTool;
40
41 public function __construct()
42 {
43 static::$formModel = new FormModel();
44 static::$ipTool = new IpTool();
45 }
46
47 public function getTemplate($Request, $post)
48 {
49 $templateName = null;
50 $newFormId = null;
51 if (isset($post->template)) {
52 $templateName = $post->template;
53 $newFormId = $post->newFormId;
54 }
55
56 $templateProvider = new TemplateProvider();
57 $form_content_raw = $templateProvider->getTemplate($templateName, $newFormId);
58 if (!$form_content_raw) {
59 return new WP_Error('template_empty', __('Template not found, by this name: ', 'bit-form') . $templateName);
60 } else {
61 return wp_json_encode(
62 [
63 'id' => 0,
64 'form_content' => $form_content_raw,
65 ]
66 );
67 }
68 }
69
70 public function saveStyleSheet($styles, $sheetName)
71 {
72 $this->createFormStylesDirIfNotExists();
73
74 if (
75 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
76 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
77 ) {
78 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
79 fwrite($createStyleFile, $styles);
80 fclose($createStyleFile);
81 return true;
82 }
83 return false;
84 }
85
86 public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43)
87 {
88 $md_width = 600;
89 $sm_width = 400;
90 $lg_styles = '';
91 $md_styles = '';
92 $sm_styles = '';
93 for ($i = 0; $i < count($layout->lg); $i++) {
94 $fld = $layout->lg[$i];
95
96 if ($fld->w < 10) {
97 $lay_row_height = 43;
98 } else {
99 $lay_row_height = 2;
100 }
101
102 $class = $fld->i;
103 $lg_g_r_s = $fld->y + 1;
104 $lg_g_c_s = $fld->x + 1;
105 $lg_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
106 $lg_g_c_e = ($fld->x + 1) + $fld->w;
107 $lg_g_r_span = $lg_g_r_e - $lg_g_r_s;
108 $lg_g_c_span = $lg_g_c_e - $lg_g_c_s;
109 $lg_min_height = $fld->h * $lay_row_height . 'px;';
110
111 $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; }";
112
113 $fld = $layout->md[$i];
114
115 $class = $fld->i;
116 $md_g_r_s = $fld->y + 1;
117 $md_g_c_s = $fld->x + 1;
118 $md_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
119 $md_g_c_e = ($fld->x + 1) + $fld->w;
120 $md_g_r_span = $lg_g_r_e - $md_g_r_s;
121 $md_g_c_span = $lg_g_c_e - $md_g_c_s;
122 $md_min_height = $fld->h * $lay_row_height . 'px;';
123
124 $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; }";
125
126 $fld = $layout->sm[$i];
127
128 $class = $fld->i;
129 $sm_g_r_s = $fld->y + 1;
130 $sm_g_c_s = $fld->x + 1;
131 $sm_g_r_e = 1 !== $fld->y ? $fld->h + ($fld->y + 1) : 1;
132 $sm_g_c_e = ($fld->x + 1) + $fld->w;
133 $sm_g_r_span = $sm_g_r_e - $sm_g_r_s;
134 $sm_g_c_span = $sm_g_c_e - $sm_g_c_s;
135 $sm_min_height = $fld->h * $lay_row_height . 'px;';
136
137 $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; }";
138 }
139 $formStyle = "._frm-g{
140 display: grid;
141 display: -ms-grid;
142 grid-template-columns: repeat( 6 , minmax( 30px , 1fr ));
143 -ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr ) minmax( 30px , 1fr );
144 }
145 {$lg_styles}
146 @media only screen and (max-width:{$md_width}px) {
147 ._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 );}
148 {$md_styles}
149 }
150 @media only screen and (max-width:{$sm_width}px) {
151 ._frm-g {grid-template-columns: repeat( 2 , minmax( 30px , 1fr ));-ms-grid-columns: minmax( 30px , 1fr ) minmax( 30px , 1fr );}
152 {$sm_styles}
153 }";
154
155 $this->createFormStylesDirIfNotExists();
156
157 if (
158 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
159 && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
160 ) {
161 $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
162 fwrite($createStyleFile, $formStyle);
163 fclose($createStyleFile);
164 return true;
165 }
166 return false;
167 }
168
169 public function createFormStylesDirIfNotExists()
170 {
171 if (!file_exists(BITFORMS_UPLOAD_DIR)) {
172 wp_mkdir_p(BITFORMS_UPLOAD_DIR);
173 }
174 if (!file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')) {
175 wp_mkdir_p(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles');
176 }
177 }
178
179 private function pdfFontDownload($fontName)
180 {
181 if (class_exists('\BitCode\BitFormPro\Admin\AppSetting\Pdf')) {
182 \BitCode\BitFormPro\Admin\AppSetting\Pdf::getInstance()->fontsDownload($fontName);
183 }
184 return false;
185 }
186
187 public function createNewForm($Request, $post)
188 {
189 // wp_send_json_success($post);
190 // exit;
191 if (!isset($post->form_id) || '' === $post->form_id) {
192 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
193 }
194
195 $formManager = new AdminFormManager($post->form_id);
196 if ($formManager->isExist()) {
197 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
198 }
199
200 if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
201 if (!empty($workFlows) && count($workFlows) > 2) {
202 return new WP_Error(
203 'free_limit',
204 __('You are allowed to add maximum 2 workflows ', 'bit-form')
205 );
206 }
207 }
208
209 if (isset($post->formStyle) && $post->formStyle) {
210 $sheetName = 'bitform-' . $post->form_id . '.css';
211 $this->saveStyleSheet($post->formStyle, $sheetName);
212 }
213
214 if (isset($post->layoutChanged) && $post->layoutChanged) {
215 $sheetName = 'bitform-layout-' . $post->form_id . '.css';
216 $rowHeight = (int) $post->rowHeight;
217 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
218 }
219
220 $fields = wp_unslash($post->fields);
221 $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
222 // $fields = $post->fields;
223 $layout = wp_unslash($post->layout);
224 $nestedLayout = isset($post->nestedLayouts) ? wp_unslash($post->nestedLayouts) : (object) [];
225 $formInfo = wp_unslash($post->formInfo);
226 $form_name = wp_unslash($post->form_name);
227 $form_name = strlen($form_name) > 50 ? substr($form_name, 0, 50) : $form_name;
228 $formSettings = (object) wp_unslash($post->formSettings);
229 $atomic_class_map = isset($post->atomicClassMap) ? wp_unslash($post->atomicClassMap) : [];
230 $breakpointSize = wp_unslash($post->breakpointSize);
231 $style = $post->style;
232 $themeVars = $post->themeVars;
233 $themeColors = $post->themeColors;
234 $staticStyles = $post->staticStyles;
235 $workFlows = wp_unslash($post->workFlows);
236 $additional = wp_unslash($post->additional);
237 $reports = !empty($post->reports) ? $post->reports : (object) [];
238 $builderSettings = (object) isset($post->builderSettings) ? wp_unslash($post->builderSettings) : [];
239
240 $mailTem = $formSettings->mailTem;
241 $pdfTem = $formSettings->pdfTem;
242 $integrations = $formSettings->integrations;
243 $formPermissions = $formSettings->formPermissions;
244
245 $user_details = static::$ipTool->getUserDetail();
246 if (empty($fields) || empty($layout)) {
247 return new WP_Error(
248 'empty_form',
249 __('Can not save empty form.', 'bit-form')
250 );
251 }
252 if (strlen($form_name) > 50) {
253 return new WP_Error(
254 'empty_form',
255 __('Form Name Should Be Within 50 Characters', 'bit-form')
256 );
257 }
258 $form_content = [
259 'fields' => $fields,
260 'layout' => $layout,
261 'nestedLayout' => $nestedLayout,
262 'formInfo' => $formInfo,
263 ];
264
265 /* if (!empty($formSettings->submitBtn)) {
266 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
267 } */
268 if (!empty($formSettings->theme)) {
269 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
270 }
271
272 if (!empty($formSettings->formPermissions)) {
273 $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
274 }
275
276 if (!empty($additional)) {
277 $form_content = array_merge($form_content, ['additional' => $additional]);
278 }
279 if (!empty($workFlows)) {
280 $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
281 $workFlowExist = [];
282 foreach ($workflows as $index => $workFlow) {
283 if (in_array($workFlow->action_type, ['always', 'onload'])) {
284 $workFlowExist['onload'] = true;
285 }
286 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
287 $workFlowExist['oninput'] = true;
288 }
289 }
290 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
291 }
292 $form_content = \wp_json_encode($form_content);
293
294 $builder_helper_state = (object) [
295 'style' => $style,
296 'staticStyles' => $staticStyles,
297 'breakpointSize' => $breakpointSize,
298 'themeVars' => $themeVars,
299 'themeColors' => $themeColors,
300 'builderSettings' => $builderSettings
301 ];
302 $atomic_class_map = \wp_json_encode($atomic_class_map);
303 $fdata = [
304 'id' => $post->form_id,
305 'form_content' => $form_content,
306 'builder_helper_state' => \wp_json_encode($builder_helper_state),
307 'atomic_class_map' => $atomic_class_map,
308 'generated_script_page_ids' => \wp_json_encode((object) []),
309 'user_id' => $user_details['id'],
310 'user_ip' => $user_details['ip'],
311 'user_device' => $user_details['device'],
312 'status' => 1,
313 'form_name' => $form_name,
314 'created_at' => $user_details['time'],
315 'updated_at' => $user_details['time'],
316 ];
317
318 $save_status = static::$formModel->insert($fdata);
319
320 if (is_wp_error($save_status)) {
321 return $save_status;
322 } elseif (!$save_status) {
323 return false;
324 } else {
325 FileHandler::createIndexFile(BITFORMS_UPLOAD_DIR . "/$save_status");
326 $formID = $save_status;
327 $integartionIDForWorkflow = [];
328 // Confiramtion Message [start]
329 if (!empty($formSettings->confirmation->type->successMsg)) {
330 $successMessages = $formSettings->confirmation->type->successMsg;
331 $successMessageHandler = new SuccessMessageHandler($formID, $user_details);
332 foreach ($successMessages as $messageKey => $messageDetail) {
333 $savedID = $successMessageHandler->saveMessage($messageDetail);
334 if ($savedID) {
335 $msgIdx = empty($messageDetail->id) ? $messageKey : wp_json_encode(['id' => $messageDetail->id]);
336 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
337 $messageDetail->id = $savedID;
338 $style = $this->updateSuccessMessageClassName($style, $messageKey, $savedID);
339 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
340 }
341 }
342 $builder_helper_state = (object) [
343 'style' => $style,
344 'breakpointSize' => $breakpointSize,
345 'themeVars' => $themeVars,
346 'themeColors' => $themeColors,
347 'builderSettings' => $builderSettings
348 ];
349 $update_status = static::$formModel->update(
350 [
351 'builder_helper_state' => \wp_json_encode($builder_helper_state),
352 'atomic_class_map' => $atomic_class_map,
353 ],
354 [
355 'id' => $formID,
356 ]
357 );
358 if (is_wp_error($update_status)) {
359 return $update_status;
360 }
361 unset($formSettings->confirmation->type->successMsg);
362 }
363 // return $formSettings;
364 // Confiramtion Message [end] */
365 // Email Template [start]
366 if (!empty($mailTem)) {
367 $emailTemplateHandler
368 = new EmailTemplateHandler($formID, $user_details);
369 foreach ($mailTem as $templateKey => $templateDetail) {
370 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
371 if ($savedID) {
372 $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
373 $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
374 }
375 }
376 }
377 // Email Template [end] */
378
379 // PDF Template [start]
380 if (!empty($pdfTem)) {
381 $pdfTemplateHandler = new PdfTemplateHandler($formID);
382 $workFlowString = '';
383 if (!empty($workFlows)) {
384 $workFlowString = wp_json_encode($workFlows);
385 }
386 foreach ($pdfTem as $templateDetail) {
387 $savedID = $pdfTemplateHandler->save($templateDetail);
388
389 $pdfSetting = $templateDetail->setting;
390
391 if (isset($pdfSetting->font->name) && !empty($pdfSetting->font->name)) {
392 $this->pdfFontDownload($pdfSetting->font->name);
393 }
394 if (!empty($workFlowString)) {
395 $workFlowString = str_replace('"pdfId":"{\"id\":\"' . $templateDetail->id . '\"}"', '"pdfId":"{\"id\":\"' . $savedID . '\"}"', $workFlowString);
396 }
397 }
398 if (!empty($workFlowString) && !empty($workFlows)) {
399 $workFlows = json_decode($workFlowString);
400 }
401 }
402 // PDF Template [end] */
403 //Integration [start] */
404 $integrationHandler = new IntegrationHandler($formID, $user_details);
405 if (!empty($formSettings->confirmation->type)) {
406 $allIntegrations = $formSettings->confirmation->type;
407 foreach ($allIntegrations as $integrationType => $integrationGroup) {
408 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
409 if (empty($singleIntegrationDetail->details)) {
410 $integrationName = $singleIntegrationDetail->title;
411 unset($singleIntegrationDetail->title, $singleIntegrationDetail->id);
412
413 $integrationDetails = !is_string($singleIntegrationDetail) ?
414 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
415 } else {
416 $integrationName = $singleIntegrationDetail->title;
417 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
418 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
419 }
420 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
421 $integIdx = empty($singleIntegrationDetail->id) ? $savedID : wp_json_encode(['id' => $singleIntegrationDetail->id]);
422 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
423 }
424 }
425 }
426 if (isset($formSettings->formAbandonment)) {
427 $formAbandonment = $formSettings->formAbandonment;
428
429 $integrationName = 'formAbandonment';
430 $integrationType = 'formAbandonment';
431 $abandonmentIntegDetails = wp_json_encode($formAbandonment);
432 $integrationHandler->saveIntegration($integrationName, $integrationType, $abandonmentIntegDetails, 'formAbandonment');
433 }
434 if (!empty($integrations)) {
435 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
436 $integrationName = $singleIntegrationDetail->name;
437 unset($singleIntegrationDetail->name);
438 $integrationType = $singleIntegrationDetail->type;
439 unset($singleIntegrationDetail->type);
440 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
441 unset($singleIntegrationDetail->id);
442 if (empty($singleIntegrationDetail->details)) {
443 $integrationDetails = !is_string($singleIntegrationDetail) ?
444 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
445 } else {
446 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
447 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
448 }
449 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
450 $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : wp_json_encode(['id' => $singleIntegrationDetailID]);
451 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
452 }
453 }
454 //Integrations [end]
455 //wrokFlows [start]
456 if (!empty($workFlows)) {
457 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
458
459 foreach ($workFlows as $index => $workFlow) {
460 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
461 $newData['workflow'] = 1;
462 }
463
464 // $workflowCount = count($workFlows);
465 // while ($workflowCount) {
466 // $workFlow = $workFlows[--$workflowCount];
467 // $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow);
468 // $newData['workflow'] = 1;
469 // }
470 }
471 //wrokFlows [end]
472 $details = [
473 'report_name' => __('All Entries', 'bit-form'),
474 'hiddenColumns' => ['__user_id', '__user_ip', '__referer', '__user_device', '__created_at', '__updated_at'],
475 'pageSize' => 10,
476 'sortBy' => [],
477 'filters' => [],
478 'globalFilter' => '',
479 'order' => []
480 ];
481 $defaultReport = [
482 'type' => 'table',
483 'category' => 'form',
484 'context' => $formID,
485 'details' => wp_json_encode($details),
486 'isDefault' => (bool) 1,
487 'user_id' => $user_details['id'],
488 'user_ip' => $user_details['ip'],
489 'user_device' => $user_details['device'],
490 'created_at' => $user_details['time'],
491 'updated_at' => $user_details['time'],
492 ];
493 $reportsModel = new ReportsModel();
494 $saveReportId = $reportsModel->insert($defaultReport);
495
496 // }
497 $updated_data = $this->getAForm(['id' => $save_status], null);
498 if (!is_wp_error($saveReportId) && isset($updated_data['form_content'])) {
499 $updated_data['form_content']['report_id'] = $saveReportId;
500 $updated_data['form_content']['is_default'] = 1;
501 }
502 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
503
504 return $updated_data;
505 }
506 }
507
508 public function updateForm($Request, $post)
509 {
510 // return ['checked dta'=>$post];
511 $formId = $post->id;
512 // get the builder_helper_state from the form
513 $builder_helper_state = self::$formModel->get(['builder_helper_state'], ['id' => $formId]);
514 $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 : '{}';
515 $builder_helper_state = json_decode($builder_helper_state);
516 if (property_exists($post, 'breakpointSize')) {
517 $builder_helper_state->breakpointSize = $post->breakpointSize;
518 }
519 if (property_exists($post, 'style')) {
520 $builder_helper_state->style = $post->style;
521 }
522 if (property_exists($post, 'staticStyles')) {
523 $builder_helper_state->staticStyles = $post->staticStyles;
524 }
525 if (property_exists($post, 'themeVars')) {
526 $builder_helper_state->themeVars = $post->themeVars;
527 }
528 if (property_exists($post, 'themeColors')) {
529 $builder_helper_state->themeColors = $post->themeColors;
530 }
531 if (property_exists($post, 'builderSettings')) {
532 $builder_helper_state->builderSettings = $post->builderSettings;
533 }
534 if (property_exists($post, 'atomicClassMap')) {
535 $atomic_class_map = \wp_json_encode((object) $post->atomicClassMap);
536 }
537
538 if (property_exists($post, 'fields') && null !== $post->fields && property_exists($post, 'layout') && $post->layout) {
539 $fields = wp_unslash($post->fields);
540 $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
541 $layout = wp_unslash($post->layout);
542 $nestedLayout = wp_unslash($post->nestedLayouts);
543 $formInfo = wp_unslash($post->formInfo);
544 $formID = wp_unslash($post->id);
545 $form_name = wp_unslash($post->form_name);
546 $formSettings = wp_unslash($post->formSettings);
547 $workFlows = wp_unslash($post->workFlows);
548 $additional = wp_unslash($post->additional);
549 $reports = wp_unslash($post->currentReport);
550 }
551
552 $mailTem = $formSettings->mailTem;
553 $pdfTem = isset($formSettings->pdfTem) ? $formSettings->pdfTem : [];
554 $integrations = $formSettings->integrations;
555
556 $user_details = static::$ipTool->getUserDetail();
557
558 if (empty($fields) || empty($layout) || is_null($formID)) {
559 return new WP_Error('empty_form', 'Can not update empty form.');
560 }
561
562 if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
563 if (count($workFlows) > 2) {
564 return new WP_Error(
565 'free_limit',
566 __('You are allowed to add maximum 2 workflows ', 'bit-form')
567 );
568 }
569 }
570
571 $form_content = [
572 'fields' => $fields,
573 'layout' => $layout,
574 'nestedLayout' => $nestedLayout,
575 'formInfo' => $formInfo,
576 ];
577
578 if (isset($post->report_id)) {
579 $form_content['report_id'] = wp_unslash($post->report_id);
580 }
581
582 /* if (!empty($formSettings->submitBtn)) {
583 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
584 } */
585 if (!empty($formSettings->theme)) {
586 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
587 }
588
589 if (!empty($formSettings->formPermissions)) {
590 $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
591 }
592 if (!empty($additional)) {
593 $form_content = array_merge($form_content, ['additional' => $additional]);
594 }
595 $integartionIDForWorkflow = [];
596 $newData['settingConfiramation'] = 0;
597 $newData['integation'] = 0;
598 $newData['mailTemplate'] = 0;
599 $newData['workflow'] = 0;
600 $newData['reports'] = 0;
601 $newData['pdfTemplate'] = 0;
602 // Confiramtion Message [start]
603 if (!empty($formSettings->confirmation->type->successMsg)) {
604 $successMessages = $formSettings->confirmation->type->successMsg;
605 $successMessageHandler
606 = new SuccessMessageHandler($formID, $user_details);
607 foreach ($successMessages as $messageKey => $messageDetail) {
608 if (empty($messageDetail->id)) {
609 $savedID = $successMessageHandler->saveMessage($messageDetail);
610 if ($savedID) {
611 $newData['settingConfiramation'] = 1;
612 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
613 $messageDetail->id = $savedID;
614 $builder_helper_state->style = $this->updateSuccessMessageClassName($builder_helper_state->style, $messageKey, $savedID);
615 if (isset($atomic_class_map)) {
616 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
617 }
618 }
619 } else {
620 $successMessageHandler->updateMessage($messageDetail);
621 }
622 }
623 unset($formSettings->confirmation->type->successMsg);
624 }
625 // return $formSettings;
626 // Confirmation Message [end] */
627 // Email Template [start]
628 if (!empty($mailTem)) {
629 $emailTemplateHandler
630 = new EmailTemplateHandler($formID, $user_details);
631 foreach ($mailTem as $templateKey => $templateDetail) {
632 if (empty($templateDetail->id)) {
633 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
634 if (is_wp_error($savedID) && 'result_empty' === $savedID->get_error_code()) {
635 $newData['mailTemplate'] = 2;
636 } else {
637 $newData['mailTemplate'] = 1;
638 $integartionIDForWorkflow['mailTem'][$templateKey] = $savedID;
639 }
640 } else {
641 $emailTemplateHandler->updateTemplate($templateDetail);
642 }
643 }
644 }
645 // return $formSettings;
646 // Email Template [end] */
647 if (!empty($pdfTem)) {
648 $pdfTemplateHandler = new PdfTemplateHandler($formID);
649
650 foreach ($pdfTem as $templateKey => $templateDetail) {
651 if (isset($templateDetail->setting->font->name)) {
652 $this->pdfFontDownload($templateDetail->setting->font->name);
653 }
654
655 $savedID = $pdfTemplateHandler->saveOrUpdate($templateDetail);
656 if (is_wp_error($savedID) && 'result_empty' === $savedID->get_error_code()) {
657 $newData['pdfTemplate'] = 2;
658 } else {
659 $newData['pdfTemplate'] = 1;
660 $integartionIDForWorkflow['pdfTem'][$templateKey] = $savedID;
661 }
662 }
663 }
664 //Integration [start] */
665 $integrationHandler = new IntegrationHandler($formID, $user_details);
666 if (!empty($formSettings->confirmation->type)) {
667 $allIntegrations = $formSettings->confirmation->type;
668 foreach ($allIntegrations as $integrationType => $integrationGroup) {
669 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
670 if (empty($singleIntegrationDetail->details)) {
671 $integrationName = $singleIntegrationDetail->title;
672 unset($singleIntegrationDetail->title);
673 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
674 unset($singleIntegrationDetail->id);
675 $integrationDetails = !is_string($singleIntegrationDetail) ?
676 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
677 } else {
678 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
679 unset($singleIntegrationDetail->id);
680 $integrationName = $singleIntegrationDetail->title;
681 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
682 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
683 }
684 if (empty($singleIntegrationDetailID)) {
685 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
686 $newData['settingConfiramation'] = 1;
687 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
688 } else {
689 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
690 }
691 }
692 }
693 }
694 if (!empty($integrations)) {
695 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
696 $integrationName = $singleIntegrationDetail->name;
697 unset($singleIntegrationDetail->name);
698 $integrationType = $singleIntegrationDetail->type;
699 unset($singleIntegrationDetail->type);
700 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
701 unset($singleIntegrationDetail->id);
702 if (empty($singleIntegrationDetail->details)) {
703 $integrationDetails = !is_string($singleIntegrationDetail) ?
704 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
705 } else {
706 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
707 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
708 }
709 if (empty($singleIntegrationDetailID)) {
710 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
711 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
712 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
713 $newData['integation'] = 2;
714 } else {
715 $newData['integation'] = 1;
716 }
717 } else {
718 $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
719 }
720 }
721 }
722 //Integrations [end]
723 //workFlows [start] */
724 $workFlowExist = [];
725 if (!empty($workFlows)) {
726 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
727 // foreach ($workFlows as $workFlowIndex => $workFlow) {
728 $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
729
730 foreach ($workflows as $index => $workFlow) {
731 if (in_array($workFlow->action_type, ['always', 'onload'])) {
732 $workFlowExist['onload'] = true;
733 }
734 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
735 $workFlowExist['oninput'] = true;
736 }
737 // $integartionIDForWorkflow = apply_filters('bitform_filter_integration_id', $workFlow, $formID, $index);
738 if (empty($workFlow->id)) {
739 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
740 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
741 $newData['workflow'] = 2;
742 } else {
743 $newData['workflow'] = 1;
744 }
745 } else {
746 $newData = $workFlowHandler->updateworkFlow($workFlow->id, $workFlow, $integartionIDForWorkflow, $index, $newData);
747 }
748 }
749 }
750 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
751 //wrokFlows [end]
752 //reports [start] */
753 if (!empty($reports)) {
754 $reportsModel = new ReportsModel();
755 $fieldNames = [];
756 foreach ($fields as $key => $field) {
757 if (!empty($field->lbl)) {
758 // $name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\\!]/', '_', $field->lbl);
759 $fieldNames["$key"] = $field->lbl;
760 }
761 }
762
763 $fieldNames['__user_id'] = __('User', 'bit-form');
764 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
765 // $fieldNames['__user_location'] = __('');
766 $fieldNames['__referer'] = __('Refer URL');
767 $fieldNames['__user_device'] = __('Device');
768 $fieldNames['__created_at'] = __('Created Time');
769 $fieldNames['__updated_at'] = __('Modified Time');
770
771 $reportIsDefault = null;
772 if (isset($form_content['report_id'])) {
773 $validDateReport = $reportsModel->validateReportFields($reports, $fieldNames);
774 if (isset($reports->isDefault)) {
775 $reportIsDefault = $reports->isDefault;
776 } else {
777 $reportIsDefault = 0;
778 }
779
780 $reportsModel->update(
781 [
782 'type' => 'table',
783 'category' => 'form',
784 'context' => $formID,
785 'details' => is_string($validDateReport) ? $validDateReport : wp_json_encode($validDateReport),
786 'isDefault' => (int) $reportIsDefault,
787 'user_id' => $user_details['id'],
788 'user_ip' => $user_details['ip'],
789 'user_device' => $user_details['device'],
790 'updated_at' => $user_details['time'],
791 ],
792 [
793 'id' => $form_content['report_id'],
794 ]
795 );
796 }
797 }
798 //reports [end]
799 //form abandonment [start]
800 if (!empty($formSettings->formAbandonment)) {
801 $formAbandonment = $formSettings->formAbandonment;
802 // search for existing form abandonment in integration table
803 $abandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
804 if (!is_wp_error($abandonmentInteg) && !empty($abandonmentInteg)) {
805 $abandonmentInteg = $abandonmentInteg[0];
806 }
807 if (isset($abandonmentInteg->id)) {
808 $abandonmentIntegID = $abandonmentInteg->id;
809 $abandonmentIntegDetails = wp_json_encode($formAbandonment);
810 $integrationHandler->updateIntegration($abandonmentIntegID, 'formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
811 } else {
812 $abandonmentIntegDetails = wp_json_encode($formAbandonment);
813 $integrationHandler->saveIntegration('formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
814 }
815 }
816 //form abandonment [end]
817 $form_content = wp_json_encode($form_content);
818 $updateData = [
819 'form_name' => $form_name,
820 'form_content' => $form_content,
821 'user_id' => $user_details['id'],
822 'user_ip' => $user_details['ip'],
823 'builder_helper_state' => \wp_json_encode((object) $builder_helper_state),
824 'generated_script_page_ids' => \wp_json_encode((object) []),
825 'user_device' => $user_details['device'],
826 'updated_at' => $user_details['time'],
827 ];
828 if (isset($atomic_class_map)) {
829 $updateData['atomic_class_map'] = $atomic_class_map;
830 }
831 $formUpdateVersion = get_option('bit-form_form_update_version');
832 if (!$formUpdateVersion) {
833 $formUpdateVersion = 1;
834 } else {
835 $formUpdateVersion = (int) $formUpdateVersion + 1;
836 }
837 update_option('bit-form_form_update_version', $formUpdateVersion);
838
839 $update_status = static::$formModel->update(
840 $updateData,
841 [
842 'id' => $formID,
843 ]
844 );
845 if (is_wp_error($update_status)) {
846 return $update_status;
847 } elseif (!$update_status) {
848 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
849 } else {
850 if (isset($post->deletedFldKey) && is_array($post->deletedFldKey)) {
851 $this->setEmptyMetaValue($post->deletedFldKey);
852 unset($post->deletedFldKey);
853 }
854
855 $updated_data = $this->getAForm(['id' => $formID], null);
856
857 if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation'] && 0 === $newData['pdfTemplate']) {
858 unset($updated_data['formSettings']);
859 }
860 if (0 === $newData['integation']) {
861 unset($updated_data['integrations']);
862 } elseif (2 === $newData['integation']) {
863 $errorIN = '';
864 $errorIN .= empty($errorIN) ? 'integation' : ', integation';
865 }
866 if (0 === $newData['mailTemplate']) {
867 unset($updated_data['mailTem']);
868 } elseif (2 === $newData['mailTemplate']) {
869 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
870 }
871 if (0 === $newData['pdfTemplate']) {
872 unset($updated_data['pdfTem']);
873 } elseif (2 === $newData['pdfTemplate']) {
874 $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
875 }
876 if (0 === $newData['workflow']) {
877 unset($updated_data['workFlows']);
878 } elseif (2 === $newData['workflow']) {
879 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
880 }
881 if (2 === $newData['reports']) {
882 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
883 }
884 if (!empty($errorIN)) {
885 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
886 return new WP_Error('Form update Error.', $updated_data);
887 }
888 if (null !== $reportIsDefault) {
889 $updated_data['form_content']['is_default'] = $reportIsDefault;
890 }
891 $updated_data['message'] = __('Form updated successfully.', 'bit-form');
892 return $updated_data;
893 }
894 }
895
896 public function setEmptyMetaValue($fieldkeys)
897 {
898 $sqlEscaped = array_map(function ($fld) {
899 return "'" . esc_sql($fld) . "'";
900 }, $fieldkeys);
901 $deletedFldKey = implode(',', $sqlEscaped);
902 global $wpdb;
903 $tablename = $wpdb->prefix . 'bitforms_form_entrymeta';
904 $sql = $wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN ( " . $deletedFldKey . ')', '');
905 $wpdb->query($sql);
906 }
907
908 public function changeFormStatus($Request, $post)
909 {
910 if (isset($Request['status']) && $Request['id']) {
911 $status = wp_unslash($Request['status']);
912 $id = wp_unslash($Request['id']);
913 } else {
914 $status = wp_unslash($post->status);
915 $id = wp_unslash($post->id);
916 }
917 $user_details = static::$ipTool->getUserDetail();
918 // return $post->fields;
919 $status = 'true' === $status || true === $status ? true : false;
920 if (!is_bool($status) || is_null($id)) {
921 // echo $status;
922 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
923 }
924 $update_status = static::$formModel->update(
925 [
926 'user_id' => $user_details['id'],
927 'user_ip' => $user_details['ip'],
928 'user_device' => $user_details['device'],
929 'status' => $status ? 1 : 0,
930 'updated_at' => $user_details['time'],
931 ],
932 [
933 'id' => $id,
934 ]
935 );
936 if (is_wp_error($update_status)) {
937 return $update_status;
938 } elseif (!$update_status) {
939 return false;
940 } else {
941 return __('Form status changed successfully', 'bit-form');
942 }
943 }
944
945 public function changeBulkFormStatus($Request, $post)
946 {
947 if (isset($Request['status']) && $Request['formID']) {
948 $status = wp_unslash($Request['status']);
949 $formID = wp_unslash($Request['formID']);
950 } else {
951 $status = wp_unslash($post->status);
952 $formID = wp_unslash($post->formID);
953 }
954 $user_details = static::$ipTool->getUserDetail();
955 // return $post->fields;
956 $status = 'true' === $status || true === $status ? true : false;
957 if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
958 // echo $status;
959 return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
960 }
961 $update_status = static::$formModel->bulkUpdate(
962 [
963 'user_id' => $user_details['id'],
964 'user_ip' => $user_details['ip'],
965 'user_device' => $user_details['device'],
966 'status' => $status ? 1 : 0,
967 'updated_at' => $user_details['time'],
968 ],
969 [
970 'id' => $formID,
971 ]
972 );
973 if (is_wp_error($update_status)) {
974 return $update_status;
975 } elseif (!$update_status) {
976 return false;
977 } else {
978 return __('Form status changed successfully', 'bit-form');
979 }
980 }
981
982 public function getAllForm()
983 {
984 global $wpdb;
985
986 $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");
987
988 if (is_wp_error($allForms)) {
989 return $allForms;
990 } elseif (!$allForms) {
991 return [];
992 } else {
993 return $allForms;
994 }
995 }
996
997 public function getAForm($Request, $post)
998 {
999 if (isset($Request['id'])) {
1000 $formID = wp_unslash($Request['id']);
1001 } else {
1002 $formID = wp_unslash($post->id);
1003 }
1004 // return $post->fields;
1005 if (is_null($formID)) {
1006 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1007 }
1008 $formManager = new AdminFormManager($formID);
1009 if (!$formManager->isExist()) {
1010 return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
1011 }
1012 $form_content = $formManager->getFormContent();
1013 $helper_states = $formManager->getFormHelperStates();
1014 if ($formManager->isExist()) {
1015 $form_content_arr = [
1016 'layout' => $form_content->layout,
1017 'nestedLayout' => !empty($form_content->nestedLayout) ? $form_content->nestedLayout : (object) [],
1018 'formInfo' => !empty($form_content->formInfo) ? $form_content->formInfo : (object) ['formName' => $formManager->getFormName()],
1019 'fields' => $form_content->fields,
1020 'form_name' => $formManager->getFormName(),
1021 'workFlowExist' => $form_content->workFlowExist,
1022 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
1023 ];
1024 $successMessageHandler
1025 = new SuccessMessageHandler($formID);
1026 $successMessages = $successMessageHandler->getAllMessage();
1027 if (!is_wp_error($successMessages)) {
1028 foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
1029 $sucessMessagevalue->message_config = json_decode($sucessMessagevalue->message_config);
1030 $allConfirmation['type']['successMsg'][$sucessMessagekey] =
1031 [
1032 'id' => $sucessMessagevalue->id,
1033 'title' => $sucessMessagevalue->message_title,
1034 'msg' => $sucessMessagevalue->message_content,
1035 'config' => $sucessMessagevalue->message_config,
1036 ];
1037 }
1038 }
1039 $emailTemplateHandler
1040 = new EmailTemplateHandler($formID);
1041 $emailTemplates = $emailTemplateHandler->getAllTemplate();
1042 if (!is_wp_error($emailTemplates)) {
1043 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1044 $mailTem[] =
1045 [
1046 'id' => $emailTemplatevalue->id,
1047 'title' => $emailTemplatevalue->title,
1048 'sub' => $emailTemplatevalue->sub,
1049 'body' => $emailTemplatevalue->body,
1050 ];
1051 }
1052 }
1053 // get all pdf template
1054 $pdfTemplateHandler = new PdfTemplateHandler($formID);
1055 $pdfTemplates = $pdfTemplateHandler->getAll();
1056
1057 if (!is_wp_error($pdfTemplates)) {
1058 foreach ($pdfTemplates as $value) {
1059 $pdfTem[] =
1060 [
1061 'id' => $value->id,
1062 'title' => $value->title,
1063 'setting' => json_decode($value->setting),
1064 'body' => $value->body,
1065 ];
1066 }
1067 }
1068
1069 $integrationHandler = new IntegrationHandler($formID);
1070 $formIntegrations = $integrationHandler->getAllIntegration('form');
1071 if (!is_wp_error($formIntegrations)) {
1072 foreach ($formIntegrations as $integrationkey => $integrationValue) {
1073 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1074 $integrationData = [
1075 'id' => $integrationValue->id,
1076 'title' => $integrationValue->integration_name,
1077 ];
1078 if (!empty($integrationValue->integration_details)) {
1079 $integration_details = (array) json_decode($integrationValue->integration_details);
1080 $integrationData = array_merge($integration_details, $integrationData);
1081 } else {
1082 $integration_details = [
1083 'url' => '',
1084 ];
1085 $integrationData = array_merge($integrationData, $integration_details);
1086 }
1087 $allConfirmation['type'][$integrationValue->integration_type][]
1088 = $integrationData;
1089 } else {
1090 $integrationData = [
1091 'id' => $integrationValue->id,
1092 'name' => $integrationValue->integration_name,
1093 'type' => $integrationValue->integration_type,
1094 ];
1095 $integrations[] = array_merge(
1096 $integrationData,
1097 is_string($integrationValue->integration_details) ?
1098 (array) json_decode($integrationValue->integration_details) :
1099 $integrationValue->integration_details
1100 );
1101 }
1102 }
1103 }
1104
1105 // get form abandonment integration if exist
1106 $formAbandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
1107 if (!is_wp_error($formAbandonmentInteg) && !empty($formAbandonmentInteg)) {
1108 $formAbandonmentInteg = $formAbandonmentInteg[0];
1109 if (!empty($formAbandonmentInteg->integration_details)) {
1110 $formAbandonment = json_decode($formAbandonmentInteg->integration_details);
1111 } else {
1112 $formAbandonment = (object) [];
1113 }
1114 } else {
1115 $formAbandonment = (object) [];
1116 }
1117
1118 $settingsContent = [
1119 'formName' => $formManager->getFormName(),
1120 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1121 'formPermissions' => isset($form_content->formPermissions) ? $form_content->formPermissions : (object) [],
1122 // 'submitBtn' => $form_content->buttons,
1123 ];
1124
1125 if (!empty($allConfirmation)) {
1126 $confirmation = [
1127 'confirmation' => $allConfirmation,
1128 ];
1129 } else {
1130 $confirmation = [
1131 'confirmation' => ['type' => []],
1132 ];
1133 }
1134 $settingsContent = array_merge($settingsContent, $confirmation);
1135 if (!empty($integrations)) {
1136 $settingsContent = array_merge(
1137 $settingsContent,
1138 [
1139 'integrations' => $integrations,
1140 ]
1141 );
1142 } else {
1143 $settingsContent = array_merge(
1144 $settingsContent,
1145 [
1146 'integrations' => []
1147 ]
1148 );
1149 }
1150
1151 if (!empty($mailTem)) {
1152 $settingsContent = array_merge(
1153 $settingsContent,
1154 [
1155 'mailTem' => $mailTem,
1156 ]
1157 );
1158 } else {
1159 $settingsContent = array_merge(
1160 $settingsContent,
1161 [
1162 'mailTem' => []
1163 ]
1164 );
1165 }
1166
1167 if (!empty($pdfTem)) {
1168 $settingsContent = array_merge(
1169 $settingsContent,
1170 [
1171 'pdfTem' => $pdfTem,
1172 ]
1173 );
1174 } else {
1175 $settingsContent = array_merge(
1176 $settingsContent,
1177 [
1178 'pdfTem' => [],
1179 ]
1180 );
1181 }
1182
1183 if (!empty($formAbandonment)) {
1184 $settingsContent = array_merge(
1185 $settingsContent,
1186 [
1187 'formAbandonment' => $formAbandonment,
1188 ]
1189 );
1190 } else {
1191 $settingsContent = array_merge(
1192 $settingsContent,
1193 [
1194 'formAbandonment' => (object) [],
1195 ]
1196 );
1197 }
1198 $formSettings = [
1199 'formSettings' => $settingsContent,
1200 ];
1201 $data = [
1202 'id' => $formID,
1203 'form_name' => $formManager->getFormName(),
1204 'form_content' => $form_content_arr,
1205 'breakpointSize' => $helper_states->breakpointSize,
1206 'style' => $helper_states->style,
1207 'themeVars' => $helper_states->themeVars,
1208 'themeColors' => $helper_states->themeColors,
1209 'builderSettings' => $helper_states->builderSettings,
1210 'additional' => empty($form_content->additional) ? [
1211 'enabled' => [
1212 'blocked_ip' => false,
1213 'restrict_form' => false,
1214 'onePerIp' => false,
1215 ],
1216 'settings' => [
1217 'restrict_form' => [
1218 'day' => [],
1219 'date' => [
1220 'from' => null,
1221 'to' => null,
1222 ],
1223 'time' => [
1224 'from' => null,
1225 'to' => null,
1226 ],
1227 ],
1228 'entry_limit' => null,
1229 'blocked_ip' => [],
1230 ],
1231 ] : $form_content->additional,
1232 'created_at' => $formManager->getFormMetaData()['created_at'],
1233 'views' => $formManager->getFormMetaData()['views'],
1234 'entries' => $formManager->getFormMetaData()['entries'],
1235 'status' => $formManager->getFormMetaData()['status'],
1236 ];
1237 $data = array_merge($data, $formSettings);
1238 $workFlowHandler = new WorkFlowHandler($formID);
1239 $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlow()];
1240 $data = array_merge($data, $workFlows);
1241 $reportsModel = new ReportsModel();
1242 $returnedReportData = $reportsModel->get(
1243 [
1244 'id',
1245 'details',
1246 'isDefault',
1247 'type',
1248 ],
1249 [
1250 'category' => 'form',
1251 'context' => $formID,
1252 ]
1253 );
1254
1255 if (!is_wp_error($returnedReportData)) {
1256 $fieldNames = [];
1257 foreach ($formManager->getFieldLabel() as $key => $field) {
1258 $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
1259 }
1260 if ($formManager->isGCLIDEnabled()) {
1261 $fieldNames['GCLID'] = 'GCLID';
1262 }
1263 foreach ($returnedReportData as $reportKey => $reportData) {
1264 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1265 if (!empty($reportDetails) && is_string($reportDetails)) {
1266 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1267 } elseif (!empty($reportDetails)) {
1268 $returnedReportData[$reportKey]->details = $reportDetails;
1269 } else {
1270 $returnedReportData[$reportKey]->details = [];
1271 }
1272 if ('1' === (string) $reportData->isDefault) {
1273 $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1274 }
1275 }
1276 $reports = ['reports' => $returnedReportData];
1277 $data = array_merge($data, $reports);
1278 }
1279
1280 $formFields = $formManager->getFieldLabel();
1281 $data = array_merge($data, ['Labels' => $formFields]);
1282
1283 return $data;
1284 }
1285 }
1286
1287 public function getAFormV1($Request, $post)
1288 {
1289 if (isset($Request['id'])) {
1290 $formID = wp_unslash($Request['id']);
1291 } else {
1292 $formID = wp_unslash($post->id);
1293 }
1294 // return $post->fields;
1295 if (is_null($formID)) {
1296 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1297 }
1298 $formManager = new AdminFormManager($formID);
1299 if (!$formManager->isExist()) {
1300 return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
1301 }
1302 $form_content = $formManager->getFormContent();
1303 if ($formManager->isExist()) {
1304 $form_content_arr = [
1305 'layout' => $form_content->layout,
1306 'fields' => $form_content->fields,
1307 'form_name' => $formManager->getFormName(),
1308 'workFlowExist' => $form_content->workFlowExist,
1309 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
1310 ];
1311 $successMessageHandler
1312 = new SuccessMessageHandler($formID);
1313 $successMessages = $successMessageHandler->getAllMessage();
1314 if (!is_wp_error($successMessages)) {
1315 foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
1316 $allConfirmation['type']['successMsg'][$sucessMessagekey] =
1317 [
1318 'id' => $sucessMessagevalue->id,
1319 'title' => $sucessMessagevalue->message_title,
1320 'msg' => $sucessMessagevalue->message_content,
1321 ];
1322 }
1323 }
1324 $emailTemplateHandler
1325 = new EmailTemplateHandler($formID);
1326 $emailTemplates = $emailTemplateHandler->getAllTemplate();
1327 if (!is_wp_error($emailTemplates)) {
1328 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1329 $mailTem[] =
1330 [
1331 'id' => $emailTemplatevalue->id,
1332 'title' => $emailTemplatevalue->title,
1333 'sub' => $emailTemplatevalue->sub,
1334 'body' => $emailTemplatevalue->body,
1335 ];
1336 }
1337 }
1338 $integrationHandler = new IntegrationHandler($formID);
1339 $formIntegrations = $integrationHandler->getAllIntegration('form');
1340 if (!is_wp_error($formIntegrations)) {
1341 foreach ($formIntegrations as $integrationkey => $integrationValue) {
1342 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1343 $integrationData = [
1344 'id' => $integrationValue->id,
1345 'title' => $integrationValue->integration_name,
1346 ];
1347 if (!empty($integrationValue->integration_details)) {
1348 // var_dump(json_decode($integrationValue->integration_details));
1349 $integration_details = (array) json_decode($integrationValue->integration_details);
1350 $integrationData = array_merge($integration_details, $integrationData);
1351 } else {
1352 $integration_details = [
1353 'url' => '',
1354 ];
1355 $integrationData = array_merge($integrationData, $integration_details);
1356 }
1357 $allConfirmation['type'][$integrationValue->integration_type][]
1358 = $integrationData;
1359 } else {
1360 $integrationData = [
1361 'id' => $integrationValue->id,
1362 'name' => $integrationValue->integration_name,
1363 'type' => $integrationValue->integration_type,
1364 ];
1365 $integrations[] = array_merge(
1366 $integrationData,
1367 is_string($integrationValue->integration_details) ?
1368 (array) json_decode($integrationValue->integration_details) :
1369 $integrationValue->integration_details
1370 );
1371 }
1372 }
1373 }
1374 $settingsContent = [
1375 'formName' => $formManager->getFormName(),
1376 'theme' => $form_content->theme,
1377 // 'submitBtn' => $form_content->buttons,
1378 ];
1379
1380 if (!empty($allConfirmation)) {
1381 $confirmation = [
1382 'confirmation' => $allConfirmation,
1383 ];
1384 } else {
1385 $confirmation = [
1386 'confirmation' => ['type' => []],
1387 ];
1388 }
1389 $settingsContent = array_merge($settingsContent, $confirmation);
1390 if (!empty($integrations)) {
1391 $settingsContent = array_merge(
1392 $settingsContent,
1393 [
1394 'integrations' => $integrations,
1395 ]
1396 );
1397 } else {
1398 $settingsContent = array_merge(
1399 $settingsContent,
1400 [
1401 'integrations' => []
1402 ]
1403 );
1404 }
1405 if (!empty($mailTem)) {
1406 $settingsContent = array_merge(
1407 $settingsContent,
1408 [
1409 'mailTem' => $mailTem,
1410 ]
1411 );
1412 } else {
1413 $settingsContent = array_merge(
1414 $settingsContent,
1415 [
1416 'mailTem' => []
1417 ]
1418 );
1419 }
1420 $formSettings = [
1421 'formSettings' => $settingsContent,
1422 ];
1423 $data = [
1424 'id' => $formID,
1425 'form_name' => $formManager->getFormName(),
1426 'form_content' => $form_content_arr,
1427 'additional' => empty($form_content->additional) ? [
1428 'enabled' => [
1429 'blocked_ip' => false,
1430 'restrict_form' => false,
1431 'onePerIp' => false,
1432 ],
1433 'settings' => [
1434 'restrict_form' => [
1435 'day' => [],
1436 'date' => [
1437 'from' => null,
1438 'to' => null,
1439 ],
1440 'time' => [
1441 'from' => null,
1442 'to' => null,
1443 ],
1444 ],
1445 'entry_limit' => null,
1446 'blocked_ip' => [],
1447 ],
1448 ] : $form_content->additional,
1449 'created_at' => $formManager->getFormMetaData()['created_at'],
1450 'views' => $formManager->getFormMetaData()['views'],
1451 'entries' => $formManager->getFormMetaData()['entries'],
1452 'status' => $formManager->getFormMetaData()['status'],
1453 ];
1454 $data = array_merge($data, $formSettings);
1455 $workFlowHandler = new WorkFlowHandler($formID);
1456 $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlowV1()];
1457 $data = array_merge($data, $workFlows);
1458 $reportsModel = new ReportsModel();
1459 $returnedReportData = $reportsModel->get(
1460 [
1461 'id',
1462 'details',
1463 'isDefault',
1464 'type',
1465 ],
1466 [
1467 'category' => 'form',
1468 'context' => $formID,
1469 ]
1470 );
1471
1472 if (!is_wp_error($returnedReportData)) {
1473 $fieldNames = [];
1474 foreach ($formManager->getFieldLabel() as $key => $field) {
1475 $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
1476 }
1477 if ($formManager->isGCLIDEnabled()) {
1478 $fieldNames['GCLID'] = 'GCLID';
1479 }
1480 foreach ($returnedReportData as $reportKey => $reportData) {
1481 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1482 if (!empty($reportDetails) && is_string($reportDetails)) {
1483 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1484 } elseif (!empty($reportDetails)) {
1485 $returnedReportData[$reportKey]->details = $reportDetails;
1486 } else {
1487 $returnedReportData[$reportKey]->details = [];
1488 }
1489 if ('1' === (string) $reportData->isDefault) {
1490 $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1491 }
1492 }
1493 $reports = ['reports' => $returnedReportData];
1494 $data = array_merge($data, $reports);
1495 }
1496
1497 $formFields = $formManager->getFieldLabel();
1498 $data = array_merge($data, ['Labels' => $formFields]);
1499
1500 return $data;
1501 }
1502 }
1503
1504 public function deleteAForm($Request, $post)
1505 {
1506 if (isset($Request['id'])) {
1507 $formID = wp_unslash($Request['id']);
1508 } else {
1509 $formID = wp_unslash($post->id);
1510 }
1511 if (is_null($formID)) {
1512 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1513 }
1514
1515 if (!filter_var($formID, FILTER_VALIDATE_INT)) {
1516 return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
1517 }
1518
1519 $delete_status = static::$formModel->delete(
1520 [
1521 'id' => $formID,
1522 ]
1523 );
1524
1525 $successMessageModel = new SuccessMessageModel();
1526 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1527
1528 $emailTemplateModel = new EmailTemplateModel();
1529 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1530
1531 $pdfTemplateModel = new PdfTemplateModel();
1532 $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
1533
1534 $integrationModel = new IntegrationModel();
1535 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1536
1537 $workFlowModel = new WorkFlowModel();
1538 $deleteworkFlowStatus = $workFlowModel->delete(['form_id' => $formID]);
1539
1540 $reportsModel = new ReportsModel();
1541 $deleteReportStatus = $reportsModel->delete(['context' => $formID]);
1542
1543 $formEntryModel = new FormEntryModel();
1544 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1545 $entries = [];
1546
1547 // checked namespace exist
1548 if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1549 \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByFormId($formID);
1550 }
1551
1552 $fileHandler = new FileHandler();
1553 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1554 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1555 }
1556 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1557 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1558 }
1559 $formStylePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles';
1560
1561 $formCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css';
1562 FileHandler::deleteIsFileExists($formCssPath);
1563
1564 $layoutCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css';
1565 FileHandler::deleteIsFileExists($layoutCssPath);
1566
1567 $customCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css';
1568 FileHandler::deleteIsFileExists($customCssPath);
1569
1570 $customJSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js';
1571 FileHandler::deleteIsFileExists($customJSPath);
1572
1573 $conversationCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css';
1574 FileHandler::deleteIsFileExists($conversationCssPath);
1575
1576 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1577 }
1578
1579 public function deleteBlukForm($Request, $post)
1580 {
1581 if (isset($Request['formID'])) {
1582 $formID = wp_unslash($Request['formID']);
1583 } else {
1584 $formID = wp_unslash($post->formID);
1585 }
1586
1587 if (is_null($formID) || !is_array($formID)) {
1588 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1589 }
1590
1591 if (!Helpers::checkIsIntArr($formID)) {
1592 return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
1593 }
1594
1595 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1596 foreach ($formID as $id) {
1597 $formCssPath = $cssPath . 'bitform-' . $id . '.css';
1598 FileHandler::deleteIsFileExists($formCssPath);
1599
1600 $layoutPath = $cssPath . 'bitform-layout-' . $id . '.css';
1601 FileHandler::deleteIsFileExists($layoutPath);
1602
1603 $bitformCustomPath = $cssPath . 'bitform-' . $id . '-formid' . '.css';
1604 FileHandler::deleteIsFileExists($bitformCustomPath);
1605 }
1606 $delete_status = static::$formModel->bulkDelete(
1607 [
1608 'id' => $formID,
1609 ]
1610 );
1611
1612 if (is_wp_error($delete_status)) {
1613 wp_send_json_error($delete_status->get_error_message(), 400);
1614 }
1615
1616 $successMessageModel
1617 = new SuccessMessageModel();
1618 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1619
1620 $emailTemplateModel = new EmailTemplateModel();
1621 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1622
1623 $pdfTemplateModel = new PdfTemplateModel();
1624 $deletePdfTemplateStatus = $pdfTemplateModel->bulkDelete(['form_id' => $formID]);
1625
1626 $integrationModel = new IntegrationModel();
1627 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1628
1629 $workFlowModel = new WorkFlowModel();
1630 $deleteworkFlowStatus = $workFlowModel->bulkDelete(['form_id' => $formID]);
1631
1632 $reportsModel = new ReportsModel();
1633 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1634
1635 $formEntryModel = new FormEntryModel();
1636 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1637
1638 if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1639 \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByBulkFormId($formID);
1640 }
1641
1642 $entries = [];
1643 foreach ($returnedEntries as $entryKey => $entryInfo) {
1644 if (!empty($entryInfo->id)) {
1645 $entries[] = $entryInfo->id;
1646 }
1647 }
1648 global $wpdb;
1649 $prefix = $wpdb->prefix;
1650 if (count($entries) > 0) {
1651 $deleteEntriesStatus = $formEntryModel->bulkDelete(
1652 [
1653 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1654 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1655 ]
1656 );
1657 }
1658
1659 // delete entry log and details
1660 $sql = 'DELETE em, e FROM wp_bitforms_form_log_details AS em JOIN wp_bitforms_form_entry_log AS e ON em.log_id = e.id WHERE form_id = %d';
1661 $wpdb->prepare($sql, $formID);
1662
1663 $fileHandler = new FileHandler();
1664 foreach ($formID as $fId) {
1665 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1666 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1667 }
1668 }
1669
1670 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1671 }
1672
1673 public function genarateNewLayoutNField($layout, $fields, $oldId, $newId)
1674 {
1675 $newField = (object) [];
1676 foreach ($layout->lg as $ind => $itm) {
1677 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1678 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
1679 $layout->md[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->md[$ind]->i);
1680 $layout->sm[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->sm[$ind]->i);
1681 $newField->{$layout->lg[$ind]->i} = $fld_tmp;
1682 }
1683 return ['layout' => $layout, 'fields' => $newField];
1684 }
1685
1686 public function duplicateAForm($Request, $post)
1687 {
1688 $oldFormId = intval($post->id);
1689 $newFormId = intval($post->newFormId);
1690 if ($oldFormId < 1) {
1691 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1692 }
1693
1694 $formManager = new AdminFormManager($oldFormId);
1695 if (!$formManager->isExist()) {
1696 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1697 }
1698
1699 $duplicatedForm = $this->getAForm($Request, $post);
1700 $duplicatedForm['form_name'] = 'Duplicate of ' . $duplicatedForm['form_name'];
1701 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1702
1703 /* echo wp_json_encode($formData);
1704 \wp_die(); */
1705 $duplicateResponse = $this->createNewForm(null, $formData);
1706
1707 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1708 // duplicate stylesheet
1709 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1710 // layout style copy
1711 $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1712 $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1713 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1714 $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1715 fwrite($createStyleFile, $newStyle);
1716 fclose($createStyleFile);
1717 // style copy
1718 $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1719 $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1720 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1721 $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1722 fwrite($createStyleFile, $newStyle);
1723 fclose($createStyleFile);
1724 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1725 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1726 return $duplicatedForm;
1727 }
1728 return $duplicateResponse;
1729 }
1730
1731 public function importAForm($post)
1732 {
1733 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1734 $newFormId = intval($post->newFormId);
1735 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1736 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1737 }
1738 $importtedForm = (array) $post->formDetail;
1739 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1740 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1741 $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayouts'];
1742 $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1743 unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1744 $formData = FormDuplicateHelper::createReplica((array) $importtedForm, $oldFormId, $newFormId);
1745
1746 if (!empty($importtedForm['rowHeight'])) {
1747 $formData->rowHeight = $importtedForm['rowHeight'];
1748 }
1749
1750 if (!empty($importtedForm['formStyle'])) {
1751 $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $importtedForm['formStyle']);
1752 $formData->layoutChanged = '-';
1753 }
1754 $importResponse = $this->createNewForm(null, $formData);
1755
1756 $customCode = [];
1757 // add custom js
1758 if (!empty($formData->customCode->customJs)) {
1759 $customJsPath = 'form-scripts';
1760 $fileName = 'bitform-custom-' . $newFormId . '.js';
1761 $customCode['JavaScript'] = $formData->customCode->customJs;
1762 Helpers::saveFile($customJsPath, $fileName, $formData->customCode->customJs, 'w');
1763 }
1764 // add custom css
1765 if (!empty($formData->customCode->customCss)) {
1766 $customCssPath = 'form-styles';
1767 $fileName = 'bitform-custom-' . $newFormId . '.css';
1768 $customCode['CSS'] = $formData->customCode->customCss;
1769 Helpers::saveFile($customCssPath, $fileName, $formData->customCode->customCss, 'w');
1770 }
1771 if (!is_wp_error($importResponse)) {
1772 $importResponse['customCode'] = $customCode;
1773 }
1774 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1775 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1776 $responseData['customCode'] = $customCode;
1777 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1778 return $responseData;
1779 }
1780 return $importResponse;
1781 }
1782
1783 // public function exportAForm($Request) {
1784 // $oldFormId = intval($Request['id']);
1785 // if ($oldFormId < 1) {
1786 // return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1787 // }
1788 // $formManager = new AdminFormManager($oldFormId);
1789 // if (!$formManager->isExist()) {
1790 // return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1791 // }
1792
1793 // $newFormId = $oldFormId;
1794 // $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1795 // $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1796
1797 // $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1798 // $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1799 // $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1800
1801 // $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1802 // $formData->layoutChanged = '-';
1803 // $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1804
1805 // $formJson = wp_json_encode($formData);
1806 // header('Content-Type: application/force-download');
1807 // header('Content-Type: application/octet-stream');
1808 // header('Content-Type: application/download');
1809 // header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
1810 // header('Content-Description: File Transfer');
1811 // header('Expires: 0');
1812 // header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1813 // header('Pragma: public');
1814 // header('Content-Length: ' . strlen($formJson));
1815 // header('Content-Transfer-Encoding: binary ');
1816 // flush();
1817 // echo $formJson;
1818 // die();
1819 // }
1820
1821 public function exportAForm($Request, $post)
1822 {
1823 $oldFormId = intval($post->id);
1824 if ($oldFormId < 1) {
1825 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1826 }
1827 $formManager = new AdminFormManager($oldFormId);
1828 if (!$formManager->isExist()) {
1829 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1830 }
1831
1832 $newFormId = $oldFormId;
1833 $duplicatedForm = $this->getAForm($Request, (object) ['id' => $oldFormId]);
1834 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1835 // for custom css
1836 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1837 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
1838 $customCssContain = Helpers::fileRead($cssPath);
1839 $formData->customCode = [];
1840 if ('' !== $customCssContain) {
1841 $formData->customCode['customCss'] = $customCssContain;
1842 }
1843 // for custom js
1844 $customJsPath = 'form-scripts/bitform-custom-' . $newFormId . '.js';
1845 $jsPath = Helpers::generatePathDirOrFile($customJsPath);
1846 $customJsContain = Helpers::fileRead($jsPath);
1847 if ('' !== $customJsContain) {
1848 $formData->customCode['customJs'] = $customJsContain;
1849 }
1850 return $formData;
1851 }
1852
1853 public function getFormEntryLabelAndCount($Request, $post)
1854 {
1855 if (isset($Request['id'])) {
1856 $id = wp_unslash($Request['id']);
1857 } else {
1858 $id = wp_unslash($post->id);
1859 }
1860 if (is_null($id)) {
1861 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1862 }
1863 $formManager = new AdminFormManager($id);
1864 if (!$formManager->isExist()) {
1865 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1866 }
1867 $formFields = $formManager->getFieldLabel();
1868 $formEntry = new FormEntryModel();
1869 $count = $formEntry->count(
1870 [
1871 'form_id' => $id,
1872 ]
1873 );
1874 $reportsModel = new ReportsModel();
1875 $returnedReportData = $reportsModel->get(
1876 [
1877 'id',
1878 'details',
1879 'isDefault',
1880 'type',
1881 ],
1882 [
1883 'category' => 'form',
1884 'context' => $id,
1885 ]
1886 );
1887 $labels = [];
1888 if (!is_wp_error($returnedReportData)) {
1889 $fieldNames = [];
1890 foreach ($formFields as $field) {
1891 $fieldNames[$field['key']] = $field['name'];
1892 $labels[$field['key']] = $field;
1893 }
1894 foreach ($returnedReportData as $reportKey => $reportData) {
1895 $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1896 if (!empty($reportDetails) && is_string($reportDetails)) {
1897 $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1898 } elseif (!empty($reportDetails)) {
1899 $returnedReportData[$reportKey]->details = $reportDetails;
1900 }
1901 }
1902 $response['reports'] = empty($returnedReportData) ? [] : $returnedReportData;
1903 }
1904
1905 $response['count'] = intval($count[0]->count);
1906 $response['Labels'] = $formFields;
1907 $response['fieldDetails'] = $labels;
1908 return $response;
1909 }
1910
1911 public function getFormEntry($Request, $post)
1912 {
1913 if (isset($Request['id'])) {
1914 $id = wp_unslash($Request['id']);
1915 $offset = isset($Request['offset']) ?
1916 wp_unslash($Request['offset']) : 0;
1917 $pageSize = isset($Request['pageSize']) ?
1918 wp_unslash($Request['pageSize']) : 10;
1919 $queryCondition = isset($Request['queryCondition']) ? wp_unslash($Request['queryCondition']) : ['form_id' => $id];
1920 } else {
1921 $id = wp_unslash($post->id);
1922 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1923 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
1924 $offset = isset($post->offset) ? wp_unslash($post->offset) : 0;
1925 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
1926 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1927 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1928 $pageSize = isset($post->pageSize) ?
1929 wp_unslash($post->pageSize) : 10;
1930 $queryCondition = isset($post->queryCondition) ? wp_unslash($post->queryCondition) : ['form_id' => $id];
1931 }
1932 if (is_null($id)) {
1933 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1934 }
1935 $formManager = new AdminFormManager($id);
1936 if (!$formManager->isExist()) {
1937 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1938 }
1939 $formEntry = new FormEntryModel();
1940 $entries = $formEntry->get(
1941 'id',
1942 $queryCondition,
1943 null,
1944 null,
1945 'created_at',
1946 'DESC'
1947 );
1948 if (is_wp_error($entries)) {
1949 if ('result_empty' === $entries->get_error_code()) {
1950 return [
1951 'count' => 0,
1952 'entries' => [],
1953 ];
1954 }
1955 return $entries;
1956 }
1957 $filter['field'] = $filters;
1958 $filter['global'] = $globalFilter;
1959
1960 $formFields = $formManager->getFieldLabel(true);
1961 $fieldDetails = $formManager->getFields();
1962
1963 $entryMeta = new FormEntryMetaModel();
1964 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1965 $customFieldHandler = new CustomFieldHandler();
1966 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1967 return $formEntries;
1968 }
1969
1970 public function getSingleEntry($formId, $entryId)
1971 {
1972 $formManager = new AdminFormManager($formId);
1973 if (!$formManager->isExist()) {
1974 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1975 }
1976
1977 $formFields = $formManager->getFieldLabel(true);
1978 $fieldDetails = $formManager->getFields();
1979 $entryMeta = new FormEntryMetaModel();
1980 // $formEntry = new FormEntryModel();
1981
1982 $entries = $entryMeta->getSingleEntryMeta($formFields, $entryId);
1983
1984 if (!is_wp_error($entries)) {
1985 return $entries[0];
1986 }
1987 return new WP_Error('entry_not_fonud', __('Entry Not Found!', 'bit-form'));
1988
1989 // $customFieldHandler = new CustomFieldHandler();
1990 // $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1991 // return $formEntries;
1992 }
1993
1994 public function getEntriesForReport($Request, $post)
1995 {
1996 if (isset($Request['id'])) {
1997 $id = wp_unslash($Request['id']);
1998 $offset = isset($Request['offset']) ?
1999 wp_unslash($Request['offset']) : null;
2000 $pageSize = isset($Request['pageSize']) ?
2001 wp_unslash($Request['pageSize']) : null;
2002 } else {
2003 $id = wp_unslash($post->id);
2004 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
2005 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
2006 $offset = isset($post->offset) ? wp_unslash($post->offset) : null;
2007 $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
2008 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
2009 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
2010 $pageSize = isset($post->pageSize) ?
2011 wp_unslash($post->pageSize) : null;
2012 }
2013 if (is_null($id)) {
2014 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
2015 }
2016 $formManager = new AdminFormManager($id);
2017 if (!$formManager->isExist()) {
2018 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2019 }
2020
2021 $formEntry = new FormEntryModel();
2022 $entries = $formEntry->get(
2023 'id',
2024 [
2025 'form_id' => $id,
2026 ],
2027 null,
2028 null,
2029 'created_at',
2030 'DESC'
2031 );
2032 if (is_wp_error($entries)) {
2033 if ('result_empty' === $entries->get_error_code()) {
2034 return [
2035 'count' => 0,
2036 'entries' => [],
2037 ];
2038 }
2039 return $entries;
2040 }
2041 $filter['field'] = $filters;
2042 $filter['global'] = $globalFilter;
2043
2044 $formFields = $formManager->getFieldLabel(true);
2045 $fieldDetails = $formManager->getFields();
2046
2047 $entryMeta = new FormEntryMetaModel();
2048 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
2049 $customFieldHandler = new CustomFieldHandler();
2050 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
2051 $formEntries['entries'] = Helpers::filterNullEntries($formEntries['entries']);
2052 return $formEntries;
2053 }
2054
2055 public function getExportEntry($post)
2056 {
2057 $formId = wp_unslash($post->formId);
2058 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
2059 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
2060 $entryCondition = isset($post->filter) ? wp_unslash($post->filter) : null;
2061 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
2062 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
2063 $formFields = json_decode($post->selectedField);
2064 if (is_null($formId)) {
2065 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
2066 }
2067 $formManager = new AdminFormManager($formId);
2068 $fieldLabels = $formManager->getFieldLabel(true);
2069 if (!$formManager->isExist()) {
2070 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2071 }
2072
2073 $formEntry = new FormEntryModel();
2074 $entries = $formEntry->get(
2075 'id',
2076 [
2077 'form_id' => $formId,
2078 ],
2079 null,
2080 null,
2081 'created_at',
2082 'DESC'
2083 );
2084 if (is_wp_error($entries)) {
2085 if ('result_empty' === $entries->get_error_code()) {
2086 return [
2087 'count' => 0,
2088 'entries' => [],
2089 ];
2090 }
2091 return $entries;
2092 }
2093 $entryMeta = new FormEntryMetaModel();
2094 $filter = [];
2095 $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField, $offset, $entryCondition);
2096 return $formEntries;
2097 }
2098
2099 public function deleteBlukFormEntries($Request, $post)
2100 {
2101 if (isset($Request['formID'])) {
2102 $formID = wp_unslash($Request['formID']);
2103 $entries = wp_unslash($Request['entries']);
2104 } else {
2105 $formID = wp_unslash($post->formID);
2106 $entries = wp_unslash($post->entries);
2107 }
2108 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
2109 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
2110 }
2111
2112 if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2113 return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
2114 }
2115
2116 if (!Helpers::checkIsIntArr($entries)) {
2117 return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2118 }
2119
2120 $formManager = new AdminFormManager($formID);
2121 if (!$formManager->isExist()) {
2122 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
2123 }
2124 $workFlowRunHelper = new WorkFlow($formID);
2125
2126 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
2127 $formManager,
2128 $formID,
2129 $entries
2130 );
2131
2132 if (isset($workFlowreturnedOnDelete['entries'])) {
2133 if (0 === count($workFlowreturnedOnDelete['entries'])) {
2134 return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
2135 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
2136 $message = __('Entry Deleted successfully', 'bit-form');
2137 } else {
2138 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
2139 $entries = $workFlowreturnedOnDelete['entries'];
2140 $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
2141 }
2142 } else {
2143 $message = __('Entry Deleted successfully', 'bit-form');
2144 }
2145 global $wpdb;
2146 $prefix = $wpdb->prefix;
2147 $formEntryModel = new FormEntryModel();
2148 $delete_status = $formEntryModel->bulkDelete(
2149 [
2150 "`{$prefix}bitforms_form_entries`.`id`" => $entries,
2151 "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
2152 ]
2153 );
2154 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
2155 $fileHandler = new FileHandler();
2156 foreach ($entries as $enrtyKey => $entryID) {
2157 $fileEntries = $fileHandler->getEntriesFileUploadDir($formID, $entryID);
2158 if (file_exists($fileEntries)) {
2159 $fileHandler->rmrf($fileEntries);
2160 }
2161 }
2162 }
2163 $count = $formEntryModel->count(
2164 [
2165 'form_id' => $formID,
2166 ]
2167 );
2168 $formManager->resetSubmissionCount(intval($count[0]->count));
2169 if (is_wp_error($delete_status)) {
2170 return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
2171 }
2172 $result['message'] = $message;
2173 return $result;
2174 }
2175
2176 public function duplicateFormEntry($Request, $post)
2177 {
2178 if (isset($Request['formID'])) {
2179 $formID = wp_unslash($Request['formID']);
2180 $entries = wp_unslash($Request['entries']);
2181 } else {
2182 $formID = wp_unslash($post->formID);
2183 $entries = wp_unslash($post->entries);
2184 }
2185 if (is_null($formID) || !is_array($entries) || empty($entries)) {
2186 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
2187 }
2188
2189 if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2190 return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
2191 }
2192
2193 if (!Helpers::checkIsIntArr($entries)) {
2194 return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2195 }
2196
2197 $formManager = new AdminFormManager($formID);
2198 if (!$formManager->isExist()) {
2199 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
2200 }
2201 $formEntryModel = new FormEntryModel();
2202 $entryMeta = new FormEntryMetaModel();
2203 $user_details = static::$ipTool->getUserDetail();
2204 $total_entries = count($entries);
2205 $duplicate_count = 0;
2206 $test = '';
2207 $fileHandler = new FileHandler();
2208 $result = [];
2209 foreach ($entries as $entryIndex => $entryID) {
2210 $duplicatedEntryId = $formEntryModel->insert(
2211 [
2212 'form_id' => $formID,
2213 'user_id' => $user_details['id'],
2214 'user_ip' => $user_details['ip'],
2215 'user_device' => $user_details['device'],
2216 'referer' => 'duplicate of #' . $entryID,
2217 'status' => 1,
2218 'created_at' => $user_details['time'],
2219 ]
2220 );
2221 if ($duplicatedEntryId) {
2222 $duplicate_status = $entryMeta->duplicateEntryMeta(
2223 [
2224 'duplicateID' => $duplicatedEntryId,
2225 'entryID' => $entryID,
2226 ]
2227 );
2228 if ($duplicate_status) {
2229 $result['details'][$entryID] = $duplicatedEntryId;
2230 $duplicate_count = $duplicate_count + 1;
2231 if (file_exists(FileHandler::getEntriesFileUploadDir($formID, $entryID))) {
2232 $fileHandler->cpyr(
2233 FileHandler::getEntriesFileUploadDir($formID, $entryID),
2234 FileHandler::getEntriesFileUploadDir($formID, $duplicatedEntryId)
2235 );
2236 }
2237 }
2238 }
2239 }
2240
2241 $count = $formEntryModel->count(
2242 [
2243 'form_id' => $formID,
2244 ]
2245 );
2246 $formManager->resetSubmissionCount(intval($count[0]->count));
2247 $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
2248 return ($total_entries === $duplicate_count) ? $result : false;
2249 }
2250
2251 public function editFormEntry($Request, $post)
2252 {
2253 if (isset($Request['formID'])) {
2254 $formID = wp_unslash($Request['formID']);
2255 $entryID = wp_unslash($Request['entryID']);
2256 } else {
2257 $formID = wp_unslash($post->formID);
2258 $entryID = wp_unslash($post->entryID);
2259 }
2260 if (is_null($formID) || is_null($entryID)) {
2261 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
2262 }
2263
2264 $formManager = new AdminFormManager($formID);
2265 if (!$formManager->isExist()) {
2266 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
2267 }
2268 $formEntryModel = new FormEntryModel();
2269 $entryMeta = new FormEntryMetaModel();
2270
2271 $formEntry = $formEntryModel->get(
2272 '*',
2273 [
2274 'form_id' => $formID,
2275 'id' => $entryID,
2276 ]
2277 );
2278
2279 if (!$formEntry) {
2280 return new WP_Error('empty_form', __('Form entries does not exist.', 'bit-form'));
2281 }
2282 $formEntryMeta = $entryMeta->get(
2283 [
2284 'meta_key',
2285 'meta_value',
2286 ],
2287 [
2288 'bitforms_form_entry_id' => $entryID,
2289 ]
2290 );
2291 $entries = [];
2292 foreach ($formEntryMeta as $key => $value) {
2293 $entries[$value->meta_key] = $value->meta_value;
2294 }
2295 $formContent = $formManager->getFormContent();
2296 $fieldsKey = $formManager->getFieldsKey();
2297 $form_fields = $formContent->fields;
2298 $layout = $formContent->layout;
2299 foreach ($form_fields as $key => $value) {
2300 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
2301 if (isset($entries[$key])) {
2302 $form_fields->{$key}->val = $entries[$key];
2303 $form_fields->{$key}->name = $key;
2304 }
2305 }
2306 $workFlowRunHelper = new WorkFlow($formID);
2307 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
2308 'edit',
2309 $form_fields
2310 );
2311 $workFlowreturnedOnUserInput = $workFlowRunHelper->executeOnUserInput(
2312 'edit',
2313 $form_fields
2314 );
2315 if (!empty($workFlowreturnedOnLoad['fields'])) {
2316 $form_fields = $workFlowreturnedOnLoad['fields'];
2317 }
2318 $formData = [
2319 'layout' => $layout,
2320 'fields' => $form_fields,
2321 'conditional' => !empty($workFlowreturnedOnUserInput['conditional']) ? $workFlowreturnedOnUserInput['conditional'] : false,
2322 'fieldToCheck' => !empty($workFlowreturnedOnUserInput['fieldToCheck']) ? $workFlowreturnedOnUserInput['fieldToCheck'] : false,
2323 'fieldToChange' => !empty($workFlowreturnedOnUserInput['fieldToChange']) ? $workFlowreturnedOnUserInput['fieldToChange'] : false,
2324 'fieldsKey' => $fieldsKey,
2325 ];
2326 return $formData;
2327 }
2328
2329 public function updateFormEntry($Request, $post)
2330 {
2331 if (isset($Request['formID'], $Request['entryID'])) {
2332 $formID = wp_unslash($Request['formID']);
2333 $entryID = wp_unslash($Request['entryID']);
2334 unset($Request['action'], $Request['formID'], $Request['entryID']);
2335 }
2336 $formManager = new AdminFormManager($formID);
2337 $formManager->fieldNameReplaceOfPost();
2338 $updatedValue = wp_unslash($_POST);
2339
2340 if (is_null($updatedValue) || !is_array($updatedValue)) {
2341 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
2342 }
2343
2344 if (is_null($formID) || is_null($entryID)) {
2345 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
2346 }
2347
2348 if (!$formManager->isExist()) {
2349 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
2350 }
2351 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
2352 }
2353
2354 public function getLogHistory($Request, $post)
2355 {
2356 if (isset($Request['formID'])) {
2357 $formID = wp_unslash($Request['formID']);
2358 $entryID = wp_unslash($Request['entryID']);
2359 } else {
2360 $formID = wp_unslash($post->formID);
2361 $entryID = wp_unslash($post->entryID);
2362 }
2363
2364 if (is_null($formID) || is_null($entryID)) {
2365 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
2366 }
2367
2368 $formManager = new AdminFormManager($formID);
2369 if (!$formManager->isExist()) {
2370 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
2371 }
2372 $formLogModel = new FormEntryLogModel();
2373
2374 $log_history = $formLogModel->geLogHistory($formID, $entryID);
2375 return $log_history;
2376 }
2377
2378 public function importDataStore($Request, $post)
2379 {
2380 if (isset($Request['formID'])) {
2381 $formID = wp_unslash($Request['formID']);
2382 } else {
2383 $formID = wp_unslash($post->formID);
2384 }
2385 if (is_null($formID)) {
2386 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
2387 }
2388 }
2389
2390 public function getAllWPPages($Request, $post)
2391 {
2392 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
2393 $allPages = [];
2394 foreach ($pages as $pageKey => $pageDetails) {
2395 // $allPages[$pageKey]['title'] = $pageDetails->post_title;
2396 // $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2397 $allPages[] = (object) [
2398 'title' => $pageDetails->post_title,
2399 'url' => get_page_link($pageDetails->ID)
2400 ];
2401 }
2402 return $allPages;
2403 }
2404
2405 public function deleteAIntegration($Request, $post)
2406 {
2407 if (isset($Request['formID']) && $Request['id']) {
2408 $formID = json_decode(wp_unslash($Request['formID']));
2409 $id = wp_unslash($Request['id']);
2410 } else {
2411 $formID = wp_unslash($post->formID);
2412 $id = wp_unslash($post->id);
2413 }
2414 if ($formID < 0 || empty($id)) {
2415 return new WP_Error('empty_form', 'Invalid Form ID or Integration ID.');
2416 }
2417
2418 $integrationHandler = new IntegrationHandler($formID);
2419 $delete_status = $integrationHandler->deleteIntegration($id);
2420 if (is_wp_error($delete_status)) {
2421 return $delete_status;
2422 }
2423
2424 return [
2425 'message' => __('Integration deleted', 'bit-form'),
2426 ];
2427 }
2428
2429 public function deleteSuccessMessage($Request, $post)
2430 {
2431 if (isset($Request['formID']) && $Request['id']) {
2432 $formID = json_decode(wp_unslash($Request['formID']));
2433 $id = wp_unslash($Request['id']);
2434 } else {
2435 $formID = wp_unslash($post->formID);
2436 $id = wp_unslash($post->id);
2437 }
2438 if (empty($formID) || empty($id)) {
2439 return new WP_Error('empty_form', 'Invalid Form ID or Message ID.');
2440 }
2441 $successMessageHandler
2442 = new SuccessMessageHandler($formID);
2443 $delete_status = $successMessageHandler->deleteMessage($id);
2444 if (is_wp_error($delete_status)) {
2445 return $delete_status;
2446 }
2447 return [
2448 'message' => __('Message deleted', 'bit-form'),
2449 ];
2450 }
2451
2452 public function deleteAWorkflow($Request, $post)
2453 {
2454 if (isset($Request['formID']) && $Request['id']) {
2455 $formID = json_decode(wp_unslash($Request['formID']));
2456 $id = wp_unslash($Request['id']);
2457 } else {
2458 $formID = wp_unslash($post->formID);
2459 $id = wp_unslash($post->id);
2460 }
2461 if (empty($formID) || empty($id)) {
2462 return new WP_Error('empty_form', 'Invalid Form ID or Workflow ID.');
2463 }
2464 $workFlowHandler = new WorkFlowHandler($formID);
2465 $delete_status = $workFlowHandler->deleteworkFlow($id);
2466 if (is_wp_error($delete_status)) {
2467 return $delete_status;
2468 }
2469 return [
2470 'message' => __('workflow deleted', 'bit-form'),
2471 ];
2472 }
2473
2474 public function deleteAMailTemplate($Request, $post)
2475 {
2476 if (isset($Request['formID']) && $Request['id']) {
2477 $formID = json_decode(wp_unslash($Request['formID']));
2478 $id = wp_unslash($Request['id']);
2479 } else {
2480 $formID = wp_unslash($post->formID);
2481 $id = wp_unslash($post->id);
2482 }
2483 if (empty($formID) || empty($id)) {
2484 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2485 }
2486 $emailTemplateHandler = new EmailTemplateHandler($formID);
2487 $delete_status = $emailTemplateHandler->deleteTemplate($id);
2488 if (is_wp_error($delete_status)) {
2489 return $delete_status;
2490 }
2491 return [
2492 'message' => __('Email Template deleted', 'bit-form'),
2493 ];
2494 }
2495
2496 public function duplicateAMailTemplate($Request, $post)
2497 {
2498 if (isset($Request['formID']) && $Request['id']) {
2499 $formID = json_decode(wp_unslash($Request['formID']));
2500 $id = wp_unslash($Request['id']);
2501 } else {
2502 $formID = wp_unslash($post->formID);
2503 $id = wp_unslash($post->id);
2504 }
2505 if (empty($formID) || empty($id)) {
2506 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2507 }
2508
2509 if (false === filter_var($id, FILTER_VALIDATE_INT)) {
2510 return new WP_Error('empty_form', 'Invalid Email Template ID.');
2511 }
2512
2513 if (false === filter_var($formID, FILTER_VALIDATE_INT)) {
2514 return new WP_Error('empty_form', 'Invalid Form ID.');
2515 }
2516
2517 $emailTemplateHandler = new EmailTemplateHandler($formID);
2518 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
2519 if (is_wp_error($duplicate_status)) {
2520 return $duplicate_status;
2521 }
2522 return [
2523 'message' => __('Email Template duplicated', 'bit-form'),
2524 ];
2525 }
2526
2527 public function setAllFormsReport($Request, $post)
2528 {
2529 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
2530 if (empty($reports)) {
2531 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
2532 }
2533 if (!empty($reports)) {
2534 $reportsModel = new ReportsModel();
2535 $user_details = static::$ipTool->getUserDetail();
2536 foreach ($reports as $reportIndex => $report) {
2537 if (empty($report->id)) {
2538 $reportSaveSatus = $reportsModel->insert(
2539 [
2540 'type' => 'table',
2541 'category' => 'app',
2542 'context' => 'allForm',
2543 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2544 'isDefault' => 1,
2545 'user_id' => $user_details['id'],
2546 'user_ip' => $user_details['ip'],
2547 'user_device' => $user_details['device'],
2548 'created_at' => $user_details['time'],
2549 'updated_at' => $user_details['time'],
2550 ]
2551 );
2552 $newData['reports'] = 1;
2553 } else {
2554 $reportSaveSatus = $reportsModel->update(
2555 [
2556 'type' => 'table',
2557 'category' => 'app',
2558 'context' => 'allForm',
2559 'details' => is_string($report->details) ? $report->details : wp_json_encode($report->details),
2560 'isDefault' => 1,
2561 'user_id' => $user_details['id'],
2562 'user_ip' => $user_details['ip'],
2563 'user_device' => $user_details['device'],
2564 'updated_at' => $user_details['time'],
2565 ],
2566 [
2567 'id' => $report->id,
2568 ]
2569 );
2570 }
2571 }
2572 }
2573 if (is_wp_error($reportSaveSatus)) {
2574 if ('result_empty' === $reportSaveSatus->get_error_code()) {
2575 return new WP_Error('empty_report_prefs', 'Nothing to save or update');
2576 }
2577 return new WP_Error('error_report_prefs', 'Error occured in saving reports');
2578 }
2579 $returnedReportData = $reportsModel->get(
2580 [
2581 'id',
2582 'details',
2583 'isDefault',
2584 'category',
2585 'context',
2586 ],
2587 [
2588 'category' => 'app',
2589 'context' => 'allForm',
2590 ]
2591 );
2592 if (!is_wp_error($returnedReportData)) {
2593 foreach ($returnedReportData as $reportKey => $reportData) {
2594 if (isset($reportData->details) && is_string($reportData->details)) {
2595 $returnedReportData[$reportKey]->details = json_decode($reportData->details);
2596 }
2597 }
2598 $reports = $returnedReportData;
2599 }
2600 return [
2601 'message' => __('Report preferrences saved successfully', 'bit-form'),
2602 'reports' => empty($reports) ? [] : $reports,
2603 ];
2604 }
2605
2606 public function savegReCaptcha($Request, $post)
2607 {
2608 $reCaptcha = $post->reCaptcha;
2609
2610 if (is_null($reCaptcha)) {
2611 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
2612 }
2613 if (is_string($reCaptcha) && !empty(json_decode($reCaptcha)->id)) {
2614 $reCaptcha = json_decode($reCaptcha);
2615 $integrationID = $reCaptcha->id;
2616 unset($reCaptcha->id);
2617 } else {
2618 $integrationID = $reCaptcha->id;
2619 unset($reCaptcha->id);
2620 }
2621 $reCaptcha = wp_json_encode($reCaptcha);
2622
2623 // $integrationName = 'google reCaptcha';
2624 $integrationName = $post->integrationName;
2625
2626 // $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
2627 $integrationType = $post->integrationType;
2628
2629 $integrationDetails = $reCaptcha;
2630 $user_details = static::$ipTool->getUserDetail();
2631 $integrationHandler = new IntegrationHandler(0, $user_details);
2632 $response = [];
2633 if (empty($integrationID)) {
2634 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2635 $response['id'] = $captchaSaveStatus;
2636 $response['message'] = __('reCAPTCHA saved successfully', 'bit-form');
2637 } else {
2638 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2639 $response['message'] = __('reCAPTCHA updated successfully', 'bit-form');
2640 }
2641
2642 if (is_wp_error($captchaSaveStatus)) {
2643 return $captchaSaveStatus;
2644 }
2645 return $response;
2646 }
2647
2648 public function savePaymentSetting($Request, $post)
2649 {
2650 if (isset($post->paySetting)) {
2651 $paySetting = $post->paySetting;
2652 }
2653 if (is_null($paySetting)) {
2654 return new WP_Error('empty_gcaptchdetails', __('Setting details is empty', 'bit-form'));
2655 }
2656 if (is_string($paySetting)) {
2657 $paySetting = json_decode($paySetting);
2658 }
2659
2660 $canSave = null;
2661 switch ($paySetting->type) {
2662 case 'PayPal':
2663 $canSave = $this->addWebhookToPaypal($paySetting);
2664 break;
2665 case 'Razorpay':
2666 $canSave = true;
2667 break;
2668 case 'Stripe':
2669 $canSave = $this->addWebhookToStripe($paySetting);
2670 break;
2671 case 'Mollie':
2672 $canSave = true;
2673 break;
2674 default:
2675 $canSave = null;
2676 }
2677 if (is_null($canSave)) {
2678 return new WP_Error('stripe', __('Please re-check your Client ID & Secret', 'bit-form'));
2679 }
2680 $integrationID = null;
2681 if (isset($paySetting->id)) {
2682 $integrationID = $paySetting->id;
2683 unset($paySetting->id);
2684 }
2685 $integrationName = $paySetting->name;
2686 $integrationType = 'payments';
2687 $paySetting = wp_json_encode($paySetting);
2688 $integrationDetails = $paySetting;
2689 $user_details = static::$ipTool->getUserDetail();
2690 $integrationHandler = new IntegrationHandler(0, $user_details);
2691 $response = [];
2692 if (empty($integrationID)) {
2693 $paymentSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2694 $response['id'] = $paymentSaveStatus;
2695 $response['message'] = __('Payment setting saved successfully', 'bit-form');
2696 } else {
2697 $paymentSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2698 $response['message'] = __('Payment setting updated successfully', 'bit-form');
2699 }
2700
2701 if (is_wp_error($paymentSaveStatus)) {
2702 return $paymentSaveStatus;
2703 }
2704 return $response;
2705 }
2706
2707 private function addWebhookToPaypal($paySetting)
2708 {
2709 $transaction_mode = $paySetting->mode;
2710 $clientId = $paySetting->clientID;
2711 $clientSecret = $paySetting->clientSecret;
2712 $base_url = 'sandbox' === $transaction_mode ? 'https://api-m.sandbox.paypal.com' : 'https://api.paypal.com';
2713 // get all webhooks
2714 $webhooks_url = $base_url . '/v1/notifications/webhooks';
2715 $webhooks_headers = [
2716 'Content-Type' => 'application/json',
2717 'Authorization' => 'Basic ' . base64_encode($clientId . ':' . $clientSecret)
2718 ];
2719 $webhook_url = get_rest_url() . 'bitform/v1/payments/paypal';
2720 // adding webhook
2721 $data = [
2722 'url' => $webhook_url,
2723 'event_types' => [
2724 [
2725 'name' => 'CHECKOUT.ORDER.APPROVED'
2726 ]
2727 ]
2728 ];
2729 $webhook_response = HttpHelper::post($webhooks_url, wp_json_encode($data), $webhooks_headers);
2730 if (is_wp_error($webhook_response) || $webhook_response->error) {
2731 return null;
2732 }
2733 return true;
2734 }
2735
2736 private function addWebhookToStripe($paySetting)
2737 {
2738 $clientSecret = $paySetting->clientSecret;
2739
2740 $create_webhook_url = 'https://api.stripe.com/v1/webhook_endpoints';
2741 $headers = [
2742 'Content-Type' => 'application/x-www-form-urlencoded',
2743 'Authorization' => "Bearer $clientSecret",
2744 ];
2745
2746 $webhook_url = get_rest_url() . 'bitform/v1/payments/stripe';
2747
2748 $apiResponse = HttpHelper::get($create_webhook_url, '', $headers);
2749
2750 if (isset($apiResponse->error)) {
2751 return null;
2752 }
2753 $webhookList = $apiResponse->data;
2754 $webhook_already_exist = false;
2755
2756 foreach ($webhookList as $webhook) {
2757 if ($webhook->url === $webhook_url) {
2758 $webhook_already_exist = true;
2759 break;
2760 }
2761 }
2762
2763 $data = [
2764 'enabled_events[]' => 'payment_intent.succeeded',
2765 'url' => $webhook_url,
2766 ];
2767
2768 if (!$webhook_already_exist) {
2769 $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2770 if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2771 return null;
2772 }
2773 }
2774 return true;
2775 }
2776
2777 public function builerHelperState($formId)
2778 {
2779 $data = static::$formModel->get(
2780 ['id', 'builder_helper_state'],
2781 ['id' => $formId]
2782 );
2783
2784 if (!is_wp_error($data)) {
2785 foreach ($data as $key => $value) {
2786 if (isset($value->builder_helper_state) && is_string($value->builder_helper_state)) {
2787 $data[$key]->builder_helper_state = json_decode($value->builder_helper_state);
2788 }
2789 }
2790 }
2791
2792 return $data;
2793 }
2794
2795 public function updateGeneratedScriptPageIds()
2796 {
2797 $updateData = [
2798 'generated_script_page_ids' => \wp_json_encode((object) []),
2799 ];
2800 $update_status = static::$formModel->update(
2801 $updateData,
2802 [
2803 'status' => 1
2804 ]
2805 );
2806 if (is_wp_error($update_status)) {
2807 return $update_status;
2808 } elseif (!$update_status) {
2809 return new WP_Error('empty_form', __('Form update failed.', 'bit-form'));
2810 } else {
2811 return true;
2812 }
2813 }
2814
2815 public function replaceAllFormsErrorMessagesByGlobalMessages()
2816 {
2817 try {
2818 $formModel = new FormModel();
2819 $allForms = $formModel->get(['id', 'form_content']);
2820
2821 foreach ($allForms as $form) {
2822 // Decode form_content JSON to stdClass
2823 $formContent = \json_decode($form->form_content);
2824 $fields = $formContent->fields ?? null;
2825 // If decode fails, skip to next
2826 if (!$fields) {
2827 Log::debug_log("Form ID {$form->id}: invalid JSON in form_content");
2828 continue;
2829 }
2830
2831 // Replace default error messages using your helper
2832 $updatedFields = Helpers::replaceFieldsDefaultErrorMsg($fields);
2833
2834 $formContent->fields = $updatedFields;
2835 // Encode back to JSON
2836 $updatedContent = \json_encode($formContent);
2837
2838 if (false === $updatedContent) {
2839 Log::debug_log("Form ID {$form->id}: JSON encoding failed");
2840 continue;
2841 }
2842 // Update form content in DB
2843 $formModel->update(
2844 ['form_content' => $updatedContent], // data to update
2845 ['id' => $form->id] // condition for update
2846 );
2847 }
2848 } catch (\Exception $e) {
2849 Log::debug_log('Error in updateAllFormsErrorMessagesWithGlobalMessages', $e->getMessage());
2850 }
2851 }
2852
2853 public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
2854 {
2855 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2856 return str_replace($TEMP_CONF_ID, $msgId, $str);
2857 }
2858
2859 public function startMigrationProcess()
2860 {
2861 Utilities::duplicateDbTable('form', 'form_v1');
2862 Utilities::duplicateDbTable('workflows', 'workflows_v1');
2863 Utilities::duplicateDbTable('success_messages', 'success_messages_v1');
2864 MigrationHelper::duplicateV1StyleFiles();
2865 $all_forms = $this->getAllForm();
2866 $v1FormContents = [];
2867 $defaultStyleClass = MigrationHelper::getBitformDefaultStyleClass();
2868 foreach ($all_forms as $form) {
2869 $formContents = $this->getAFormV1(['id' => $form->id], ['id' => $form->id]);
2870 $v1FormContents[] = $formContents;
2871 FrontEndScriptGenerator::saveCssFile("{$form->id}", $defaultStyleClass);
2872 FrontEndScriptGenerator::saveCssFile("{$form->id}-formid", $defaultStyleClass);
2873 }
2874 set_transient('bitforms_v1_form_contents', $v1FormContents);
2875 update_option('bitforms_migrating_to_v2', true);
2876 }
2877 }
2878