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 +872 -237 2.10.03.3.1 View file →
@@ -13,23 +13,24 @@
13 13 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
14 14 use BitCode\BitForm\Core\Database\FormEntryModel;
15 15 use BitCode\BitForm\Core\Database\FormModel;
16 16 use BitCode\BitForm\Core\Database\IntegrationModel;
17 -use BitCode\BitForm\Core\Database\PdfTemplateModel;
18 17 use BitCode\BitForm\Core\Database\ReportsModel;
19 18 use BitCode\BitForm\Core\Database\SuccessMessageModel;
20 19 use BitCode\BitForm\Core\Database\WorkFlowModel;
20 +use BitCode\BitForm\Core\Form\FormManager;
21 21 use BitCode\BitForm\Core\Integration\IntegrationHandler;
22 22 use BitCode\BitForm\Core\Messages\EmailTemplateHandler;
23 -use BitCode\BitForm\Core\Messages\PdfTemplateHandler;
24 23 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
24 +use BitCode\BitForm\Core\Migration\MigrationHelper;
25 25 use BitCode\BitForm\Core\Util\FileHandler;
26 26 use BitCode\BitForm\Core\Util\FormDuplicateHelper;
27 27 use BitCode\BitForm\Core\Util\HttpHelper;
28 28 use BitCode\BitForm\Core\Util\IpTool;
29 +use BitCode\BitForm\Core\Util\Log;
30 +use BitCode\BitForm\Core\Util\Utilities;
29 31 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
30 32 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
31 -use BitCode\BitFormPro\Admin\AppSetting\Pdf;
32 33 use WP_Error;
33 34
34 35 class AdminFormHandler
35 36 {
@@ -70,14 +71,12 @@
70 71 $this->createFormStylesDirIfNotExists();
71 72
72 73 if (
73 74 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
74 - && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
75 + && wp_is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
75 76 ) {
76 - $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
77 - fwrite($createStyleFile, $styles);
78 - fclose($createStyleFile);
79 - return true;
77 + $filePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName;
78 + return FileHandler::writeFile($filePath, $styles);
80 79 }
81 80 return false;
82 81 }
83 82
@@ -87,9 +86,9 @@
87 86 $sm_width = 400;
88 87 $lg_styles = '';
89 88 $md_styles = '';
90 89 $sm_styles = '';
91 - for ($i = 0; $i < count($layout->lg); $i++) {
90 + for ($i = 0; $i < count($layout->lg ?? []); $i++) {
92 91 $fld = $layout->lg[$i];
93 92
94 93 if ($fld->w < 10) {
95 94 $lay_row_height = 43;
@@ -153,14 +152,12 @@
153 152 $this->createFormStylesDirIfNotExists();
154 153
155 154 if (
156 155 file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
157 - && is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
156 + && wp_is_writable(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles')
158 157 ) {
159 - $createStyleFile = fopen(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName, 'w');
160 - fwrite($createStyleFile, $formStyle);
161 - fclose($createStyleFile);
162 - return true;
158 + $filePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . $sheetName;
159 + return FileHandler::writeFile($filePath, $formStyle);
163 160 }
164 161 return false;
165 162 }
166 163
@@ -176,9 +173,9 @@
176 173
177 174 private function pdfFontDownload($fontName)
178 175 {
179 176 if (class_exists('\BitCode\BitFormPro\Admin\AppSetting\Pdf')) {
180 - Pdf::getInstance()->fontsDownload($fontName);
177 + \BitCode\BitFormPro\Admin\AppSetting\Pdf::getInstance()->fontsDownload($fontName);
181 178 }
182 179 return false;
183 180 }
184 181
@@ -194,17 +191,8 @@
194 191 if ($formManager->isExist()) {
195 192 return new WP_Error('empty_form', __('Error Occurred, Please Reload', 'bit-form'));
196 193 }
197 194
198 - if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
199 - if (!empty($workFlows) && count($workFlows) > 2) {
200 - return new WP_Error(
201 - 'free_limit',
202 - __('You are allowed to add maximum 2 workflows ', 'bit-form')
203 - );
204 - }
205 - }
206 -
207 195 if (isset($post->formStyle) && $post->formStyle) {
208 196 $sheetName = 'bitform-' . $post->form_id . '.css';
209 197 $this->saveStyleSheet($post->formStyle, $sheetName);
210 198 }
@@ -210,18 +198,20 @@
210 198 }
211 199
212 200 if (isset($post->layoutChanged) && $post->layoutChanged) {
213 201 $sheetName = 'bitform-layout-' . $post->form_id . '.css';
214 - $rowHeight = (int)$post->rowHeight;
202 + $rowHeight = (int) $post->rowHeight;
215 203 $this->saveLayoutStyleSheet($post->layout, $sheetName, $rowHeight);
216 204 }
217 205
218 206 $fields = wp_unslash($post->fields);
207 + $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
219 208 // $fields = $post->fields;
220 209 $layout = wp_unslash($post->layout);
221 - $nestedLayout = isset($post->nestedLayout) ? wp_unslash($post->nestedLayout) : (object) [];
210 + $nestedLayout = isset($post->nestedLayouts) ? wp_unslash($post->nestedLayouts) : (object) [];
222 211 $formInfo = wp_unslash($post->formInfo);
223 212 $form_name = wp_unslash($post->form_name);
213 + $form_name = strlen($form_name) > 50 ? substr($form_name, 0, 50) : $form_name;
224 214 $formSettings = (object) wp_unslash($post->formSettings);
225 215 $atomic_class_map = isset($post->atomicClassMap) ? wp_unslash($post->atomicClassMap) : [];
226 216 $breakpointSize = wp_unslash($post->breakpointSize);
227 217 $style = $post->style;
@@ -235,8 +225,9 @@
235 225
236 226 $mailTem = $formSettings->mailTem;
237 227 $pdfTem = $formSettings->pdfTem;
238 228 $integrations = $formSettings->integrations;
229 + $formPermissions = $formSettings->formPermissions;
239 230
240 231 $user_details = static::$ipTool->getUserDetail();
241 232 if (empty($fields) || empty($layout)) {
242 233 return new WP_Error(
@@ -249,8 +240,12 @@
249 240 'empty_form',
250 241 __('Form Name Should Be Within 50 Characters', 'bit-form')
251 242 );
252 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);
253 248 $form_content = [
254 249 'fields' => $fields,
255 250 'layout' => $layout,
256 251 'nestedLayout' => $nestedLayout,
@@ -263,8 +258,12 @@
263 258 if (!empty($formSettings->theme)) {
264 259 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
265 260 }
266 261
262 + if (!empty($formSettings->formPermissions)) {
263 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
264 + }
265 +
267 266 if (!empty($additional)) {
268 267 $form_content = array_merge($form_content, ['additional' => $additional]);
269 268 }
270 269 if (!empty($workFlows)) {
@@ -312,10 +311,11 @@
312 311 return $save_status;
313 312 } elseif (!$save_status) {
314 313 return false;
315 314 } else {
316 - wp_mkdir_p(BITFORMS_UPLOAD_DIR . "/$save_status");
315 + FileHandler::createIndexFile(BITFORMS_UPLOAD_DIR . "/$save_status");
317 316 $formID = $save_status;
317 + do_action('bitform_admin_form_changed');
318 318 $integartionIDForWorkflow = [];
319 319 // Confiramtion Message [start]
320 320 if (!empty($formSettings->confirmation->type->successMsg)) {
321 321 $successMessages = $formSettings->confirmation->type->successMsg;
@@ -324,8 +324,11 @@
324 324 $savedID = $successMessageHandler->saveMessage($messageDetail);
325 325 if ($savedID) {
326 326 $msgIdx = empty($messageDetail->id) ? $messageKey : wp_json_encode(['id' => $messageDetail->id]);
327 327 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
328 + if (!empty($messageDetail->clRef)) {
329 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
330 + }
328 331 $messageDetail->id = $savedID;
329 332 $style = $this->updateSuccessMessageClassName($style, $messageKey, $savedID);
330 333 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
331 334 }
@@ -338,10 +341,10 @@
338 341 'builderSettings' => $builderSettings
339 342 ];
340 343 $update_status = static::$formModel->update(
341 344 [
342 - 'builder_helper_state' => \wp_json_encode($builder_helper_state),
343 - 'atomic_class_map' => $atomic_class_map,
345 + 'builder_helper_state' => \wp_json_encode($builder_helper_state),
346 + 'atomic_class_map' => $atomic_class_map,
344 347 ],
345 348 [
346 349 'id' => $formID,
347 350 ]
@@ -358,31 +361,55 @@
358 361 $emailTemplateHandler
359 362 = new EmailTemplateHandler($formID, $user_details);
360 363 foreach ($mailTem as $templateKey => $templateDetail) {
361 364 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
362 - if ($savedID) {
365 + if ($savedID && !is_wp_error($savedID)) {
363 366 $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
364 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);
365 374 }
366 375 }
367 376 }
368 377 // Email Template [end] */
369 - // if (!empty($pdfTem)) {
370 - // $pdfTemplateHandler = new PdfTemplateHandler($formID);
371 - // foreach ($pdfTem as $templateKey => $templateDetail) {
372 - // $savedID = $pdfTemplateHandler->save($templateDetail);
373 378
374 - // $pdfSetting = $templateDetail->setting;
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);
375 388
376 - // if( isset($pdfSetting->font->name) && !empty($pdfSetting->font->name)) {
377 - // $this->pdfFontDownload($pdfSetting->font->name);
378 - // }
379 - // // if ($savedID) {
380 - // // $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
381 - // // $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
382 - // // }
383 - // }
384 - // }
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] */
385 412 //Integration [start] */
386 413 $integrationHandler = new IntegrationHandler($formID, $user_details);
387 414 if (!empty($formSettings->confirmation->type)) {
388 415 $allIntegrations = $formSettings->confirmation->type;
@@ -387,8 +414,14 @@
387 414 if (!empty($formSettings->confirmation->type)) {
388 415 $allIntegrations = $formSettings->confirmation->type;
389 416 foreach ($allIntegrations as $integrationType => $integrationGroup) {
390 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 + }
391 424 if (empty($singleIntegrationDetail->details)) {
392 425 $integrationName = $singleIntegrationDetail->title;
393 426 unset($singleIntegrationDetail->title, $singleIntegrationDetail->id);
394 427
@@ -398,14 +431,25 @@
398 431 $integrationName = $singleIntegrationDetail->title;
399 432 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
400 433 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
401 434 }
402 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
435 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
403 436 $integIdx = empty($singleIntegrationDetail->id) ? $savedID : wp_json_encode(['id' => $singleIntegrationDetail->id]);
404 437 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
438 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
439 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
440 + }
405 441 }
406 442 }
407 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 + }
408 452 if (!empty($integrations)) {
409 453 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
410 454 $integrationName = $singleIntegrationDetail->name;
411 455 unset($singleIntegrationDetail->name);
@@ -412,8 +456,11 @@
412 456 $integrationType = $singleIntegrationDetail->type;
413 457 unset($singleIntegrationDetail->type);
414 458 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
415 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);
416 463 if (empty($singleIntegrationDetail->details)) {
417 464 $integrationDetails = !is_string($singleIntegrationDetail) ?
418 465 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
419 466 } else {
@@ -422,8 +469,11 @@
422 469 }
423 470 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
424 471 $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : wp_json_encode(['id' => $singleIntegrationDetailID]);
425 472 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
473 + if (!empty($clRef) && !is_wp_error($savedID)) {
474 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
475 + }
426 476 }
427 477 }
428 478 //Integrations [end]
429 479 //wrokFlows [start]
@@ -443,9 +493,9 @@
443 493 // }
444 494 }
445 495 //wrokFlows [end]
446 496 $details = [
447 - 'report_name' => 'All Entries',
497 + 'report_name' => __('All Entries', 'bit-form'),
448 498 'hiddenColumns' => ['__user_id', '__user_ip', '__referer', '__user_device', '__created_at', '__updated_at'],
449 499 'pageSize' => 10,
450 500 'sortBy' => [],
451 501 'filters' => [],
@@ -474,8 +524,12 @@
474 524 $updated_data['form_content']['is_default'] = 1;
475 525 }
476 526 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
477 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 +
478 532 return $updated_data;
479 533 }
480 534 }
481 535
@@ -505,13 +559,14 @@
505 559 if (property_exists($post, 'builderSettings')) {
506 560 $builder_helper_state->builderSettings = $post->builderSettings;
507 561 }
508 562 if (property_exists($post, 'atomicClassMap')) {
509 - $atomic_class_map = \wp_json_encode((object)$post->atomicClassMap);
563 + $atomic_class_map = \wp_json_encode((object) $post->atomicClassMap);
510 564 }
511 565
512 566 if (property_exists($post, 'fields') && null !== $post->fields && property_exists($post, 'layout') && $post->layout) {
513 567 $fields = wp_unslash($post->fields);
568 + $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
514 569 $layout = wp_unslash($post->layout);
515 570 $nestedLayout = wp_unslash($post->nestedLayouts);
516 571 $formInfo = wp_unslash($post->formInfo);
517 572 $formID = wp_unslash($post->id);
@@ -531,16 +586,10 @@
531 586 if (empty($fields) || empty($layout) || is_null($formID)) {
532 587 return new WP_Error('empty_form', 'Can not update empty form.');
533 588 }
534 589
535 - if (!class_exists('BitCode\\BitFormPro\\Plugin')) {
536 - if (count($workFlows) > 2) {
537 - return new WP_Error(
538 - 'free_limit',
539 - __('You are allowed to add maximum 2 workflows ', 'bit-form')
540 - );
541 - }
542 - }
590 + // Guard: never persist orphan fields (see createNewForm). Fail closed.
591 + $this->pruneOrphanFields($fields, $nestedLayout, $layout, $formID, $post);
543 592
544 593 $form_content = [
545 594 'fields' => $fields,
546 595 'layout' => $layout,
@@ -557,8 +606,12 @@
557 606 } */
558 607 if (!empty($formSettings->theme)) {
559 608 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
560 609 }
610 +
611 + if (!empty($formSettings->formPermissions)) {
612 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
613 + }
561 614 if (!empty($additional)) {
562 615 $form_content = array_merge($form_content, ['additional' => $additional]);
563 616 }
564 617 $integartionIDForWorkflow = [];
@@ -566,8 +619,9 @@
566 619 $newData['integation'] = 0;
567 620 $newData['mailTemplate'] = 0;
568 621 $newData['workflow'] = 0;
569 622 $newData['reports'] = 0;
623 + $newData['pdfTemplate'] = 0;
570 624 // Confiramtion Message [start]
571 625 if (!empty($formSettings->confirmation->type->successMsg)) {
572 626 $successMessages = $formSettings->confirmation->type->successMsg;
573 627 $successMessageHandler
@@ -577,8 +631,11 @@
577 631 $savedID = $successMessageHandler->saveMessage($messageDetail);
578 632 if ($savedID) {
579 633 $newData['settingConfiramation'] = 1;
580 634 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
635 + if (!empty($messageDetail->clRef)) {
636 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
637 + }
581 638 $messageDetail->id = $savedID;
582 639 $builder_helper_state->style = $this->updateSuccessMessageClassName($builder_helper_state->style, $messageKey, $savedID);
583 640 if (isset($atomic_class_map)) {
584 641 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
@@ -603,18 +660,29 @@
603 660 $newData['mailTemplate'] = 2;
604 661 } else {
605 662 $newData['mailTemplate'] = 1;
606 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);
607 670 }
608 671 } else {
609 - $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 + }
610 678 }
611 679 }
612 680 }
613 681 // return $formSettings;
614 682 // Email Template [end] */
615 - if (!empty($pdfTem)) {
616 - $pdfTemplateHandler = new PdfTemplateHandler($formID);
683 + if (!empty($pdfTem) && class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
684 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
617 685
618 686 foreach ($pdfTem as $templateKey => $templateDetail) {
619 687 if (isset($templateDetail->setting->font->name)) {
620 688 $this->pdfFontDownload($templateDetail->setting->font->name);
@@ -634,8 +702,15 @@
634 702 if (!empty($formSettings->confirmation->type)) {
635 703 $allIntegrations = $formSettings->confirmation->type;
636 704 foreach ($allIntegrations as $integrationType => $integrationGroup) {
637 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 + }
638 713 if (empty($singleIntegrationDetail->details)) {
639 714 $integrationName = $singleIntegrationDetail->title;
640 715 unset($singleIntegrationDetail->title);
641 716 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
@@ -649,13 +724,16 @@
649 724 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
650 725 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
651 726 }
652 727 if (empty($singleIntegrationDetailID)) {
653 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
728 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
654 729 $newData['settingConfiramation'] = 1;
655 730 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
731 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
732 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
733 + }
656 734 } else {
657 - $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
735 + $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
658 736 }
659 737 }
660 738 }
661 739 }
@@ -666,8 +744,11 @@
666 744 $integrationType = $singleIntegrationDetail->type;
667 745 unset($singleIntegrationDetail->type);
668 746 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
669 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);
670 751 if (empty($singleIntegrationDetail->details)) {
671 752 $integrationDetails = !is_string($singleIntegrationDetail) ?
672 753 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
673 754 } else {
@@ -676,8 +757,11 @@
676 757 }
677 758 if (empty($singleIntegrationDetailID)) {
678 759 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
679 760 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
761 + if (!empty($clRef) && !is_wp_error($savedID)) {
762 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
763 + }
680 764 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
681 765 $newData['integation'] = 2;
682 766 } else {
683 767 $newData['integation'] = 1;
@@ -701,8 +785,9 @@
701 785 }
702 786 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
703 787 $workFlowExist['oninput'] = true;
704 788 }
789 + // $integartionIDForWorkflow = apply_filters('bitform_filter_integration_id', $workFlow, $formID, $index);
705 790 if (empty($workFlow->id)) {
706 791 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
707 792 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
708 793 $newData['workflow'] = 2;
@@ -716,8 +801,11 @@
716 801 }
717 802 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
718 803 //wrokFlows [end]
719 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;
720 808 if (!empty($reports)) {
721 809 $reportsModel = new ReportsModel();
722 810 $fieldNames = [];
723 811 foreach ($fields as $key => $field) {
@@ -729,15 +817,19 @@
729 817
730 818 $fieldNames['__user_id'] = __('User', 'bit-form');
731 819 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
732 820 // $fieldNames['__user_location'] = __('');
733 - $fieldNames['__referer'] = __('Refer URL');
734 - $fieldNames['__user_device'] = __('Device');
735 - $fieldNames['__created_at'] = __('Created Time');
736 - $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');
737 825
738 826 $reportIsDefault = null;
739 - 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)) {
740 832 $validDateReport = $reportsModel->validateReportFields($reports, $fieldNames);
741 833 if (isset($reports->isDefault)) {
742 834 $reportIsDefault = $reports->isDefault;
743 835 } else {
@@ -786,9 +878,9 @@
786 878 'form_name' => $form_name,
787 879 'form_content' => $form_content,
788 880 'user_id' => $user_details['id'],
789 881 'user_ip' => $user_details['ip'],
790 - 'builder_helper_state' => \wp_json_encode((object)$builder_helper_state),
882 + 'builder_helper_state' => \wp_json_encode((object) $builder_helper_state),
791 883 'generated_script_page_ids' => \wp_json_encode((object) []),
792 884 'user_device' => $user_details['device'],
793 885 'updated_at' => $user_details['time'],
794 886 ];
@@ -794,15 +886,16 @@
794 886 ];
795 887 if (isset($atomic_class_map)) {
796 888 $updateData['atomic_class_map'] = $atomic_class_map;
797 889 }
798 - $formUpdateVersion = get_option('bit-form_form_update_version');
890 + $formUpdateVersion = get_option('bitform_form_update_version');
799 891 if (!$formUpdateVersion) {
800 892 $formUpdateVersion = 1;
801 893 } else {
802 894 $formUpdateVersion = (int) $formUpdateVersion + 1;
803 895 }
804 - update_option('bit-form_form_update_version', $formUpdateVersion);
896 + update_option('bitform_form_update_version', $formUpdateVersion);
897 + do_action('bitform_admin_form_changed');
805 898
806 899 $update_status = static::$formModel->update(
807 900 $updateData,
808 901 [
@@ -820,9 +913,9 @@
820 913 }
821 914
822 915 $updated_data = $this->getAForm(['id' => $formID], null);
823 916
824 - if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation']) {
917 + if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation'] && 0 === $newData['pdfTemplate']) {
825 918 unset($updated_data['formSettings']);
826 919 }
827 920 if (0 === $newData['integation']) {
828 921 unset($updated_data['integrations']);
@@ -834,13 +927,13 @@
834 927 unset($updated_data['mailTem']);
835 928 } elseif (2 === $newData['mailTemplate']) {
836 929 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
837 930 }
838 - // if (0 === $newData['pdfTemplate']) {
839 - // unset($updated_data['pdfTem']);
840 - // } elseif (2 === $newData['pdfTemplate']) {
841 - // $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
842 - // }
931 + if (0 === $newData['pdfTemplate']) {
932 + unset($updated_data['pdfTem']);
933 + } elseif (2 === $newData['pdfTemplate']) {
934 + $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
935 + }
843 936 if (0 === $newData['workflow']) {
844 937 unset($updated_data['workFlows']);
845 938 } elseif (2 === $newData['workflow']) {
846 939 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
@@ -847,9 +940,14 @@
847 940 }
848 941 if (2 === $newData['reports']) {
849 942 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
850 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 +
851 948 if (!empty($errorIN)) {
949 + /* translators: %s: comma-separated list of areas where error occurred */
852 950 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
853 951 return new WP_Error('Form update Error.', $updated_data);
854 952 }
855 953 if (null !== $reportIsDefault) {
@@ -854,30 +952,77 @@
854 952 }
855 953 if (null !== $reportIsDefault) {
856 954 $updated_data['form_content']['is_default'] = $reportIsDefault;
857 955 }
858 - $updated_data['message'] = __('Form updated successfully.', 'bitform');
956 + $updated_data['message'] = __('Form updated successfully.', 'bit-form');
957 +
859 958 return $updated_data;
860 959 }
861 960 }
862 961
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 +
863 1008 public function setEmptyMetaValue($fieldkeys)
864 1009 {
865 - $sqlEscaped = array_map(function ($fld) {
866 - return "'" . esc_sql($fld) . "'";
867 - }, $fieldkeys);
868 - $deletedFldKey = implode(',', $sqlEscaped);
869 1010 global $wpdb;
870 - $tablename = $wpdb->prefix . 'bitforms_form_entrymeta';
871 - $sql = $wpdb->prepare("UPDATE $tablename SET meta_value = %s WHERE meta_key IN ( " . $deletedFldKey . ')', '');
872 - $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 + ));
873 1018 }
874 1019
875 1020 public function changeFormStatus($Request, $post)
876 1021 {
877 1022 if (isset($Request['status']) && $Request['id']) {
878 - $status = wp_unslash($Request['status']);
879 - $id = wp_unslash($Request['id']);
1023 + $status = sanitize_text_field(wp_unslash($Request['status']));
1024 + $id = absint(wp_unslash($Request['id']));
880 1025 } else {
881 1026 $status = wp_unslash($post->status);
882 1027 $id = wp_unslash($post->id);
883 1028 }
@@ -911,10 +1056,10 @@
911 1056
912 1057 public function changeBulkFormStatus($Request, $post)
913 1058 {
914 1059 if (isset($Request['status']) && $Request['formID']) {
915 - $status = wp_unslash($Request['status']);
916 - $formID = wp_unslash($Request['formID']);
1060 + $status = sanitize_text_field(wp_unslash($Request['status']));
1061 + $formID = array_map('absint', wp_unslash($Request['formID']));
917 1062 } else {
918 1063 $status = wp_unslash($post->status);
919 1064 $formID = wp_unslash($post->formID);
920 1065 }
@@ -949,9 +1094,13 @@
949 1094 public function getAllForm()
950 1095 {
951 1096 global $wpdb;
952 1097
953 - $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");
954 1103
955 1104 if (is_wp_error($allForms)) {
956 1105 return $allForms;
957 1106 } elseif (!$allForms) {
@@ -962,10 +1111,10 @@
962 1111 }
963 1112
964 1113 public function getAForm($Request, $post)
965 1114 {
966 - if (isset($Request['id'])) {
967 - $formID = wp_unslash($Request['id']);
1115 + if (!empty($Request['id'])) {
1116 + $formID = absint(wp_unslash($Request['id']));
968 1117 } else {
969 1118 $formID = wp_unslash($post->id);
970 1119 }
971 1120 // return $post->fields;
@@ -984,9 +1133,9 @@
984 1133 'nestedLayout' => !empty($form_content->nestedLayout) ? $form_content->nestedLayout : (object) [],
985 1134 'formInfo' => !empty($form_content->formInfo) ? $form_content->formInfo : (object) ['formName' => $formManager->getFormName()],
986 1135 'fields' => $form_content->fields,
987 1136 'form_name' => $formManager->getFormName(),
988 - 'workFlowExist' => $form_content->workFlowExist,
1137 + 'workFlowExist' => isset($form_content->workFlowExist) ? $form_content->workFlowExist : [],
989 1138 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
990 1139 ];
991 1140 $successMessageHandler
992 1141 = new SuccessMessageHandler($formID);
@@ -1009,28 +1158,37 @@
1009 1158 if (!is_wp_error($emailTemplates)) {
1010 1159 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1011 1160 $mailTem[] =
1012 1161 [
1013 - 'id' => $emailTemplatevalue->id,
1014 - 'title' => $emailTemplatevalue->title,
1015 - 'sub' => $emailTemplatevalue->sub,
1016 - '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),
1017 1168 ];
1018 1169 }
1019 1170 }
1020 1171 // get all pdf template
1021 - $pdfTemplateHandler = new PdfTemplateHandler($formID);
1022 - $pdfTemplates = $pdfTemplateHandler->getAll();
1172 + if (class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
1173 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
1174 + $pdfTemplates = $pdfTemplateHandler->getAll();
1023 1175
1024 - if (!is_wp_error($pdfTemplates)) {
1025 - foreach ($pdfTemplates as $value) {
1026 - $pdfTem[] =
1027 - [
1028 - 'id' => $value->id,
1029 - 'title' => $value->title,
1030 - 'setting' => json_decode($value->setting),
1031 - 'body' => $value->body,
1032 - ];
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 + }
1033 1191 }
1034 1192 }
1035 1193
1036 1194 $integrationHandler = new IntegrationHandler($formID);
@@ -1038,10 +1196,11 @@
1038 1196 if (!is_wp_error($formIntegrations)) {
1039 1197 foreach ($formIntegrations as $integrationkey => $integrationValue) {
1040 1198 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1041 1199 $integrationData = [
1042 - 'id' => $integrationValue->id,
1043 - 'title' => $integrationValue->integration_name,
1200 + 'id' => $integrationValue->id,
1201 + 'title' => $integrationValue->integration_name,
1202 + 'status' => isset($integrationValue->status) ? (int) $integrationValue->status : 1,
1044 1203 ];
1045 1204 if (!empty($integrationValue->integration_details)) {
1046 1205 $integration_details = (array) json_decode($integrationValue->integration_details);
1047 1206 $integrationData = array_merge($integration_details, $integrationData);
@@ -1067,11 +1226,26 @@
1067 1226 );
1068 1227 }
1069 1228 }
1070 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 +
1071 1244 $settingsContent = [
1072 - 'formName' => $formManager->getFormName(),
1073 - '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) [],
1074 1248 // 'submitBtn' => $form_content->buttons,
1075 1249 ];
1076 1250
1077 1251 if (!empty($allConfirmation)) {
@@ -1130,8 +1304,24 @@
1130 1304 'pdfTem' => [],
1131 1305 ]
1132 1306 );
1133 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 + }
1134 1324 $formSettings = [
1135 1325 'formSettings' => $settingsContent,
1136 1326 ];
1137 1327 $data = [
@@ -1142,12 +1332,14 @@
1142 1332 'style' => $helper_states->style,
1143 1333 'themeVars' => $helper_states->themeVars,
1144 1334 'themeColors' => $helper_states->themeColors,
1145 1335 'builderSettings' => $helper_states->builderSettings,
1336 + 'customCode' => FrontEndScriptGenerator::getCustomCodes($formID),
1146 1337 'additional' => empty($form_content->additional) ? [
1147 1338 'enabled' => [
1148 1339 'blocked_ip' => false,
1149 1340 'restrict_form' => false,
1341 + 'onePerIp' => false,
1150 1342 ],
1151 1343 'settings' => [
1152 1344 'restrict_form' => [
1153 1345 'day' => [],
@@ -1162,9 +1354,8 @@
1162 1354 ],
1163 1355 'entry_limit' => null,
1164 1356 'blocked_ip' => [],
1165 1357 ],
1166 - 'onePerIp' => false,
1167 1358 ] : $form_content->additional,
1168 1359 'created_at' => $formManager->getFormMetaData()['created_at'],
1169 1360 'views' => $formManager->getFormMetaData()['views'],
1170 1361 'entries' => $formManager->getFormMetaData()['entries'],
@@ -1205,9 +1396,9 @@
1205 1396 } else {
1206 1397 $returnedReportData[$reportKey]->details = [];
1207 1398 }
1208 1399 if ('1' === (string) $reportData->isDefault) {
1209 - $returnedReportData[$reportKey]->details->report_name = 'All Entries';
1400 + $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1210 1401 }
1211 1402 }
1212 1403 $reports = ['reports' => $returnedReportData];
1213 1404 $data = array_merge($data, $reports);
@@ -1219,12 +1410,233 @@
1219 1410 return $data;
1220 1411 }
1221 1412 }
1222 1413
1414 + public function getAFormV1($Request, $post)
1415 + {
1416 + if (!empty($Request['id'])) {
1417 + $formID = absint(wp_unslash($Request['id']));
1418 + } else {
1419 + $formID = wp_unslash($post->id);
1420 + }
1421 + // return $post->fields;
1422 + if (is_null($formID)) {
1423 + return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
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 +
1223 1635 public function deleteAForm($Request, $post)
1224 1636 {
1225 - if (isset($Request['id'])) {
1226 - $formID = wp_unslash($Request['id']);
1637 + if (!empty($Request['id'])) {
1638 + $formID = absint(wp_unslash($Request['id']));
1227 1639 } else {
1228 1640 $formID = wp_unslash($post->id);
1229 1641 }
1230 1642 if (is_null($formID)) {
@@ -1229,24 +1641,30 @@
1229 1641 }
1230 1642 if (is_null($formID)) {
1231 1643 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1232 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 +
1233 1650 $delete_status = static::$formModel->delete(
1234 1651 [
1235 1652 'id' => $formID,
1236 1653 ]
1237 1654 );
1655 + do_action('bitform_admin_form_changed');
1238 1656
1239 - $successMessageModel
1240 - = new SuccessMessageModel();
1657 + $successMessageModel = new SuccessMessageModel();
1241 1658 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1242 1659
1243 - $emailTemplateModel
1244 - = new EmailTemplateModel();
1660 + $emailTemplateModel = new EmailTemplateModel();
1245 1661 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1246 1662
1247 - $pdfTemplateModel = new PdfTemplateModel();
1248 - $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
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 + }
1249 1667
1250 1668 $integrationModel = new IntegrationModel();
1251 1669 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1252 1670
@@ -1259,22 +1677,11 @@
1259 1677 $formEntryModel = new FormEntryModel();
1260 1678 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1261 1679 $entries = [];
1262 1680
1263 - if (!is_wp_error($returnedEntries)) {
1264 - foreach ($returnedEntries as $entryKey => $entryInfo) {
1265 - $entries[] = $entryInfo->id;
1266 - }
1267 - global $wpdb;
1268 - $prefix = $wpdb->prefix;
1269 - if (count($entries) > 0) {
1270 - $deleteEntriesStatus = $formEntryModel->bulkDelete(
1271 - [
1272 - "`{$prefix}bitforms_form_entries`.`id`" => $entries,
1273 - "`{$prefix}bitforms_form_entries`.`form_id`" => $formID,
1274 - ]
1275 - );
1276 - }
1681 + // checked namespace exist
1682 + if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1683 + \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByFormId($formID);
1277 1684 }
1278 1685
1279 1686 $fileHandler = new FileHandler();
1280 1687 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
@@ -1282,45 +1689,54 @@
1282 1689 }
1283 1690 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1284 1691 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1285 1692 }
1286 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css')) {
1287 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css');
1288 - }
1289 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css')) {
1290 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css');
1291 - }
1292 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css')) {
1293 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css');
1294 - }
1295 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js')) {
1296 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js');
1297 - }
1298 - if (file_exists(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css')) {
1299 - unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css');
1300 - }
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 +
1301 1710 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1302 1711 }
1303 1712
1304 1713 public function deleteBlukForm($Request, $post)
1305 1714 {
1306 - if (isset($Request['formID'])) {
1307 - $formID = wp_unslash($Request['formID']);
1715 + if (!empty($Request['formID'])) {
1716 + $formID = array_map('absint', wp_unslash($Request['formID']));
1308 1717 } else {
1309 1718 $formID = wp_unslash($post->formID);
1310 1719 }
1720 +
1311 1721 if (is_null($formID) || !is_array($formID)) {
1312 1722 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1313 1723 }
1724 +
1725 + if (!Helpers::checkIsIntArr($formID)) {
1726 + return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
1727 + }
1728 +
1314 1729 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1315 1730 foreach ($formID as $id) {
1316 - unlink($cssPath . 'bitform-' . $id . '.css');
1317 - if (file_exists($cssPath . 'bitform-layout-' . $id . '.css')) {
1318 - unlink($cssPath . 'bitform-layout-' . $id . '.css');
1319 - }
1320 - if (file_exists($cssPath . 'bitform-' . $id . '-formid' . '.css')) {
1321 - unlink($cssPath . 'bitform-' . $id . '-formid' . '.css');
1322 - }
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);
1323 1739 }
1324 1740 $delete_status = static::$formModel->bulkDelete(
1325 1741 [
1326 1742 'id' => $formID,
@@ -1325,16 +1741,26 @@
1325 1741 [
1326 1742 'id' => $formID,
1327 1743 ]
1328 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 +
1329 1751 $successMessageModel
1330 1752 = new SuccessMessageModel();
1331 1753 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1332 1754
1333 - $emailTemplateModel
1334 - = new EmailTemplateModel();
1755 + $emailTemplateModel = new EmailTemplateModel();
1335 1756 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1336 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 +
1337 1763 $integrationModel = new IntegrationModel();
1338 1764 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1339 1765
1340 1766 $workFlowModel = new WorkFlowModel();
@@ -1344,8 +1770,13 @@
1344 1770 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1345 1771
1346 1772 $formEntryModel = new FormEntryModel();
1347 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 +
1348 1779 $entries = [];
1349 1780 foreach ($returnedEntries as $entryKey => $entryInfo) {
1350 1781 if (!empty($entryInfo->id)) {
1351 1782 $entries[] = $entryInfo->id;
@@ -1361,16 +1792,19 @@
1361 1792 ]
1362 1793 );
1363 1794 }
1364 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 +
1365 1802 $fileHandler = new FileHandler();
1366 1803 foreach ($formID as $fId) {
1367 1804 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1368 1805 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1369 1806 }
1370 -
1371 - // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-' . $fId . '.css');
1372 - // unlink(BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR . 'bitform-layout-' . $fId . '.css');
1373 1807 }
1374 1808
1375 1809 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1376 1810 }
@@ -1412,21 +1846,15 @@
1412 1846 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1413 1847 // duplicate stylesheet
1414 1848 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1415 1849 // layout style copy
1416 - $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1417 - $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1850 + $styleStr = FileHandler::readFile($style_dir . 'bitform-layout-' . $oldFormId . '.css');
1418 1851 $newStyle = str_replace(".bf$oldFormId-", ".bf$newFormId-", $styleStr);
1419 - $createStyleFile = fopen($style_dir . "bitform-layout-$newFormId.css", 'w');
1420 - fwrite($createStyleFile, $newStyle);
1421 - fclose($createStyleFile);
1852 + FileHandler::writeFile($style_dir . "bitform-layout-$newFormId.css", $newStyle);
1422 1853 // style copy
1423 - $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1424 - $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1854 + $styleStr = FileHandler::readFile($style_dir . 'bitform-' . $oldFormId . '.css');
1425 1855 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1426 - $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1427 - fwrite($createStyleFile, $newStyle);
1428 - fclose($createStyleFile);
1856 + FileHandler::writeFile($style_dir . "bitform-$newFormId.css", $newStyle);
1429 1857 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1430 1858 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1431 1859 return $duplicatedForm;
1432 1860 }
@@ -1439,15 +1867,15 @@
1439 1867 $newFormId = intval($post->newFormId);
1440 1868 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1441 1869 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1442 1870 }
1443 - $importtedForm = (array)$post->formDetail;
1871 + $importtedForm = (array) $post->formDetail;
1444 1872 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1445 1873 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1446 - $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayout'];
1874 + $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayouts'];
1447 1875 $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1448 1876 unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1449 - $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1877 + $formData = FormDuplicateHelper::createReplica((array) $importtedForm, $oldFormId, $newFormId);
1450 1878
1451 1879 if (!empty($importtedForm['rowHeight'])) {
1452 1880 $formData->rowHeight = $importtedForm['rowHeight'];
1453 1881 }
@@ -1457,10 +1885,29 @@
1457 1885 $formData->layoutChanged = '-';
1458 1886 }
1459 1887 $importResponse = $this->createNewForm(null, $formData);
1460 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 + }
1461 1907 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1462 1908 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1909 + $responseData['customCode'] = $customCode;
1463 1910 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1464 1911 return $responseData;
1465 1912 }
1466 1913 return $importResponse;
@@ -1515,9 +1962,9 @@
1515 1962 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1516 1963 }
1517 1964
1518 1965 $newFormId = $oldFormId;
1519 - $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1966 + $duplicatedForm = $this->getAForm($Request, (object) ['id' => $oldFormId]);
1520 1967 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1521 1968 // for custom css
1522 1969 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1523 1970 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
@@ -1537,10 +1984,10 @@
1537 1984 }
1538 1985
1539 1986 public function getFormEntryLabelAndCount($Request, $post)
1540 1987 {
1541 - if (isset($Request['id'])) {
1542 - $id = wp_unslash($Request['id']);
1988 + if (!empty($Request['id'])) {
1989 + $id = absint(wp_unslash($Request['id']));
1543 1990 } else {
1544 1991 $id = wp_unslash($post->id);
1545 1992 }
1546 1993 if (is_null($id)) {
@@ -1593,16 +2040,74 @@
1593 2040 $response['fieldDetails'] = $labels;
1594 2041 return $response;
1595 2042 }
1596 2043
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 +
1597 2101 public function getFormEntry($Request, $post)
1598 2102 {
1599 - if (isset($Request['id'])) {
1600 - $id = wp_unslash($Request['id']);
2103 + if (!empty($Request['id'])) {
2104 + $id = absint(wp_unslash($Request['id']));
1601 2105 $offset = isset($Request['offset']) ?
1602 2106 wp_unslash($Request['offset']) : 0;
1603 2107 $pageSize = isset($Request['pageSize']) ?
1604 2108 wp_unslash($Request['pageSize']) : 10;
2109 + $queryCondition = isset($Request['queryCondition']) ? wp_unslash($Request['queryCondition']) : ['form_id' => $id];
1605 2110 } else {
1606 2111 $id = wp_unslash($post->id);
1607 2112 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1608 2113 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
@@ -1611,9 +2116,11 @@
1611 2116 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1612 2117 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1613 2118 $pageSize = isset($post->pageSize) ?
1614 2119 wp_unslash($post->pageSize) : 10;
2120 + $queryCondition = isset($post->queryCondition) ? wp_unslash($post->queryCondition) : ['form_id' => $id];
1615 2121 }
2122 + $queryCondition = $this->sanitizeEntryQueryCondition($queryCondition, $id);
1616 2123 if (is_null($id)) {
1617 2124 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1618 2125 }
1619 2126 $formManager = new AdminFormManager($id);
@@ -1619,15 +2126,12 @@
1619 2126 $formManager = new AdminFormManager($id);
1620 2127 if (!$formManager->isExist()) {
1621 2128 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1622 2129 }
1623 -
1624 2130 $formEntry = new FormEntryModel();
1625 2131 $entries = $formEntry->get(
1626 2132 'id',
1627 - [
1628 - 'form_id' => $id,
1629 - ],
2133 + $queryCondition,
1630 2134 null,
1631 2135 null,
1632 2136 'created_at',
1633 2137 'DESC'
@@ -1653,12 +2157,36 @@
1653 2157 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1654 2158 return $formEntries;
1655 2159 }
1656 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 +
1657 2185 public function getEntriesForReport($Request, $post)
1658 2186 {
1659 - if (isset($Request['id'])) {
1660 - $id = wp_unslash($Request['id']);
2187 + if (!empty($Request['id'])) {
2188 + $id = absint(wp_unslash($Request['id']));
1661 2189 $offset = isset($Request['offset']) ?
1662 2190 wp_unslash($Request['offset']) : null;
1663 2191 $pageSize = isset($Request['pageSize']) ?
1664 2192 wp_unslash($Request['pageSize']) : null;
@@ -1719,8 +2247,9 @@
1719 2247 {
1720 2248 $formId = wp_unslash($post->formId);
1721 2249 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1722 2250 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
2251 + $entryCondition = isset($post->filter) ? wp_unslash($post->filter) : null;
1723 2252 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1724 2253 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1725 2254 $formFields = json_decode($post->selectedField);
1726 2255 if (is_null($formId)) {
@@ -1753,17 +2282,17 @@
1753 2282 return $entries;
1754 2283 }
1755 2284 $entryMeta = new FormEntryMetaModel();
1756 2285 $filter = [];
1757 - $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
2286 + $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField, $offset, $entryCondition);
1758 2287 return $formEntries;
1759 2288 }
1760 2289
1761 2290 public function deleteBlukFormEntries($Request, $post)
1762 2291 {
1763 - if (isset($Request['formID'])) {
1764 - $formID = wp_unslash($Request['formID']);
1765 - $entries = wp_unslash($Request['entries']);
2292 + if (!empty($Request['formID'])) {
2293 + $formID = absint(wp_unslash($Request['formID']));
2294 + $entries = array_map('absint', wp_unslash($Request['entries']));
1766 2295 } else {
1767 2296 $formID = wp_unslash($post->formID);
1768 2297 $entries = wp_unslash($post->entries);
1769 2298 }
@@ -1769,21 +2298,32 @@
1769 2298 }
1770 2299 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1771 2300 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1772 2301 }
2302 +
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 +
1773 2311 $formManager = new AdminFormManager($formID);
1774 2312 if (!$formManager->isExist()) {
1775 2313 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1776 2314 }
1777 2315 $workFlowRunHelper = new WorkFlow($formID);
2316 +
1778 2317 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1779 2318 $formManager,
1780 2319 $formID,
1781 2320 $entries
1782 2321 );
2322 +
1783 2323 if (isset($workFlowreturnedOnDelete['entries'])) {
1784 2324 if (0 === count($workFlowreturnedOnDelete['entries'])) {
1785 - return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
2325 + return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1786 2326 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1787 2327 $message = __('Entry Deleted successfully', 'bit-form');
1788 2328 } else {
1789 2329 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
@@ -1804,9 +2344,9 @@
1804 2344 );
1805 2345 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1806 2346 $fileHandler = new FileHandler();
1807 2347 foreach ($entries as $enrtyKey => $entryID) {
1808 - $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
2348 + $fileEntries = $fileHandler->getEntriesFileUploadDir($formID, $entryID);
1809 2349 if (file_exists($fileEntries)) {
1810 2350 $fileHandler->rmrf($fileEntries);
1811 2351 }
1812 2352 }
@@ -1825,11 +2365,11 @@
1825 2365 }
1826 2366
1827 2367 public function duplicateFormEntry($Request, $post)
1828 2368 {
1829 - if (isset($Request['formID'])) {
1830 - $formID = wp_unslash($Request['formID']);
1831 - $entries = wp_unslash($Request['entries']);
2369 + if (!empty($Request['formID'])) {
2370 + $formID = absint(wp_unslash($Request['formID']));
2371 + $entries = array_map('absint', wp_unslash($Request['entries']));
1832 2372 } else {
1833 2373 $formID = wp_unslash($post->formID);
1834 2374 $entries = wp_unslash($post->entries);
1835 2375 }
@@ -1836,8 +2376,16 @@
1836 2376 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1837 2377 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1838 2378 }
1839 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 +
1840 2388 $formManager = new AdminFormManager($formID);
1841 2389 if (!$formManager->isExist()) {
1842 2390 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1843 2391 }
@@ -1870,12 +2418,12 @@
1870 2418 );
1871 2419 if ($duplicate_status) {
1872 2420 $result['details'][$entryID] = $duplicatedEntryId;
1873 2421 $duplicate_count = $duplicate_count + 1;
1874 - if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
2422 + if (file_exists(FileHandler::getEntriesFileUploadDir($formID, $entryID))) {
1875 2423 $fileHandler->cpyr(
1876 - BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1877 - BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
2424 + FileHandler::getEntriesFileUploadDir($formID, $entryID),
2425 + FileHandler::getEntriesFileUploadDir($formID, $duplicatedEntryId)
1878 2426 );
1879 2427 }
1880 2428 }
1881 2429 }
@@ -1892,11 +2440,11 @@
1892 2440 }
1893 2441
1894 2442 public function editFormEntry($Request, $post)
1895 2443 {
1896 - if (isset($Request['formID'])) {
1897 - $formID = wp_unslash($Request['formID']);
1898 - $entryID = wp_unslash($Request['entryID']);
2444 + if (!empty($Request['formID'])) {
2445 + $formID = absint(wp_unslash($Request['formID']));
2446 + $entryID = absint(wp_unslash($Request['entryID']));
1899 2447 } else {
1900 2448 $formID = wp_unslash($post->formID);
1901 2449 $entryID = wp_unslash($post->entryID);
1902 2450 }
@@ -1971,15 +2519,16 @@
1971 2519
1972 2520 public function updateFormEntry($Request, $post)
1973 2521 {
1974 2522 if (isset($Request['formID'], $Request['entryID'])) {
1975 - $formID = wp_unslash($Request['formID']);
1976 - $entryID = wp_unslash($Request['entryID']);
2523 + $formID = absint(wp_unslash($Request['formID']));
2524 + $entryID = absint(wp_unslash($Request['entryID']));
1977 2525 unset($Request['action'], $Request['formID'], $Request['entryID']);
1978 2526 }
1979 2527 $formManager = new AdminFormManager($formID);
1980 2528 $formManager->fieldNameReplaceOfPost();
1981 - $updatedValue = wp_unslash($_POST);
2529 + // Called from AdminAjax handler; nonce already verified at AJAX entry before dispatch.
2530 + $updatedValue = is_array($post) ? $post : wp_unslash($_POST);
1982 2531
1983 2532 if (is_null($updatedValue) || !is_array($updatedValue)) {
1984 2533 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1985 2534 }
@@ -1995,11 +2544,11 @@
1995 2544 }
1996 2545
1997 2546 public function getLogHistory($Request, $post)
1998 2547 {
1999 - if (isset($Request['formID'])) {
2000 - $formID = wp_unslash($Request['formID']);
2001 - $entryID = wp_unslash($Request['entryID']);
2548 + if (!empty($Request['formID'])) {
2549 + $formID = absint(wp_unslash($Request['formID']));
2550 + $entryID = absint(wp_unslash($Request['entryID']));
2002 2551 } else {
2003 2552 $formID = wp_unslash($post->formID);
2004 2553 $entryID = wp_unslash($post->entryID);
2005 2554 }
@@ -2019,10 +2568,10 @@
2019 2568 }
2020 2569
2021 2570 public function importDataStore($Request, $post)
2022 2571 {
2023 - if (isset($Request['formID'])) {
2024 - $formID = wp_unslash($Request['formID']);
2572 + if (!empty($Request['formID'])) {
2573 + $formID = absint(wp_unslash($Request['formID']));
2025 2574 } else {
2026 2575 $formID = wp_unslash($post->formID);
2027 2576 }
2028 2577 if (is_null($formID)) {
@@ -2034,10 +2583,14 @@
2034 2583 {
2035 2584 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
2036 2585 $allPages = [];
2037 2586 foreach ($pages as $pageKey => $pageDetails) {
2038 - $allPages[$pageKey]['title'] = $pageDetails->post_title;
2039 - $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 + ];
2040 2593 }
2041 2594 return $allPages;
2042 2595 }
2043 2596
@@ -2042,11 +2595,11 @@
2042 2595 }
2043 2596
2044 2597 public function deleteAIntegration($Request, $post)
2045 2598 {
2046 - if (isset($Request['formID']) && $Request['id']) {
2047 - $formID = json_decode(wp_unslash($Request['formID']));
2048 - $id = wp_unslash($Request['id']);
2599 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2600 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2601 + $id = absint(wp_unslash($Request['id']));
2049 2602 } else {
2050 2603 $formID = wp_unslash($post->formID);
2051 2604 $id = wp_unslash($post->id);
2052 2605 }
@@ -2066,11 +2619,11 @@
2066 2619 }
2067 2620
2068 2621 public function deleteSuccessMessage($Request, $post)
2069 2622 {
2070 - if (isset($Request['formID']) && $Request['id']) {
2071 - $formID = json_decode(wp_unslash($Request['formID']));
2072 - $id = wp_unslash($Request['id']);
2623 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2624 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2625 + $id = absint(wp_unslash($Request['id']));
2073 2626 } else {
2074 2627 $formID = wp_unslash($post->formID);
2075 2628 $id = wp_unslash($post->id);
2076 2629 }
@@ -2089,11 +2642,11 @@
2089 2642 }
2090 2643
2091 2644 public function deleteAWorkflow($Request, $post)
2092 2645 {
2093 - if (isset($Request['formID']) && $Request['id']) {
2094 - $formID = json_decode(wp_unslash($Request['formID']));
2095 - $id = wp_unslash($Request['id']);
2646 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2647 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2648 + $id = absint(wp_unslash($Request['id']));
2096 2649 } else {
2097 2650 $formID = wp_unslash($post->formID);
2098 2651 $id = wp_unslash($post->id);
2099 2652 }
@@ -2111,11 +2664,11 @@
2111 2664 }
2112 2665
2113 2666 public function deleteAMailTemplate($Request, $post)
2114 2667 {
2115 - if (isset($Request['formID']) && $Request['id']) {
2116 - $formID = json_decode(wp_unslash($Request['formID']));
2117 - $id = wp_unslash($Request['id']);
2668 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2669 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2670 + $id = absint(wp_unslash($Request['id']));
2118 2671 } else {
2119 2672 $formID = wp_unslash($post->formID);
2120 2673 $id = wp_unslash($post->id);
2121 2674 }
@@ -2133,11 +2686,11 @@
2133 2686 }
2134 2687
2135 2688 public function duplicateAMailTemplate($Request, $post)
2136 2689 {
2137 - if (isset($Request['formID']) && $Request['id']) {
2138 - $formID = json_decode(wp_unslash($Request['formID']));
2139 - $id = wp_unslash($Request['id']);
2690 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2691 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2692 + $id = absint(wp_unslash($Request['id']));
2140 2693 } else {
2141 2694 $formID = wp_unslash($post->formID);
2142 2695 $id = wp_unslash($post->id);
2143 2696 }
@@ -2143,8 +2696,17 @@
2143 2696 }
2144 2697 if (empty($formID) || empty($id)) {
2145 2698 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2146 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 +
2147 2709 $emailTemplateHandler = new EmailTemplateHandler($formID);
2148 2710 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
2149 2711 if (is_wp_error($duplicate_status)) {
2150 2712 return $duplicate_status;
@@ -2285,22 +2847,34 @@
2285 2847 }
2286 2848 if (is_string($paySetting)) {
2287 2849 $paySetting = json_decode($paySetting);
2288 2850 }
2851 +
2289 2852 $canSave = null;
2290 -
2291 - if ('PayPal' === $paySetting->type) {
2292 - $canSave = $this->addWebhookToPaypal($paySetting);
2293 - } elseif ('Razorpay' === $paySetting->type) {
2294 - $canSave = true;
2295 - } elseif ('Stripe' === $paySetting->type) {
2296 - $canSave = $this->addWebhookToStripe($paySetting);
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;
2297 2868 }
2298 2869 if (is_null($canSave)) {
2299 2870 return new WP_Error('stripe', __('Please re-check your Client ID & Secret', 'bit-form'));
2300 2871 }
2301 - $integrationID = $paySetting->id;
2302 - unset($paySetting->id);
2872 + $integrationID = null;
2873 + if (isset($paySetting->id)) {
2874 + $integrationID = $paySetting->id;
2875 + unset($paySetting->id);
2876 + }
2303 2877 $integrationName = $paySetting->name;
2304 2878 $integrationType = 'payments';
2305 2879 $paySetting = wp_json_encode($paySetting);
2306 2880 $integrationDetails = $paySetting;
@@ -2378,15 +2952,16 @@
2378 2952 }
2379 2953 }
2380 2954
2381 2955 $data = [
2382 - 'enabled_events[]' => 'payment_intent.succeeded',
2383 - 'url' => $webhook_url,
2956 + 'enabled_events[]' => 'payment_intent.succeeded',
2957 + 'url' => $webhook_url,
2384 2958 ];
2385 2959
2386 2960 if (!$webhook_already_exist) {
2387 2961 $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2388 2962 if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2963 + Log::debug_log(['Stripe webhook creation failed' => $webhook_response]);
2389 2964 return null;
2390 2965 }
2391 2966 }
2392 2967 return true;
@@ -2429,10 +3004,70 @@
2429 3004 return true;
2430 3005 }
2431 3006 }
2432 3007
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 +
2433 3049 public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
2434 3050 {
2435 3051 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2436 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);
2437 3072 }
2438 3073 }