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/Frontend/Form/FrontendFormHandler.php +318 -59 -3.0.13.3.1 View file →
@@ -15,14 +15,21 @@
15 15 use BitCode\BitForm\Core\Integration\IntegrationHandler;
16 16 use BitCode\BitForm\Core\Util\EscapingHelper;
17 17 use BitCode\BitForm\Core\Util\FieldValueHandler;
18 18 use BitCode\BitForm\Core\Util\FileDownloadProvider;
19 +use BitCode\BitForm\Core\Util\FileHandler;
19 20 use BitCode\BitForm\Core\Util\FrontendHelpers;
21 +use BitCode\BitForm\Core\Util\Log;
22 +use BitCode\BitForm\Core\Util\SmartTagRegistry;
20 23 use BitCode\BitForm\Core\Util\SmartTags;
24 +use BitCode\BitForm\Core\Util\Utilities;
21 25 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
22 26
23 27 final class FrontendFormHandler
24 28 {
29 + /** Largest stored signature inlined into the page as a data URI. */
30 + private const MAX_INLINE_SIGNATURE_BYTES = 2097152;
31 +
25 32 public function __construct()
26 33 {
27 34 // before markup load - formids [], posts [1,2]
28 35 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
@@ -28,9 +35,11 @@
28 35 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
29 36 // markup loads - formids []
30 37 add_shortcode('bitform', [$this, 'handleFrontendRenderRequest']);
31 38 // after markup load - formids [1,35,3]
32 - add_action('wp_footer', [$this, 'generateJS']);
39 + // After popup plugins render at 10 (that is when popup-only forms register
40 + // their formID), before wp_print_footer_scripts at 20.
41 + add_action('wp_footer', [$this, 'generateJS'], 15);
33 42 }
34 43
35 44 private function validPassowordResetToken($token, $userID, $formId)
36 45 {
@@ -59,10 +68,43 @@
59 68
60 69 return $formScriptSrc;
61 70 }
62 71
72 + private function getJSFilePath($postId)
73 + {
74 + return BITFORMS_CONTENT_DIR . "/form-scripts/$postId/bitform-js-$postId.js";
75 + }
76 +
77 + /**
78 + * Does this page's bundle need (re)generating?
79 + *
80 + * The DB flag alone is not enough: a page marked generated whose file was never written
81 + * (crashed generation, unwritable uploads dir) would enqueue a 404 forever. Conversely a
82 + * file that cannot be written must not make every request rebuild it, so a missing file
83 + * is retried on a backoff window rather than on every hit.
84 + *
85 + * @param int $postId
86 + * @param bool $regenerateScriptFlag DB-side verdict from regenerateScriptChecker()
87 + *
88 + * @return bool
89 + */
90 + private function needsScriptGeneration($postId, $regenerateScriptFlag)
91 + {
92 + if (file_exists($this->getJSFilePath($postId))) {
93 + return (bool) $regenerateScriptFlag;
94 + }
95 + $retryKey = 'bitforms_js_regen_' . $postId;
96 + if (get_transient($retryKey)) {
97 + return false;
98 + }
99 + set_transient($retryKey, 1, 5 * MINUTE_IN_SECONDS);
100 + return true;
101 + }
102 +
63 103 public function generateJs($formID = null, $entryID = null, $formType = null)
64 104 {
105 + // bitform-js-{postId}.js is disk-cached per post ID with no language key.
106 + // Display strings must stay out of it and travel in bf_globals per request.
65 107 // return true;
66 108 $isFormPreview = get_transient('bitform_form_preview');
67 109 if ($isFormPreview && !$formID) {
68 110 delete_transient('bitform_form_preview');
@@ -122,8 +164,10 @@
122 164 if (!$regenerateScriptFlag) {
123 165 $regenerateScriptFlag = $this->deleteUnusedFormPageIds($postId, $bfUniqFormIds);
124 166 }
125 167 $isJsGenerating = get_option('bitforms_frontend_js_generating');
168 + // The fast path also requires the cached bundle to exist on disk, not just be flagged in the DB.
169 + $regenerateScriptFlag = $this->needsScriptGeneration($postId, $regenerateScriptFlag);
126 170 if (!$regenerateScriptFlag && !$isJsGenerating && !empty($formIDs)) {
127 171 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
128 172 return;
129 173 }
@@ -156,8 +200,13 @@
156 200 $frontendScriptGenObj->generateJsFile($formContents, $allFields, $contentIds, $postId, $formIDs, $previewMode);
157 201 if ('preview' === $previewMode) {
158 202 return;
159 203 }
204 + // Only mark the page as generated once the bundle is verifiably on disk; otherwise the
205 + // next request must retry generation instead of fast-pathing to a stale/missing file.
206 + if (!empty($bfUniqFormIds) && file_exists($this->getJSFilePath($postId))) {
207 + $this->markScriptGenerated($bfUniqFormIds, $postId);
208 + }
160 209 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
161 210 }
162 211
163 212 private function deleteUnusedFormPageIds($postId, $formIDs)
@@ -173,9 +222,9 @@
173 222 );
174 223 $regenerateScriptFlag = false;
175 224 foreach ($forms as $form) {
176 225 $formId = $form->id;
177 - $generatedScriptPageIdsDecoded = json_decode($form->generated_script_page_ids, true);
226 + $generatedScriptPageIdsDecoded = json_decode((string) $form->generated_script_page_ids, true);
178 227 $generatedScriptPageIds = is_array($generatedScriptPageIdsDecoded) ? array_keys($generatedScriptPageIdsDecoded) : [];
179 228 if (!empty($generatedScriptPageIds) && !in_array($formId, $formIDs) && in_array($postId, $generatedScriptPageIds)) {
180 229 unset($generatedScriptPageIdsDecoded[$postId]);
181 230 if (empty($generatedScriptPageIdsDecoded)) {
@@ -203,10 +252,11 @@
203 252 if (!is_a($post, 'WP_Post') && !isset($post->ID)) {
204 253 return;
205 254 }
206 255 $postId = $post->ID;
207 - $regenerateScriptFlag = false;
208 - $formModel = new FormModel();
256 + // Read-only check. Marking the page as generated is deferred to markScriptGenerated(),
257 + // called only after the bundle file is actually written — marking here left the DB
258 + // saying "generated" while the file stayed stale whenever generation failed mid-way.
209 259 foreach ($formsIds as $formId) {
210 260 $formInstance = FormManager::getInstance($formId);
211 261 if (!$formInstance->isExist()) {
212 262 continue;
@@ -212,18 +262,35 @@
212 262 continue;
213 263 }
214 264 $generatedPages = $formInstance->getFormData('generated_script_page_ids');
215 265 if (empty($generatedPages)) {
216 - $regenerateScriptFlag = true;
217 - } elseif (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || (isset($generatedPages->{$postId}) && false === $generatedPages->{$postId}))) {
218 - $regenerateScriptFlag = true;
266 + return true;
219 267 }
220 - if (!$regenerateScriptFlag) {
268 + if (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || false === $generatedPages->{$postId})) {
269 + return true;
270 + }
271 + }
272 + return false;
273 + }
274 +
275 + private function markScriptGenerated($formsIds, $postId)
276 + {
277 + // Fetched via FormModel rather than FormManager: FormManager keeps its row in a static
278 + // property shared across instances, so after the render loop it holds the last form's
279 + // data regardless of which instance is asked.
280 + $formModel = new FormModel();
281 + foreach ($formsIds as $formId) {
282 + $form = $formModel->get(['generated_script_page_ids'], ['id' => $formId]);
283 + if (is_wp_error($form) || empty($form)) {
221 284 continue;
222 285 }
286 + $generatedPages = Utilities::jsonObj($form[0]->generated_script_page_ids ?? '');
223 287 if (!is_object($generatedPages)) {
224 288 $generatedPages = (object) [];
225 289 }
290 + if (!empty($generatedPages->{$postId})) {
291 + continue;
292 + }
226 293 $generatedPages->{$postId} = true;
227 294 $formModel->update(
228 295 [
229 296 'generated_script_page_ids' => \wp_json_encode($generatedPages)
@@ -232,9 +299,8 @@
232 299 'id' => $formId,
233 300 ]
234 301 );
235 302 }
236 - return $regenerateScriptFlag;
237 303 }
238 304
239 305 private function addInlineScript($code, $handle = '', $position = 'after')
240 306 {
@@ -279,9 +345,9 @@
279 345
280 346 return $fields;
281 347 }
282 348
283 - private function executeOnUserInput($formID, $shortCodeCounter, $fields)
349 + private function executeOnUserInput($formID, $shortCodeCounter, $workFlowRunType = 'create')
284 350 {
285 351 $FrontendFormManager = FrontendFormManager::getInstance($formID, $shortCodeCounter);
286 352 $previousValue = $this->getValuesFromQueryParams();
287 353 $formContent = $FrontendFormManager->getFormContentWithValue($previousValue);
@@ -287,9 +353,9 @@
287 353 $formContent = $FrontendFormManager->getFormContentWithValue($previousValue);
288 354 $customCodesExist = strpos(FrontEndScriptGenerator::getCustomCodes($formID)['JavaScript'], 'bfVars');
289 355 if ($customCodesExist || (!empty($formContent->workFlowExist) && !empty($formContent->workFlowExist->oninput))) {
290 356 $workFlowRunHelper = new WorkFlow($formID);
291 - return $workFlowRunHelper->executeOnUserInput('create', $fields);
357 + return $workFlowRunHelper->executeOnUserInput($workFlowRunType);
292 358 }
293 359 }
294 360
295 361 private function getValuesFromQueryParams()
@@ -296,21 +362,20 @@
296 362 {
297 363 // Read-only: query string parsed to pre-fill form fields. Values are sanitized per field before use.
298 364 $queryParamsValue = [];
299 365 if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
300 - $reqField = sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING']));
366 + $reqField = wp_unslash($_SERVER['QUERY_STRING']);
301 367 foreach (explode('&', $reqField) as $keyValue) {
302 - // $pattern = '/([a-zA-Z0-9])([a-zA-Z])\=+/';
303 - $pattern = '/([^.]+)=(.*?)([^.]+)/';
304 - $matches = preg_match($pattern, $keyValue, $matchFormat);
305 - if ($matches) {
368 + if (false !== strpos($keyValue, '=')) {
306 369 list($field, $value) = explode('=', $keyValue, 2);
307 370
308 371 if (!trim($value)) {
309 372 continue;
310 373 }
311 -
312 - $queryParamsValue[$field][] = sanitize_text_field(urldecode($value));
374 + $field = sanitize_text_field(urldecode($field));
375 + if (!empty($field)) {
376 + $queryParamsValue[$field][] = sanitize_text_field(urldecode($value));
377 + }
313 378 }
314 379 }
315 380 }
316 381
@@ -410,9 +475,9 @@
410 475 $fields = apply_filters('bitform_filter_before_workflow_onload_fields', $fields, $formID);
411 476 $fields = $this->triggerWorkflowOnLoad($formID, $shortCodeCounter, $fields, $workFlowRunType);
412 477 $fields = apply_filters('bitform_filter_after_workflow_onload_fields', $fields, $formID);
413 478 do_action('bitform_onload_fields', $fields, $formID);
414 - $workFlowreturnedOnUserInput = $this->executeOnUserInput($formID, $shortCodeCounter, $fields);
479 + $workFlowreturnedOnUserInput = $this->executeOnUserInput($formID, $shortCodeCounter, $workFlowRunType);
415 480
416 481 // test for form before remove
417 482 $noLabelFieldTypes = ['decision-box', 'gdpr', 'html', 'shortcode', 'button', 'paypal', 'razorpay', 'recaptcha', 'turnstile', 'hcaptcha', 'stripe', 'spacer'];
418 483 foreach ($fields as $fldKey => $field) {
@@ -433,12 +498,14 @@
433 498 $FrontendFormManager->getCaptchaSettings()
434 499 && !is_null($integration->integration_type)
435 500 && 'gReCaptcha' === $integration->integration_type
436 501 ) {
437 - $integrationDetails = json_decode($integration->integration_details);
438 - $integrationDetails->id = $integration->id;
439 - $reCAPTCHA = $integrationDetails;
440 - $reCAPTCHAVersion = 'v2';
502 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
503 + if ($integrationDetails) {
504 + $integrationDetails->id = $integration->id;
505 + $reCAPTCHA = $integrationDetails;
506 + $reCAPTCHAVersion = 'v2';
507 + }
441 508 }
442 509
443 510 if (
444 511 $FrontendFormManager->getTurnstileSettings()
@@ -444,10 +511,10 @@
444 511 $FrontendFormManager->getTurnstileSettings()
445 512 && !is_null($integration->integration_type)
446 513 && 'turnstileCaptcha' === $integration->integration_type
447 514 ) {
448 - $integrationDetails = json_decode($integration->integration_details);
449 - $turnstileSiteKey = $integrationDetails->siteKey;
515 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
516 + $turnstileSiteKey = $integrationDetails->siteKey ?? '';
450 517 }
451 518
452 519 if (
453 520 $FrontendFormManager->isFieldTypeExist('hcaptcha')
@@ -453,18 +520,20 @@
453 520 $FrontendFormManager->isFieldTypeExist('hcaptcha')
454 521 && !is_null($integration->integration_type)
455 522 && 'hcaptcha' === $integration->integration_type
456 523 ) {
457 - $integrationDetails = json_decode($integration->integration_details);
458 - $hCaptchaSiteKey = $integrationDetails->siteKey;
524 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
525 + $hCaptchaSiteKey = $integrationDetails->siteKey ?? '';
459 526 }
460 527
461 528 if ($captchaV3Settings) {
462 529 if (!is_null($integration->integration_type) && 'gReCaptchaV3' === $integration->integration_type) {
463 - $integrationDetails = json_decode($integration->integration_details);
464 - $integrationDetails->id = $integration->id;
465 - $reCAPTCHA = $integrationDetails;
466 - $reCAPTCHAVersion = 'v3';
530 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
531 + if ($integrationDetails) {
532 + $integrationDetails->id = $integration->id;
533 + $reCAPTCHA = $integrationDetails;
534 + $reCAPTCHAVersion = 'v3';
535 + }
467 536 }
468 537 }
469 538 }
470 539 }
@@ -497,19 +566,20 @@
497 566 $paymentIntegration = $integrationHandler->getAIntegration($fldData->payIntegID);
498 567 if (is_wp_error($paymentIntegration)) {
499 568 continue;
500 569 }
570 + $paymentIntegrationRow = Utilities::firstRow($paymentIntegration);
501 571 if ('paypal' === $fldData->typ) {
502 - $integrationDetails = json_decode($paymentIntegration[0]->integration_details);
503 - $clientID = $integrationDetails->clientID;
572 + $integrationDetails = Utilities::jsonObj($paymentIntegrationRow->integration_details ?? '');
573 + $clientID = $integrationDetails->clientID ?? '';
504 574 $fields->{$fldKey}->clientId = $clientID;
505 575 } elseif ('razorpay' === $fldData->typ) {
506 - $integrationDetails = json_decode($paymentIntegration[0]->integration_details);
507 - $clientID = $integrationDetails->apiKey;
576 + $integrationDetails = Utilities::jsonObj($paymentIntegrationRow->integration_details ?? '');
577 + $clientID = $integrationDetails->apiKey ?? '';
508 578 $fields->{$fldKey}->clientId = $clientID;
509 579 } elseif ('stripe' === $fldData->typ) {
510 - $integrationDetails = json_decode($paymentIntegration[0]->integration_details);
511 - $publishableKey = $integrationDetails->publishableKey;
580 + $integrationDetails = Utilities::jsonObj($paymentIntegrationRow->integration_details ?? '');
581 + $publishableKey = $integrationDetails->publishableKey ?? '';
512 582 $fields->{$fldKey}->publishableKey = $publishableKey;
513 583 }
514 584 }
515 585 }
@@ -529,9 +599,9 @@
529 599 'appID' => "bitforms_{$formID}",
530 600 'GCLID' => $FrontendFormManager->isGCLIDEnabled(),
531 601 'assetUrl' => BITFORMS_ASSET_URI,
532 602 'onfieldCondition' => !empty($workFlowreturnedOnUserInput['onfield_input_conditions']) ? $workFlowreturnedOnUserInput['onfield_input_conditions'] : false,
533 - 'smartTags' => SmartTags::smartTags(SmartTags::getPostUserData()),
603 + 'smartTags' => $this->buildFrontendSmartTags($formID, $workFlowreturnedOnUserInput, $fields),
534 604 'paymentCallbackUrl' => get_rest_url() . 'bitform/v1/payments/razorpay',
535 605 'gRecaptchaSiteKey' => !empty($reCAPTCHA->siteKey) ? $reCAPTCHA->siteKey : null,
536 606 'gRecaptchaVersion' => !empty($reCAPTCHAVersion) ? $reCAPTCHAVersion : null,
537 607 'turnstileSiteKey' => !empty($turnstileSiteKey) ? $turnstileSiteKey : null,
@@ -539,8 +609,9 @@
539 609 ];
540 610
541 611 if ($entryId) {
542 612 $bitFormFrontArr['entryId'] = $entryId;
613 + self::markResponseUncacheable();
543 614 }
544 615
545 616 if (isset($additional->enabled->validateFocusLost)) {
546 617 $bitFormFrontArr['validateFocusLost'] = true;
@@ -546,11 +617,13 @@
546 617 $bitFormFrontArr['validateFocusLost'] = true;
547 618 }
548 619
549 620 if (!empty($isAbandoned)) {
621 + // One visitor's typed values, so this response must not be page-cached.
550 622 $bitFormFrontArr['oldValues'] = $this->getFieldsValue($formID, $isAbandoned);
623 + self::markResponseUncacheable();
551 624 if (empty($entryId)) {
552 - $bitFormFrontArr['entryId'] = $isAbandoned;
625 + $bitFormFrontArr['entryId'] = $entryId;
553 626 }
554 627 }
555 628
556 629 $formInfo = $FrontendFormManager->getFormInfo();
@@ -585,27 +658,31 @@
585 658 $layout = wp_json_encode($layout);
586 659 $buttons = wp_json_encode($buttons);
587 660 $frontArr = wp_json_encode($bitFormFrontArr);
588 661
589 - $bfGlobals = sprintf('
590 - if(!window.bf_globals) {
591 - window.bf_globals = {}
592 - } if(!window.bf_globals.%1$s) {
593 - window.bf_globals.%1$s = {}
662 + $bfGlobals = sprintf('
663 + if(!window.bf_globals) {
664 + window.bf_globals = {}
665 + } if(!window.bf_globals.%1$s) {
666 + window.bf_globals.%1$s = {}
594 667 }
595 - if(document.getElementById("%1$s")) {
596 - window.bf_globals.%1$s = {
597 - ...window.bf_globals.%1$s,
598 - ...%2$s
599 - };
600 - }', $FormIdentifier, $frontArr);
668 + window.bf_globals.%1$s = {
669 + ...window.bf_globals.%1$s,
670 + ...%2$s
671 + };
672 + if (typeof window.bitformInit === "function") { window.bitformInit("%1$s"); }', $FormIdentifier, $frontArr);
601 673
674 + // Inert copy of the config. Optimizers only rewrite executable scripts, so
675 + // this survives and travels with the markup; the runtime hydrates from it
676 + // whenever bf_globals is missing.
677 + $configTag = self::buildFormConfigTag($FormIdentifier, $bitFormFrontArr);
678 +
602 679 if ('conversational' === $formType
603 680 && isset($formContent->formInfo->conversationalSettings->enable)
604 681 && $formContent->formInfo->conversationalSettings->enable) {
605 - $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages);
682 + $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages, null, !empty($entryId));
606 683 } else {
607 - $html = $FrontendFormManager->formView($fields, $file, $errorMessages);
684 + $html = $FrontendFormManager->formView($fields, $file, $errorMessages, null, !empty($entryId));
608 685 }
609 686
610 687 // if form preview then return html otherwise echo with output buffer
611 688 if ($formPreview) {
@@ -613,8 +690,9 @@
613 690 $formViewObject = new \stdClass();
614 691 $formViewObject->html = $html;
615 692 $formViewObject->font = $font;
616 693 $formViewObject->bfGlobals = $bfGlobals;
694 + $formViewObject->configTag = $configTag;
617 695 $formViewObject->formContent = $formContent;
618 696 return $formViewObject;
619 697 }
620 698
@@ -621,13 +699,110 @@
621 699 $bfGlobalsHandle = 'bitform-bf-globals-' . sanitize_key($FormIdentifier);
622 700 $this->addInlineScript($bfGlobals, $bfGlobalsHandle, 'after');
623 701 $this->emitShowPickerBridge();
624 702
703 + // Printed outside wp_kses rather than allowing <script> in form markup.
704 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built by buildFormConfigTag(), JSON_HEX_* escaped.
705 + echo $configTag;
625 706 echo wp_kses(trim($html), EscapingHelper::getFormAllowedHtml($formContent));
626 707 return ob_get_clean();
627 708 }
628 709
629 710 /**
711 + * Keep per-visitor config (oldValues, entryId) out of full-page caches.
712 + *
713 + * @return void
714 + */
715 + public static function markResponseUncacheable()
716 + {
717 + // DONOTCACHEPAGE does the work; caches read it at shutdown. Rendering
718 + // usually runs after headers are sent, so nocache_headers() is a bonus.
719 + if (!defined('DONOTCACHEPAGE')) {
720 + define('DONOTCACHEPAGE', true);
721 + }
722 + if (!headers_sent() && function_exists('nocache_headers')) {
723 + nocache_headers();
724 + }
725 + }
726 +
727 + /**
728 + * Build the inert JSON config block for a rendered form.
729 + *
730 + * JSON_HEX_* escapes < > & as \u00XX so no field value can close the script
731 + * element or inject markup.
732 + *
733 + * @param string $formIdentifier
734 + * @param array $config
735 + *
736 + * @return string
737 + */
738 + public static function buildFormConfigTag($formIdentifier, $config)
739 + {
740 + $json = wp_json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
741 + if (false === $json) {
742 + return '';
743 + }
744 + // Some optimizers wrap any inline <script>, including application/json,
745 + // in DOMContentLoaded boilerplate that corrupts the JSON. These attributes
746 + // make the common ones skip it; the JS side also salvage-parses.
747 + return sprintf(
748 + '<script type="application/json" class="bf-form-config" id="bf-config-%1$s" data-bf-form="%1$s" data-no-optimize="1" data-no-defer="1" data-no-minify="1" data-cfasync="false" nowprocket>%2$s</script>',
749 + esc_attr($formIdentifier),
750 + $json
751 + );
752 + }
753 +
754 + /**
755 + * Build the smart-tag map exposed to the browser in window.bf_globals[formId].smartTags.
756 + *
757 + * Security: the legacy code shipped the ENTIRE ~43-tag map to every visitor, leaking
758 + * PII (admin/user/author email) and freezing per-visitor request data (IP, time,
759 + * browser, referer) into cacheable HTML. We now emit ONLY tags that are (a) actually
760 + * referenced by this form's client-evaluated surfaces — conditional logic, payment
761 + * notes, admin custom JS — AND (b) flagged frontend-safe in the registry (static/post
762 + * context only). Sensitive (identity) and request/visitor tags are never emitted; they
763 + * resolve server-side at submit time instead.
764 + *
765 + * @param int|string $formID
766 + * @param mixed $workflowConditions on-field input conditions (client-evaluated)
767 + * @param mixed $fields form fields object (carries payment notes, etc.)
768 + * @return array<string,string>
769 + */
770 + private function buildFrontendSmartTags($formID, $workflowConditions, $fields)
771 + {
772 + // Haystack = only surfaces the browser actually evaluates against smartTags.
773 + $haystack = wp_json_encode($workflowConditions) . ' ' . wp_json_encode($fields);
774 + $customJs = FrontEndScriptGenerator::getCustomCodes($formID)['JavaScript'];
775 + if (is_string($customJs) && '' !== $customJs) {
776 + $haystack .= ' ' . $customJs;
777 + }
778 +
779 + $ctx = SmartTags::getPostUserData();
780 + $frontendSmartTags = [];
781 + $referenced = [];
782 + foreach (SmartTags::smartTagFieldKeys() as $key) {
783 + if (!SmartTagRegistry::isFrontendExposable($key)) {
784 + continue; // identity / request / param tags never travel to the browser
785 + }
786 + // Match '${' . key prefix so keys containing spaces/slashes/commas are handled.
787 + if (false !== strpos($haystack, '${' . $key)) {
788 + $referenced[] = $key;
789 + $frontendSmartTags[$key] = SmartTagRegistry::resolve($key, $ctx);
790 + }
791 + }
792 +
793 + /**
794 + * Escape hatch: a site that genuinely needs an extra tag client-side can opt it
795 + * back in explicitly here, rather than core shipping everything by default.
796 + *
797 + * @param array<string,string> $frontendSmartTags resolved frontend-safe smart tags
798 + * @param int|string $formID
799 + * @param string[] $referenced keys detected in client surfaces
800 + */
801 + return apply_filters('bitform_frontend_smarttags', $frontendSmartTags, $formID, $referenced);
802 + }
803 +
804 + /**
630 805 * Delegated listener that opens the native picker on date/time inputs marked
631 806 * with data-bf-show-picker. Replaces the legacy hardcoded onclick attribute.
632 807 * Registered as inline script once per request via wp_add_inline_script so
633 808 * the markup never travels through wp_kses().
@@ -642,8 +817,15 @@
642 817 $code = 'if(!window.__bfShowPickerBound){window.__bfShowPickerBound=true;document.addEventListener("click",function(e){var t=e.target;if(t&&t.matches&&t.matches("input[data-bf-show-picker=\"1\"]")&&typeof t.showPicker==="function"){try{t.showPicker();}catch(_){}}});}';
643 818 $this->addInlineScript($code, 'bitform-show-picker-bridge', 'after');
644 819 }
645 820
821 + /**
822 + * Does this form row exist?
823 + *
824 + * @param int $formID
825 + *
826 + * @return bool
827 + */
646 828 private function isExist($formID)
647 829 {
648 830 $formModel = new FormModel();
649 831 $form = $formModel->get(
@@ -653,12 +835,32 @@
653 835 [
654 836 'id' => $formID,
655 837 ]
656 838 );
657 - if (!is_wp_error($form)) {
658 - return true;
839 +
840 + if (is_wp_error($form)) {
841 + if ('result_empty' !== $form->get_error_code()) {
842 + Log::debug_log([
843 + 'message' => 'Form lookup failed — reported to the visitor as a missing form',
844 + 'formID' => $formID,
845 + 'code' => $form->get_error_code(),
846 + 'error' => $form->get_error_message(),
847 + ]);
848 + }
849 +
850 + return false;
659 851 }
660 - return false;
852 +
853 + if (empty($form)) {
854 + Log::debug_log([
855 + 'message' => 'Form lookup returned no rows without an error (is the form table present?)',
856 + 'formID' => $formID,
857 + ]);
858 +
859 + return false;
860 + }
861 +
862 + return true;
661 863 }
662 864
663 865 private function getFieldsValue($formID, $entryID)
664 866 {
@@ -714,8 +916,23 @@
714 916 'bitforms_form_entry_id' => $entryID,
715 917 ]
716 918 );
717 919 if (!is_wp_error($metaValues)) {
920 + $urlQuery = wp_parse_url(FileDownloadProvider::getBaseDownloadURL(), PHP_URL_QUERY);
921 + $baseDLURL = FileDownloadProvider::getBaseDownloadURL();
922 + $baseDLURL = empty($urlQuery) ? $baseDLURL . '?' : $baseDLURL . '&';
923 + $baseDLURL .= "formID={$formID}&entryID={$entryID}";
924 +
925 + foreach ($fields as $field) {
926 + if ('file-up' === $field->typ || 'advanced-file-up' === $field->typ) {
927 + if (!isset($field->config)) {
928 + $field->config = (object) [];
929 + } elseif (is_array($field->config)) {
930 + $field->config = (object) $field->config;
931 + }
932 + $field->config->baseDLURL = $baseDLURL;
933 + }
934 + }
718 935 foreach ($metaValues as $metaValue) {
719 936 $metaKey = $metaValue->meta_key;
720 937 $metaVal = $metaValue->meta_value;
721 938 // if meta value is array then convert to string
@@ -732,17 +949,59 @@
732 949 $fields->{$metaKey}->val = $metaVal;
733 950 if ('file-up' === $fields->{$metaKey}->typ || 'advanced-file-up' === $fields->{$metaKey}->typ) {
734 951 $fields->{$metaKey}->val = $metaValue->meta_value;
735 952 $fields->{$metaKey}->config->oldFiles = $metaValue->meta_value;
736 - $urlQuery = wp_parse_url(FileDownloadProvider::getBaseDownloadURL(), PHP_URL_QUERY);
737 - $baseDLURL = FileDownloadProvider::getBaseDownloadURL();
738 - $baseDLURL = empty($urlQuery) ? $baseDLURL . '?' : $baseDLURL . '&';
739 - $fields->{$metaKey}->config->baseDLURL = $baseDLURL . "formID={$formID}&entryID={$entryID}";
740 953 }
954 + if ('signature' === $fields->{$metaKey}->typ) {
955 + $this->setOldSignature($fields->{$metaKey}, $formID, $entryID, $metaValue->meta_value);
956 + }
741 957 }
742 958 }
743 959 }
744 960 return $fields;
961 + }
962 +
963 + /** Give the signature field its stored signature: a data URI to redraw, and the name it posts back as `_old`. */
964 + private function setOldSignature($field, $formID, $entryID, $storedValue)
965 + {
966 + $fileName = is_string($storedValue) ? trim($storedValue) : '';
967 + $decoded = json_decode($fileName, true);
968 + if (is_array($decoded)) {
969 + $fileName = empty($decoded) ? '' : trim((string) reset($decoded));
970 + }
971 + // signature-failed.png means the stored signature was never usable.
972 + if ('' === $fileName || 'signature-failed.png' === $fileName) {
973 + return;
974 + }
975 + $fileName = sanitize_file_name($fileName);
976 + if (!isset($field->config)) {
977 + $field->config = (object) [];
978 + } elseif (is_array($field->config)) {
979 + $field->config = (object) $field->config;
980 + }
981 + $field->config->oldSignatureFile = $fileName;
982 +
983 + $filePath = FileHandler::getEntriesFileUploadDir($formID, $entryID) . DIRECTORY_SEPARATOR . $fileName;
984 + if (!is_file($filePath) || !is_readable($filePath)) {
985 + return;
986 + }
987 + // The types getSignatureFilePath() writes; wp_check_filetype() reports none for SVG.
988 + $signatureMimeTypes = ['png' => 'image/png', 'jpg' => 'image/jpeg', 'svg' => 'image/svg+xml'];
989 + $extension = strtolower((string) pathinfo($fileName, PATHINFO_EXTENSION));
990 + if (!isset($signatureMimeTypes[$extension])) {
991 + return;
992 + }
993 + $mimeType = $signatureMimeTypes[$extension];
994 + // A hand-drawn signature is a few KB; a larger file is not worth inlining.
995 + if (filesize($filePath) > self::MAX_INLINE_SIGNATURE_BYTES) {
996 + return;
997 + }
998 + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_get_contents -- local upload dir read, inlined as a data URI for the signature pad.
999 + $contents = file_get_contents($filePath);
1000 + if (false === $contents || '' === $contents) {
1001 + return;
1002 + }
1003 + $field->config->oldSignature = 'data:' . $mimeType . ';base64,' . base64_encode($contents);
745 1004 }
746 1005
747 1006 public function loadAssets($formID = 0, $fromType = 'classic')
748 1007 {