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