PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / V3.3.2
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder vV3.3.2
V3.3.2 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 All 139 releases
← All changes | includes/Admin/Form/AdminFormHandler.php +880 -238 2.10.0 → V3.3.2 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,13 @@
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);
248 + FormManager::syncCompositeChildNames($fields);
253 249 $form_content = [
254 250 'fields' => $fields,
255 251 'layout' => $layout,
256 252 'nestedLayout' => $nestedLayout,
@@ -263,8 +259,12 @@
263 259 if (!empty($formSettings->theme)) {
264 260 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
265 261 }
266 262
263 + if (!empty($formSettings->formPermissions)) {
264 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
265 + }
266 +
267 267 if (!empty($additional)) {
268 268 $form_content = array_merge($form_content, ['additional' => $additional]);
269 269 }
270 270 if (!empty($workFlows)) {
@@ -312,10 +312,11 @@
312 312 return $save_status;
313 313 } elseif (!$save_status) {
314 314 return false;
315 315 } else {
316 - wp_mkdir_p(BITFORMS_UPLOAD_DIR . "/$save_status");
316 + FileHandler::createIndexFile(BITFORMS_UPLOAD_DIR . "/$save_status");
317 317 $formID = $save_status;
318 + do_action('bitform_admin_form_changed');
318 319 $integartionIDForWorkflow = [];
319 320 // Confiramtion Message [start]
320 321 if (!empty($formSettings->confirmation->type->successMsg)) {
321 322 $successMessages = $formSettings->confirmation->type->successMsg;
@@ -324,8 +325,11 @@
324 325 $savedID = $successMessageHandler->saveMessage($messageDetail);
325 326 if ($savedID) {
326 327 $msgIdx = empty($messageDetail->id) ? $messageKey : wp_json_encode(['id' => $messageDetail->id]);
327 328 $integartionIDForWorkflow['successMsg'][$msgIdx] = $savedID;
329 + if (!empty($messageDetail->clRef)) {
330 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
331 + }
328 332 $messageDetail->id = $savedID;
329 333 $style = $this->updateSuccessMessageClassName($style, $messageKey, $savedID);
330 334 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
331 335 }
@@ -338,10 +342,10 @@
338 342 'builderSettings' => $builderSettings
339 343 ];
340 344 $update_status = static::$formModel->update(
341 345 [
342 - 'builder_helper_state' => \wp_json_encode($builder_helper_state),
343 - 'atomic_class_map' => $atomic_class_map,
346 + 'builder_helper_state' => \wp_json_encode($builder_helper_state),
347 + 'atomic_class_map' => $atomic_class_map,
344 348 ],
345 349 [
346 350 'id' => $formID,
347 351 ]
@@ -358,31 +362,55 @@
358 362 $emailTemplateHandler
359 363 = new EmailTemplateHandler($formID, $user_details);
360 364 foreach ($mailTem as $templateKey => $templateDetail) {
361 365 $savedID = $emailTemplateHandler->saveTemplate($templateDetail);
362 - if ($savedID) {
366 + if ($savedID && !is_wp_error($savedID)) {
363 367 $tempIdx = empty($templateDetail->id) ? $templateKey : wp_json_encode(['id' => $templateDetail->id]);
364 368 $integartionIDForWorkflow['mailNotify'][$tempIdx] = $savedID;
369 + if (!empty($templateDetail->clRef)) {
370 + $integartionIDForWorkflow['emailCLRef'][$templateDetail->clRef] = $savedID;
371 + }
372 + // return the new id (and drop the temp ref) so the frontend reconciles the template
373 + $templateDetail->id = $savedID;
374 + unset($templateDetail->clRef);
365 375 }
366 376 }
367 377 }
368 378 // Email Template [end] */
369 - // if (!empty($pdfTem)) {
370 - // $pdfTemplateHandler = new PdfTemplateHandler($formID);
371 - // foreach ($pdfTem as $templateKey => $templateDetail) {
372 - // $savedID = $pdfTemplateHandler->save($templateDetail);
373 379
374 - // $pdfSetting = $templateDetail->setting;
380 + // PDF Template [start]
381 + if (!empty($pdfTem) && class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
382 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
383 + $workFlowString = '';
384 + if (!empty($workFlows)) {
385 + $workFlowString = wp_json_encode($workFlows);
386 + }
387 + foreach ($pdfTem as $templateDetail) {
388 + $savedID = $pdfTemplateHandler->save($templateDetail);
375 389
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 - // }
390 + $pdfSetting = $templateDetail->setting;
391 +
392 + if (isset($pdfSetting->font->name) && !empty($pdfSetting->font->name)) {
393 + $this->pdfFontDownload($pdfSetting->font->name);
394 + }
395 + if (!empty($workFlowString)) {
396 + $workFlowString = str_replace('"pdfId":"{\"id\":\"' . $templateDetail->id . '\"}"', '"pdfId":"{\"id\":\"' . $savedID . '\"}"', $workFlowString);
397 + // Multi-PDF: remap ids inside "pdfIds":[...] segments only — email-template ids use
398 + // the same {\"id\":N} token shape, so a global replace would corrupt them.
399 + $workFlowString = preg_replace_callback(
400 + '/"pdfIds":\[[^\]]*\]/',
401 + function ($matches) use ($templateDetail, $savedID) {
402 + return str_replace('{\"id\":\"' . $templateDetail->id . '\"}', '{\"id\":\"' . $savedID . '\"}', $matches[0]);
403 + },
404 + $workFlowString
405 + );
406 + }
407 + }
408 + if (!empty($workFlowString) && !empty($workFlows)) {
409 + $workFlows = json_decode($workFlowString);
410 + }
411 + }
412 + // PDF Template [end] */
385 413 //Integration [start] */
386 414 $integrationHandler = new IntegrationHandler($formID, $user_details);
387 415 if (!empty($formSettings->confirmation->type)) {
388 416 $allIntegrations = $formSettings->confirmation->type;
@@ -387,8 +415,14 @@
387 415 if (!empty($formSettings->confirmation->type)) {
388 416 $allIntegrations = $formSettings->confirmation->type;
389 417 foreach ($allIntegrations as $integrationType => $integrationGroup) {
390 418 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
419 + $integrationStatus = isset($singleIntegrationDetail->status) ? (int) $singleIntegrationDetail->status : 1;
420 + // Inline-CL temp ref for a brand-new redirect (reconciled to the real id for workflow rows).
421 + $clRef = isset($singleIntegrationDetail->clRef) ? $singleIntegrationDetail->clRef : null;
422 + if (is_object($singleIntegrationDetail)) {
423 + unset($singleIntegrationDetail->status, $singleIntegrationDetail->clRef);
424 + }
391 425 if (empty($singleIntegrationDetail->details)) {
392 426 $integrationName = $singleIntegrationDetail->title;
393 427 unset($singleIntegrationDetail->title, $singleIntegrationDetail->id);
394 428
@@ -398,14 +432,25 @@
398 432 $integrationName = $singleIntegrationDetail->title;
399 433 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
400 434 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
401 435 }
402 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
436 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
403 437 $integIdx = empty($singleIntegrationDetail->id) ? $savedID : wp_json_encode(['id' => $singleIntegrationDetail->id]);
404 438 $integartionIDForWorkflow[$integrationType][$integIdx] = $savedID;
439 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
440 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
441 + }
405 442 }
406 443 }
407 444 }
445 + if (isset($formSettings->formAbandonment)) {
446 + $formAbandonment = $formSettings->formAbandonment;
447 +
448 + $integrationName = 'formAbandonment';
449 + $integrationType = 'formAbandonment';
450 + $abandonmentIntegDetails = wp_json_encode($formAbandonment);
451 + $integrationHandler->saveIntegration($integrationName, $integrationType, $abandonmentIntegDetails, 'formAbandonment');
452 + }
408 453 if (!empty($integrations)) {
409 454 foreach ($integrations as $singleIntegrationKey => $singleIntegrationDetail) {
410 455 $integrationName = $singleIntegrationDetail->name;
411 456 unset($singleIntegrationDetail->name);
@@ -412,8 +457,11 @@
412 457 $integrationType = $singleIntegrationDetail->type;
413 458 unset($singleIntegrationDetail->type);
414 459 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
415 460 unset($singleIntegrationDetail->id);
461 + // Inline-CL temp ref for a brand-new integration (reconciled to the real id for workflow rows).
462 + $clRef = isset($singleIntegrationDetail->__bf_cl_ref) ? $singleIntegrationDetail->__bf_cl_ref : null;
463 + unset($singleIntegrationDetail->__bf_cl_ref);
416 464 if (empty($singleIntegrationDetail->details)) {
417 465 $integrationDetails = !is_string($singleIntegrationDetail) ?
418 466 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
419 467 } else {
@@ -422,8 +470,11 @@
422 470 }
423 471 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
424 472 $integIdx = empty($singleIntegrationDetailID) ? $singleIntegrationKey : wp_json_encode(['id' => $singleIntegrationDetailID]);
425 473 $integartionIDForWorkflow['integ'][$integIdx] = $savedID;
474 + if (!empty($clRef) && !is_wp_error($savedID)) {
475 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
476 + }
426 477 }
427 478 }
428 479 //Integrations [end]
429 480 //wrokFlows [start]
@@ -443,9 +494,9 @@
443 494 // }
444 495 }
445 496 //wrokFlows [end]
446 497 $details = [
447 - 'report_name' => 'All Entries',
498 + 'report_name' => __('All Entries', 'bit-form'),
448 499 'hiddenColumns' => ['__user_id', '__user_ip', '__referer', '__user_device', '__created_at', '__updated_at'],
449 500 'pageSize' => 10,
450 501 'sortBy' => [],
451 502 'filters' => [],
@@ -474,8 +525,12 @@
474 525 $updated_data['form_content']['is_default'] = 1;
475 526 }
476 527 $updated_data['message'] = __('Form Saved successfully', 'bit-form');
477 528
529 + // Form and dependent rows are persisted; multilingual providers register
530 + // the form's translatable strings here.
531 + do_action('bitform_form_saved', $save_status);
532 +
478 533 return $updated_data;
479 534 }
480 535 }
481 536
@@ -505,13 +560,14 @@
505 560 if (property_exists($post, 'builderSettings')) {
506 561 $builder_helper_state->builderSettings = $post->builderSettings;
507 562 }
508 563 if (property_exists($post, 'atomicClassMap')) {
509 - $atomic_class_map = \wp_json_encode((object)$post->atomicClassMap);
564 + $atomic_class_map = \wp_json_encode((object) $post->atomicClassMap);
510 565 }
511 566
512 567 if (property_exists($post, 'fields') && null !== $post->fields && property_exists($post, 'layout') && $post->layout) {
513 568 $fields = wp_unslash($post->fields);
569 + $fields = Helpers::replaceFieldsDefaultErrorMsg($fields);
514 570 $layout = wp_unslash($post->layout);
515 571 $nestedLayout = wp_unslash($post->nestedLayouts);
516 572 $formInfo = wp_unslash($post->formInfo);
517 573 $formID = wp_unslash($post->id);
@@ -531,16 +587,11 @@
531 587 if (empty($fields) || empty($layout) || is_null($formID)) {
532 588 return new WP_Error('empty_form', 'Can not update empty form.');
533 589 }
534 590
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 - }
591 + // Guard: never persist orphan fields (see createNewForm). Fail closed.
592 + $this->pruneOrphanFields($fields, $nestedLayout, $layout, $formID, $post);
593 + FormManager::syncCompositeChildNames($fields);
543 594
544 595 $form_content = [
545 596 'fields' => $fields,
546 597 'layout' => $layout,
@@ -557,8 +608,12 @@
557 608 } */
558 609 if (!empty($formSettings->theme)) {
559 610 $form_content = array_merge($form_content, ['theme' => $formSettings->theme]);
560 611 }
612 +
613 + if (!empty($formSettings->formPermissions)) {
614 + $form_content = array_merge($form_content, ['formPermissions' => $formSettings->formPermissions]);
615 + }
561 616 if (!empty($additional)) {
562 617 $form_content = array_merge($form_content, ['additional' => $additional]);
563 618 }
564 619 $integartionIDForWorkflow = [];
@@ -566,8 +621,9 @@
566 621 $newData['integation'] = 0;
567 622 $newData['mailTemplate'] = 0;
568 623 $newData['workflow'] = 0;
569 624 $newData['reports'] = 0;
625 + $newData['pdfTemplate'] = 0;
570 626 // Confiramtion Message [start]
571 627 if (!empty($formSettings->confirmation->type->successMsg)) {
572 628 $successMessages = $formSettings->confirmation->type->successMsg;
573 629 $successMessageHandler
@@ -577,8 +633,11 @@
577 633 $savedID = $successMessageHandler->saveMessage($messageDetail);
578 634 if ($savedID) {
579 635 $newData['settingConfiramation'] = 1;
580 636 $integartionIDForWorkflow['successMsg'][$messageKey] = $savedID;
637 + if (!empty($messageDetail->clRef)) {
638 + $integartionIDForWorkflow['confirmationCLRef'][$messageDetail->clRef] = $savedID;
639 + }
581 640 $messageDetail->id = $savedID;
582 641 $builder_helper_state->style = $this->updateSuccessMessageClassName($builder_helper_state->style, $messageKey, $savedID);
583 642 if (isset($atomic_class_map)) {
584 643 $atomic_class_map = $this->updateSuccessMessageClassName($atomic_class_map, $messageKey, $savedID);
@@ -603,18 +662,29 @@
603 662 $newData['mailTemplate'] = 2;
604 663 } else {
605 664 $newData['mailTemplate'] = 1;
606 665 $integartionIDForWorkflow['mailTem'][$templateKey] = $savedID;
666 + if (!empty($templateDetail->clRef)) {
667 + $integartionIDForWorkflow['emailCLRef'][$templateDetail->clRef] = $savedID;
668 + }
669 + // return the new id (and drop the temp ref) so the frontend reconciles the template
670 + $templateDetail->id = $savedID;
671 + unset($templateDetail->clRef);
607 672 }
608 673 } else {
609 - $emailTemplateHandler->updateTemplate($templateDetail);
674 + $updated = $emailTemplateHandler->updateTemplate($templateDetail);
675 + if (is_wp_error($updated) && 'db_error' === $updated->get_error_code()) {
676 + $newData['mailTemplate'] = 2;
677 + } elseif (0 === $newData['mailTemplate']) {
678 + $newData['mailTemplate'] = 1;
679 + }
610 680 }
611 681 }
612 682 }
613 683 // return $formSettings;
614 684 // Email Template [end] */
615 - if (!empty($pdfTem)) {
616 - $pdfTemplateHandler = new PdfTemplateHandler($formID);
685 + if (!empty($pdfTem) && class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
686 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
617 687
618 688 foreach ($pdfTem as $templateKey => $templateDetail) {
619 689 if (isset($templateDetail->setting->font->name)) {
620 690 $this->pdfFontDownload($templateDetail->setting->font->name);
@@ -634,8 +704,15 @@
634 704 if (!empty($formSettings->confirmation->type)) {
635 705 $allIntegrations = $formSettings->confirmation->type;
636 706 foreach ($allIntegrations as $integrationType => $integrationGroup) {
637 707 foreach ($integrationGroup as $singleIntegrationKey => $singleIntegrationDetail) {
708 + // Redirect (and webhook) enable/disable toggle persists to the integration status column.
709 + $integrationStatus = isset($singleIntegrationDetail->status) ? (int) $singleIntegrationDetail->status : 1;
710 + // Inline-CL temp ref for a brand-new redirect (reconciled to the real id for workflow rows).
711 + $clRef = isset($singleIntegrationDetail->clRef) ? $singleIntegrationDetail->clRef : null;
712 + if (is_object($singleIntegrationDetail)) {
713 + unset($singleIntegrationDetail->status, $singleIntegrationDetail->clRef);
714 + }
638 715 if (empty($singleIntegrationDetail->details)) {
639 716 $integrationName = $singleIntegrationDetail->title;
640 717 unset($singleIntegrationDetail->title);
641 718 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
@@ -649,13 +726,16 @@
649 726 $integrationDetails = !is_string($singleIntegrationDetail->details) ?
650 727 wp_json_encode($singleIntegrationDetail->details) : $singleIntegrationDetail->details;
651 728 }
652 729 if (empty($singleIntegrationDetailID)) {
653 - $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
730 + $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
654 731 $newData['settingConfiramation'] = 1;
655 732 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
733 + if (!empty($clRef) && 'redirectPage' === $integrationType) {
734 + $integartionIDForWorkflow['redirectCLRef'][$clRef] = $savedID;
735 + }
656 736 } else {
657 - $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form');
737 + $integrationHandler->updateIntegration($singleIntegrationDetailID, $integrationName, $integrationType, $integrationDetails, 'form', $integrationStatus);
658 738 }
659 739 }
660 740 }
661 741 }
@@ -666,8 +746,11 @@
666 746 $integrationType = $singleIntegrationDetail->type;
667 747 unset($singleIntegrationDetail->type);
668 748 $singleIntegrationDetailID = empty($singleIntegrationDetail->id) ? null : $singleIntegrationDetail->id;
669 749 unset($singleIntegrationDetail->id);
750 + // Inline-CL temp ref for a brand-new integration (reconciled to the real id for workflow rows).
751 + $clRef = isset($singleIntegrationDetail->__bf_cl_ref) ? $singleIntegrationDetail->__bf_cl_ref : null;
752 + unset($singleIntegrationDetail->__bf_cl_ref);
670 753 if (empty($singleIntegrationDetail->details)) {
671 754 $integrationDetails = !is_string($singleIntegrationDetail) ?
672 755 wp_json_encode($singleIntegrationDetail) : $singleIntegrationDetail;
673 756 } else {
@@ -676,8 +759,11 @@
676 759 }
677 760 if (empty($singleIntegrationDetailID)) {
678 761 $savedID = $integrationHandler->saveIntegration($integrationName, $integrationType, $integrationDetails, 'form');
679 762 $integartionIDForWorkflow[$integrationType][$singleIntegrationKey] = $savedID;
763 + if (!empty($clRef) && !is_wp_error($savedID)) {
764 + $integartionIDForWorkflow['integrationCLRef'][$clRef] = $savedID;
765 + }
680 766 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
681 767 $newData['integation'] = 2;
682 768 } else {
683 769 $newData['integation'] = 1;
@@ -701,8 +787,9 @@
701 787 }
702 788 if ('oninput' === $workFlow->action_type || ('always' === $workFlow->action_type && 'cond' === $workFlow->action_behaviour)) {
703 789 $workFlowExist['oninput'] = true;
704 790 }
791 + // $integartionIDForWorkflow = apply_filters('bitform_filter_integration_id', $workFlow, $formID, $index);
705 792 if (empty($workFlow->id)) {
706 793 $savedID = $workFlowHandler->saveworkFlow($workFlow, $integartionIDForWorkflow, $index);
707 794 if (is_wp_error($savedID) && 'result_empty' !== $savedID->get_error_code()) {
708 795 $newData['workflow'] = 2;
@@ -716,8 +803,11 @@
716 803 }
717 804 $form_content = array_merge($form_content, ['workFlowExist' => $workFlowExist]);
718 805 //wrokFlows [end]
719 806 //reports [start] */
807 + // read unconditionally after the reports block; a save without currentReport
808 + // must not trip an undefined-variable warning
809 + $reportIsDefault = null;
720 810 if (!empty($reports)) {
721 811 $reportsModel = new ReportsModel();
722 812 $fieldNames = [];
723 813 foreach ($fields as $key => $field) {
@@ -729,15 +819,19 @@
729 819
730 820 $fieldNames['__user_id'] = __('User', 'bit-form');
731 821 $fieldNames['__user_ip'] = __('IP address', 'bit-form');
732 822 // $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');
823 + $fieldNames['__referer'] = __('Refer URL', 'bit-form');
824 + $fieldNames['__user_device'] = __('Device', 'bit-form');
825 + $fieldNames['__created_at'] = __('Created Time', 'bit-form');
826 + $fieldNames['__updated_at'] = __('Modified Time', 'bit-form');
737 827
738 828 $reportIsDefault = null;
739 - if (isset($form_content['report_id'])) {
829 + // The client posts currentReport as {} whenever its report atom has not resolved yet. That
830 + // is an empty stdClass, which empty() above treats as non-empty, so we reach here with
831 + // nothing to save — and writing the validated result would replace the stored report's
832 + // column order, hidden columns, page size and name with an empty list. Leave the row alone.
833 + if (isset($form_content['report_id']) && ReportsModel::isValidatableReport($reports)) {
740 834 $validDateReport = $reportsModel->validateReportFields($reports, $fieldNames);
741 835 if (isset($reports->isDefault)) {
742 836 $reportIsDefault = $reports->isDefault;
743 837 } else {
@@ -786,9 +880,9 @@
786 880 'form_name' => $form_name,
787 881 'form_content' => $form_content,
788 882 'user_id' => $user_details['id'],
789 883 'user_ip' => $user_details['ip'],
790 - 'builder_helper_state' => \wp_json_encode((object)$builder_helper_state),
884 + 'builder_helper_state' => \wp_json_encode((object) $builder_helper_state),
791 885 'generated_script_page_ids' => \wp_json_encode((object) []),
792 886 'user_device' => $user_details['device'],
793 887 'updated_at' => $user_details['time'],
794 888 ];
@@ -794,15 +888,16 @@
794 888 ];
795 889 if (isset($atomic_class_map)) {
796 890 $updateData['atomic_class_map'] = $atomic_class_map;
797 891 }
798 - $formUpdateVersion = get_option('bit-form_form_update_version');
892 + $formUpdateVersion = get_option('bitform_form_update_version');
799 893 if (!$formUpdateVersion) {
800 894 $formUpdateVersion = 1;
801 895 } else {
802 896 $formUpdateVersion = (int) $formUpdateVersion + 1;
803 897 }
804 - update_option('bit-form_form_update_version', $formUpdateVersion);
898 + update_option('bitform_form_update_version', $formUpdateVersion);
899 + do_action('bitform_admin_form_changed');
805 900
806 901 $update_status = static::$formModel->update(
807 902 $updateData,
808 903 [
@@ -820,9 +915,9 @@
820 915 }
821 916
822 917 $updated_data = $this->getAForm(['id' => $formID], null);
823 918
824 - if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation']) {
919 + if (0 === $newData['settingConfiramation'] && 0 === $newData['mailTemplate'] && 0 === $newData['integation'] && 0 === $newData['pdfTemplate']) {
825 920 unset($updated_data['formSettings']);
826 921 }
827 922 if (0 === $newData['integation']) {
828 923 unset($updated_data['integrations']);
@@ -834,13 +929,13 @@
834 929 unset($updated_data['mailTem']);
835 930 } elseif (2 === $newData['mailTemplate']) {
836 931 $errorIN .= empty($errorIN) ? 'mailTemplate' : ', mailTemplate';
837 932 }
838 - // if (0 === $newData['pdfTemplate']) {
839 - // unset($updated_data['pdfTem']);
840 - // } elseif (2 === $newData['pdfTemplate']) {
841 - // $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
842 - // }
933 + if (0 === $newData['pdfTemplate']) {
934 + unset($updated_data['pdfTem']);
935 + } elseif (2 === $newData['pdfTemplate']) {
936 + $errorIN .= empty($errorIN) ? 'pdfTemplate' : ', pdfTemplate';
937 + }
843 938 if (0 === $newData['workflow']) {
844 939 unset($updated_data['workFlows']);
845 940 } elseif (2 === $newData['workflow']) {
846 941 $errorIN .= empty($errorIN) ? 'workflow' : ', workflow';
@@ -847,9 +942,14 @@
847 942 }
848 943 if (2 === $newData['reports']) {
849 944 $errorIN .= empty($errorIN) ? 'reports' : ', reports';
850 945 }
946 + // See createNewForm(). Fired before the partial-failure return: the rows
947 + // that did save are already persisted, so their strings still need registering.
948 + do_action('bitform_form_saved', $formId);
949 +
851 950 if (!empty($errorIN)) {
951 + /* translators: %s: comma-separated list of areas where error occurred */
852 952 $updated_data['message'] = sprintf(__('Error Occured in saving %s', 'bit-form'), $errorIN);
853 953 return new WP_Error('Form update Error.', $updated_data);
854 954 }
855 955 if (null !== $reportIsDefault) {
@@ -854,30 +954,77 @@
854 954 }
855 955 if (null !== $reportIsDefault) {
856 956 $updated_data['form_content']['is_default'] = $reportIsDefault;
857 957 }
858 - $updated_data['message'] = __('Form updated successfully.', 'bitform');
958 + $updated_data['message'] = __('Form updated successfully.', 'bit-form');
959 +
859 960 return $updated_data;
860 961 }
861 962 }
862 963
964 + /**
965 + * Drop orphan fields (present in `fields` but in no layout) from form_content
966 + * before persisting, and remove now-childless nestedLayout entries.
967 + *
968 + * Entry meta is NEVER touched here — only explicit user deletes clear meta
969 + * (see setEmptyMetaValue). Fail closed: an unusable/partial layout, or a
970 + * client that flagged a failed pre-save layout sync (->skipOrphanPrune),
971 + * prunes nothing. Pruned keys are logged, never silently dropped.
972 + *
973 + * @param object|array $fields by ref; orphan keys removed
974 + * @param object|null $nestedLayout by ref; stale container entries removed
975 + * @param array|object $layout raw layout (single or multi-step)
976 + * @param int|string|null $formID for logging ('new' when absent)
977 + * @param object $post raw request; honors ->skipOrphanPrune
978 + */
979 + private function pruneOrphanFields(&$fields, &$nestedLayout, $layout, $formID, $post)
980 + {
981 + $formLabel = $formID ? $formID : 'new';
982 + if (isset($post->skipOrphanPrune) && $post->skipOrphanPrune) {
983 + Log::debug_log('Bit Form: orphan prune skipped (client reported failed layout sync). FormID=' . $formLabel);
984 + return;
985 + }
986 + $orphanFldKeys = FormManager::computeOrphanFieldKeys($layout, $nestedLayout, $fields);
987 + // null = unusable/partial layout (fail closed); [] = nothing to prune
988 + if (!is_array($orphanFldKeys) || empty($orphanFldKeys)) {
989 + return;
990 + }
991 + Log::debug_log('Bit Form: pruning orphan fields (absent from every layout). FormID=' . $formLabel . ' keys=' . implode(',', $orphanFldKeys));
992 + foreach ($orphanFldKeys as $orphanKey) {
993 + if (is_object($fields)) {
994 + unset($fields->{$orphanKey});
995 + } elseif (is_array($fields)) {
996 + unset($fields[$orphanKey]);
997 + }
998 + }
999 + // prune stale nestedLayout entries — containers that no longer exist in fields
1000 + if (is_object($nestedLayout)) {
1001 + foreach (array_keys(get_object_vars($nestedLayout)) as $nKey) {
1002 + $parentExists = is_object($fields) ? isset($fields->{$nKey}) : isset($fields[$nKey]);
1003 + if (!$parentExists) {
1004 + unset($nestedLayout->{$nKey});
1005 + }
1006 + }
1007 + }
1008 + }
1009 +
863 1010 public function setEmptyMetaValue($fieldkeys)
864 1011 {
865 - $sqlEscaped = array_map(function ($fld) {
866 - return "'" . esc_sql($fld) . "'";
867 - }, $fieldkeys);
868 - $deletedFldKey = implode(',', $sqlEscaped);
869 1012 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);
1013 + // Placeholders and arguments built dynamically from $fieldkeys; count matches at runtime.
1014 + $placeholders = implode(',', array_fill(0, \count($fieldkeys), '%s'));
1015 + $wpdb->query($wpdb->prepare(
1016 + "UPDATE `{$wpdb->prefix}bitforms_form_entrymeta` SET meta_value = %s WHERE meta_key IN ($placeholders)",
1017 + '',
1018 + ...$fieldkeys
1019 + ));
873 1020 }
874 1021
875 1022 public function changeFormStatus($Request, $post)
876 1023 {
877 1024 if (isset($Request['status']) && $Request['id']) {
878 - $status = wp_unslash($Request['status']);
879 - $id = wp_unslash($Request['id']);
1025 + $status = sanitize_text_field(wp_unslash($Request['status']));
1026 + $id = absint(wp_unslash($Request['id']));
880 1027 } else {
881 1028 $status = wp_unslash($post->status);
882 1029 $id = wp_unslash($post->id);
883 1030 }
@@ -911,10 +1058,10 @@
911 1058
912 1059 public function changeBulkFormStatus($Request, $post)
913 1060 {
914 1061 if (isset($Request['status']) && $Request['formID']) {
915 - $status = wp_unslash($Request['status']);
916 - $formID = wp_unslash($Request['formID']);
1062 + $status = sanitize_text_field(wp_unslash($Request['status']));
1063 + $formID = array_map('absint', wp_unslash($Request['formID']));
917 1064 } else {
918 1065 $status = wp_unslash($post->status);
919 1066 $formID = wp_unslash($post->formID);
920 1067 }
@@ -949,9 +1096,13 @@
949 1096 public function getAllForm()
950 1097 {
951 1098 global $wpdb;
952 1099
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");
1100 + // Direct query: table name interpolation only (no user input). $wpdb->prepare() cannot parameterize table names.
1101 + $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
1102 + FROM `{$wpdb->prefix}bitforms_form` as forms
1103 + LEFT JOIN `{$wpdb->prefix}bitforms_form_entries` as entries ON forms.id = entries.form_id
1104 + GROUP BY forms.id");
954 1105
955 1106 if (is_wp_error($allForms)) {
956 1107 return $allForms;
957 1108 } elseif (!$allForms) {
@@ -962,10 +1113,10 @@
962 1113 }
963 1114
964 1115 public function getAForm($Request, $post)
965 1116 {
966 - if (isset($Request['id'])) {
967 - $formID = wp_unslash($Request['id']);
1117 + if (!empty($Request['id'])) {
1118 + $formID = absint(wp_unslash($Request['id']));
968 1119 } else {
969 1120 $formID = wp_unslash($post->id);
970 1121 }
971 1122 // return $post->fields;
@@ -984,9 +1135,9 @@
984 1135 'nestedLayout' => !empty($form_content->nestedLayout) ? $form_content->nestedLayout : (object) [],
985 1136 'formInfo' => !empty($form_content->formInfo) ? $form_content->formInfo : (object) ['formName' => $formManager->getFormName()],
986 1137 'fields' => $form_content->fields,
987 1138 'form_name' => $formManager->getFormName(),
988 - 'workFlowExist' => $form_content->workFlowExist,
1139 + 'workFlowExist' => isset($form_content->workFlowExist) ? $form_content->workFlowExist : [],
989 1140 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
990 1141 ];
991 1142 $successMessageHandler
992 1143 = new SuccessMessageHandler($formID);
@@ -1009,28 +1160,37 @@
1009 1160 if (!is_wp_error($emailTemplates)) {
1010 1161 foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1011 1162 $mailTem[] =
1012 1163 [
1013 - 'id' => $emailTemplatevalue->id,
1014 - 'title' => $emailTemplatevalue->title,
1015 - 'sub' => $emailTemplatevalue->sub,
1016 - 'body' => $emailTemplatevalue->body,
1164 + 'id' => $emailTemplatevalue->id,
1165 + 'title' => $emailTemplatevalue->title,
1166 + 'sub' => $emailTemplatevalue->sub,
1167 + 'body' => $emailTemplatevalue->body,
1168 + 'status' => isset($emailTemplatevalue->status) ? (int) $emailTemplatevalue->status : 1,
1169 + 'config' => EmailTemplateHandler::normalizeConfig($emailTemplatevalue->config ?? null),
1017 1170 ];
1018 1171 }
1019 1172 }
1020 1173 // get all pdf template
1021 - $pdfTemplateHandler = new PdfTemplateHandler($formID);
1022 - $pdfTemplates = $pdfTemplateHandler->getAll();
1174 + if (class_exists('\BitCode\BitFormPro\Core\Messages\PdfTemplateHandler')) {
1175 + $pdfTemplateHandler = new \BitCode\BitFormPro\Core\Messages\PdfTemplateHandler($formID);
1176 + $pdfTemplates = $pdfTemplateHandler->getAll();
1023 1177
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 - ];
1178 + if (!is_wp_error($pdfTemplates)) {
1179 + foreach ($pdfTemplates as $value) {
1180 + $pdfTem[] =
1181 + [
1182 + 'id' => $value->id,
1183 + 'title' => $value->title,
1184 + 'setting' => json_decode($value->setting),
1185 + 'pdf_config' => !empty($value->pdf_config) ? json_decode($value->pdf_config) : (object) [
1186 + 'status' => 1,
1187 + 'header' => '',
1188 + 'footer' => '',
1189 + ],
1190 + 'body' => $value->body,
1191 + ];
1192 + }
1033 1193 }
1034 1194 }
1035 1195
1036 1196 $integrationHandler = new IntegrationHandler($formID);
@@ -1038,10 +1198,11 @@
1038 1198 if (!is_wp_error($formIntegrations)) {
1039 1199 foreach ($formIntegrations as $integrationkey => $integrationValue) {
1040 1200 if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1041 1201 $integrationData = [
1042 - 'id' => $integrationValue->id,
1043 - 'title' => $integrationValue->integration_name,
1202 + 'id' => $integrationValue->id,
1203 + 'title' => $integrationValue->integration_name,
1204 + 'status' => isset($integrationValue->status) ? (int) $integrationValue->status : 1,
1044 1205 ];
1045 1206 if (!empty($integrationValue->integration_details)) {
1046 1207 $integration_details = (array) json_decode($integrationValue->integration_details);
1047 1208 $integrationData = array_merge($integration_details, $integrationData);
@@ -1067,11 +1228,26 @@
1067 1228 );
1068 1229 }
1069 1230 }
1070 1231 }
1232 +
1233 + // get form abandonment integration if exist
1234 + $formAbandonmentInteg = $integrationHandler->getAllIntegration('formAbandonment', 'formAbandonment');
1235 + if (!is_wp_error($formAbandonmentInteg) && !empty($formAbandonmentInteg)) {
1236 + $formAbandonmentInteg = $formAbandonmentInteg[0];
1237 + if (!empty($formAbandonmentInteg->integration_details)) {
1238 + $formAbandonment = json_decode($formAbandonmentInteg->integration_details);
1239 + } else {
1240 + $formAbandonment = (object) [];
1241 + }
1242 + } else {
1243 + $formAbandonment = (object) [];
1244 + }
1245 +
1071 1246 $settingsContent = [
1072 - 'formName' => $formManager->getFormName(),
1073 - 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1247 + 'formName' => $formManager->getFormName(),
1248 + 'theme' => isset($form_content->theme) ? $form_content->theme : 'default',
1249 + 'formPermissions' => isset($form_content->formPermissions) ? $form_content->formPermissions : (object) [],
1074 1250 // 'submitBtn' => $form_content->buttons,
1075 1251 ];
1076 1252
1077 1253 if (!empty($allConfirmation)) {
@@ -1130,8 +1306,24 @@
1130 1306 'pdfTem' => [],
1131 1307 ]
1132 1308 );
1133 1309 }
1310 +
1311 + if (!empty($formAbandonment)) {
1312 + $settingsContent = array_merge(
1313 + $settingsContent,
1314 + [
1315 + 'formAbandonment' => $formAbandonment,
1316 + ]
1317 + );
1318 + } else {
1319 + $settingsContent = array_merge(
1320 + $settingsContent,
1321 + [
1322 + 'formAbandonment' => (object) [],
1323 + ]
1324 + );
1325 + }
1134 1326 $formSettings = [
1135 1327 'formSettings' => $settingsContent,
1136 1328 ];
1137 1329 $data = [
@@ -1142,12 +1334,14 @@
1142 1334 'style' => $helper_states->style,
1143 1335 'themeVars' => $helper_states->themeVars,
1144 1336 'themeColors' => $helper_states->themeColors,
1145 1337 'builderSettings' => $helper_states->builderSettings,
1338 + 'customCode' => FrontEndScriptGenerator::getCustomCodes($formID),
1146 1339 'additional' => empty($form_content->additional) ? [
1147 1340 'enabled' => [
1148 1341 'blocked_ip' => false,
1149 1342 'restrict_form' => false,
1343 + 'onePerIp' => false,
1150 1344 ],
1151 1345 'settings' => [
1152 1346 'restrict_form' => [
1153 1347 'day' => [],
@@ -1162,9 +1356,8 @@
1162 1356 ],
1163 1357 'entry_limit' => null,
1164 1358 'blocked_ip' => [],
1165 1359 ],
1166 - 'onePerIp' => false,
1167 1360 ] : $form_content->additional,
1168 1361 'created_at' => $formManager->getFormMetaData()['created_at'],
1169 1362 'views' => $formManager->getFormMetaData()['views'],
1170 1363 'entries' => $formManager->getFormMetaData()['entries'],
@@ -1205,9 +1398,9 @@
1205 1398 } else {
1206 1399 $returnedReportData[$reportKey]->details = [];
1207 1400 }
1208 1401 if ('1' === (string) $reportData->isDefault) {
1209 - $returnedReportData[$reportKey]->details->report_name = 'All Entries';
1402 + $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1210 1403 }
1211 1404 }
1212 1405 $reports = ['reports' => $returnedReportData];
1213 1406 $data = array_merge($data, $reports);
@@ -1219,12 +1412,233 @@
1219 1412 return $data;
1220 1413 }
1221 1414 }
1222 1415
1416 + public function getAFormV1($Request, $post)
1417 + {
1418 + if (!empty($Request['id'])) {
1419 + $formID = absint(wp_unslash($Request['id']));
1420 + } else {
1421 + $formID = wp_unslash($post->id);
1422 + }
1423 + // return $post->fields;
1424 + if (is_null($formID)) {
1425 + return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1426 + }
1427 + $formManager = new AdminFormManager($formID);
1428 + if (!$formManager->isExist()) {
1429 + return new WP_Error('not_exists', __('Form is not exists.', 'bit-form'));
1430 + }
1431 + $form_content = $formManager->getFormContent();
1432 + if ($formManager->isExist()) {
1433 + $form_content_arr = [
1434 + 'layout' => $form_content->layout,
1435 + 'fields' => $form_content->fields,
1436 + 'form_name' => $formManager->getFormName(),
1437 + 'workFlowExist' => isset($form_content->workFlowExist) ? $form_content->workFlowExist : [],
1438 + 'report_id' => isset($form_content->report_id) ? $form_content->report_id : null
1439 + ];
1440 + $successMessageHandler
1441 + = new SuccessMessageHandler($formID);
1442 + $successMessages = $successMessageHandler->getAllMessage();
1443 + if (!is_wp_error($successMessages)) {
1444 + foreach ($successMessages as $sucessMessagekey => $sucessMessagevalue) {
1445 + $allConfirmation['type']['successMsg'][$sucessMessagekey] =
1446 + [
1447 + 'id' => $sucessMessagevalue->id,
1448 + 'title' => $sucessMessagevalue->message_title,
1449 + 'msg' => $sucessMessagevalue->message_content,
1450 + 'config' => !empty($sucessMessagevalue->message_config) ? json_decode($sucessMessagevalue->message_config) : (object) [],
1451 + ];
1452 + }
1453 + }
1454 + $emailTemplateHandler
1455 + = new EmailTemplateHandler($formID);
1456 + $emailTemplates = $emailTemplateHandler->getAllTemplate();
1457 + if (!is_wp_error($emailTemplates)) {
1458 + foreach ($emailTemplates as $emailTemplatekey => $emailTemplatevalue) {
1459 + $mailTem[] =
1460 + [
1461 + 'id' => $emailTemplatevalue->id,
1462 + 'title' => $emailTemplatevalue->title,
1463 + 'sub' => $emailTemplatevalue->sub,
1464 + 'body' => $emailTemplatevalue->body,
1465 + 'status' => isset($emailTemplatevalue->status) ? (int) $emailTemplatevalue->status : 1,
1466 + 'config' => EmailTemplateHandler::normalizeConfig($emailTemplatevalue->config ?? null),
1467 + ];
1468 + }
1469 + }
1470 + $integrationHandler = new IntegrationHandler($formID);
1471 + $formIntegrations = $integrationHandler->getAllIntegration('form');
1472 + if (!is_wp_error($formIntegrations)) {
1473 + foreach ($formIntegrations as $integrationkey => $integrationValue) {
1474 + if ('redirectPage' === $integrationValue->integration_type || 'webHooks' === $integrationValue->integration_type) {
1475 + $integrationData = [
1476 + 'id' => $integrationValue->id,
1477 + 'title' => $integrationValue->integration_name,
1478 + 'status' => isset($integrationValue->status) ? (int) $integrationValue->status : 1,
1479 + ];
1480 + if (!empty($integrationValue->integration_details)) {
1481 + // var_dump(json_decode($integrationValue->integration_details));
1482 + $integration_details = (array) json_decode($integrationValue->integration_details);
1483 + $integrationData = array_merge($integration_details, $integrationData);
1484 + } else {
1485 + $integration_details = [
1486 + 'url' => '',
1487 + ];
1488 + $integrationData = array_merge($integrationData, $integration_details);
1489 + }
1490 + $allConfirmation['type'][$integrationValue->integration_type][]
1491 + = $integrationData;
1492 + } else {
1493 + $integrationData = [
1494 + 'id' => $integrationValue->id,
1495 + 'name' => $integrationValue->integration_name,
1496 + 'type' => $integrationValue->integration_type,
1497 + ];
1498 + $integrations[] = array_merge(
1499 + $integrationData,
1500 + is_string($integrationValue->integration_details) ?
1501 + (array) json_decode($integrationValue->integration_details) :
1502 + $integrationValue->integration_details
1503 + );
1504 + }
1505 + }
1506 + }
1507 + $settingsContent = [
1508 + 'formName' => $formManager->getFormName(),
1509 + 'theme' => $form_content->theme,
1510 + // 'submitBtn' => $form_content->buttons,
1511 + ];
1512 +
1513 + if (!empty($allConfirmation)) {
1514 + $confirmation = [
1515 + 'confirmation' => $allConfirmation,
1516 + ];
1517 + } else {
1518 + $confirmation = [
1519 + 'confirmation' => ['type' => []],
1520 + ];
1521 + }
1522 + $settingsContent = array_merge($settingsContent, $confirmation);
1523 + if (!empty($integrations)) {
1524 + $settingsContent = array_merge(
1525 + $settingsContent,
1526 + [
1527 + 'integrations' => $integrations,
1528 + ]
1529 + );
1530 + } else {
1531 + $settingsContent = array_merge(
1532 + $settingsContent,
1533 + [
1534 + 'integrations' => []
1535 + ]
1536 + );
1537 + }
1538 + if (!empty($mailTem)) {
1539 + $settingsContent = array_merge(
1540 + $settingsContent,
1541 + [
1542 + 'mailTem' => $mailTem,
1543 + ]
1544 + );
1545 + } else {
1546 + $settingsContent = array_merge(
1547 + $settingsContent,
1548 + [
1549 + 'mailTem' => []
1550 + ]
1551 + );
1552 + }
1553 + $formSettings = [
1554 + 'formSettings' => $settingsContent,
1555 + ];
1556 + $data = [
1557 + 'id' => $formID,
1558 + 'form_name' => $formManager->getFormName(),
1559 + 'form_content' => $form_content_arr,
1560 + 'additional' => empty($form_content->additional) ? [
1561 + 'enabled' => [
1562 + 'blocked_ip' => false,
1563 + 'restrict_form' => false,
1564 + 'onePerIp' => false,
1565 + ],
1566 + 'settings' => [
1567 + 'restrict_form' => [
1568 + 'day' => [],
1569 + 'date' => [
1570 + 'from' => null,
1571 + 'to' => null,
1572 + ],
1573 + 'time' => [
1574 + 'from' => null,
1575 + 'to' => null,
1576 + ],
1577 + ],
1578 + 'entry_limit' => null,
1579 + 'blocked_ip' => [],
1580 + ],
1581 + ] : $form_content->additional,
1582 + 'created_at' => $formManager->getFormMetaData()['created_at'],
1583 + 'views' => $formManager->getFormMetaData()['views'],
1584 + 'entries' => $formManager->getFormMetaData()['entries'],
1585 + 'status' => $formManager->getFormMetaData()['status'],
1586 + ];
1587 + $data = array_merge($data, $formSettings);
1588 + $workFlowHandler = new WorkFlowHandler($formID);
1589 + $workFlows = ['workFlows' => $workFlowHandler->getAllworkFlowV1()];
1590 + $data = array_merge($data, $workFlows);
1591 + $reportsModel = new ReportsModel();
1592 + $returnedReportData = $reportsModel->get(
1593 + [
1594 + 'id',
1595 + 'details',
1596 + 'isDefault',
1597 + 'type',
1598 + ],
1599 + [
1600 + 'category' => 'form',
1601 + 'context' => $formID,
1602 + ]
1603 + );
1604 +
1605 + if (!is_wp_error($returnedReportData)) {
1606 + $fieldNames = [];
1607 + foreach ($formManager->getFieldLabel() as $key => $field) {
1608 + $fieldNames[$field['key']] = isset($field->lbl) ? $field->lbl : '';
1609 + }
1610 + if ($formManager->isGCLIDEnabled()) {
1611 + $fieldNames['GCLID'] = 'GCLID';
1612 + }
1613 + foreach ($returnedReportData as $reportKey => $reportData) {
1614 + $reportDetails = $reportsModel->validateReportFields($reportData, $fieldNames);
1615 + if (!empty($reportDetails) && is_string($reportDetails)) {
1616 + $returnedReportData[$reportKey]->details = json_decode($reportDetails);
1617 + } elseif (!empty($reportDetails)) {
1618 + $returnedReportData[$reportKey]->details = $reportDetails;
1619 + } else {
1620 + $returnedReportData[$reportKey]->details = [];
1621 + }
1622 + if ('1' === (string) $reportData->isDefault) {
1623 + $returnedReportData[$reportKey]->details->report_name = __('All Entries', 'bit-form');
1624 + }
1625 + }
1626 + $reports = ['reports' => $returnedReportData];
1627 + $data = array_merge($data, $reports);
1628 + }
1629 +
1630 + $formFields = $formManager->getFieldLabel();
1631 + $data = array_merge($data, ['Labels' => $formFields]);
1632 +
1633 + return $data;
1634 + }
1635 + }
1636 +
1223 1637 public function deleteAForm($Request, $post)
1224 1638 {
1225 - if (isset($Request['id'])) {
1226 - $formID = wp_unslash($Request['id']);
1639 + if (!empty($Request['id'])) {
1640 + $formID = absint(wp_unslash($Request['id']));
1227 1641 } else {
1228 1642 $formID = wp_unslash($post->id);
1229 1643 }
1230 1644 if (is_null($formID)) {
@@ -1229,24 +1643,30 @@
1229 1643 }
1230 1644 if (is_null($formID)) {
1231 1645 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1232 1646 }
1647 +
1648 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
1649 + return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
1650 + }
1651 +
1233 1652 $delete_status = static::$formModel->delete(
1234 1653 [
1235 1654 'id' => $formID,
1236 1655 ]
1237 1656 );
1657 + do_action('bitform_admin_form_changed');
1238 1658
1239 - $successMessageModel
1240 - = new SuccessMessageModel();
1659 + $successMessageModel = new SuccessMessageModel();
1241 1660 $deleteMsgStatus = $successMessageModel->delete(['form_id' => $formID]);
1242 1661
1243 - $emailTemplateModel
1244 - = new EmailTemplateModel();
1662 + $emailTemplateModel = new EmailTemplateModel();
1245 1663 $deleteTemplateStatus = $emailTemplateModel->delete(['form_id' => $formID]);
1246 1664
1247 - $pdfTemplateModel = new PdfTemplateModel();
1248 - $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
1665 + if (class_exists('\BitCode\BitFormPro\Core\Database\PdfTemplateModel')) {
1666 + $pdfTemplateModel = new \BitCode\BitFormPro\Core\Database\PdfTemplateModel();
1667 + $deletePdfTemplateStatus = $pdfTemplateModel->delete(['form_id' => $formID]);
1668 + }
1249 1669
1250 1670 $integrationModel = new IntegrationModel();
1251 1671 $deleteIntegrationStatus = $integrationModel->delete(['form_id' => $formID]);
1252 1672
@@ -1259,22 +1679,11 @@
1259 1679 $formEntryModel = new FormEntryModel();
1260 1680 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1261 1681 $entries = [];
1262 1682
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 - }
1683 + // checked namespace exist
1684 + if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1685 + \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByFormId($formID);
1277 1686 }
1278 1687
1279 1688 $fileHandler = new FileHandler();
1280 1689 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
@@ -1282,45 +1691,54 @@
1282 1691 }
1283 1692 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1284 1693 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID);
1285 1694 }
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 - }
1695 + $formStylePath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles';
1696 +
1697 + $formCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-' . $formID . '.css';
1698 + FileHandler::deleteIsFileExists($formCssPath);
1699 +
1700 + $layoutCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-layout-' . $formID . '.css';
1701 + FileHandler::deleteIsFileExists($layoutCssPath);
1702 +
1703 + $customCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.css';
1704 + FileHandler::deleteIsFileExists($customCssPath);
1705 +
1706 + $customJSPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-scripts' . DIRECTORY_SEPARATOR . 'bitform-custom-' . $formID . '.js';
1707 + FileHandler::deleteIsFileExists($customJSPath);
1708 +
1709 + $conversationCssPath = $formStylePath . DIRECTORY_SEPARATOR . 'bitform-conversational-' . $formID . '.css';
1710 + FileHandler::deleteIsFileExists($conversationCssPath);
1711 +
1301 1712 return is_wp_error($delete_status) ? $delete_status : __('Form deleted successfully.', 'bit-form');
1302 1713 }
1303 1714
1304 1715 public function deleteBlukForm($Request, $post)
1305 1716 {
1306 - if (isset($Request['formID'])) {
1307 - $formID = wp_unslash($Request['formID']);
1717 + if (!empty($Request['formID'])) {
1718 + $formID = array_map('absint', wp_unslash($Request['formID']));
1308 1719 } else {
1309 1720 $formID = wp_unslash($post->formID);
1310 1721 }
1722 +
1311 1723 if (is_null($formID) || !is_array($formID)) {
1312 1724 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1313 1725 }
1726 +
1727 + if (!Helpers::checkIsIntArr($formID)) {
1728 + return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
1729 + }
1730 +
1314 1731 $cssPath = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1315 1732 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 - }
1733 + $formCssPath = $cssPath . 'bitform-' . $id . '.css';
1734 + FileHandler::deleteIsFileExists($formCssPath);
1735 +
1736 + $layoutPath = $cssPath . 'bitform-layout-' . $id . '.css';
1737 + FileHandler::deleteIsFileExists($layoutPath);
1738 +
1739 + $bitformCustomPath = $cssPath . 'bitform-' . $id . '-formid' . '.css';
1740 + FileHandler::deleteIsFileExists($bitformCustomPath);
1323 1741 }
1324 1742 $delete_status = static::$formModel->bulkDelete(
1325 1743 [
1326 1744 'id' => $formID,
@@ -1325,16 +1743,26 @@
1325 1743 [
1326 1744 'id' => $formID,
1327 1745 ]
1328 1746 );
1747 + do_action('bitform_admin_form_changed');
1748 +
1749 + if (is_wp_error($delete_status)) {
1750 + wp_send_json_error($delete_status->get_error_message(), 400);
1751 + }
1752 +
1329 1753 $successMessageModel
1330 1754 = new SuccessMessageModel();
1331 1755 $deleteMsgStatus = $successMessageModel->bulkDelete(['form_id' => $formID]);
1332 1756
1333 - $emailTemplateModel
1334 - = new EmailTemplateModel();
1757 + $emailTemplateModel = new EmailTemplateModel();
1335 1758 $deleteTemplateStatus = $emailTemplateModel->bulkDelete(['form_id' => $formID]);
1336 1759
1760 + if (class_exists('\BitCode\BitFormPro\Core\Database\PdfTemplateModel')) {
1761 + $pdfTemplateModel = new \BitCode\BitFormPro\Core\Database\PdfTemplateModel();
1762 + $deletePdfTemplateStatus = $pdfTemplateModel->bulkDelete(['form_id' => $formID]);
1763 + }
1764 +
1337 1765 $integrationModel = new IntegrationModel();
1338 1766 $deleteIntegrationStatus = $integrationModel->bulkDelete(['form_id' => $formID]);
1339 1767
1340 1768 $workFlowModel = new WorkFlowModel();
@@ -1344,8 +1772,13 @@
1344 1772 $deleteReportStatus = $reportsModel->bulkDelete(['context' => $formID]);
1345 1773
1346 1774 $formEntryModel = new FormEntryModel();
1347 1775 $returnedEntries = $formEntryModel->get('id', ['form_id' => $formID]);
1776 +
1777 + if (class_exists('\BitCode\BitFormPro\Admin\BfTable\Table')) {
1778 + \BitCode\BitFormPro\Admin\BfTable\Table::deleteTableByBulkFormId($formID);
1779 + }
1780 +
1348 1781 $entries = [];
1349 1782 foreach ($returnedEntries as $entryKey => $entryInfo) {
1350 1783 if (!empty($entryInfo->id)) {
1351 1784 $entries[] = $entryInfo->id;
@@ -1361,16 +1794,19 @@
1361 1794 ]
1362 1795 );
1363 1796 }
1364 1797
1798 + // delete entry log and details; table name interpolation only — $wpdb->prepare() parameterizes the form_id value.
1799 + $wpdb->query($wpdb->prepare(
1800 + "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",
1801 + $formID
1802 + ));
1803 +
1365 1804 $fileHandler = new FileHandler();
1366 1805 foreach ($formID as $fId) {
1367 1806 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId)) {
1368 1807 $fileHandler->rmrf(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $fId);
1369 1808 }
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 1809 }
1374 1810
1375 1811 return is_wp_error($delete_status) ? $delete_status : __('Forms deleted successfully.', 'bit-form');
1376 1812 }
@@ -1412,21 +1848,15 @@
1412 1848 if (!is_wp_error($duplicateResponse) || (is_wp_error($duplicateResponse) && 'result_empty' === $duplicateResponse->get_error_code())) {
1413 1849 // duplicate stylesheet
1414 1850 $style_dir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR . 'form-styles' . DIRECTORY_SEPARATOR;
1415 1851 // layout style copy
1416 - $mainFormLayStyle = fopen($style_dir . 'bitform-layout-' . $oldFormId . '.css', 'r');
1417 - $styleStr = fread($mainFormLayStyle, filesize($style_dir . 'bitform-layout-' . $oldFormId . '.css'));
1852 + $styleStr = FileHandler::readFile($style_dir . 'bitform-layout-' . $oldFormId . '.css');
1418 1853 $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);
1854 + FileHandler::writeFile($style_dir . "bitform-layout-$newFormId.css", $newStyle);
1422 1855 // style copy
1423 - $mainFormStyle = fopen($style_dir . 'bitform-' . $oldFormId . '.css', 'r');
1424 - $styleStr = fread($mainFormStyle, filesize($style_dir . 'bitform-' . $oldFormId . '.css'));
1856 + $styleStr = FileHandler::readFile($style_dir . 'bitform-' . $oldFormId . '.css');
1425 1857 $newStyle = str_replace("-$oldFormId", "-$newFormId", $styleStr);
1426 - $createStyleFile = fopen($style_dir . "bitform-$newFormId.css", 'w');
1427 - fwrite($createStyleFile, $newStyle);
1428 - fclose($createStyleFile);
1858 + FileHandler::writeFile($style_dir . "bitform-$newFormId.css", $newStyle);
1429 1859 $duplicatedForm = $this->getAForm(null, (object) ['id' => $newFormId]);
1430 1860 $duplicatedForm['message'] = __('Form duplicated successfully', 'bit-form');
1431 1861 return $duplicatedForm;
1432 1862 }
@@ -1439,15 +1869,15 @@
1439 1869 $newFormId = intval($post->newFormId);
1440 1870 if (!$oldFormId || empty($post->formDetail->fields) || empty($post->formDetail->layout)) {
1441 1871 return new WP_Error('invalid_form', __('Please import a valid json.', 'bit-form'));
1442 1872 }
1443 - $importtedForm = (array)$post->formDetail;
1873 + $importtedForm = (array) $post->formDetail;
1444 1874 $importtedForm['form_content']['fields'] = $importtedForm['fields'];
1445 1875 $importtedForm['form_content']['layout'] = $importtedForm['layout'];
1446 - $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayout'];
1876 + $importtedForm['form_content']['nestedLayout'] = $importtedForm['nestedLayouts'];
1447 1877 $importtedForm['form_content']['formInfo'] = $importtedForm['formInfo'];
1448 1878 unset($importtedForm['fields'], $importtedForm['layout'], $importtedForm['nestedLayout'], $importtedForm['formInfo']);
1449 - $formData = FormDuplicateHelper::createReplica((array)$importtedForm, $oldFormId, $newFormId);
1879 + $formData = FormDuplicateHelper::createReplica((array) $importtedForm, $oldFormId, $newFormId);
1450 1880
1451 1881 if (!empty($importtedForm['rowHeight'])) {
1452 1882 $formData->rowHeight = $importtedForm['rowHeight'];
1453 1883 }
@@ -1457,10 +1887,29 @@
1457 1887 $formData->layoutChanged = '-';
1458 1888 }
1459 1889 $importResponse = $this->createNewForm(null, $formData);
1460 1890
1891 + $customCode = [];
1892 + // add custom js
1893 + if (!empty($formData->customCode->customJs)) {
1894 + $customJsPath = 'form-scripts';
1895 + $fileName = 'bitform-custom-' . $newFormId . '.js';
1896 + $customCode['JavaScript'] = $formData->customCode->customJs;
1897 + Helpers::saveFile($customJsPath, $fileName, $formData->customCode->customJs, 'w');
1898 + }
1899 + // add custom css
1900 + if (!empty($formData->customCode->customCss)) {
1901 + $customCssPath = 'form-styles';
1902 + $fileName = 'bitform-custom-' . $newFormId . '.css';
1903 + $customCode['CSS'] = $formData->customCode->customCss;
1904 + Helpers::saveFile($customCssPath, $fileName, $formData->customCode->customCss, 'w');
1905 + }
1906 + if (!is_wp_error($importResponse)) {
1907 + $importResponse['customCode'] = $customCode;
1908 + }
1461 1909 if (!is_wp_error($importResponse) || (is_wp_error($importResponse) && 'result_empty' === $importResponse->get_error_code())) {
1462 1910 $responseData = $this->getAForm(null, (object) ['id' => $newFormId]);
1911 + $responseData['customCode'] = $customCode;
1463 1912 $responseData['message'] = __('Form imported successfully.', 'bit-form');
1464 1913 return $responseData;
1465 1914 }
1466 1915 return $importResponse;
@@ -1515,9 +1964,9 @@
1515 1964 return new WP_Error('empty_form', __('Form does not exists.', 'bit-form'));
1516 1965 }
1517 1966
1518 1967 $newFormId = $oldFormId;
1519 - $duplicatedForm = $this->getAForm($Request, (object)['id' => $oldFormId]);
1968 + $duplicatedForm = $this->getAForm($Request, (object) ['id' => $oldFormId]);
1520 1969 $formData = FormDuplicateHelper::createReplica($duplicatedForm, $oldFormId, $newFormId);
1521 1970 // for custom css
1522 1971 $customCssPath = 'form-styles/bitform-custom-' . $newFormId . '.css';
1523 1972 $cssPath = Helpers::generatePathDirOrFile($customCssPath);
@@ -1537,10 +1986,10 @@
1537 1986 }
1538 1987
1539 1988 public function getFormEntryLabelAndCount($Request, $post)
1540 1989 {
1541 - if (isset($Request['id'])) {
1542 - $id = wp_unslash($Request['id']);
1990 + if (!empty($Request['id'])) {
1991 + $id = absint(wp_unslash($Request['id']));
1543 1992 } else {
1544 1993 $id = wp_unslash($post->id);
1545 1994 }
1546 1995 if (is_null($id)) {
@@ -1593,16 +2042,74 @@
1593 2042 $response['fieldDetails'] = $labels;
1594 2043 return $response;
1595 2044 }
1596 2045
2046 + /**
2047 + * Sanitize a request-supplied entry query condition before it reaches the Model
2048 + * layer. Only known entry-table columns are allowed as condition keys, operators
2049 + * are restricted to a safe allow-list ['form_id' => $id] when nothing valid remains.
2050 + *
2051 + * @param mixed $queryCondition
2052 + * @param int $id
2053 + * @return array
2054 + */
2055 + private function sanitizeEntryQueryCondition($queryCondition, $id)
2056 + {
2057 + $allowedColumns = [
2058 + 'id', 'form_id', 'status', 'created_at', 'updated_at',
2059 + 'user_id', 'user_ip', 'user_device', 'user_location', 'referer',
2060 + ];
2061 + $allowedOperators = ['=', '!=', '<>', '<', '>', '<=', '>=', 'LIKE', 'IN'];
2062 +
2063 + if (!is_array($queryCondition)) {
2064 + return ['form_id' => $id];
2065 + }
2066 +
2067 + $safe = [];
2068 + foreach ($queryCondition as $key => $value) {
2069 + if (!in_array($key, $allowedColumns, true)) {
2070 + continue;
2071 + }
2072 +
2073 + if (is_array($value)) {
2074 + // Never honour a request-supplied raw SQL fragment.
2075 + unset($value['raw']);
2076 +
2077 + if (array_key_exists('operator', $value) || array_key_exists('value', $value)) {
2078 + $operator = isset($value['operator']) && is_string($value['operator'])
2079 + ? strtoupper(trim($value['operator']))
2080 + : '=';
2081 + if (!in_array($operator, $allowedOperators, true)) {
2082 + $operator = '=';
2083 + }
2084 + $condValue = isset($value['value']) ? $value['value'] : '';
2085 + if (is_scalar($condValue)) {
2086 + $safe[$key] = ['operator' => $operator, 'value' => $condValue];
2087 + }
2088 + } else {
2089 + // IN-style list: keep scalar members only (bound by the Model).
2090 + $list = array_values(array_filter($value, 'is_scalar'));
2091 + if (!empty($list)) {
2092 + $safe[$key] = $list;
2093 + }
2094 + }
2095 + } elseif (is_scalar($value)) {
2096 + $safe[$key] = $value;
2097 + }
2098 + }
2099 +
2100 + return empty($safe) ? ['form_id' => $id] : $safe;
2101 + }
2102 +
1597 2103 public function getFormEntry($Request, $post)
1598 2104 {
1599 - if (isset($Request['id'])) {
1600 - $id = wp_unslash($Request['id']);
2105 + if (!empty($Request['id'])) {
2106 + $id = absint(wp_unslash($Request['id']));
1601 2107 $offset = isset($Request['offset']) ?
1602 2108 wp_unslash($Request['offset']) : 0;
1603 2109 $pageSize = isset($Request['pageSize']) ?
1604 2110 wp_unslash($Request['pageSize']) : 10;
2111 + $queryCondition = isset($Request['queryCondition']) ? wp_unslash($Request['queryCondition']) : ['form_id' => $id];
1605 2112 } else {
1606 2113 $id = wp_unslash($post->id);
1607 2114 $conditions = isset($post->conditions) ? wp_unslash($post->conditions) : [];
1608 2115 $dateBetweenFilter = isset($post->entriesFilterByDate) ? wp_unslash($post->entriesFilterByDate) : [];
@@ -1611,9 +2118,11 @@
1611 2118 $filters = isset($post->filters) ? wp_unslash($post->filters) : null;
1612 2119 $globalFilter = isset($post->globalFilter) ? wp_unslash($post->globalFilter) : null;
1613 2120 $pageSize = isset($post->pageSize) ?
1614 2121 wp_unslash($post->pageSize) : 10;
2122 + $queryCondition = isset($post->queryCondition) ? wp_unslash($post->queryCondition) : ['form_id' => $id];
1615 2123 }
2124 + $queryCondition = $this->sanitizeEntryQueryCondition($queryCondition, $id);
1616 2125 if (is_null($id)) {
1617 2126 return new WP_Error('empty_form', __('Form id is empty.', 'bit-form'));
1618 2127 }
1619 2128 $formManager = new AdminFormManager($id);
@@ -1619,15 +2128,12 @@
1619 2128 $formManager = new AdminFormManager($id);
1620 2129 if (!$formManager->isExist()) {
1621 2130 return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
1622 2131 }
1623 -
1624 2132 $formEntry = new FormEntryModel();
1625 2133 $entries = $formEntry->get(
1626 2134 'id',
1627 - [
1628 - 'form_id' => $id,
1629 - ],
2135 + $queryCondition,
1630 2136 null,
1631 2137 null,
1632 2138 'created_at',
1633 2139 'DESC'
@@ -1653,12 +2159,36 @@
1653 2159 $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
1654 2160 return $formEntries;
1655 2161 }
1656 2162
2163 + public function getSingleEntry($formId, $entryId)
2164 + {
2165 + $formManager = new AdminFormManager($formId);
2166 + if (!$formManager->isExist()) {
2167 + return new WP_Error('empty_form', __('Form does not exists', 'bit-form'));
2168 + }
2169 +
2170 + $formFields = $formManager->getFieldLabel(true);
2171 + $fieldDetails = $formManager->getFields();
2172 + $entryMeta = new FormEntryMetaModel();
2173 + // $formEntry = new FormEntryModel();
2174 +
2175 + $entries = $entryMeta->getSingleEntryMeta($formFields, $entryId);
2176 +
2177 + if (!is_wp_error($entries)) {
2178 + return $entries[0];
2179 + }
2180 + return new WP_Error('entry_not_fonud', __('Entry Not Found!', 'bit-form'));
2181 +
2182 + // $customFieldHandler = new CustomFieldHandler();
2183 + // $formEntries = $customFieldHandler->updatedEntries($formEntries, $fieldDetails);
2184 + // return $formEntries;
2185 + }
2186 +
1657 2187 public function getEntriesForReport($Request, $post)
1658 2188 {
1659 - if (isset($Request['id'])) {
1660 - $id = wp_unslash($Request['id']);
2189 + if (!empty($Request['id'])) {
2190 + $id = absint(wp_unslash($Request['id']));
1661 2191 $offset = isset($Request['offset']) ?
1662 2192 wp_unslash($Request['offset']) : null;
1663 2193 $pageSize = isset($Request['pageSize']) ?
1664 2194 wp_unslash($Request['pageSize']) : null;
@@ -1719,8 +2249,9 @@
1719 2249 {
1720 2250 $formId = wp_unslash($post->formId);
1721 2251 $fileFormate = isset($post->fileFormate) ? wp_unslash($post->fileFormate) : null;
1722 2252 $limit = isset($post->limit) ? wp_unslash($post->limit) : null;
2253 + $entryCondition = isset($post->filter) ? wp_unslash($post->filter) : null;
1723 2254 $sortBy = isset($post->sort) ? wp_unslash($post->sort) : 'ASC';
1724 2255 $sortByField = isset($post->sortField) ? wp_unslash($post->sortField) : 'bitforms_form_entry_id';
1725 2256 $formFields = json_decode($post->selectedField);
1726 2257 if (is_null($formId)) {
@@ -1753,17 +2284,17 @@
1753 2284 return $entries;
1754 2285 }
1755 2286 $entryMeta = new FormEntryMetaModel();
1756 2287 $filter = [];
1757 - $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField);
2288 + $formEntries = $entryMeta->getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit, $sortBy, $sortByField, $offset, $entryCondition);
1758 2289 return $formEntries;
1759 2290 }
1760 2291
1761 2292 public function deleteBlukFormEntries($Request, $post)
1762 2293 {
1763 - if (isset($Request['formID'])) {
1764 - $formID = wp_unslash($Request['formID']);
1765 - $entries = wp_unslash($Request['entries']);
2294 + if (!empty($Request['formID'])) {
2295 + $formID = absint(wp_unslash($Request['formID']));
2296 + $entries = array_map('absint', wp_unslash($Request['entries']));
1766 2297 } else {
1767 2298 $formID = wp_unslash($post->formID);
1768 2299 $entries = wp_unslash($post->entries);
1769 2300 }
@@ -1769,21 +2300,32 @@
1769 2300 }
1770 2301 if (is_null($formID) || !is_array($entries) || 0 === count($entries)) {
1771 2302 return new WP_Error('empty_form', __('Invalid Form ID or Entries ID.', 'bit-form'));
1772 2303 }
2304 +
2305 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2306 + return new WP_Error('invalid_form', __('Form id is invalid.', 'bit-form'));
2307 + }
2308 +
2309 + if (!Helpers::checkIsIntArr($entries)) {
2310 + return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2311 + }
2312 +
1773 2313 $formManager = new AdminFormManager($formID);
1774 2314 if (!$formManager->isExist()) {
1775 2315 return new WP_Error('empty_form', __('Form does not exist.', 'bit-form'));
1776 2316 }
1777 2317 $workFlowRunHelper = new WorkFlow($formID);
2318 +
1778 2319 $workFlowreturnedOnDelete = $workFlowRunHelper->executeOnDelete(
1779 2320 $formManager,
1780 2321 $formID,
1781 2322 $entries
1782 2323 );
2324 +
1783 2325 if (isset($workFlowreturnedOnDelete['entries'])) {
1784 2326 if (0 === count($workFlowreturnedOnDelete['entries'])) {
1785 - return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
2327 + return ['message' => __('Entry Deletetion prevented by workflow', 'bit-form')];
1786 2328 } elseif (count($workFlowreturnedOnDelete['entries']) === count($entries)) {
1787 2329 $message = __('Entry Deleted successfully', 'bit-form');
1788 2330 } else {
1789 2331 $result['prevented'] = array_diff($entries, $workFlowreturnedOnDelete['entries']);
@@ -1804,9 +2346,9 @@
1804 2346 );
1805 2347 if (file_exists(BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID)) {
1806 2348 $fileHandler = new FileHandler();
1807 2349 foreach ($entries as $enrtyKey => $entryID) {
1808 - $fileEntries = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formID . DIRECTORY_SEPARATOR . $entryID;
2350 + $fileEntries = $fileHandler->getEntriesFileUploadDir($formID, $entryID);
1809 2351 if (file_exists($fileEntries)) {
1810 2352 $fileHandler->rmrf($fileEntries);
1811 2353 }
1812 2354 }
@@ -1825,11 +2367,11 @@
1825 2367 }
1826 2368
1827 2369 public function duplicateFormEntry($Request, $post)
1828 2370 {
1829 - if (isset($Request['formID'])) {
1830 - $formID = wp_unslash($Request['formID']);
1831 - $entries = wp_unslash($Request['entries']);
2371 + if (!empty($Request['formID'])) {
2372 + $formID = absint(wp_unslash($Request['formID']));
2373 + $entries = array_map('absint', wp_unslash($Request['entries']));
1832 2374 } else {
1833 2375 $formID = wp_unslash($post->formID);
1834 2376 $entries = wp_unslash($post->entries);
1835 2377 }
@@ -1836,8 +2378,16 @@
1836 2378 if (is_null($formID) || !is_array($entries) || empty($entries)) {
1837 2379 return new WP_Error('empty_form', __('Form id or entries id is invalid', 'bit-form'));
1838 2380 }
1839 2381
2382 + if (!filter_var($formID, FILTER_VALIDATE_INT)) {
2383 + return new WP_Error('invalid_form', __('Form id is invalid', 'bit-form'));
2384 + }
2385 +
2386 + if (!Helpers::checkIsIntArr($entries)) {
2387 + return new WP_Error('invalid_entries', __('Entries id is invalid', 'bit-form'));
2388 + }
2389 +
1840 2390 $formManager = new AdminFormManager($formID);
1841 2391 if (!$formManager->isExist()) {
1842 2392 return new WP_Error('empty_form', __('Form does not exist', 'bit-form'));
1843 2393 }
@@ -1870,12 +2420,12 @@
1870 2420 );
1871 2421 if ($duplicate_status) {
1872 2422 $result['details'][$entryID] = $duplicatedEntryId;
1873 2423 $duplicate_count = $duplicate_count + 1;
1874 - if (file_exists(BITFORMS_UPLOAD_DIR . "/$formID/$entryID")) {
2424 + if (file_exists(FileHandler::getEntriesFileUploadDir($formID, $entryID))) {
1875 2425 $fileHandler->cpyr(
1876 - BITFORMS_UPLOAD_DIR . "/$formID/$entryID",
1877 - BITFORMS_UPLOAD_DIR . "/$formID/$duplicatedEntryId"
2426 + FileHandler::getEntriesFileUploadDir($formID, $entryID),
2427 + FileHandler::getEntriesFileUploadDir($formID, $duplicatedEntryId)
1878 2428 );
1879 2429 }
1880 2430 }
1881 2431 }
@@ -1892,11 +2442,11 @@
1892 2442 }
1893 2443
1894 2444 public function editFormEntry($Request, $post)
1895 2445 {
1896 - if (isset($Request['formID'])) {
1897 - $formID = wp_unslash($Request['formID']);
1898 - $entryID = wp_unslash($Request['entryID']);
2446 + if (!empty($Request['formID'])) {
2447 + $formID = absint(wp_unslash($Request['formID']));
2448 + $entryID = absint(wp_unslash($Request['entryID']));
1899 2449 } else {
1900 2450 $formID = wp_unslash($post->formID);
1901 2451 $entryID = wp_unslash($post->entryID);
1902 2452 }
@@ -1941,10 +2491,15 @@
1941 2491 $layout = $formContent->layout;
1942 2492 foreach ($form_fields as $key => $value) {
1943 2493 // $field_name = preg_replace('/[\`\~\!\@\#\$\'\.\s\?\+\-\*\&\|\/\\!]/', '_', $value->lbl);
1944 2494 if (isset($entries[$key])) {
1945 - $form_fields->{$key}->val = $entries[$key];
2495 + $isPassword = isset($value->typ) && 'password' === $value->typ;
2496 + // Never hand a stored password back to the browser; blank keeps it on update.
2497 + $form_fields->{$key}->val = $isPassword ? '' : $entries[$key];
1946 2498 $form_fields->{$key}->name = $key;
2499 + if ($isPassword && '' !== (string) $entries[$key] && isset($value->valid) && is_object($value->valid)) {
2500 + $form_fields->{$key}->valid->req = false;
2501 + }
1947 2502 }
1948 2503 }
1949 2504 $workFlowRunHelper = new WorkFlow($formID);
1950 2505 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
@@ -1971,15 +2526,16 @@
1971 2526
1972 2527 public function updateFormEntry($Request, $post)
1973 2528 {
1974 2529 if (isset($Request['formID'], $Request['entryID'])) {
1975 - $formID = wp_unslash($Request['formID']);
1976 - $entryID = wp_unslash($Request['entryID']);
2530 + $formID = absint(wp_unslash($Request['formID']));
2531 + $entryID = absint(wp_unslash($Request['entryID']));
1977 2532 unset($Request['action'], $Request['formID'], $Request['entryID']);
1978 2533 }
1979 2534 $formManager = new AdminFormManager($formID);
1980 2535 $formManager->fieldNameReplaceOfPost();
1981 - $updatedValue = wp_unslash($_POST);
2536 + // Called from AdminAjax handler; nonce already verified at AJAX entry before dispatch.
2537 + $updatedValue = is_array($post) ? $post : wp_unslash($_POST);
1982 2538
1983 2539 if (is_null($updatedValue) || !is_array($updatedValue)) {
1984 2540 return new WP_Error('empty_data', __('Failed to update, Data is empty.', 'bit-form'));
1985 2541 }
@@ -1995,11 +2551,11 @@
1995 2551 }
1996 2552
1997 2553 public function getLogHistory($Request, $post)
1998 2554 {
1999 - if (isset($Request['formID'])) {
2000 - $formID = wp_unslash($Request['formID']);
2001 - $entryID = wp_unslash($Request['entryID']);
2555 + if (!empty($Request['formID'])) {
2556 + $formID = absint(wp_unslash($Request['formID']));
2557 + $entryID = absint(wp_unslash($Request['entryID']));
2002 2558 } else {
2003 2559 $formID = wp_unslash($post->formID);
2004 2560 $entryID = wp_unslash($post->entryID);
2005 2561 }
@@ -2019,10 +2575,10 @@
2019 2575 }
2020 2576
2021 2577 public function importDataStore($Request, $post)
2022 2578 {
2023 - if (isset($Request['formID'])) {
2024 - $formID = wp_unslash($Request['formID']);
2579 + if (!empty($Request['formID'])) {
2580 + $formID = absint(wp_unslash($Request['formID']));
2025 2581 } else {
2026 2582 $formID = wp_unslash($post->formID);
2027 2583 }
2028 2584 if (is_null($formID)) {
@@ -2034,10 +2590,14 @@
2034 2590 {
2035 2591 $pages = get_pages(['post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'desc']);
2036 2592 $allPages = [];
2037 2593 foreach ($pages as $pageKey => $pageDetails) {
2038 - $allPages[$pageKey]['title'] = $pageDetails->post_title;
2039 - $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2594 + // $allPages[$pageKey]['title'] = $pageDetails->post_title;
2595 + // $allPages[$pageKey]['url'] = get_page_link($pageDetails->ID);
2596 + $allPages[] = (object) [
2597 + 'title' => $pageDetails->post_title,
2598 + 'url' => get_page_link($pageDetails->ID)
2599 + ];
2040 2600 }
2041 2601 return $allPages;
2042 2602 }
2043 2603
@@ -2042,11 +2602,11 @@
2042 2602 }
2043 2603
2044 2604 public function deleteAIntegration($Request, $post)
2045 2605 {
2046 - if (isset($Request['formID']) && $Request['id']) {
2047 - $formID = json_decode(wp_unslash($Request['formID']));
2048 - $id = wp_unslash($Request['id']);
2606 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2607 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2608 + $id = absint(wp_unslash($Request['id']));
2049 2609 } else {
2050 2610 $formID = wp_unslash($post->formID);
2051 2611 $id = wp_unslash($post->id);
2052 2612 }
@@ -2066,11 +2626,11 @@
2066 2626 }
2067 2627
2068 2628 public function deleteSuccessMessage($Request, $post)
2069 2629 {
2070 - if (isset($Request['formID']) && $Request['id']) {
2071 - $formID = json_decode(wp_unslash($Request['formID']));
2072 - $id = wp_unslash($Request['id']);
2630 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2631 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2632 + $id = absint(wp_unslash($Request['id']));
2073 2633 } else {
2074 2634 $formID = wp_unslash($post->formID);
2075 2635 $id = wp_unslash($post->id);
2076 2636 }
@@ -2089,11 +2649,11 @@
2089 2649 }
2090 2650
2091 2651 public function deleteAWorkflow($Request, $post)
2092 2652 {
2093 - if (isset($Request['formID']) && $Request['id']) {
2094 - $formID = json_decode(wp_unslash($Request['formID']));
2095 - $id = wp_unslash($Request['id']);
2653 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2654 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2655 + $id = absint(wp_unslash($Request['id']));
2096 2656 } else {
2097 2657 $formID = wp_unslash($post->formID);
2098 2658 $id = wp_unslash($post->id);
2099 2659 }
@@ -2111,11 +2671,11 @@
2111 2671 }
2112 2672
2113 2673 public function deleteAMailTemplate($Request, $post)
2114 2674 {
2115 - if (isset($Request['formID']) && $Request['id']) {
2116 - $formID = json_decode(wp_unslash($Request['formID']));
2117 - $id = wp_unslash($Request['id']);
2675 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2676 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2677 + $id = absint(wp_unslash($Request['id']));
2118 2678 } else {
2119 2679 $formID = wp_unslash($post->formID);
2120 2680 $id = wp_unslash($post->id);
2121 2681 }
@@ -2133,11 +2693,11 @@
2133 2693 }
2134 2694
2135 2695 public function duplicateAMailTemplate($Request, $post)
2136 2696 {
2137 - if (isset($Request['formID']) && $Request['id']) {
2138 - $formID = json_decode(wp_unslash($Request['formID']));
2139 - $id = wp_unslash($Request['id']);
2697 + if (!empty($Request['formID']) && !empty($Request['id'])) {
2698 + $formID = absint(json_decode(wp_unslash($Request['formID'])));
2699 + $id = absint(wp_unslash($Request['id']));
2140 2700 } else {
2141 2701 $formID = wp_unslash($post->formID);
2142 2702 $id = wp_unslash($post->id);
2143 2703 }
@@ -2143,8 +2703,17 @@
2143 2703 }
2144 2704 if (empty($formID) || empty($id)) {
2145 2705 return new WP_Error('empty_form', 'Invalid Form ID or Email Template ID.');
2146 2706 }
2707 +
2708 + if (false === filter_var($id, FILTER_VALIDATE_INT)) {
2709 + return new WP_Error('empty_form', 'Invalid Email Template ID.');
2710 + }
2711 +
2712 + if (false === filter_var($formID, FILTER_VALIDATE_INT)) {
2713 + return new WP_Error('empty_form', 'Invalid Form ID.');
2714 + }
2715 +
2147 2716 $emailTemplateHandler = new EmailTemplateHandler($formID);
2148 2717 $duplicate_status = $emailTemplateHandler->duplicateTemplate($id);
2149 2718 if (is_wp_error($duplicate_status)) {
2150 2719 return $duplicate_status;
@@ -2285,22 +2854,34 @@
2285 2854 }
2286 2855 if (is_string($paySetting)) {
2287 2856 $paySetting = json_decode($paySetting);
2288 2857 }
2858 +
2289 2859 $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);
2860 + switch ($paySetting->type) {
2861 + case 'PayPal':
2862 + $canSave = $this->addWebhookToPaypal($paySetting);
2863 + break;
2864 + case 'Razorpay':
2865 + $canSave = true;
2866 + break;
2867 + case 'Stripe':
2868 + $canSave = $this->addWebhookToStripe($paySetting);
2869 + break;
2870 + case 'Mollie':
2871 + $canSave = true;
2872 + break;
2873 + default:
2874 + $canSave = null;
2297 2875 }
2298 2876 if (is_null($canSave)) {
2299 2877 return new WP_Error('stripe', __('Please re-check your Client ID & Secret', 'bit-form'));
2300 2878 }
2301 - $integrationID = $paySetting->id;
2302 - unset($paySetting->id);
2879 + $integrationID = null;
2880 + if (isset($paySetting->id)) {
2881 + $integrationID = $paySetting->id;
2882 + unset($paySetting->id);
2883 + }
2303 2884 $integrationName = $paySetting->name;
2304 2885 $integrationType = 'payments';
2305 2886 $paySetting = wp_json_encode($paySetting);
2306 2887 $integrationDetails = $paySetting;
@@ -2378,15 +2959,16 @@
2378 2959 }
2379 2960 }
2380 2961
2381 2962 $data = [
2382 - 'enabled_events[]' => 'payment_intent.succeeded',
2383 - 'url' => $webhook_url,
2963 + 'enabled_events[]' => 'payment_intent.succeeded',
2964 + 'url' => $webhook_url,
2384 2965 ];
2385 2966
2386 2967 if (!$webhook_already_exist) {
2387 2968 $webhook_response = HttpHelper::post($create_webhook_url, $data, $headers);
2388 2969 if (is_wp_error($webhook_response) || (isset($webhook_response->error) && $webhook_response->error)) {
2970 + Log::debug_log(['Stripe webhook creation failed' => $webhook_response]);
2389 2971 return null;
2390 2972 }
2391 2973 }
2392 2974 return true;
@@ -2429,10 +3011,70 @@
2429 3011 return true;
2430 3012 }
2431 3013 }
2432 3014
3015 + public function replaceAllFormsErrorMessagesByGlobalMessages()
3016 + {
3017 + try {
3018 + $formModel = new FormModel();
3019 + $allForms = $formModel->get(['id', 'form_content']);
3020 +
3021 + foreach ($allForms as $form) {
3022 + // Decode form_content JSON to stdClass
3023 + $formContent = \json_decode($form->form_content);
3024 + $fields = $formContent->fields ?? null;
3025 + // If decode fails, skip to next
3026 + if (!$fields) {
3027 + Log::debug_log("Form ID {$form->id}: invalid JSON in form_content");
3028 + continue;
3029 + }
3030 +
3031 + // Replace default error messages using your helper
3032 + $updatedFields = Helpers::replaceFieldsDefaultErrorMsg($fields);
3033 +
3034 + $formContent->fields = $updatedFields;
3035 + // Encode back to JSON
3036 + $updatedContent = \json_encode($formContent);
3037 +
3038 + if (false === $updatedContent) {
3039 + Log::debug_log("Form ID {$form->id}: JSON encoding failed");
3040 + continue;
3041 + }
3042 + // Update form content in DB
3043 + $formModel->update(
3044 + ['form_content' => $updatedContent], // data to update
3045 + ['id' => $form->id] // condition for update
3046 + );
3047 + }
3048 + } catch (\Exception $e) {
3049 + Log::debug_log([
3050 + 'message' => 'Error in updateAllFormsErrorMessagesWithGlobalMessages',
3051 + 'error' => $e->getMessage(),
3052 + ]);
3053 + }
3054 + }
3055 +
2433 3056 public function updateSuccessMessageClassName($str, $msgIdx, $msgId)
2434 3057 {
2435 3058 $TEMP_CONF_ID = '_tmp_' . $msgIdx . '_conf_id';
2436 3059 return str_replace($TEMP_CONF_ID, $msgId, $str);
3060 + }
3061 +
3062 + public function startMigrationProcess()
3063 + {
3064 + Utilities::duplicateDbTable('form', 'form_v1');
3065 + Utilities::duplicateDbTable('workflows', 'workflows_v1');
3066 + Utilities::duplicateDbTable('success_messages', 'success_messages_v1');
3067 + MigrationHelper::duplicateV1StyleFiles();
3068 + $all_forms = $this->getAllForm();
3069 + $v1FormContents = [];
3070 + $defaultStyleClass = MigrationHelper::getBitformDefaultStyleClass();
3071 + foreach ($all_forms as $form) {
3072 + $formContents = $this->getAFormV1(['id' => $form->id], ['id' => $form->id]);
3073 + $v1FormContents[] = $formContents;
3074 + FrontEndScriptGenerator::saveCssFile("{$form->id}", $defaultStyleClass);
3075 + FrontEndScriptGenerator::saveCssFile("{$form->id}-formid", $defaultStyleClass);
3076 + }
3077 + set_transient('bitforms_v1_form_contents', $v1FormContents);
3078 + update_option('bitforms_migrating_to_v2', true);
2437 3079 }
2438 3080 }