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