PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 3.3.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v3.3.1
3.3.1 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 All 138 releases
← All changes | includes/Admin/Form/AdminFormHandler.php +1390 -476 2.03.3.1 View file →
@@ -16,29 +16,36 @@
16 16 use BitCode\BitForm\Core\Database\IntegrationModel;
17 17 use BitCode\BitForm\Core\Database\ReportsModel;
18 18 use BitCode\BitForm\Core\Database\SuccessMessageModel;
19 19 use BitCode\BitForm\Core\Database\WorkFlowModel;
20 +use BitCode\BitForm\Core\Form\FormManager;
20 21 use BitCode\BitForm\Core\Integration\IntegrationHandler;
21 22 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
22 23 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
24 +use BitCode\BitForm\Core\Migration\MigrationHelper;
23 25 use BitCode\BitForm\Core\Util\FileHandler;
24 26 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
25 27 use BitCode\BitForm\Core\Util\HttpHelper;
26 28 use BitCode\BitForm\Core\Util\IpTool;
29 +use BitCode\BitForm\Core\Util\Log;
30 +use BitCode\BitForm\Core\Util\Utilities;
31 +use BitCode\BitForm\Core\WorkFlow\WorkFlow;
27 32 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
28 -use BitCode\BitForm\Core\WorkFlow\WorkFlowRunHelper;
29 33 use WP_Error;
30 34
31 -class AdminFormHandler {
35 +class AdminFormHandler
36 +{
32 37 private static $formModel;
33 38 private static $ipTool;
34 39
35 - public function __construct() {
40 + public function __construct()
41 + {
36 42 static::$formModel = new FormModel();
37 43 static::$ipTool = new IpTool();
38 44 }
39 45
40 - public function getTemplate($Request, $post) {
46 + public function getTemplate($Request, $post)
47 + {
41 48 $templateName = null;
42 49 $newFormId = null;
43 50 if (isset($post->template)) {
44 51 $templateName = $post->template;
@@ -49,9 +56,9 @@
49 56 $form_content_raw = $templateProvider->getTemplate($templateName, $newFormId);
50 57 if (!$form_content_raw) {
51 58 return new WP_Error('template_empty', __('Template not found, by this name: ', 'bit-form') . $templateName);
52 59 } else {
53 - return \json_encode(
60 + return wp_json_encode(
54 61 [
55 62 'id' => 0,
56 63 'form_content' => $form_content_raw,
57 64 ]
@@ -58,30 +65,30 @@
58 65 );
59 66 }
60 67 }
61 68
62 - public function saveStyleSheet($styles, $sheetName) {
69 + public function saveStyleSheet($styles, $sheetName)
70 + {
63 71 $this->createFormStylesDirIfNotExists();
64 72
65 73 if (
66 74 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
67 - && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
75 + && wp_is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
68 76 ) {
69 - $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
70 - fwrite($createStyleFile, $styles);
71 - fclose($createStyleFile);
72 - return true;
77 + $filePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName;
78 + return FileHandler::writeFile($filePath, $styles);
73 79 }
74 80 return false;
75 81 }
76 82
77 - public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43) {
83 + public function saveLayoutStyleSheet($layout, $sheetName, $lay_row_height = 43)
84 + {
78 85 $md_width = 600;
79 86 $sm_width = 400;
80 87 $lg_styles = '';
81 88 $md_styles = '';
82 89 $sm_styles = '';
83 - for ($i = 0; $i < count($layout->lg); $i++) {
90 + for ($i = 0; $i < count($layout->lg ?? []); $i++) {
84 91 $fld = $layout->lg[$i];
85 92
86 93 if ($fld->w < 10) {
87 94 $lay_row_height = 43;
@@ -145,19 +152,18 @@
145 152 $this->createFormStylesDirIfNotExists();
146 153
147 154 if (
148 155 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
149 - && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
156 + && wp_is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
150 157 ) {
151 - $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
152 - fwrite($createStyleFile, $formStyle);
153 - fclose($createStyleFile);
154 - return true;
158 + $filePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName;
159 + return FileHandler::writeFile($filePath, $formStyle);
155 160 }
156 161 return false;
157 162 }
158 163
159 - public function createFormStylesDirIfNotExists() {
164 + public function createFormStylesDirIfNotExists()
165 + {
160 166 if (!file_exists(BITFORMS_UPLOAD_DIR)) {
161 167 wp_mkdir_p(BITFORMS_UPLOAD_DIR);
162 168 }
163 169 if (!file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')) {
@@ -164,9 +170,18 @@
164 170 wp_mkdir_p(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles');
165 171 }
166 172 }
167 173
168 - public function createNewForm($Request, $post) {
174 + private function pdfFontDownload($fontName)
175 + {
176 + if (class_exists('\BitCode\BitFormPro\Admin\AppSetting\Pdf')) {
177 + \BitCode\BitFormPro\Admin\AppSetting\Pdf::getInstance()->fontsDownload($fontName);
178 + }
179 + return false;
180 + }
181 +
182 + public function createNewForm($Request, $post)
183 + {
169 184 // wp_send_json_success($post);
170 185 // exit;
171 186 if (!isset($post->form_id) || '' === $post->form_id) {
172 187 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
@@ -176,17 +191,8 @@
176 191 if ($formManager->isExist()) {
177 192 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
178 193 }
179 194
180 - if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
181 - if (!empty($workFlows) && count($workFlows) > 2) {
182 - return new WP_Error(
183 - 'free_limit',
184 - __('You are allowed to add maximum 2 workflows ', 'bit-form')
185 - );
186 - }
187 - }
188 -
189 195 if (isset($post->formStyle) && $post->formStyle) {
190 196 $sheetName = 'bitform-' . $post->form_id . '.css';
191 197 $this->saveStyleSheet($post->formStyle, $sheetName);
192 198 }
@@ -192,15 +198,20 @@
192 198 }
193 199
194 200 if (isset($post->layoutChanged) && $post->layoutChanged) {
195 201 $sheetName = 'bitform-layout-' . $post->form_id . '.css';
196 - $rowHeight = (int)$post->rowHeight;
202 + $rowHeight = (int) $post->rowHeight;
197 203 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
198 204 }
199 205
200 206 $fields = wp_unslash($post->fields);
207 + $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
208 + // $fields = $post->fields;
201 209 $layout = wp_unslash($post->layout);
210 + $nestedLayout = isset($post->nestedLayouts) ? wp_unslash($post->nestedLayouts) : (object) [];
211 + $formInfo = wp_unslash($post->formInfo);
202 212 $form_name = wp_unslash($post->form_name);
213 + $form_name = strlen($form_name) > 50 ? substr($form_name, 0, 50) : $form_name;
203 214 $formSettings = (object) wp_unslash($post->formSettings);
204 215 $atomic_class_map = isset($post->atomicClassMap) ? wp_unslash($post->atomicClassMap) : [];
205 216 $breakpointSize = wp_unslash($post->breakpointSize);
206 217 $style = $post->style;
@@ -212,9 +223,11 @@
212 223 $reports = !empty($post->reports) ? $post->reports : (object) [];
213 224 $builderSettings = (object) isset($post->builderSettings) ? wp_unslash($post->builderSettings) : [];
214 225
215 226 $mailTem = $formSettings->mailTem;
227 + $pdfTem = $formSettings->pdfTem;
216 228 $integrations = $formSettings->integrations;
229 + $formPermissions = $formSettings->formPermissions;
217 230
218 231 $user_details = static::$ipTool->getUserDetail();
219 232 if (empty($fields) || empty($layout)) {
220 233 return new WP_Error(
@@ -227,11 +240,17 @@
227 240 'empty_form',
228 241 __('Form Name Should Be Within 50 Characters', 'bit-form')
229 242 );
230 243 }
244 + // Guard: never persist orphan fields (in fields but in no layout) — they
245 + // render nothing yet their validation rules block submission. Covers old
246 + // clients and hand-edited imports (importAForm funnels through here).
247 + $this->pruneOrphanFields($fields, $nestedLayout, $layout, null, $post);
231 248 $form_content = [
232 - 'fields' => $fields,
233 - 'layout' => $layout,
249 + 'fields' => $fields,
250 + 'layout' => $layout,
251 + 'nestedLayout' => $nestedLayout,
252 + 'formInfo' => $formInfo,
234 253 ];
235 254
236 255 /* if (!empty($formSettings->submitBtn)) {
237 256 $form_content = array_merge($form_content, array('buttons' => $formSettings->submitBtn));
@@ -239,20 +258,26 @@
239 258 if (!empty($formSettings->theme)) {
240 259 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
241 260 }
242 261
262 + if (!empty($formSettings->formPermissions)) {
263 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
264 + }
265 +
243 266 if (!empty($additional)) {
244 267 $form_content = array_merge($form_content, ['additional' => $additional]);
245 268 }
246 269 if (!empty($workFlows)) {
247 - $workFlowsStr = is_string($workFlows) ? $workFlows : json_encode($workFlows);
270 + $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
248 271 $workFlowExist = [];
249 - if (\strpos($workFlowsStr, 'onload')) {
250 - $workFlowExist['onload'] = true;
272 + foreach ($workflows as $index => $workFlow) {
273 + if (in_array($workFlow->action_type, ['always', 'onload'])) {
274 + $workFlowExist['onload'] = true;
275 + }
276 + if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
277 + $workFlowExist['oninput'] = true;
278 + }
251 279 }
252 - if (\strpos($workFlowsStr, 'oninput')) {
253 - $workFlowExist['oninput'] = true;
254 - }
255 280 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
256 281 }
257 282 $form_content = \wp_json_encode($form_content);
258 283
@@ -286,10 +311,11 @@
286 311 return $save_status;
287 312 } elseif (!$save_status) {
288 313 return false;
289 314 } else {
290 - wp_mkdir_p(BITFORMS_UPLOAD_DIR . "/$save_status");
315 + FileHandler::createIndexFile(BITFORMS_UPLOAD_DIR . "/$save_status");
291 316 $formID = $save_status;
317 + do_action('bitform_admin_form_changed');
292 318 $integartionIDForWorkflow = [];
293 319 // Confiramtion Message [start]
294 320 if (!empty($formSettings->confirmation->type->successMsg)) {
295 321 $successMessages = $formSettings->confirmation->type->successMsg;
@@ -296,10 +322,13 @@
296 322 $successMessageHandler = new SuccessMessageHandler($formID, $user_details);
297 323 foreach ($successMessages as $messageKey => $messageDetail) {
298 324 $savedID = $successMessageHandler->saveMessage($messageDetail);
299 325 if ($savedID) {
300 - $msgIdx = empty($messageDetail->id) ? $messageKey : \json_encode(['id' => $messageDetail->id]);
326 + $msgIdx = empty($messageDetail->id) ? $messageKey : wp_json_encode(['id' => $messageDetail->id]);
301 327 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
328 + if (!empty($messageDetail->clRef)) {
329 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
330 + }
302 331 $messageDetail->id = $savedID;
303 332 $style = $this->updateSuccessMessageClassName($style, $messageKey, $savedID);
304 333 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
305 334 }
@@ -311,11 +340,13 @@
311 340 'themeColors' => $themeColors,
312 341 'builderSettings' => $builderSettings
313 342 ];
314 343 $update_status = static::$formModel->update(
315 - ['builder_helper_state' => \wp_json_encode($builder_helper_state),
316 - 'atomic_class_map' => $atomic_class_map, ],
317 344 [
345 + 'builder_helper_state' => \wp_json_encode($builder_helper_state),
346 + 'atomic_class_map' => $atomic_class_map,
347 + ],
348 + [
318 349 'id' => $formID,
319 350 ]
320 351 );
321 352 if (is_wp_error($update_status)) {
@@ -330,15 +361,55 @@
330 361 $emailTemplateHandler
331 362 = new EmailTemplateHandler($formID, $user_details);
332 363 foreach ($mailTem as $templateKey => $templateDetail) {
333 364 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
334 - if ($savedID) {
335 - $tempIdx = empty($templateDetail->id) ? $templateKey : \json_encode(['id' => $templateDetail->id]);
365 + if ($savedID && !is_wp_error($savedID)) {
366 + $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
336 367 $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
368 + if (!empty($templateDetail->clRef)) {
369 + $integartionIDForWorkflow['emailCLRef'][$templateDetail->clRef] = $savedID;
370 + }
371 + // return the new id (and drop the temp ref) so the frontend reconciles the template
372 + $templateDetail->id = $savedID;
373 + unset($templateDetail->clRef);
337 374 }
338 375 }
339 376 }
340 377 // Email Template [end] */
378 +
379 + // PDF Template [start]
380 + if (!empty($pdfTem) && class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
381 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
382 + $workFlowString = '';
383 + if (!empty($workFlows)) {
384 + $workFlowString = wp_json_encode($workFlows);
385 + }
386 + foreach ($pdfTem as $templateDetail) {
387 + $savedID = $pdfTemplateHandler->save($templateDetail);
388 +
389 + $pdfSetting = $templateDetail->setting;
390 +
391 + if (isset($pdfSetting->font->name) && !empty($pdfSetting->font->name)) {
392 + $this->pdfFontDownload($pdfSetting->font->name);
393 + }
394 + if (!empty($workFlowString)) {
395 + $workFlowString = str_replace('"pdfId":"{\"id\":\"' . $templateDetail->id . '\"}"', '"pdfId":"{\"id\":\"' . $savedID . '\"}"', $workFlowString);
396 + // Multi-PDF: remap ids inside "pdfIds":[...] segments only — email-template ids use
397 + // the same {\"id\":N} token shape, so a global replace would corrupt them.
398 + $workFlowString = preg_replace_callback(
399 + '/"pdfIds":\[[^\]]*\]/',
400 + function ($matches) use ($templateDetail, $savedID) {
401 + return str_replace('{\"id\":\"' . $templateDetail->id . '\"}', '{\"id\":\"' . $savedID . '\"}', $matches[0]);
402 + },
403 + $workFlowString
404 + );
405 + }
406 + }
407 + if (!empty($workFlowString) && !empty($workFlows)) {
408 + $workFlows = json_decode($workFlowString);
409 + }
410 + }
411 + // PDF Template [end] */
341 412 //Integration [start] */
342 413 $integrationHandler = new IntegrationHandler($formID, $user_details);
343 414 if (!empty($formSettings->confirmation->type)) {
344 415 $allIntegrations = $formSettings->confirmation->type;
@@ -343,8 +414,14 @@
343 414 if (!empty($formSettings->confirmation->type)) {
344 415 $allIntegrations = $formSettings->confirmation->type;
345 416 foreach ($allIntegrations as $integrationType => $integrationGroup) {
346 417 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
418 + $integrationStatus = isset($singleIntegrationDetail->status) ? (int) $singleIntegrationDetail->status : 1;
419 + // Inline-CL temp ref for a brand-new redirect (reconciled to the real id for workflow rows).
420 + $clRef = isset($singleIntegrationDetail->clRef) ? $singleIntegrationDetail->clRef : null;
421 + if (is_object($singleIntegrationDetail)) {
422 + unset($singleIntegrationDetail->status, $singleIntegrationDetail->clRef);
423 + }
347 424 if (empty($singleIntegrationDetail->details)) {
348 425 $integrationName = $singleIntegrationDetail->title;
349 426 unset($singleIntegrationDetail->title, $singleIntegrationDetail->id);
350 427
@@ -354,14 +431,25 @@
354 431 $integrationName = $singleIntegrationDetail->title;
355 432 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
356 433 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
357 434 }
358 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
359 - $integIdx = empty($singleIntegrationDetail->id) ? $savedID : \json_encode(['id' => $singleIntegrationDetail->id]);
435 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
436 + $integIdx = empty($singleIntegrationDetail->id) ? $savedID : wp_json_encode(['id' => $singleIntegrationDetail->id]);
360 437 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
438 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
439 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
440 + }
361 441 }
362 442 }
363 443 }
444 + if (isset($formSettings->formAbandonment)) {
445 + $formAbandonment = $formSettings->formAbandonment;
446 +
447 + $integrationName = 'formAbandonment';
448 + $integrationType = 'formAbandonment';
449 + $abandonmentIntegDetails = wp_json_encode($formAbandonment);
450 + $integrationHandler->saveIntegration($integrationName, $integrationType, $abandonmentIntegDetails, 'formAbandonment');
451 + }
364 452 if (!empty($integrations)) {
365 453 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
366 454 $integrationName = $singleIntegrationDetail->name;
367 455 unset($singleIntegrationDetail->name);
@@ -368,8 +456,11 @@
368 456 $integrationType = $singleIntegrationDetail->type;
369 457 unset($singleIntegrationDetail->type);
370 458 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
371 459 unset($singleIntegrationDetail->id);
460 + // Inline-CL temp ref for a brand-new integration (reconciled to the real id for workflow rows).
461 + $clRef = isset($singleIntegrationDetail->__bf_cl_ref) ? $singleIntegrationDetail->__bf_cl_ref : null;
462 + unset($singleIntegrationDetail->__bf_cl_ref);
372 463 if (empty($singleIntegrationDetail->details)) {
373 464 $integrationDetails = !is_string($singleIntegrationDetail) ?
374 465 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
375 466 } else {
@@ -376,10 +467,13 @@
376 467 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
377 468 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
378 469 }
379 470 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
380 - $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : \json_encode(['id' => $singleIntegrationDetailID]);
471 + $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : wp_json_encode(['id' => $singleIntegrationDetailID]);
381 472 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
473 + if (!empty($clRef) && !is_wp_error($savedID)) {
474 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
475 + }
382 476 }
383 477 }
384 478 //Integrations [end]
385 479 //wrokFlows [start]
@@ -399,10 +493,10 @@
399 493 // }
400 494 }
401 495 //wrokFlows [end]
402 496 $details = [
403 - 'report_name' => 'All Entries',
404 - 'hiddenColumns' => [],
497 + 'report_name' => __('All Entries', 'bit-form'),
498 + 'hiddenColumns' => ['__user_id', '__user_ip', '__referer', '__user_device', '__created_at', '__updated_at'],
405 499 'pageSize' => 10,
406 500 'sortBy' => [],
407 501 'filters' => [],
408 502 'globalFilter' => '',
@@ -430,24 +524,19 @@
430 524 $updated_data['form_content']['is_default'] = 1;
431 525 }
432 526 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
433 527
528 + // Form and dependent rows are persisted; multilingual providers register
529 + // the form's translatable strings here.
530 + do_action('bitform_form_saved', $save_status);
531 +
434 532 return $updated_data;
435 533 }
436 534 }
437 535
438 - public function updateForm($Request, $post) {
439 - // wp_send_json_success($post);
440 - if ($post->formStyle) {
441 - $sheetName = 'bitform-' . $post->id . '.css';
442 - $this->saveStyleSheet($post->formStyle, $sheetName);
443 - }
444 -
445 - if ($post->layoutChanged) {
446 - $sheetName = 'bitform-layout-' . $post->id . '.css';
447 - $rowHeight = (int)$post->rowHeight;
448 - $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
449 - }
536 + public function updateForm($Request, $post)
537 + {
538 + // return ['checked dta'=>$post];
450 539 $formId = $post->id;
451 540 // get the builder_helper_state from the form
452 541 $builder_helper_state = self::$formModel->get(['builder_helper_state'], ['id' => $formId]);
453 542 $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 : '{}';
@@ -470,14 +559,17 @@
470 559 if (property_exists($post, 'builderSettings')) {
471 560 $builder_helper_state->builderSettings = $post->builderSettings;
472 561 }
473 562 if (property_exists($post, 'atomicClassMap')) {
474 - $atomic_class_map = \wp_json_encode((object)$post->atomicClassMap);
563 + $atomic_class_map = \wp_json_encode((object) $post->atomicClassMap);
475 564 }
476 565
477 566 if (property_exists($post, 'fields') && null !== $post->fields && property_exists($post, 'layout') && $post->layout) {
478 567 $fields = wp_unslash($post->fields);
568 + $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
479 569 $layout = wp_unslash($post->layout);
570 + $nestedLayout = wp_unslash($post->nestedLayouts);
571 + $formInfo = wp_unslash($post->formInfo);
480 572 $formID = wp_unslash($post->id);
481 573 $form_name = wp_unslash($post->form_name);
482 574 $formSettings = wp_unslash($post->formSettings);
483 575 $workFlows = wp_unslash($post->workFlows);
@@ -485,27 +577,27 @@
485 577 $reports = wp_unslash($post->currentReport);
486 578 }
487 579
488 580 $mailTem = $formSettings->mailTem;
581 + $pdfTem = isset($formSettings->pdfTem) ? $formSettings->pdfTem : [];
489 582 $integrations = $formSettings->integrations;
490 583
491 584 $user_details = static::$ipTool->getUserDetail();
585 +
492 586 if (empty($fields) || empty($layout) || is_null($formID)) {
493 587 return new WP_Error('empty_form', 'Can not update empty form.');
494 588 }
495 589
496 - if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
497 - if (count($workFlows) > 2) {
498 - return new WP_Error(
499 - 'free_limit',
500 - __('You are allowed to add maximum 2 workflows ', 'bit-form')
501 - );
502 - }
503 - }
590 + // Guard: never persist orphan fields (see createNewForm). Fail closed.
591 + $this->pruneOrphanFields($fields, $nestedLayout, $layout, $formID, $post);
592 +
504 593 $form_content = [
505 - 'fields' => $fields,
506 - 'layout' => $layout,
594 + 'fields' => $fields,
595 + 'layout' => $layout,
596 + 'nestedLayout' => $nestedLayout,
597 + 'formInfo' => $formInfo,
507 598 ];
599 +
508 600 if (isset($post->report_id)) {
509 601 $form_content['report_id'] = wp_unslash($post->report_id);
510 602 }
511 603
@@ -514,8 +606,12 @@
514 606 } */
515 607 if (!empty($formSettings->theme)) {
516 608 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
517 609 }
610 +
611 + if (!empty($formSettings->formPermissions)) {
612 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
613 + }
518 614 if (!empty($additional)) {
519 615 $form_content = array_merge($form_content, ['additional' => $additional]);
520 616 }
521 617 $integartionIDForWorkflow = [];
@@ -523,8 +619,9 @@
523 619 $newData['integation'] = 0;
524 620 $newData['mailTemplate'] = 0;
525 621 $newData['workflow'] = 0;
526 622 $newData['reports'] = 0;
623 + $newData['pdfTemplate'] = 0;
527 624 // Confiramtion Message [start]
528 625 if (!empty($formSettings->confirmation->type->successMsg)) {
529 626 $successMessages = $formSettings->confirmation->type->successMsg;
530 627 $successMessageHandler
@@ -534,8 +631,11 @@
534 631 $savedID = $successMessageHandler->saveMessage($messageDetail);
535 632 if ($savedID) {
536 633 $newData['settingConfiramation'] = 1;
537 634 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
635 + if (!empty($messageDetail->clRef)) {
636 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
637 + }
538 638 $messageDetail->id = $savedID;
539 639 $builder_helper_state->style = $this->updateSuccessMessageClassName($builder_helper_state->style, $messageKey, $savedID);
540 640 if (isset($atomic_class_map)) {
541 641 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
@@ -547,9 +647,9 @@
547 647 }
548 648 unset($formSettings->confirmation->type->successMsg);
549 649 }
550 650 // return $formSettings;
551 - // Confiramtion Message [end] */
651 + // Confirmation Message [end] */
552 652 // Email Template [start]
553 653 if (!empty($mailTem)) {
554 654 $emailTemplateHandler
555 655 = new EmailTemplateHandler($formID, $user_details);
@@ -560,16 +660,44 @@
560 660 $newData['mailTemplate'] = 2;
561 661 } else {
562 662 $newData['mailTemplate'] = 1;
563 663 $integartionIDForWorkflow['mailTem'][$templateKey] = $savedID;
664 + if (!empty($templateDetail->clRef)) {
665 + $integartionIDForWorkflow['emailCLRef'][$templateDetail->clRef] = $savedID;
666 + }
667 + // return the new id (and drop the temp ref) so the frontend reconciles the template
668 + $templateDetail->id = $savedID;
669 + unset($templateDetail->clRef);
564 670 }
565 671 } else {
566 - $emailTemplateHandler->updateTemplate($templateDetail);
672 + $updated = $emailTemplateHandler->updateTemplate($templateDetail);
673 + if (is_wp_error($updated) && 'db_error' === $updated->get_error_code()) {
674 + $newData['mailTemplate'] = 2;
675 + } elseif (0 === $newData['mailTemplate']) {
676 + $newData['mailTemplate'] = 1;
677 + }
567 678 }
568 679 }
569 680 }
570 681 // return $formSettings;
571 682 // Email Template [end] */
683 + if (!empty($pdfTem) && class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
684 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
685 +
686 + foreach ($pdfTem as $templateKey => $templateDetail) {
687 + if (isset($templateDetail->setting->font->name)) {
688 + $this->pdfFontDownload($templateDetail->setting->font->name);
689 + }
690 +
691 + $savedID = $pdfTemplateHandler->saveOrUpdate($templateDetail);
692 + if (is_wp_error($savedID) && 'result_empty' === $savedID->get_error_code()) {
693 + $newData['pdfTemplate'] = 2;
694 + } else {
695 + $newData['pdfTemplate'] = 1;
696 + $integartionIDForWorkflow['pdfTem'][$templateKey] = $savedID;
697 + }
698 + }
699 + }
572 700 //Integration [start] */
573 701 $integrationHandler = new IntegrationHandler($formID, $user_details);
574 702 if (!empty($formSettings->confirmation->type)) {
575 703 $allIntegrations = $formSettings->confirmation->type;
@@ -574,8 +702,15 @@
574 702 if (!empty($formSettings->confirmation->type)) {
575 703 $allIntegrations = $formSettings->confirmation->type;
576 704 foreach ($allIntegrations as $integrationType => $integrationGroup) {
577 705 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
706 + // Redirect (and webhook) enable/disable toggle persists to the integration status column.
707 + $integrationStatus = isset($singleIntegrationDetail->status) ? (int) $singleIntegrationDetail->status : 1;
708 + // Inline-CL temp ref for a brand-new redirect (reconciled to the real id for workflow rows).
709 + $clRef = isset($singleIntegrationDetail->clRef) ? $singleIntegrationDetail->clRef : null;
710 + if (is_object($singleIntegrationDetail)) {
711 + unset($singleIntegrationDetail->status, $singleIntegrationDetail->clRef);
712 + }
578 713 if (empty($singleIntegrationDetail->details)) {
579 714 $integrationName = $singleIntegrationDetail->title;
580 715 unset($singleIntegrationDetail->title);
581 716 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
@@ -589,13 +724,16 @@
589 724 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
590 725 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
591 726 }
592 727 if (empty($singleIntegrationDetailID)) {
593 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
728 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
594 729 $newData['settingConfiramation'] = 1;
595 730 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
731 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
732 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
733 + }
596 734 } else {
597 - $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
735 + $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
598 736 }
599 737 }
600 738 }
601 739 }
@@ -606,8 +744,11 @@
606 744 $integrationType = $singleIntegrationDetail->type;
607 745 unset($singleIntegrationDetail->type);
608 746 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
609 747 unset($singleIntegrationDetail->id);
748 + // Inline-CL temp ref for a brand-new integration (reconciled to the real id for workflow rows).
749 + $clRef = isset($singleIntegrationDetail->__bf_cl_ref) ? $singleIntegrationDetail->__bf_cl_ref : null;
750 + unset($singleIntegrationDetail->__bf_cl_ref);
610 751 if (empty($singleIntegrationDetail->details)) {
611 752 $integrationDetails = !is_string($singleIntegrationDetail) ?
612 753 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
613 754 } else {
@@ -616,8 +757,11 @@
616 757 }
617 758 if (empty($singleIntegrationDetailID)) {
618 759 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
619 760 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
761 + if (!empty($clRef) && !is_wp_error($savedID)) {
762 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
763 + }
620 764 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
621 765 $newData['integation'] = 2;
622 766 } else {
623 767 $newData['integation'] = 1;
@@ -632,16 +776,18 @@
632 776 $workFlowExist = [];
633 777 if (!empty($workFlows)) {
634 778 $workFlowHandler = new WorkFlowHandler($formID, $user_details);
635 779 // foreach ($workFlows as $workFlowIndex => $workFlow) {
780 + $workflows = is_string($workFlows) ? json_decode($workFlows) : $workFlows;
636 781
637 - foreach ($workFlows as $index => $workFlow) {
638 - if ('onload' === $workFlow->action_type) {
782 + foreach ($workflows as $index => $workFlow) {
783 + if (in_array($workFlow->action_type, ['always', 'onload'])) {
639 784 $workFlowExist['onload'] = true;
640 785 }
641 - if ('oninput' === $workFlow->action_type) {
786 + if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
642 787 $workFlowExist['oninput'] = true;
643 788 }
789 + // $integartionIDForWorkflow = apply_filters('bitform_filter_integration_id', $workFlow, $formID, $index);
644 790 if (empty($workFlow->id)) {
645 791 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
646 792 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
647 793 $newData['workflow'] = 2;
@@ -648,9 +794,9 @@
648 794 } else {
649 795 $newData['workflow'] = 1;
650 796 }
651 797 } else {
652 - $newData = $workFlowHandler->updateworkFlow($workFlow->id, $workFlow, $integartionIDForWorkflow, $index, $newData);
798 + $newData = $workFlowHandler->updateworkFlow($workFlow->id, $workFlow, $integartionIDForWorkflow, $index, $newData);
653 799 }
654 800 }
655 801 }
656 802 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
@@ -655,8 +801,11 @@
655 801 }
656 802 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
657 803 //wrokFlows [end]
658 804 //reports [start] */
805 + // read unconditionally after the reports block; a save without currentReport
806 + // must not trip an undefined-variable warning
807 + $reportIsDefault = null;
659 808 if (!empty($reports)) {
660 809 $reportsModel = new ReportsModel();
661 810 $fieldNames = [];
662 811 foreach ($fields as $key => $field) {
@@ -668,15 +817,19 @@
668 817
669 818 $fieldNames['__user_id'] = __('User', 'bit-form');
670 819 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
671 820 // $fieldNames['__user_location'] = __('');
672 - $fieldNames['__referer'] = __('Refer URL');
673 - $fieldNames['__user_device'] = __('Device');
674 - $fieldNames['__created_at'] = __('Created Time');
675 - $fieldNames['__updated_at'] = __('Modified Time');
821 + $fieldNames['__referer'] = __('Refer URL', 'bit-form');
822 + $fieldNames['__user_device'] = __('Device', 'bit-form');
823 + $fieldNames['__created_at'] = __('Created Time', 'bit-form');
824 + $fieldNames['__updated_at'] = __('Modified Time', 'bit-form');
676 825
677 826 $reportIsDefault = null;
678 - if (isset($form_content['report_id'])) {
827 + // The client posts currentReport as {} whenever its report atom has not resolved yet. That
828 + // is an empty stdClass, which empty() above treats as non-empty, so we reach here with
829 + // nothing to save — and writing the validated result would replace the stored report's
830 + // column order, hidden columns, page size and name with an empty list. Leave the row alone.
831 + if (isset($form_content['report_id']) && ReportsModel::isValidatableReport($reports)) {
679 832 $validDateReport = $reportsModel->validateReportFields($reports, $fieldNames);
680 833 if (isset($reports->isDefault)) {
681 834 $reportIsDefault = $reports->isDefault;
682 835 } else {
@@ -701,8 +854,26 @@
701 854 );
702 855 }
703 856 }
704 857 //reports [end]
858 + //form abandonment [start]
859 + if (!empty($formSettings->formAbandonment)) {
860 + $formAbandonment = $formSettings->formAbandonment;
861 + // search for existing form abandonment in integration table
862 + $abandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
863 + if (!is_wp_error($abandonmentInteg) && !empty($abandonmentInteg)) {
864 + $abandonmentInteg = $abandonmentInteg[0];
865 + }
866 + if (isset($abandonmentInteg->id)) {
867 + $abandonmentIntegID = $abandonmentInteg->id;
868 + $abandonmentIntegDetails = wp_json_encode($formAbandonment);
869 + $integrationHandler->updateIntegration($abandonmentIntegID, 'formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
870 + } else {
871 + $abandonmentIntegDetails = wp_json_encode($formAbandonment);
872 + $integrationHandler->saveIntegration('formAbandonment', 'formAbandonment', $abandonmentIntegDetails, 'formAbandonment');
873 + }
874 + }
875 + //form abandonment [end]
705 876 $form_content = wp_json_encode($form_content);
706 877 $updateData = [
707 878 'form_name' => $form_name,
708 879 'form_content' => $form_content,
@@ -707,24 +878,24 @@
707 878 'form_name' => $form_name,
708 879 'form_content' => $form_content,
709 880 'user_id' => $user_details['id'],
710 881 'user_ip' => $user_details['ip'],
711 - 'builder_helper_state' => \wp_json_encode((object)$builder_helper_state),
882 + 'builder_helper_state' => \wp_json_encode((object) $builder_helper_state),
712 883 'generated_script_page_ids' => \wp_json_encode((object) []),
713 884 'user_device' => $user_details['device'],
714 - 'status' => 1,
715 885 'updated_at' => $user_details['time'],
716 886 ];
717 887 if (isset($atomic_class_map)) {
718 888 $updateData['atomic_class_map'] = $atomic_class_map;
719 889 }
720 - $formUpdateVersion = get_option('bit-form_form_update_version');
890 + $formUpdateVersion = get_option('bitform_form_update_version');
721 891 if (!$formUpdateVersion) {
722 892 $formUpdateVersion = 1;
723 893 } else {
724 894 $formUpdateVersion = (int) $formUpdateVersion + 1;
725 895 }
726 - update_option('bit-form_form_update_version', $formUpdateVersion);
896 + update_option('bitform_form_update_version', $formUpdateVersion);
897 + do_action('bitform_admin_form_changed');
727 898
728 899 $update_status = static::$formModel->update(
729 900 $updateData,
730 901 [
@@ -741,9 +912,10 @@
741 912 unset($post->deletedFldKey);
742 913 }
743 914
744 915 $updated_data = $this->getAForm(['id' => $formID], null);
745 - if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation']) {
916 +
917 + if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation'] && 0 === $newData['pdfTemplate']) {
746 918 unset($updated_data['formSettings']);
747 919 }
748 920 if (0 === $newData['integation']) {
749 921 unset($updated_data['integrations']);
@@ -755,8 +927,13 @@
755 927 unset($updated_data['mailTem']);
756 928 } elseif (2 === $newData['mailTemplate']) {
757 929 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
758 930 }
931 + if (0 === $newData['pdfTemplate']) {
932 + unset($updated_data['pdfTem']);
933 + } elseif (2 === $newData['pdfTemplate']) {
934 + $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
935 + }
759 936 if (0 === $newData['workflow']) {
760 937 unset($updated_data['workFlows']);
761 938 } elseif (2 === $newData['workflow']) {
762 939 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
@@ -763,9 +940,14 @@
763 940 }
764 941 if (2 === $newData['reports']) {
765 942 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
766 943 }
944 + // See createNewForm(). Fired before the partial-failure return: the rows
945 + // that did save are already persisted, so their strings still need registering.
946 + do_action('bitform_form_saved', $formId);
947 +
767 948 if (!empty($errorIN)) {
949 + /* translators: %s: comma-separated list of areas where error occurred */
768 950 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
769 951 return new WP_Error('Form update Error.', $updated_data);
770 952 }
771 953 if (null !== $reportIsDefault) {
@@ -770,113 +952,169 @@
770 952 }
771 953 if (null !== $reportIsDefault) {
772 954 $updated_data['form_content']['is_default'] = $reportIsDefault;
773 955 }
774 - $updated_data['message'] = __('Form updated successfully.', 'bitform');
956 + $updated_data['message'] = __('Form updated successfully.', 'bit-form');
957 +
775 958 return $updated_data;
776 959 }
777 960 }
778 961
779 - public function setEmptyMetaValue($fieldkeys) {
780 - $sqlEscaped = array_map(function ($fld) {
781 - return "'" . esc_sql($fld) . "'";
782 - }, $fieldkeys);
783 - $deletedFldKey = implode(',', $sqlEscaped);
962 + /**
963 + * Drop orphan fields (present in `fields` but in no layout) from form_content
964 + * before persisting, and remove now-childless nestedLayout entries.
965 + *
966 + * Entry meta is NEVER touched here — only explicit user deletes clear meta
967 + * (see setEmptyMetaValue). Fail closed: an unusable/partial layout, or a
968 + * client that flagged a failed pre-save layout sync (->skipOrphanPrune),
969 + * prunes nothing. Pruned keys are logged, never silently dropped.
970 + *
971 + * @param object|array $fields by ref; orphan keys removed
972 + * @param object|null $nestedLayout by ref; stale container entries removed
973 + * @param array|object $layout raw layout (single or multi-step)
974 + * @param int|string|null $formID for logging ('new' when absent)
975 + * @param object $post raw request; honors ->skipOrphanPrune
976 + */
977 + private function pruneOrphanFields(&$fields, &$nestedLayout, $layout, $formID, $post)
978 + {
979 + $formLabel = $formID ? $formID : 'new';
980 + if (isset($post->skipOrphanPrune) && $post->skipOrphanPrune) {
981 + Log::debug_log('Bit Form: orphan prune skipped (client reported failed layout sync). FormID=' . $formLabel);
982 + return;
983 + }
984 + $orphanFldKeys = FormManager::computeOrphanFieldKeys($layout, $nestedLayout, $fields);
985 + // null = unusable/partial layout (fail closed); [] = nothing to prune
986 + if (!is_array($orphanFldKeys) || empty($orphanFldKeys)) {
987 + return;
988 + }
989 + Log::debug_log('Bit Form: pruning orphan fields (absent from every layout). FormID=' . $formLabel . ' keys=' . implode(',', $orphanFldKeys));
990 + foreach ($orphanFldKeys as $orphanKey) {
991 + if (is_object($fields)) {
992 + unset($fields->{$orphanKey});
993 + } elseif (is_array($fields)) {
994 + unset($fields[$orphanKey]);
995 + }
996 + }
997 + // prune stale nestedLayout entries — containers that no longer exist in fields
998 + if (is_object($nestedLayout)) {
999 + foreach (array_keys(get_object_vars($nestedLayout)) as $nKey) {
1000 + $parentExists = is_object($fields) ? isset($fields->{$nKey}) : isset($fields[$nKey]);
1001 + if (!$parentExists) {
1002 + unset($nestedLayout->{$nKey});
1003 + }
1004 + }
1005 + }
1006 + }
1007 +
1008 + public function setEmptyMetaValue($fieldkeys)
1009 + {
784 1010 global $wpdb;
785 - $tablename = $wpdb->prefix . 'bitforms_form_entrymeta';
786 - $sql = $wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN ( " . $deletedFldKey . ')', '');
787 - $wpdb->query($sql);
1011 + // Placeholders and arguments built dynamically from $fieldkeys; count matches at runtime.
1012 + $placeholders = implode(',', array_fill(0, \count($fieldkeys), '%s'));
1013 + $wpdb->query($wpdb->prepare(
1014 + "UPDATE `{$wpdb->prefix}bitforms_form_entrymeta` SET meta_value = %s WHERE meta_key IN ($placeholders)",
1015 + '',
1016 + ...$fieldkeys
1017 + ));
788 1018 }
789 1019
790 - public function changeFormStatus($Request, $post) {
791 - if (isset($Request['status']) && $Request['id']) {
792 - $status = wp_unslash($Request['status']);
793 - $id = wp_unslash($Request['id']);
794 - } else {
795 - $status = wp_unslash($post->status);
796 - $id = wp_unslash($post->id);
797 - }
798 - $user_details = static::$ipTool->getUserDetail();
799 - // return $post->fields;
800 - $status = 'true' === $status || true === $status ? true : false;
801 - if (!is_bool($status) || is_null($id)) {
802 - // echo $status;
803 - return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
804 - }
805 - $update_status = static::$formModel->update(
806 - [
807 - 'user_id' => $user_details['id'],
808 - 'user_ip' => $user_details['ip'],
809 - 'user_device' => $user_details['device'],
810 - 'status' => $status ? 1 : 0,
811 - 'updated_at' => $user_details['time'],
812 - ],
813 - [
814 - 'id' => $id,
815 - ]
816 - );
817 - if (is_wp_error($update_status)) {
818 - return $update_status;
819 - } elseif (!$update_status) {
820 - return false;
821 - } else {
822 - return __('Form status changed successfully', 'bit-form');
823 - }
1020 + public function changeFormStatus($Request, $post)
1021 + {
1022 + if (isset($Request['status']) && $Request['id']) {
1023 + $status = sanitize_text_field(wp_unslash($Request['status']));
1024 + $id = absint(wp_unslash($Request['id']));
1025 + } else {
1026 + $status = wp_unslash($post->status);
1027 + $id = wp_unslash($post->id);
824 1028 }
1029 + $user_details = static::$ipTool->getUserDetail();
1030 + // return $post->fields;
1031 + $status = 'true' === $status || true === $status ? true : false;
1032 + if (!is_bool($status) || is_null($id)) {
1033 + // echo $status;
1034 + return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
1035 + }
1036 + $update_status = static::$formModel->update(
1037 + [
1038 + 'user_id' => $user_details['id'],
1039 + 'user_ip' => $user_details['ip'],
1040 + 'user_device' => $user_details['device'],
1041 + 'status' => $status ? 1 : 0,
1042 + 'updated_at' => $user_details['time'],
1043 + ],
1044 + [
1045 + 'id' => $id,
1046 + ]
1047 + );
1048 + if (is_wp_error($update_status)) {
1049 + return $update_status;
1050 + } elseif (!$update_status) {
1051 + return false;
1052 + } else {
1053 + return __('Form status changed successfully', 'bit-form');
1054 + }
1055 + }
825 1056
826 - public function changeBulkFormStatus($Request, $post) {
827 - if (isset($Request['status']) && $Request['formID']) {
828 - $status = wp_unslash($Request['status']);
829 - $formID = wp_unslash($Request['formID']);
830 - } else {
831 - $status = wp_unslash($post->status);
832 - $formID = wp_unslash($post->formID);
833 - }
834 - $user_details = static::$ipTool->getUserDetail();
835 - // return $post->fields;
836 - $status = 'true' === $status || true === $status ? true : false;
837 - if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
838 - // echo $status;
839 - return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
840 - }
841 - $update_status = static::$formModel->bulkUpdate(
842 - [
843 - 'user_id' => $user_details['id'],
844 - 'user_ip' => $user_details['ip'],
845 - 'user_device' => $user_details['device'],
846 - 'status' => $status ? 1 : 0,
847 - 'updated_at' => $user_details['time'],
848 - ],
849 - [
850 - 'id' => $formID,
851 - ]
852 - );
853 - if (is_wp_error($update_status)) {
854 - return $update_status;
855 - } elseif (!$update_status) {
856 - return false;
857 - } else {
858 - return __('Form status changed successfully', 'bit-form');
859 - }
1057 + public function changeBulkFormStatus($Request, $post)
1058 + {
1059 + if (isset($Request['status']) && $Request['formID']) {
1060 + $status = sanitize_text_field(wp_unslash($Request['status']));
1061 + $formID = array_map('absint', wp_unslash($Request['formID']));
1062 + } else {
1063 + $status = wp_unslash($post->status);
1064 + $formID = wp_unslash($post->formID);
860 1065 }
1066 + $user_details = static::$ipTool->getUserDetail();
1067 + // return $post->fields;
1068 + $status = 'true' === $status || true === $status ? true : false;
1069 + if (!is_bool($status) || is_null($formID) || !is_array($formID)) {
1070 + // echo $status;
1071 + return new WP_Error('status_change', __('Form status change failed.', 'bit-form'));
1072 + }
1073 + $update_status = static::$formModel->bulkUpdate(
1074 + [
1075 + 'user_id' => $user_details['id'],
1076 + 'user_ip' => $user_details['ip'],
1077 + 'user_device' => $user_details['device'],
1078 + 'status' => $status ? 1 : 0,
1079 + 'updated_at' => $user_details['time'],
1080 + ],
1081 + [
1082 + 'id' => $formID,
1083 + ]
1084 + );
1085 + if (is_wp_error($update_status)) {
1086 + return $update_status;
1087 + } elseif (!$update_status) {
1088 + return false;
1089 + } else {
1090 + return __('Form status changed successfully', 'bit-form');
1091 + }
1092 + }
861 1093
862 - public function getAllForm() {
863 - global $wpdb;
1094 + public function getAllForm()
1095 + {
1096 + global $wpdb;
864 1097
865 - $allForms = $wpdb->get_results("SELECT forms.id,forms.entries as fm_entries,forms.form_name,forms.status,forms.views,forms.created_at,COUNT(entries.id) as entries FROM `{$wpdb->prefix}bitforms_form` as forms LEFT JOIN `{$wpdb->prefix}bitforms_form_entries` as entries ON forms.id = entries.form_id GROUP BY forms.id");
1098 + // Direct query: table name interpolation only (no user input). $wpdb->prepare() cannot parameterize table names.
1099 + $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
1100 + FROM `{$wpdb->prefix}bitforms_form` as forms
1101 + LEFT JOIN `{$wpdb->prefix}bitforms_form_entries` as entries ON forms.id = entries.form_id
1102 + GROUP BY forms.id");
866 1103
867 - if (is_wp_error($allForms)) {
868 - return $allForms;
869 - } elseif (!$allForms) {
870 - return [];
871 - } else {
872 - return $allForms;
873 - }
1104 + if (is_wp_error($allForms)) {
1105 + return $allForms;
1106 + } elseif (!$allForms) {
1107 + return [];
1108 + } else {
1109 + return $allForms;
874 1110 }
1111 + }
875 1112
876 - public function getAForm($Request, $post) {
877 - if (isset($Request['id'])) {
878 - $formID = wp_unslash($Request['id']);
1113 + public function getAForm($Request, $post)
1114 + {
1115 + if (!empty($Request['id'])) {
1116 + $formID = absint(wp_unslash($Request['id']));
879 1117 } else {
880 1118 $formID = wp_unslash($post->id);
881 1119 }
882 1120 // return $post->fields;
@@ -891,11 +1129,13 @@
891 1129 $helper_states = $formManager->getFormHelperStates();
892 1130 if ($formManager->isExist()) {
893 1131 $form_content_arr = [
894 1132 'layout' => $form_content->layout,
1133 + 'nestedLayout' => !empty($form_content->nestedLayout) ? $form_content->nestedLayout : (object) [],
1134 + 'formInfo' => !empty($form_content->formInfo) ? $form_content->formInfo : (object) ['formName' => $formManager->getFormName()],
895 1135 'fields' => $form_content->fields,
896 1136 'form_name' => $formManager->getFormName(),
897 - 'workFlowExist' => $form_content->workFlowExist,
1137 + 'workFlowExist' => isset($form_content->workFlowExist) ? $form_content->workFlowExist : [],
898 1138 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
899 1139 ];
900 1140 $successMessageHandler
901 1141 = new SuccessMessageHandler($formID);
@@ -918,15 +1158,40 @@
918 1158 if (!is_wp_error($emailTemplates)) {
919 1159 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
920 1160 $mailTem[] =
921 1161 [
922 - 'id' => $emailTemplatevalue->id,
923 - 'title' => $emailTemplatevalue->title,
924 - 'sub' => $emailTemplatevalue->sub,
925 - 'body' => $emailTemplatevalue->body,
1162 + 'id' => $emailTemplatevalue->id,
1163 + 'title' => $emailTemplatevalue->title,
1164 + 'sub' => $emailTemplatevalue->sub,
1165 + 'body' => $emailTemplatevalue->body,
1166 + 'status' => isset($emailTemplatevalue->status) ? (int) $emailTemplatevalue->status : 1,
1167 + 'config' => EmailTemplateHandler::normalizeConfig($emailTemplatevalue->config ?? null),
926 1168 ];
927 1169 }
928 1170 }
1171 + // get all pdf template
1172 + if (class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
1173 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
1174 + $pdfTemplates = $pdfTemplateHandler->getAll();
1175 +
1176 + if (!is_wp_error($pdfTemplates)) {
1177 + foreach ($pdfTemplates as $value) {
1178 + $pdfTem[] =
1179 + [
1180 + 'id' => $value->id,
1181 + 'title' => $value->title,
1182 + 'setting' => json_decode($value->setting),
1183 + 'pdf_config' => !empty($value->pdf_config) ? json_decode($value->pdf_config) : (object) [
1184 + 'status' => 1,
1185 + 'header' => '',
1186 + 'footer' => '',
1187 + ],
1188 + 'body' => $value->body,
1189 + ];
1190 + }
1191 + }
1192 + }
1193 +
929 1194 $integrationHandler = new IntegrationHandler($formID);
930 1195 $formIntegrations = $integrationHandler->getAllIntegration('form');
931 1196 if (!is_wp_error($formIntegrations)) {
932 1197 foreach ($formIntegrations as $integrationkey => $integrationValue) {
@@ -931,10 +1196,11 @@
931 1196 if (!is_wp_error($formIntegrations)) {
932 1197 foreach ($formIntegrations as $integrationkey => $integrationValue) {
933 1198 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
934 1199 $integrationData = [
935 - 'id' => $integrationValue->id,
936 - 'title' => $integrationValue->integration_name,
1200 + 'id' => $integrationValue->id,
1201 + 'title' => $integrationValue->integration_name,
1202 + 'status' => isset($integrationValue->status) ? (int) $integrationValue->status : 1,
937 1203 ];
938 1204 if (!empty($integrationValue->integration_details)) {
939 1205 $integration_details = (array) json_decode($integrationValue->integration_details);
940 1206 $integrationData = array_merge($integration_details, $integrationData);
@@ -954,17 +1220,32 @@
954 1220 ];
955 1221 $integrations[] = array_merge(
956 1222 $integrationData,
957 1223 is_string($integrationValue->integration_details) ?
958 - (array) json_decode($integrationValue->integration_details) :
959 - $integrationValue->integration_details
1224 + (array) json_decode($integrationValue->integration_details) :
1225 + $integrationValue->integration_details
960 1226 );
961 1227 }
962 1228 }
963 1229 }
1230 +
1231 + // get form abandonment integration if exist
1232 + $formAbandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
1233 + if (!is_wp_error($formAbandonmentInteg) && !empty($formAbandonmentInteg)) {
1234 + $formAbandonmentInteg = $formAbandonmentInteg[0];
1235 + if (!empty($formAbandonmentInteg->integration_details)) {
1236 + $formAbandonment = json_decode($formAbandonmentInteg->integration_details);
1237 + } else {
1238 + $formAbandonment = (object) [];
1239 + }
1240 + } else {
1241 + $formAbandonment = (object) [];
1242 + }
1243 +
964 1244 $settingsContent = [
965 - 'formName' => $formManager->getFormName(),
966 - 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1245 + 'formName' => $formManager->getFormName(),
1246 + 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1247 + 'formPermissions' => isset($form_content->formPermissions) ? $form_content->formPermissions : (object) [],
967 1248 // 'submitBtn' => $form_content->buttons,
968 1249 ];
969 1250
970 1251 if (!empty($allConfirmation)) {
@@ -991,8 +1272,9 @@
991 1272 'integrations' => []
992 1273 ]
993 1274 );
994 1275 }
1276 +
995 1277 if (!empty($mailTem)) {
996 1278 $settingsContent = array_merge(
997 1279 $settingsContent,
998 1280 [
@@ -1006,8 +1288,40 @@
1006 1288 'mailTem' => []
1007 1289 ]
1008 1290 );
1009 1291 }
1292 +
1293 + if (!empty($pdfTem)) {
1294 + $settingsContent = array_merge(
1295 + $settingsContent,
1296 + [
1297 + 'pdfTem' => $pdfTem,
1298 + ]
1299 + );
1300 + } else {
1301 + $settingsContent = array_merge(
1302 + $settingsContent,
1303 + [
1304 + 'pdfTem' => [],
1305 + ]
1306 + );
1307 + }
1308 +
1309 + if (!empty($formAbandonment)) {
1310 + $settingsContent = array_merge(
1311 + $settingsContent,
1312 + [
1313 + 'formAbandonment' => $formAbandonment,
1314 + ]
1315 + );
1316 + } else {
1317 + $settingsContent = array_merge(
1318 + $settingsContent,
1319 + [
1320 + 'formAbandonment' => (object) [],
1321 + ]
1322 + );
1323 + }
1010 1324 $formSettings = [
1011 1325 'formSettings' => $settingsContent,
1012 1326 ];
1013 1327 $data = [
@@ -1018,12 +1332,14 @@
1018 1332 'style' => $helper_states->style,
1019 1333 'themeVars' => $helper_states->themeVars,
1020 1334 'themeColors' => $helper_states->themeColors,
1021 1335 'builderSettings' => $helper_states->builderSettings,
1336 + 'customCode' => FrontEndScriptGenerator::getCustomCodes($formID),
1022 1337 'additional' => empty($form_content->additional) ? [
1023 1338 'enabled' => [
1024 1339 'blocked_ip' => false,
1025 1340 'restrict_form' => false,
1341 + 'onePerIp' => false,
1026 1342 ],
1027 1343 'settings' => [
1028 1344 'restrict_form' => [
1029 1345 'day' => [],
@@ -1038,9 +1354,8 @@
1038 1354 ],
1039 1355 'entry_limit' => null,
1040 1356 'blocked_ip' => [],
1041 1357 ],
1042 - 'onePerIp' => false,
1043 1358 ] : $form_content->additional,
1044 1359 'created_at' => $formManager->getFormMetaData()['created_at'],
1045 1360 'views' => $formManager->getFormMetaData()['views'],
1046 1361 'entries' => $formManager->getFormMetaData()['entries'],
@@ -1081,9 +1396,9 @@
1081 1396 } else {
1082 1397 $returnedReportData[$reportKey]->details = [];
1083 1398 }
1084 1399 if ('1' === (string) $reportData->isDefault) {
1085 - $returnedReportData[$reportKey]->details->report_name = 'All Entries';
1400 + $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1086 1401 }
1087 1402 }
1088 1403 $reports = ['reports' => $returnedReportData];
1089 1404 $data = array_merge($data, $reports);
@@ -1095,31 +1410,262 @@
1095 1410 return $data;
1096 1411 }
1097 1412 }
1098 1413
1099 - public function deleteAForm($Request, $post) {
1100 - if (isset($Request['id'])) {
1101 - $formID = wp_unslash($Request['id']);
1414 + public function getAFormV1($Request, $post)
1415 + {
1416 + if (!empty($Request['id'])) {
1417 + $formID = absint(wp_unslash($Request['id']));
1102 1418 } else {
1103 1419 $formID = wp_unslash($post->id);
1104 1420 }
1421 + // return $post->fields;
1105 1422 if (is_null($formID)) {
1106 1423 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1107 1424 }
1425 + $formManager = new AdminFormManager($formID);
1426 + if (!$formManager->isExist()) {
1427 + return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
1428 + }
1429 + $form_content = $formManager->getFormContent();
1430 + if ($formManager->isExist()) {
1431 + $form_content_arr = [
1432 + 'layout' => $form_content->layout,
1433 + 'fields' => $form_content->fields,
1434 + 'form_name' => $formManager->getFormName(),
1435 + 'workFlowExist' => isset($form_content->workFlowExist) ? $form_content->workFlowExist : [],
1436 + 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
1437 + ];
1438 + $successMessageHandler
1439 + = new SuccessMessageHandler($formID);
1440 + $successMessages = $successMessageHandler->getAllMessage();
1441 + if (!is_wp_error($successMessages)) {
1442 + foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
1443 + $allConfirmation['type']['successMsg'][$sucessMessagekey] =
1444 + [
1445 + 'id' => $sucessMessagevalue->id,
1446 + 'title' => $sucessMessagevalue->message_title,
1447 + 'msg' => $sucessMessagevalue->message_content,
1448 + 'config' => !empty($sucessMessagevalue->message_config) ? json_decode($sucessMessagevalue->message_config) : (object) [],
1449 + ];
1450 + }
1451 + }
1452 + $emailTemplateHandler
1453 + = new EmailTemplateHandler($formID);
1454 + $emailTemplates = $emailTemplateHandler->getAllTemplate();
1455 + if (!is_wp_error($emailTemplates)) {
1456 + foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1457 + $mailTem[] =
1458 + [
1459 + 'id' => $emailTemplatevalue->id,
1460 + 'title' => $emailTemplatevalue->title,
1461 + 'sub' => $emailTemplatevalue->sub,
1462 + 'body' => $emailTemplatevalue->body,
1463 + 'status' => isset($emailTemplatevalue->status) ? (int) $emailTemplatevalue->status : 1,
1464 + 'config' => EmailTemplateHandler::normalizeConfig($emailTemplatevalue->config ?? null),
1465 + ];
1466 + }
1467 + }
1468 + $integrationHandler = new IntegrationHandler($formID);
1469 + $formIntegrations = $integrationHandler->getAllIntegration('form');
1470 + if (!is_wp_error($formIntegrations)) {
1471 + foreach ($formIntegrations as $integrationkey => $integrationValue) {
1472 + if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1473 + $integrationData = [
1474 + 'id' => $integrationValue->id,
1475 + 'title' => $integrationValue->integration_name,
1476 + 'status' => isset($integrationValue->status) ? (int) $integrationValue->status : 1,
1477 + ];
1478 + if (!empty($integrationValue->integration_details)) {
1479 + // var_dump(json_decode($integrationValue->integration_details));
1480 + $integration_details = (array) json_decode($integrationValue->integration_details);
1481 + $integrationData = array_merge($integration_details, $integrationData);
1482 + } else {
1483 + $integration_details = [
1484 + 'url' => '',
1485 + ];
1486 + $integrationData = array_merge($integrationData, $integration_details);
1487 + }
1488 + $allConfirmation['type'][$integrationValue->integration_type][]
1489 + = $integrationData;
1490 + } else {
1491 + $integrationData = [
1492 + 'id' => $integrationValue->id,
1493 + 'name' => $integrationValue->integration_name,
1494 + 'type' => $integrationValue->integration_type,
1495 + ];
1496 + $integrations[] = array_merge(
1497 + $integrationData,
1498 + is_string($integrationValue->integration_details) ?
1499 + (array) json_decode($integrationValue->integration_details) :
1500 + $integrationValue->integration_details
1501 + );
1502 + }
1503 + }
1504 + }
1505 + $settingsContent = [
1506 + 'formName' => $formManager->getFormName(),
1507 + 'theme' => $form_content->theme,
1508 + // 'submitBtn' => $form_content->buttons,
1509 + ];
1510 +
1511 + if (!empty($allConfirmation)) {
1512 + $confirmation = [
1513 + 'confirmation' => $allConfirmation,
1514 + ];
1515 + } else {
1516 + $confirmation = [
1517 + 'confirmation' => ['type' => []],
1518 + ];
1519 + }
1520 + $settingsContent = array_merge($settingsContent, $confirmation);
1521 + if (!empty($integrations)) {
1522 + $settingsContent = array_merge(
1523 + $settingsContent,
1524 + [
1525 + 'integrations' => $integrations,
1526 + ]
1527 + );
1528 + } else {
1529 + $settingsContent = array_merge(
1530 + $settingsContent,
1531 + [
1532 + 'integrations' => []
1533 + ]
1534 + );
1535 + }
1536 + if (!empty($mailTem)) {
1537 + $settingsContent = array_merge(
1538 + $settingsContent,
1539 + [
1540 + 'mailTem' => $mailTem,
1541 + ]
1542 + );
1543 + } else {
1544 + $settingsContent = array_merge(
1545 + $settingsContent,
1546 + [
1547 + 'mailTem' => []
1548 + ]
1549 + );
1550 + }
1551 + $formSettings = [
1552 + 'formSettings' => $settingsContent,
1553 + ];
1554 + $data = [
1555 + 'id' => $formID,
1556 + 'form_name' => $formManager->getFormName(),
1557 + 'form_content' => $form_content_arr,
1558 + 'additional' => empty($form_content->additional) ? [
1559 + 'enabled' => [
1560 + 'blocked_ip' => false,
1561 + 'restrict_form' => false,
1562 + 'onePerIp' => false,
1563 + ],
1564 + 'settings' => [
1565 + 'restrict_form' => [
1566 + 'day' => [],
1567 + 'date' => [
1568 + 'from' => null,
1569 + 'to' => null,
1570 + ],
1571 + 'time' => [
1572 + 'from' => null,
1573 + 'to' => null,
1574 + ],
1575 + ],
1576 + 'entry_limit' => null,
1577 + 'blocked_ip' => [],
1578 + ],
1579 + ] : $form_content->additional,
1580 + 'created_at' => $formManager->getFormMetaData()['created_at'],
1581 + 'views' => $formManager->getFormMetaData()['views'],
1582 + 'entries' => $formManager->getFormMetaData()['entries'],
1583 + 'status' => $formManager->getFormMetaData()['status'],
1584 + ];
1585 + $data = array_merge($data, $formSettings);
1586 + $workFlowHandler = new WorkFlowHandler($formID);
1587 + $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlowV1()];
1588 + $data = array_merge($data, $workFlows);
1589 + $reportsModel = new ReportsModel();
1590 + $returnedReportData = $reportsModel->get(
1591 + [
1592 + 'id',
1593 + 'details',
1594 + 'isDefault',
1595 + 'type',
1596 + ],
1597 + [
1598 + 'category' => 'form',
1599 + 'context' => $formID,
1600 + ]
1601 + );
1602 +
1603 + if (!is_wp_error($returnedReportData)) {
1604 + $fieldNames = [];
1605 + foreach ($formManager->getFieldLabel() as $key => $field) {
1606 + $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
1607 + }
1608 + if ($formManager->isGCLIDEnabled()) {
1609 + $fieldNames['GCLID'] = 'GCLID';
1610 + }
1611 + foreach ($returnedReportData as $reportKey => $reportData) {
1612 + $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1613 + if (!empty($reportDetails) && is_string($reportDetails)) {
1614 + $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1615 + } elseif (!empty($reportDetails)) {
1616 + $returnedReportData[$reportKey]->details = $reportDetails;
1617 + } else {
1618 + $returnedReportData[$reportKey]->details = [];
1619 + }
1620 + if ('1' === (string) $reportData->isDefault) {
1621 + $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1622 + }
1623 + }
1624 + $reports = ['reports' => $returnedReportData];
1625 + $data = array_merge($data, $reports);
1626 + }
1627 +
1628 + $formFields = $formManager->getFieldLabel();
1629 + $data = array_merge($data, ['Labels' => $formFields]);
1630 +
1631 + return $data;
1632 + }
1633 + }
1634 +
1635 + public function deleteAForm($Request, $post)
1636 + {
1637 + if (!empty($Request['id'])) {
1638 + $formID = absint(wp_unslash($Request['id']));
1639 + } else {
1640 + $formID = wp_unslash($post->id);
1641 + }
1642 + if (is_null($formID)) {
1643 + return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1644 + }
1645 +
1646 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
1647 + return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
1648 + }
1649 +
1108 1650 $delete_status = static::$formModel->delete(
1109 1651 [
1110 1652 'id' => $formID,
1111 1653 ]
1112 1654 );
1655 + do_action('bitform_admin_form_changed');
1113 1656
1114 - $successMessageModel
1115 - = new SuccessMessageModel();
1657 + $successMessageModel = new SuccessMessageModel();
1116 1658 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1117 1659
1118 - $emailTemplateModel
1119 - = new EmailTemplateModel();
1660 + $emailTemplateModel = new EmailTemplateModel();
1120 1661 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1121 1662
1663 + if (class_exists('\BitCode\BitFormPro\Core\Database\PdfTemplateModel')) {
1664 + $pdfTemplateModel = new \BitCode\BitFormPro\Core\Database\PdfTemplateModel();
1665 + $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
1666 + }
1667 +
1122 1668 $integrationModel = new IntegrationModel();
1123 1669 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1124 1670
1125 1671 $workFlowModel = new WorkFlowModel();
@@ -1131,22 +1677,11 @@
1131 1677 $formEntryModel = new FormEntryModel();
1132 1678 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1133 1679 $entries = [];
1134 1680
1135 - if (!is_wp_error($returnedEntries)) {
1136 - foreach ($returnedEntries as $entryKey => $entryInfo) {
1137 - $entries[] = $entryInfo->id;
1138 - }
1139 - global $wpdb;
1140 - $prefix = $wpdb->prefix;
1141 - if (count($entries) > 0) {
1142 - $deleteEntriesStatus = $formEntryModel->bulkDelete(
1143 - [
1144 - "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1145 - "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1146 - ]
1147 - );
1148 - }
1681 + // checked namespace exist
1682 + if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1683 + \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByFormId($formID);
1149 1684 }
1150 1685
1151 1686 $fileHandler = new FileHandler();
1152 1687 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
@@ -1154,35 +1689,54 @@
1154 1689 }
1155 1690 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1156 1691 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1157 1692 }
1158 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1159 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1160 - }
1161 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1162 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1163 - }
1693 + $formStylePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles';
1694 +
1695 + $formCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css';
1696 + FileHandler::deleteIsFileExists($formCssPath);
1697 +
1698 + $layoutCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css';
1699 + FileHandler::deleteIsFileExists($layoutCssPath);
1700 +
1701 + $customCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css';
1702 + FileHandler::deleteIsFileExists($customCssPath);
1703 +
1704 + $customJSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js';
1705 + FileHandler::deleteIsFileExists($customJSPath);
1706 +
1707 + $conversationCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css';
1708 + FileHandler::deleteIsFileExists($conversationCssPath);
1709 +
1164 1710 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1165 1711 }
1166 1712
1167 - public function deleteBlukForm($Request, $post) {
1168 - if (isset($Request['formID'])) {
1169 - $formID = wp_unslash($Request['formID']);
1713 + public function deleteBlukForm($Request, $post)
1714 + {
1715 + if (!empty($Request['formID'])) {
1716 + $formID = array_map('absint', wp_unslash($Request['formID']));
1170 1717 } else {
1171 1718 $formID = wp_unslash($post->formID);
1172 1719 }
1720 +
1173 1721 if (is_null($formID) || !is_array($formID)) {
1174 1722 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1175 1723 }
1724 +
1725 + if (!Helpers::checkIsIntArr($formID)) {
1726 + return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
1727 + }
1728 +
1176 1729 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1177 1730 foreach ($formID as $id) {
1178 - unlink($cssPath . 'bitform-' . $id . '.css');
1179 - if (file_exists($cssPath . 'bitform-layout-' . $id . '.css')) {
1180 - unlink($cssPath . 'bitform-layout-' . $id . '.css');
1181 - }
1182 - if (file_exists($cssPath . 'bitform-' . $id . '-formid' . '.css')) {
1183 - unlink($cssPath . 'bitform-' . $id . '-formid' . '.css');
1184 - }
1731 + $formCssPath = $cssPath . 'bitform-' . $id . '.css';
1732 + FileHandler::deleteIsFileExists($formCssPath);
1733 +
1734 + $layoutPath = $cssPath . 'bitform-layout-' . $id . '.css';
1735 + FileHandler::deleteIsFileExists($layoutPath);
1736 +
1737 + $bitformCustomPath = $cssPath . 'bitform-' . $id . '-formid' . '.css';
1738 + FileHandler::deleteIsFileExists($bitformCustomPath);
1185 1739 }
1186 1740 $delete_status = static::$formModel->bulkDelete(
1187 1741 [
1188 1742 'id' => $formID,
@@ -1187,16 +1741,26 @@
1187 1741 [
1188 1742 'id' => $formID,
1189 1743 ]
1190 1744 );
1745 + do_action('bitform_admin_form_changed');
1746 +
1747 + if (is_wp_error($delete_status)) {
1748 + wp_send_json_error($delete_status->get_error_message(), 400);
1749 + }
1750 +
1191 1751 $successMessageModel
1192 1752 = new SuccessMessageModel();
1193 1753 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1194 1754
1195 - $emailTemplateModel
1196 - = new EmailTemplateModel();
1755 + $emailTemplateModel = new EmailTemplateModel();
1197 1756 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1198 1757
1758 + if (class_exists('\BitCode\BitFormPro\Core\Database\PdfTemplateModel')) {
1759 + $pdfTemplateModel = new \BitCode\BitFormPro\Core\Database\PdfTemplateModel();
1760 + $deletePdfTemplateStatus = $pdfTemplateModel->bulkDelete(['form_id' => $formID]);
1761 + }
1762 +
1199 1763 $integrationModel = new IntegrationModel();
1200 1764 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1201 1765
1202 1766 $workFlowModel = new WorkFlowModel();
@@ -1206,11 +1770,18 @@
1206 1770 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1207 1771
1208 1772 $formEntryModel = new FormEntryModel();
1209 1773 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1774 +
1775 + if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1776 + \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByBulkFormId($formID);
1777 + }
1778 +
1210 1779 $entries = [];
1211 1780 foreach ($returnedEntries as $entryKey => $entryInfo) {
1212 - $entries[] = $entryInfo->id;
1781 + if (!empty($entryInfo->id)) {
1782 + $entries[] = $entryInfo->id;
1783 + }
1213 1784 }
1214 1785 global $wpdb;
1215 1786 $prefix = $wpdb->prefix;
1216 1787 if (count($entries) > 0) {
@@ -1221,22 +1792,26 @@
1221 1792 ]
1222 1793 );
1223 1794 }
1224 1795
1796 + // delete entry log and details; table name interpolation only — $wpdb->prepare() parameterizes the form_id value.
1797 + $wpdb->query($wpdb->prepare(
1798 + "DELETE em, e FROM `{$prefix}bitforms_form_log_details` AS em JOIN `{$prefix}bitforms_form_entry_log` AS e ON em.log_id = e.id WHERE e.form_id = %d",
1799 + $formID
1800 + ));
1801 +
1225 1802 $fileHandler = new FileHandler();
1226 1803 foreach ($formID as $fId) {
1227 1804 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1228 1805 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1229 1806 }
1230 -
1231 - // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1232 - // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1233 1807 }
1234 1808
1235 1809 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1236 1810 }
1237 1811
1238 - public function genarateNewLayoutNField($layout, $fields, $oldId, $newId) {
1812 + public function genarateNewLayoutNField($layout, $fields, $oldId, $newId)
1813 + {
1239 1814 $newField = (object) [];
1240 1815 foreach ($layout->lg as $ind => $itm) {
1241 1816 $fld_tmp = $fields->{$layout->lg[$ind]->i};
1242 1817 $layout->lg[$ind]->i = str_replace("bf$oldId-", "bf$newId-", $layout->lg[$ind]->i);
@@ -1246,9 +1821,10 @@
1246 1821 }
1247 1822 return ['layout' => $layout, 'fields' => $newField];
1248 1823 }
1249 1824
1250 - public function duplicateAForm($Request, $post) {
1825 + public function duplicateAForm($Request, $post)
1826 + {
1251 1827 $oldFormId = intval($post->id);
1252 1828 $newFormId = intval($post->newFormId);
1253 1829 if ($oldFormId < 1) {
1254 1830 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
@@ -1270,21 +1846,15 @@
1270 1846 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1271 1847 // duplicate stylesheet
1272 1848 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1273 1849 // layout style copy
1274 - $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1275 - $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1850 + $styleStr = FileHandler::readFile($style_dir . 'bitform-layout-' . $oldFormId . '.css');
1276 1851 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1277 - $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1278 - fwrite($createStyleFile, $newStyle);
1279 - fclose($createStyleFile);
1852 + FileHandler::writeFile($style_dir . "bitform-layout-$newFormId.css", $newStyle);
1280 1853 // style copy
1281 - $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1282 - $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1854 + $styleStr = FileHandler::readFile($style_dir . 'bitform-' . $oldFormId . '.css');
1283 1855 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1284 - $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1285 - fwrite($createStyleFile, $newStyle);
1286 - fclose($createStyleFile);
1856 + FileHandler::writeFile($style_dir . "bitform-$newFormId.css", $newStyle);
1287 1857 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1288 1858 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1289 1859 return $duplicatedForm;
1290 1860 }
@@ -1290,19 +1860,22 @@
1290 1860 }
1291 1861 return $duplicateResponse;
1292 1862 }
1293 1863
1294 - public function importAForm($post) {
1864 + public function importAForm($post)
1865 + {
1295 1866 $oldFormId = !empty($post->formDetail->form_id) ? $post->formDetail->form_id : null;
1296 1867 $newFormId = intval($post->newFormId);
1297 1868 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1298 1869 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1299 1870 }
1300 - $importtedForm = (array)$post->formDetail;
1871 + $importtedForm = (array) $post->formDetail;
1301 1872 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1302 1873 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1303 - unset($importtedForm['fields'], $importtedForm['layout']);
1304 - $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1874 + $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayouts'];
1875 + $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1876 + unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1877 + $formData = FormDuplicateHelper::createReplica((array) $importtedForm, $oldFormId, $newFormId);
1305 1878
1306 1879 if (!empty($importtedForm['rowHeight'])) {
1307 1880 $formData->rowHeight = $importtedForm['rowHeight'];
1308 1881 }
@@ -1312,10 +1885,29 @@
1312 1885 $formData->layoutChanged = '-';
1313 1886 }
1314 1887 $importResponse = $this->createNewForm(null, $formData);
1315 1888
1889 + $customCode = [];
1890 + // add custom js
1891 + if (!empty($formData->customCode->customJs)) {
1892 + $customJsPath = 'form-scripts';
1893 + $fileName = 'bitform-custom-' . $newFormId . '.js';
1894 + $customCode['JavaScript'] = $formData->customCode->customJs;
1895 + Helpers::saveFile($customJsPath, $fileName, $formData->customCode->customJs, 'w');
1896 + }
1897 + // add custom css
1898 + if (!empty($formData->customCode->customCss)) {
1899 + $customCssPath = 'form-styles';
1900 + $fileName = 'bitform-custom-' . $newFormId . '.css';
1901 + $customCode['CSS'] = $formData->customCode->customCss;
1902 + Helpers::saveFile($customCssPath, $fileName, $formData->customCode->customCss, 'w');
1903 + }
1904 + if (!is_wp_error($importResponse)) {
1905 + $importResponse['customCode'] = $customCode;
1906 + }
1316 1907 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1317 1908 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1909 + $responseData['customCode'] = $customCode;
1318 1910 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1319 1911 return $responseData;
1320 1912 }
1321 1913 return $importResponse;
@@ -1342,9 +1934,9 @@
1342 1934 // $formData->formStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1343 1935 // $formData->layoutChanged = '-';
1344 1936 // $formData->rowHeight = FormDuplicateHelper::calcRowHeight($styleStr, $oldFormId);
1345 1937
1346 - // $formJson = json_encode($formData);
1938 + // $formJson = wp_json_encode($formData);
1347 1939 // header('Content-Type: application/force-download');
1348 1940 // header('Content-Type: application/octet-stream');
1349 1941 // header('Content-Type: application/download');
1350 1942 // header('Content-Disposition: attachment; filename="bitform_export_' . $oldFormId . '.json"');
@@ -1358,9 +1950,10 @@
1358 1950 // echo $formJson;
1359 1951 // die();
1360 1952 // }
1361 1953
1362 - public function exportAForm($Request, $post) {
1954 + public function exportAForm($Request, $post)
1955 + {
1363 1956 $oldFormId = intval($post->id);
1364 1957 if ($oldFormId < 1) {
1365 1958 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1366 1959 }
@@ -1369,9 +1962,9 @@
1369 1962 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1370 1963 }
1371 1964
1372 1965 $newFormId = $oldFormId;
1373 - $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1966 + $duplicatedForm = $this->getAForm($Request, (object) ['id' => $oldFormId]);
1374 1967 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1375 1968 // for custom css
1376 1969 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1377 1970 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
@@ -1389,11 +1982,12 @@
1389 1982 }
1390 1983 return $formData;
1391 1984 }
1392 1985
1393 - public function getFormEntryLabelAndCount($Request, $post) {
1394 - if (isset($Request['id'])) {
1395 - $id = wp_unslash($Request['id']);
1986 + public function getFormEntryLabelAndCount($Request, $post)
1987 + {
1988 + if (!empty($Request['id'])) {
1989 + $id = absint(wp_unslash($Request['id']));
1396 1990 } else {
1397 1991 $id = wp_unslash($post->id);
1398 1992 }
1399 1993 if (is_null($id)) {
@@ -1446,15 +2040,74 @@
1446 2040 $response['fieldDetails'] = $labels;
1447 2041 return $response;
1448 2042 }
1449 2043
1450 - public function getFormEntry($Request, $post) {
1451 - if (isset($Request['id'])) {
1452 - $id = wp_unslash($Request['id']);
2044 + /**
2045 + * Sanitize a request-supplied entry query condition before it reaches the Model
2046 + * layer. Only known entry-table columns are allowed as condition keys, operators
2047 + * are restricted to a safe allow-list ['form_id' => $id] when nothing valid remains.
2048 + *
2049 + * @param mixed $queryCondition
2050 + * @param int $id
2051 + * @return array
2052 + */
2053 + private function sanitizeEntryQueryCondition($queryCondition, $id)
2054 + {
2055 + $allowedColumns = [
2056 + 'id', 'form_id', 'status', 'created_at', 'updated_at',
2057 + 'user_id', 'user_ip', 'user_device', 'user_location', 'referer',
2058 + ];
2059 + $allowedOperators = ['=', '!=', '<>', '<', '>', '<=', '>=', 'LIKE', 'IN'];
2060 +
2061 + if (!is_array($queryCondition)) {
2062 + return ['form_id' => $id];
2063 + }
2064 +
2065 + $safe = [];
2066 + foreach ($queryCondition as $key => $value) {
2067 + if (!in_array($key, $allowedColumns, true)) {
2068 + continue;
2069 + }
2070 +
2071 + if (is_array($value)) {
2072 + // Never honour a request-supplied raw SQL fragment.
2073 + unset($value['raw']);
2074 +
2075 + if (array_key_exists('operator', $value) || array_key_exists('value', $value)) {
2076 + $operator = isset($value['operator']) && is_string($value['operator'])
2077 + ? strtoupper(trim($value['operator']))
2078 + : '=';
2079 + if (!in_array($operator, $allowedOperators, true)) {
2080 + $operator = '=';
2081 + }
2082 + $condValue = isset($value['value']) ? $value['value'] : '';
2083 + if (is_scalar($condValue)) {
2084 + $safe[$key] = ['operator' => $operator, 'value' => $condValue];
2085 + }
2086 + } else {
2087 + // IN-style list: keep scalar members only (bound by the Model).
2088 + $list = array_values(array_filter($value, 'is_scalar'));
2089 + if (!empty($list)) {
2090 + $safe[$key] = $list;
2091 + }
2092 + }
2093 + } elseif (is_scalar($value)) {
2094 + $safe[$key] = $value;
2095 + }
2096 + }
2097 +
2098 + return empty($safe) ? ['form_id' => $id] : $safe;
2099 + }
2100 +
2101 + public function getFormEntry($Request, $post)
2102 + {
2103 + if (!empty($Request['id'])) {
2104 + $id = absint(wp_unslash($Request['id']));
1453 2105 $offset = isset($Request['offset']) ?
1454 2106 wp_unslash($Request['offset']) : 0;
1455 2107 $pageSize = isset($Request['pageSize']) ?
1456 2108 wp_unslash($Request['pageSize']) : 10;
2109 + $queryCondition = isset($Request['queryCondition']) ? wp_unslash($Request['queryCondition']) : ['form_id' => $id];
1457 2110 } else {
1458 2111 $id = wp_unslash($post->id);
1459 2112 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1460 2113 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
@@ -1463,9 +2116,11 @@
1463 2116 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1464 2117 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1465 2118 $pageSize = isset($post->pageSize) ?
1466 2119 wp_unslash($post->pageSize) : 10;
2120 + $queryCondition = isset($post->queryCondition) ? wp_unslash($post->queryCondition) : ['form_id' => $id];
1467 2121 }
2122 + $queryCondition = $this->sanitizeEntryQueryCondition($queryCondition, $id);
1468 2123 if (is_null($id)) {
1469 2124 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1470 2125 }
1471 2126 $formManager = new AdminFormManager($id);
@@ -1471,9 +2126,90 @@
1471 2126 $formManager = new AdminFormManager($id);
1472 2127 if (!$formManager->isExist()) {
1473 2128 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1474 2129 }
2130 + $formEntry = new FormEntryModel();
2131 + $entries = $formEntry->get(
2132 + 'id',
2133 + $queryCondition,
2134 + null,
2135 + null,
2136 + 'created_at',
2137 + 'DESC'
2138 + );
2139 + if (is_wp_error($entries)) {
2140 + if ('result_empty' === $entries->get_error_code()) {
2141 + return [
2142 + 'count' => 0,
2143 + 'entries' => [],
2144 + ];
2145 + }
2146 + return $entries;
2147 + }
2148 + $filter['field'] = $filters;
2149 + $filter['global'] = $globalFilter;
1475 2150
2151 + $formFields = $formManager->getFieldLabel(true);
2152 + $fieldDetails = $formManager->getFields();
2153 +
2154 + $entryMeta = new FormEntryMetaModel();
2155 + $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
2156 + $customFieldHandler = new CustomFieldHandler();
2157 + $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
2158 + return $formEntries;
2159 + }
2160 +
2161 + public function getSingleEntry($formId, $entryId)
2162 + {
2163 + $formManager = new AdminFormManager($formId);
2164 + if (!$formManager->isExist()) {
2165 + return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2166 + }
2167 +
2168 + $formFields = $formManager->getFieldLabel(true);
2169 + $fieldDetails = $formManager->getFields();
2170 + $entryMeta = new FormEntryMetaModel();
2171 + // $formEntry = new FormEntryModel();
2172 +
2173 + $entries = $entryMeta->getSingleEntryMeta($formFields, $entryId);
2174 +
2175 + if (!is_wp_error($entries)) {
2176 + return $entries[0];
2177 + }
2178 + return new WP_Error('entry_not_fonud', __('Entry Not Found!', 'bit-form'));
2179 +
2180 + // $customFieldHandler = new CustomFieldHandler();
2181 + // $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
2182 + // return $formEntries;
2183 + }
2184 +
2185 + public function getEntriesForReport($Request, $post)
2186 + {
2187 + if (!empty($Request['id'])) {
2188 + $id = absint(wp_unslash($Request['id']));
2189 + $offset = isset($Request['offset']) ?
2190 + wp_unslash($Request['offset']) : null;
2191 + $pageSize = isset($Request['pageSize']) ?
2192 + wp_unslash($Request['pageSize']) : null;
2193 + } else {
2194 + $id = wp_unslash($post->id);
2195 + $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
2196 + $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
2197 + $offset = isset($post->offset) ? wp_unslash($post->offset) : null;
2198 + $sortBy = isset($post->sortBy) ? wp_unslash($post->sortBy) : null;
2199 + $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
2200 + $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
2201 + $pageSize = isset($post->pageSize) ?
2202 + wp_unslash($post->pageSize) : null;
2203 + }
2204 + if (is_null($id)) {
2205 + return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
2206 + }
2207 + $formManager = new AdminFormManager($id);
2208 + if (!$formManager->isExist()) {
2209 + return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2210 + }
2211 +
1476 2212 $formEntry = new FormEntryModel();
1477 2213 $entries = $formEntry->get(
1478 2214 'id',
1479 2215 [
@@ -1502,188 +2238,213 @@
1502 2238 $entryMeta = new FormEntryMetaModel();
1503 2239 $formEntries = $entryMeta->getEntryMeta($formFields, $entries, $pageSize, $offset, $filter, $sortBy, $conditions, $dateBetweenFilter);
1504 2240 $customFieldHandler = new CustomFieldHandler();
1505 2241 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
2242 + $formEntries['entries'] = Helpers::filterNullEntries($formEntries['entries']);
1506 2243 return $formEntries;
1507 2244 }
1508 2245
1509 - public function getExportEntry($post) {
1510 - $formId = wp_unslash($post->formId);
1511 - $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1512 - $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
1513 - $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1514 - $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1515 - $formFields = json_decode($post->selectedField);
1516 - if (is_null($formId)) {
1517 - return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
2246 + public function getExportEntry($post)
2247 + {
2248 + $formId = wp_unslash($post->formId);
2249 + $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
2250 + $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
2251 + $entryCondition = isset($post->filter) ? wp_unslash($post->filter) : null;
2252 + $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
2253 + $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
2254 + $formFields = json_decode($post->selectedField);
2255 + if (is_null($formId)) {
2256 + return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
2257 + }
2258 + $formManager = new AdminFormManager($formId);
2259 + $fieldLabels = $formManager->getFieldLabel(true);
2260 + if (!$formManager->isExist()) {
2261 + return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2262 + }
2263 +
2264 + $formEntry = new FormEntryModel();
2265 + $entries = $formEntry->get(
2266 + 'id',
2267 + [
2268 + 'form_id' => $formId,
2269 + ],
2270 + null,
2271 + null,
2272 + 'created_at',
2273 + 'DESC'
2274 + );
2275 + if (is_wp_error($entries)) {
2276 + if ('result_empty' === $entries->get_error_code()) {
2277 + return [
2278 + 'count' => 0,
2279 + 'entries' => [],
2280 + ];
1518 2281 }
1519 - $formManager = new AdminFormManager($formId);
1520 - $fieldLabels = $formManager->getFieldLabel(true);
1521 - if (!$formManager->isExist()) {
1522 - return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1523 - }
2282 + return $entries;
2283 + }
2284 + $entryMeta = new FormEntryMetaModel();
2285 + $filter = [];
2286 + $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField, $offset, $entryCondition);
2287 + return $formEntries;
2288 + }
1524 2289
1525 - $formEntry = new FormEntryModel();
1526 - $entries = $formEntry->get(
1527 - 'id',
1528 - [
1529 - 'form_id' => $formId,
1530 - ],
1531 - null,
1532 - null,
1533 - 'created_at',
1534 - 'DESC'
1535 - );
1536 - if (is_wp_error($entries)) {
1537 - if ('result_empty' === $entries->get_error_code()) {
1538 - return [
1539 - 'count' => 0,
1540 - 'entries' => [],
1541 - ];
1542 - }
1543 - return $entries;
1544 - }
1545 - $entryMeta = new FormEntryMetaModel();
1546 - $filter = [];
1547 - $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
1548 - return $formEntries;
2290 + public function deleteBlukFormEntries($Request, $post)
2291 + {
2292 + if (!empty($Request['formID'])) {
2293 + $formID = absint(wp_unslash($Request['formID']));
2294 + $entries = array_map('absint', wp_unslash($Request['entries']));
2295 + } else {
2296 + $formID = wp_unslash($post->formID);
2297 + $entries = wp_unslash($post->entries);
1549 2298 }
2299 + if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
2300 + return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
2301 + }
1550 2302
1551 - public function deleteBlukFormEntries($Request, $post) {
1552 - if (isset($Request['formID'])) {
1553 - $formID = wp_unslash($Request['formID']);
1554 - $entries = wp_unslash($Request['entries']);
2303 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2304 + return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
2305 + }
2306 +
2307 + if (!Helpers::checkIsIntArr($entries)) {
2308 + return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2309 + }
2310 +
2311 + $formManager = new AdminFormManager($formID);
2312 + if (!$formManager->isExist()) {
2313 + return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
2314 + }
2315 + $workFlowRunHelper = new WorkFlow($formID);
2316 +
2317 + $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
2318 + $formManager,
2319 + $formID,
2320 + $entries
2321 + );
2322 +
2323 + if (isset($workFlowreturnedOnDelete['entries'])) {
2324 + if (0 === count($workFlowreturnedOnDelete['entries'])) {
2325 + return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
2326 + } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
2327 + $message = __('Entry Deleted successfully', 'bit-form');
1555 2328 } else {
1556 - $formID = wp_unslash($post->formID);
1557 - $entries = wp_unslash($post->entries);
2329 + $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
2330 + $entries = $workFlowreturnedOnDelete['entries'];
2331 + $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
1558 2332 }
1559 - if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1560 - return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1561 - }
1562 - $formManager = new AdminFormManager($formID);
1563 - if (!$formManager->isExist()) {
1564 - return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1565 - }
1566 - $workFlowRunHelper = new WorkFlowRunHelper($formID);
1567 - $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1568 - $formManager,
1569 - $formID,
1570 - $entries
1571 - );
1572 - if (isset($workFlowreturnedOnDelete['entries'])) {
1573 - if (0 === count($workFlowreturnedOnDelete['entries'])) {
1574 - return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1575 - } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1576 - $message = __('Entry Deleted successfully', 'bit-form');
1577 - } else {
1578 - $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
1579 - $entries = $workFlowreturnedOnDelete['entries'];
1580 - $message = __('Entry Deleted successfully, Some prevented by workflow', 'bit-form');
2333 + } else {
2334 + $message = __('Entry Deleted successfully', 'bit-form');
2335 + }
2336 + global $wpdb;
2337 + $prefix = $wpdb->prefix;
2338 + $formEntryModel = new FormEntryModel();
2339 + $delete_status = $formEntryModel->bulkDelete(
2340 + [
2341 + "`{$prefix}bitforms_form_entries`.`id`" => $entries,
2342 + "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
2343 + ]
2344 + );
2345 + if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
2346 + $fileHandler = new FileHandler();
2347 + foreach ($entries as $enrtyKey => $entryID) {
2348 + $fileEntries = $fileHandler->getEntriesFileUploadDir($formID, $entryID);
2349 + if (file_exists($fileEntries)) {
2350 + $fileHandler->rmrf($fileEntries);
1581 2351 }
1582 - } else {
1583 - $message = __('Entry Deleted successfully', 'bit-form');
1584 2352 }
1585 - global $wpdb;
1586 - $prefix = $wpdb->prefix;
1587 - $formEntryModel = new FormEntryModel();
1588 - $delete_status = $formEntryModel->bulkDelete(
2353 + }
2354 + $count = $formEntryModel->count(
2355 + [
2356 + 'form_id' => $formID,
2357 + ]
2358 + );
2359 + $formManager->resetSubmissionCount(intval($count[0]->count));
2360 + if (is_wp_error($delete_status)) {
2361 + return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
2362 + }
2363 + $result['message'] = $message;
2364 + return $result;
2365 + }
2366 +
2367 + public function duplicateFormEntry($Request, $post)
2368 + {
2369 + if (!empty($Request['formID'])) {
2370 + $formID = absint(wp_unslash($Request['formID']));
2371 + $entries = array_map('absint', wp_unslash($Request['entries']));
2372 + } else {
2373 + $formID = wp_unslash($post->formID);
2374 + $entries = wp_unslash($post->entries);
2375 + }
2376 + if (is_null($formID) || !is_array($entries) || empty($entries)) {
2377 + return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
2378 + }
2379 +
2380 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2381 + return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
2382 + }
2383 +
2384 + if (!Helpers::checkIsIntArr($entries)) {
2385 + return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2386 + }
2387 +
2388 + $formManager = new AdminFormManager($formID);
2389 + if (!$formManager->isExist()) {
2390 + return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
2391 + }
2392 + $formEntryModel = new FormEntryModel();
2393 + $entryMeta = new FormEntryMetaModel();
2394 + $user_details = static::$ipTool->getUserDetail();
2395 + $total_entries = count($entries);
2396 + $duplicate_count = 0;
2397 + $test = '';
2398 + $fileHandler = new FileHandler();
2399 + $result = [];
2400 + foreach ($entries as $entryIndex => $entryID) {
2401 + $duplicatedEntryId = $formEntryModel->insert(
1589 2402 [
1590 - "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1591 - "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
2403 + 'form_id' => $formID,
2404 + 'user_id' => $user_details['id'],
2405 + 'user_ip' => $user_details['ip'],
2406 + 'user_device' => $user_details['device'],
2407 + 'referer' => 'duplicate of #' . $entryID,
2408 + 'status' => 1,
2409 + 'created_at' => $user_details['time'],
1592 2410 ]
1593 2411 );
1594 - if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1595 - $fileHandler = new FileHandler();
1596 - foreach ($entries as $enrtyKey => $entryID) {
1597 - $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
1598 - if (file_exists($fileEntries)) {
1599 - $fileHandler->rmrf($fileEntries);
1600 - }
1601 - }
1602 - }
1603 - $count = $formEntryModel->count(
1604 - [
1605 - 'form_id' => $formID,
1606 - ]
1607 - );
1608 - $formManager->resetSubmissionCount(intval($count[0]->count));
1609 - if (is_wp_error($delete_status)) {
1610 - return new WP_Error('entry_not_exists', __('Form entry deletion failed.', 'bit-form'));
1611 - }
1612 - $result['message'] = $message;
1613 - return $result;
1614 - }
1615 -
1616 - public function duplicateFormEntry($Request, $post) {
1617 - if (isset($Request['formID'])) {
1618 - $formID = wp_unslash($Request['formID']);
1619 - $entries = wp_unslash($Request['entries']);
1620 - } else {
1621 - $formID = wp_unslash($post->formID);
1622 - $entries = wp_unslash($post->entries);
1623 - }
1624 - if (is_null($formID) || !is_array($entries) || empty($entries)) {
1625 - return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1626 - }
1627 -
1628 - $formManager = new AdminFormManager($formID);
1629 - if (!$formManager->isExist()) {
1630 - return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1631 - }
1632 - $formEntryModel = new FormEntryModel();
1633 - $entryMeta = new FormEntryMetaModel();
1634 - $user_details = static::$ipTool->getUserDetail();
1635 - $total_entries = count($entries);
1636 - $duplicate_count = 0;
1637 - $test = '';
1638 - $fileHandler = new FileHandler();
1639 - $result = [];
1640 - foreach ($entries as $entryIndex => $entryID) {
1641 - $duplicatedEntryId = $formEntryModel->insert(
2412 + if ($duplicatedEntryId) {
2413 + $duplicate_status = $entryMeta->duplicateEntryMeta(
1642 2414 [
1643 - 'form_id' => $formID,
1644 - 'user_id' => $user_details['id'],
1645 - 'user_ip' => $user_details['ip'],
1646 - 'user_device' => $user_details['device'],
1647 - 'referer' => 'duplicate of #' . $entryID,
1648 - 'status' => 1,
1649 - 'created_at' => $user_details['time'],
2415 + 'duplicateID' => $duplicatedEntryId,
2416 + 'entryID' => $entryID,
1650 2417 ]
1651 2418 );
1652 - if ($duplicatedEntryId) {
1653 - $duplicate_status = $entryMeta->duplicateEntryMeta(
1654 - [
1655 - 'duplicateID' => $duplicatedEntryId,
1656 - 'entryID' => $entryID,
1657 - ]
1658 - );
1659 - if ($duplicate_status) {
1660 - $result['details'][$entryID] = $duplicatedEntryId;
1661 - $duplicate_count = $duplicate_count + 1;
1662 - if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
1663 - $fileHandler->cpyr(
1664 - BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1665 - BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
1666 - );
1667 - }
2419 + if ($duplicate_status) {
2420 + $result['details'][$entryID] = $duplicatedEntryId;
2421 + $duplicate_count = $duplicate_count + 1;
2422 + if (file_exists(FileHandler::getEntriesFileUploadDir($formID, $entryID))) {
2423 + $fileHandler->cpyr(
2424 + FileHandler::getEntriesFileUploadDir($formID, $entryID),
2425 + FileHandler::getEntriesFileUploadDir($formID, $duplicatedEntryId)
2426 + );
1668 2427 }
1669 2428 }
1670 2429 }
2430 + }
1671 2431
1672 - $count = $formEntryModel->count(
1673 - [
1674 - 'form_id' => $formID,
1675 - ]
1676 - );
1677 - $formManager->resetSubmissionCount(intval($count[0]->count));
1678 - $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
1679 - return ($total_entries === $duplicate_count) ? $result : false;
1680 - }
2432 + $count = $formEntryModel->count(
2433 + [
2434 + 'form_id' => $formID,
2435 + ]
2436 + );
2437 + $formManager->resetSubmissionCount(intval($count[0]->count));
2438 + $result['message'] = 1 === count($entries) ? __('Entry Duplicated successfully', 'bit-form') : __('Entries Duplicated successfully', 'bit-form');
2439 + return ($total_entries === $duplicate_count) ? $result : false;
2440 + }
1681 2441
1682 - public function editFormEntry($Request, $post) {
1683 - if (isset($Request['formID'])) {
1684 - $formID = wp_unslash($Request['formID']);
1685 - $entryID = wp_unslash($Request['entryID']);
2442 + public function editFormEntry($Request, $post)
2443 + {
2444 + if (!empty($Request['formID'])) {
2445 + $formID = absint(wp_unslash($Request['formID']));
2446 + $entryID = absint(wp_unslash($Request['entryID']));
1686 2447 } else {
1687 2448 $formID = wp_unslash($post->formID);
1688 2449 $entryID = wp_unslash($post->entryID);
1689 2450 }
@@ -1732,9 +2493,9 @@
1732 2493 $form_fields->{$key}->val = $entries[$key];
1733 2494 $form_fields->{$key}->name = $key;
1734 2495 }
1735 2496 }
1736 - $workFlowRunHelper = new WorkFlowRunHelper($formID);
2497 + $workFlowRunHelper = new WorkFlow($formID);
1737 2498 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
1738 2499 'edit',
1739 2500 $form_fields
1740 2501 );
@@ -1755,16 +2516,19 @@
1755 2516 ];
1756 2517 return $formData;
1757 2518 }
1758 2519
1759 - public function updateFormEntry($Request, $post) {
2520 + public function updateFormEntry($Request, $post)
2521 + {
1760 2522 if (isset($Request['formID'], $Request['entryID'])) {
1761 - $formID = wp_unslash($Request['formID']);
1762 - $entryID = wp_unslash($Request['entryID']);
2523 + $formID = absint(wp_unslash($Request['formID']));
2524 + $entryID = absint(wp_unslash($Request['entryID']));
1763 2525 unset($Request['action'], $Request['formID'], $Request['entryID']);
1764 -
1765 - $updatedValue = wp_unslash($post);
1766 2526 }
2527 + $formManager = new AdminFormManager($formID);
2528 + $formManager->fieldNameReplaceOfPost();
2529 + // Called from AdminAjax handler; nonce already verified at AJAX entry before dispatch.
2530 + $updatedValue = is_array($post) ? $post : wp_unslash($_POST);
1767 2531
1768 2532 if (is_null($updatedValue) || !is_array($updatedValue)) {
1769 2533 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1770 2534 }
@@ -1772,9 +2536,8 @@
1772 2536 if (is_null($formID) || is_null($entryID)) {
1773 2537 return new WP_Error('empty_data', __('Invalid Form ID or entries ID.', 'bit-form'));
1774 2538 }
1775 2539
1776 - $formManager = new AdminFormManager($formID);
1777 2540 if (!$formManager->isExist()) {
1778 2541 return new WP_Error('empty_data', __('Form does not exist.', 'bit-form'));
1779 2542 }
1780 2543 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
@@ -1779,12 +2542,13 @@
1779 2542 }
1780 2543 return $formManager->updateFormEntry($updatedValue, $formID, $entryID);
1781 2544 }
1782 2545
1783 - public function getLogHistory($Request, $post) {
1784 - if (isset($Request['formID'])) {
1785 - $formID = wp_unslash($Request['formID']);
1786 - $entryID = wp_unslash($Request['entryID']);
2546 + public function getLogHistory($Request, $post)
2547 + {
2548 + if (!empty($Request['formID'])) {
2549 + $formID = absint(wp_unslash($Request['formID']));
2550 + $entryID = absint(wp_unslash($Request['entryID']));
1787 2551 } else {
1788 2552 $formID = wp_unslash($post->formID);
1789 2553 $entryID = wp_unslash($post->entryID);
1790 2554 }
@@ -1802,11 +2566,12 @@
1802 2566 $log_history = $formLogModel->geLogHistory($formID, $entryID);
1803 2567 return $log_history;
1804 2568 }
1805 2569
1806 - public function importDataStore($Request, $post) {
1807 - if (isset($Request['formID'])) {
1808 - $formID = wp_unslash($Request['formID']);
2570 + public function importDataStore($Request, $post)
2571 + {
2572 + if (!empty($Request['formID'])) {
2573 + $formID = absint(wp_unslash($Request['formID']));
1809 2574 } else {
1810 2575 $formID = wp_unslash($post->formID);
1811 2576 }
1812 2577 if (is_null($formID)) {
@@ -1813,22 +2578,28 @@
1813 2578 return new WP_Error('empty_form', __('Invalid Form id or entries id.', 'bit-form'));
1814 2579 }
1815 2580 }
1816 2581
1817 - public function getAllWPPages($Request, $post) {
2582 + public function getAllWPPages($Request, $post)
2583 + {
1818 2584 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
1819 2585 $allPages = [];
1820 2586 foreach ($pages as $pageKey => $pageDetails) {
1821 - $allPages[$pageKey]['title'] = $pageDetails->post_title;
1822 - $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2587 + // $allPages[$pageKey]['title'] = $pageDetails->post_title;
2588 + // $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2589 + $allPages[] = (object) [
2590 + 'title' => $pageDetails->post_title,
2591 + 'url' => get_page_link($pageDetails->ID)
2592 + ];
1823 2593 }
1824 2594 return $allPages;
1825 2595 }
1826 2596
1827 - public function deleteAIntegration($Request, $post) {
1828 - if (isset($Request['formID']) && $Request['id']) {
1829 - $formID = json_decode(wp_unslash($Request['formID']));
1830 - $id = wp_unslash($Request['id']);
2597 + public function deleteAIntegration($Request, $post)
2598 + {
2599 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2600 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2601 + $id = absint(wp_unslash($Request['id']));
1831 2602 } else {
1832 2603 $formID = wp_unslash($post->formID);
1833 2604 $id = wp_unslash($post->id);
1834 2605 }
@@ -1846,12 +2617,13 @@
1846 2617 'message' => __('Integration deleted', 'bit-form'),
1847 2618 ];
1848 2619 }
1849 2620
1850 - public function deleteSuccessMessage($Request, $post) {
1851 - if (isset($Request['formID']) && $Request['id']) {
1852 - $formID = json_decode(wp_unslash($Request['formID']));
1853 - $id = wp_unslash($Request['id']);
2621 + public function deleteSuccessMessage($Request, $post)
2622 + {
2623 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2624 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2625 + $id = absint(wp_unslash($Request['id']));
1854 2626 } else {
1855 2627 $formID = wp_unslash($post->formID);
1856 2628 $id = wp_unslash($post->id);
1857 2629 }
@@ -1868,12 +2640,13 @@
1868 2640 'message' => __('Message deleted', 'bit-form'),
1869 2641 ];
1870 2642 }
1871 2643
1872 - public function deleteAWorkflow($Request, $post) {
1873 - if (isset($Request['formID']) && $Request['id']) {
1874 - $formID = json_decode(wp_unslash($Request['formID']));
1875 - $id = wp_unslash($Request['id']);
2644 + public function deleteAWorkflow($Request, $post)
2645 + {
2646 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2647 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2648 + $id = absint(wp_unslash($Request['id']));
1876 2649 } else {
1877 2650 $formID = wp_unslash($post->formID);
1878 2651 $id = wp_unslash($post->id);
1879 2652 }
@@ -1889,12 +2662,13 @@
1889 2662 'message' => __('workflow deleted', 'bit-form'),
1890 2663 ];
1891 2664 }
1892 2665
1893 - public function deleteAMailTemplate($Request, $post) {
1894 - if (isset($Request['formID']) && $Request['id']) {
1895 - $formID = json_decode(wp_unslash($Request['formID']));
1896 - $id = wp_unslash($Request['id']);
2666 + public function deleteAMailTemplate($Request, $post)
2667 + {
2668 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2669 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2670 + $id = absint(wp_unslash($Request['id']));
1897 2671 } else {
1898 2672 $formID = wp_unslash($post->formID);
1899 2673 $id = wp_unslash($post->id);
1900 2674 }
@@ -1910,12 +2684,13 @@
1910 2684 'message' => __('Email Template deleted', 'bit-form'),
1911 2685 ];
1912 2686 }
1913 2687
1914 - public function duplicateAMailTemplate($Request, $post) {
1915 - if (isset($Request['formID']) && $Request['id']) {
1916 - $formID = json_decode(wp_unslash($Request['formID']));
1917 - $id = wp_unslash($Request['id']);
2688 + public function duplicateAMailTemplate($Request, $post)
2689 + {
2690 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2691 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2692 + $id = absint(wp_unslash($Request['id']));
1918 2693 } else {
1919 2694 $formID = wp_unslash($post->formID);
1920 2695 $id = wp_unslash($post->id);
1921 2696 }
@@ -1921,8 +2696,17 @@
1921 2696 }
1922 2697 if (empty($formID) || empty($id)) {
1923 2698 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
1924 2699 }
2700 +
2701 + if (false === filter_var($id, FILTER_VALIDATE_INT)) {
2702 + return new WP_Error('empty_form', 'Invalid Email Template ID.');
2703 + }
2704 +
2705 + if (false === filter_var($formID, FILTER_VALIDATE_INT)) {
2706 + return new WP_Error('empty_form', 'Invalid Form ID.');
2707 + }
2708 +
1925 2709 $emailTemplateHandler = new EmailTemplateHandler($formID);
1926 2710 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
1927 2711 if (is_wp_error($duplicate_status)) {
1928 2712 return $duplicate_status;
@@ -1931,9 +2715,10 @@
1931 2715 'message' => __('Email Template duplicated', 'bit-form'),
1932 2716 ];
1933 2717 }
1934 2718
1935 - public function setAllFormsReport($Request, $post) {
2719 + public function setAllFormsReport($Request, $post)
2720 + {
1936 2721 $reports = empty($post->reports) ? null : wp_unslash($post->reports);
1937 2722 if (empty($reports)) {
1938 2723 return new WP_Error('empty_report_prefs', 'Report data is Empty, nothing to save or update.');
1939 2724 }
@@ -2009,9 +2794,10 @@
2009 2794 'reports' => empty($reports) ? [] : $reports,
2010 2795 ];
2011 2796 }
2012 2797
2013 - public function savegReCaptcha($Request, $post) {
2798 + public function savegReCaptcha($Request, $post)
2799 + {
2014 2800 $reCaptcha = $post->reCaptcha;
2015 2801
2016 2802 if (is_null($reCaptcha)) {
2017 2803 return new WP_Error('empty_gcaptchdetails', __('g-ReCAPTCHA details is empty', 'bit-form'));
@@ -2023,11 +2809,16 @@
2023 2809 } else {
2024 2810 $integrationID = $reCaptcha->id;
2025 2811 unset($reCaptcha->id);
2026 2812 }
2027 - $reCaptcha = json_encode($reCaptcha);
2028 - $integrationName = 'google reCaptcha';
2029 - $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
2813 + $reCaptcha = wp_json_encode($reCaptcha);
2814 +
2815 + // $integrationName = 'google reCaptcha';
2816 + $integrationName = $post->integrationName;
2817 +
2818 + // $integrationType = 'v2' === $post->version ? 'gReCaptcha' : 'gReCaptchaV3';
2819 + $integrationType = $post->integrationType;
2820 +
2030 2821 $integrationDetails = $reCaptcha;
2031 2822 $user_details = static::$ipTool->getUserDetail();
2032 2823 $integrationHandler = new IntegrationHandler(0, $user_details);
2033 2824 $response = [];
@@ -2033,12 +2824,12 @@
2033 2824 $response = [];
2034 2825 if (empty($integrationID)) {
2035 2826 $captchaSaveStatus = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'app');
2036 2827 $response['id'] = $captchaSaveStatus;
2037 - $response['message'] = __('g-reCAPTCHA saved successfully', 'bit-form');
2828 + $response['message'] = __('reCAPTCHA saved successfully', 'bit-form');
2038 2829 } else {
2039 2830 $captchaSaveStatus = $integrationHandler->updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, 'app');
2040 - $response['message'] = __('g-reCAPTCHA updated successfully', 'bit-form');
2831 + $response['message'] = __('reCAPTCHA updated successfully', 'bit-form');
2041 2832 }
2042 2833
2043 2834 if (is_wp_error($captchaSaveStatus)) {
2044 2835 return $captchaSaveStatus;
@@ -2045,9 +2836,10 @@
2045 2836 }
2046 2837 return $response;
2047 2838 }
2048 2839
2049 - public function savePaymentSetting($Request, $post) {
2840 + public function savePaymentSetting($Request, $post)
2841 + {
2050 2842 if (isset($post->paySetting)) {
2051 2843 $paySetting = $post->paySetting;
2052 2844 }
2053 2845 if (is_null($paySetting)) {
@@ -2055,21 +2847,37 @@
2055 2847 }
2056 2848 if (is_string($paySetting)) {
2057 2849 $paySetting = json_decode($paySetting);
2058 2850 }
2059 - if ('PayPal' === $paySetting->type) {
2060 - $canSave = $this->addWebhookToPaypal($paySetting);
2061 - } elseif ('Razorpay' === $paySetting->type) {
2062 - $canSave = true;
2851 +
2852 + $canSave = null;
2853 + switch ($paySetting->type) {
2854 + case 'PayPal':
2855 + $canSave = $this->addWebhookToPaypal($paySetting);
2856 + break;
2857 + case 'Razorpay':
2858 + $canSave = true;
2859 + break;
2860 + case 'Stripe':
2861 + $canSave = $this->addWebhookToStripe($paySetting);
2862 + break;
2863 + case 'Mollie':
2864 + $canSave = true;
2865 + break;
2866 + default:
2867 + $canSave = null;
2063 2868 }
2064 2869 if (is_null($canSave)) {
2065 - return ['message' => __('Please re-check your Client ID & Secret', 'bit-form')];
2870 + return new WP_Error('stripe', __('Please re-check your Client ID & Secret', 'bit-form'));
2066 2871 }
2067 - $integrationID = $paySetting->id;
2068 - unset($paySetting->id);
2872 + $integrationID = null;
2873 + if (isset($paySetting->id)) {
2874 + $integrationID = $paySetting->id;
2875 + unset($paySetting->id);
2876 + }
2069 2877 $integrationName = $paySetting->name;
2070 2878 $integrationType = 'payments';
2071 - $paySetting = json_encode($paySetting);
2879 + $paySetting = wp_json_encode($paySetting);
2072 2880 $integrationDetails = $paySetting;
2073 2881 $user_details = static::$ipTool->getUserDetail();
2074 2882 $integrationHandler = new IntegrationHandler(0, $user_details);
2075 2883 $response = [];
@@ -2087,9 +2895,10 @@
2087 2895 }
2088 2896 return $response;
2089 2897 }
2090 2898
2091 - private function addWebhookToPaypal($paySetting) {
2899 + private function addWebhookToPaypal($paySetting)
2900 + {
2092 2901 $transaction_mode = $paySetting->mode;
2093 2902 $clientId = $paySetting->clientID;
2094 2903 $clientSecret = $paySetting->clientSecret;
2095 2904 $base_url = 'sandbox' === $transaction_mode ? 'https://api-m.sandbox.paypal.com' : 'https://api.paypal.com';
@@ -2115,9 +2924,52 @@
2115 2924 }
2116 2925 return true;
2117 2926 }
2118 2927
2119 - public function builerHelperState($formId) {
2928 + private function addWebhookToStripe($paySetting)
2929 + {
2930 + $clientSecret = $paySetting->clientSecret;
2931 +
2932 + $create_webhook_url = 'https://api.stripe.com/v1/webhook_endpoints';
2933 + $headers = [
2934 + 'Content-Type' => 'application/x-www-form-urlencoded',
2935 + 'Authorization' => "Bearer $clientSecret",
2936 + ];
2937 +
2938 + $webhook_url = get_rest_url() . 'bitform/v1/payments/stripe';
2939 +
2940 + $apiResponse = HttpHelper::get($create_webhook_url, '', $headers);
2941 +
2942 + if (isset($apiResponse->error)) {
2943 + return null;
2944 + }
2945 + $webhookList = $apiResponse->data;
2946 + $webhook_already_exist = false;
2947 +
2948 + foreach ($webhookList as $webhook) {
2949 + if ($webhook->url === $webhook_url) {
2950 + $webhook_already_exist = true;
2951 + break;
2952 + }
2953 + }
2954 +
2955 + $data = [
2956 + 'enabled_events[]' => 'payment_intent.succeeded',
2957 + 'url' => $webhook_url,
2958 + ];
2959 +
2960 + if (!$webhook_already_exist) {
2961 + $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2962 + if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2963 + Log::debug_log(['Stripe webhook creation failed' => $webhook_response]);
2964 + return null;
2965 + }
2966 + }
2967 + return true;
2968 + }
2969 +
2970 + public function builerHelperState($formId)
2971 + {
2120 2972 $data = static::$formModel->get(
2121 2973 ['id', 'builder_helper_state'],
2122 2974 ['id' => $formId]
2123 2975 );
@@ -2132,9 +2984,10 @@
2132 2984
2133 2985 return $data;
2134 2986 }
2135 2987
2136 - public function updateGeneratedScriptPageIds() {
2988 + public function updateGeneratedScriptPageIds()
2989 + {
2137 2990 $updateData = [
2138 2991 'generated_script_page_ids' => \wp_json_encode((object) []),
2139 2992 ];
2140 2993 $update_status = static::$formModel->update(
@@ -2151,9 +3004,70 @@
2151 3004 return true;
2152 3005 }
2153 3006 }
2154 3007
2155 - public function updateSuccessMessageClassName($str, $msgIdx, $msgId) {
3008 + public function replaceAllFormsErrorMessagesByGlobalMessages()
3009 + {
3010 + try {
3011 + $formModel = new FormModel();
3012 + $allForms = $formModel->get(['id', 'form_content']);
3013 +
3014 + foreach ($allForms as $form) {
3015 + // Decode form_content JSON to stdClass
3016 + $formContent = \json_decode($form->form_content);
3017 + $fields = $formContent->fields ?? null;
3018 + // If decode fails, skip to next
3019 + if (!$fields) {
3020 + Log::debug_log("Form ID {$form->id}: invalid JSON in form_content");
3021 + continue;
3022 + }
3023 +
3024 + // Replace default error messages using your helper
3025 + $updatedFields = Helpers::replaceFieldsDefaultErrorMsg($fields);
3026 +
3027 + $formContent->fields = $updatedFields;
3028 + // Encode back to JSON
3029 + $updatedContent = \json_encode($formContent);
3030 +
3031 + if (false === $updatedContent) {
3032 + Log::debug_log("Form ID {$form->id}: JSON encoding failed");
3033 + continue;
3034 + }
3035 + // Update form content in DB
3036 + $formModel->update(
3037 + ['form_content' => $updatedContent], // data to update
3038 + ['id' => $form->id] // condition for update
3039 + );
3040 + }
3041 + } catch (\Exception $e) {
3042 + Log::debug_log([
3043 + 'message' => 'Error in updateAllFormsErrorMessagesWithGlobalMessages',
3044 + 'error' => $e->getMessage(),
3045 + ]);
3046 + }
3047 + }
3048 +
3049 + public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
3050 + {
2156 3051 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2157 3052 return str_replace($TEMP_CONF_ID, $msgId, $str);
3053 + }
3054 +
3055 + public function startMigrationProcess()
3056 + {
3057 + Utilities::duplicateDbTable('form', 'form_v1');
3058 + Utilities::duplicateDbTable('workflows', 'workflows_v1');
3059 + Utilities::duplicateDbTable('success_messages', 'success_messages_v1');
3060 + MigrationHelper::duplicateV1StyleFiles();
3061 + $all_forms = $this->getAllForm();
3062 + $v1FormContents = [];
3063 + $defaultStyleClass = MigrationHelper::getBitformDefaultStyleClass();
3064 + foreach ($all_forms as $form) {
3065 + $formContents = $this->getAFormV1(['id' => $form->id], ['id' => $form->id]);
3066 + $v1FormContents[] = $formContents;
3067 + FrontEndScriptGenerator::saveCssFile("{$form->id}", $defaultStyleClass);
3068 + FrontEndScriptGenerator::saveCssFile("{$form->id}-formid", $defaultStyleClass);
3069 + }
3070 + set_transient('bitforms_v1_form_contents', $v1FormContents);
3071 + update_option('bitforms_migrating_to_v2', true);
2158 3072 }
2159 3073 }