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/Frontend/Form/FrontendFormHandler.php +272 -49 3.2.0 → V3.3.2 View file →
@@ -8,8 +8,9 @@
8 8
9 9 use BitCode\BitForm\Admin\Form\AdminFormHandler;
10 10 use BitCode\BitForm\Admin\Form\FrontEndScriptGenerator;
11 11 use BitCode\BitForm\Admin\Form\Helpers;
12 +use BitCode\BitForm\Core\Cryptography\Cryptography;
12 13 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
13 14 use BitCode\BitForm\Core\Database\FormModel;
14 15 use BitCode\BitForm\Core\Form\FormManager;
15 16 use BitCode\BitForm\Core\Integration\IntegrationHandler;
@@ -15,9 +16,11 @@
15 16 use BitCode\BitForm\Core\Integration\IntegrationHandler;
16 17 use BitCode\BitForm\Core\Util\EscapingHelper;
17 18 use BitCode\BitForm\Core\Util\FieldValueHandler;
18 19 use BitCode\BitForm\Core\Util\FileDownloadProvider;
20 +use BitCode\BitForm\Core\Util\FileHandler;
19 21 use BitCode\BitForm\Core\Util\FrontendHelpers;
22 +use BitCode\BitForm\Core\Util\Log;
20 23 use BitCode\BitForm\Core\Util\SmartTagRegistry;
21 24 use BitCode\BitForm\Core\Util\SmartTags;
22 25 use BitCode\BitForm\Core\Util\Utilities;
23 26 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
@@ -23,8 +26,11 @@
23 26 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
24 27
25 28 final class FrontendFormHandler
26 29 {
30 + /** Largest stored signature inlined into the page as a data URI. */
31 + private const MAX_INLINE_SIGNATURE_BYTES = 2097152;
32 +
27 33 public function __construct()
28 34 {
29 35 // before markup load - formids [], posts [1,2]
30 36 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
@@ -30,29 +36,37 @@
30 36 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
31 37 // markup loads - formids []
32 38 add_shortcode('bitform', [$this, 'handleFrontendRenderRequest']);
33 39 // after markup load - formids [1,35,3]
34 - add_action('wp_footer', [$this, 'generateJS']);
40 + // After popup plugins render at 10 (that is when popup-only forms register
41 + // their formID), before wp_print_footer_scripts at 20.
42 + add_action('wp_footer', [$this, 'generateJS'], 15);
35 43 }
36 44
37 - private function validPassowordResetToken($token, $userID, $formId)
45 + /**
46 + * A reset form opened from a used or expired link cannot succeed, so show why instead of
47 + * the form. Returns the notice markup, or '' when the link is fine or the form is not a
48 + * reset form. Rendered in place of the form (the old exit() cut the page off mid-theme).
49 + *
50 + * @param string $token key from the reset link
51 + * @param string $userID user ID from the reset link
52 + * @param int $formId form being rendered
53 + *
54 + * @return string
55 + */
56 + private function invalidPasswordResetNotice($token, $userID, $formId)
38 57 {
39 58 $existResetInteg = (new IntegrationHandler($formId))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
40 - if (!is_wp_error($existResetInteg) && count($existResetInteg) > 0) {
41 - if ('reset' === $existResetInteg[0]->integration_name) {
42 - $user = get_userdata($userID);
43 - if ($user) {
44 - $validKey = check_password_reset_key($token, $user->user_login);
45 - if (is_wp_error($validKey)) {
46 - echo "<div id='bf-resp' style='display:grid;justify-content:center;color:#860000;'>This password reset token is invalid.</div>";
47 - exit();
48 - }
49 - } else {
50 - echo "<div id='bf-resp' style='display:grid;justify-content:center;color:#860000;'>Invalid User!!</div>";
51 - exit();
52 - }
53 - }
59 + if (is_wp_error($existResetInteg) || empty($existResetInteg) || 'reset' !== $existResetInteg[0]->integration_name) {
60 + return '';
54 61 }
62 + $user = get_userdata((int) $userID);
63 + if ($user && !is_wp_error(check_password_reset_key($token, $user->user_login))) {
64 + return '';
65 + }
66 + return "<div id='bf-resp' role='alert' style='display:grid;justify-content:center;color:#860000;'>"
67 + . esc_html__('This password reset link is invalid or has expired. Please request a new one.', 'bit-form')
68 + . '</div>';
55 69 }
56 70
57 71 private function getJSFileSrc($postId)
58 72 {
@@ -61,10 +75,43 @@
61 75
62 76 return $formScriptSrc;
63 77 }
64 78
79 + private function getJSFilePath($postId)
80 + {
81 + return BITFORMS_CONTENT_DIR . "/form-scripts/$postId/bitform-js-$postId.js";
82 + }
83 +
84 + /**
85 + * Does this page's bundle need (re)generating?
86 + *
87 + * The DB flag alone is not enough: a page marked generated whose file was never written
88 + * (crashed generation, unwritable uploads dir) would enqueue a 404 forever. Conversely a
89 + * file that cannot be written must not make every request rebuild it, so a missing file
90 + * is retried on a backoff window rather than on every hit.
91 + *
92 + * @param int $postId
93 + * @param bool $regenerateScriptFlag DB-side verdict from regenerateScriptChecker()
94 + *
95 + * @return bool
96 + */
97 + private function needsScriptGeneration($postId, $regenerateScriptFlag)
98 + {
99 + if (file_exists($this->getJSFilePath($postId))) {
100 + return (bool) $regenerateScriptFlag;
101 + }
102 + $retryKey = 'bitforms_js_regen_' . $postId;
103 + if (get_transient($retryKey)) {
104 + return false;
105 + }
106 + set_transient($retryKey, 1, 5 * MINUTE_IN_SECONDS);
107 + return true;
108 + }
109 +
65 110 public function generateJs($formID = null, $entryID = null, $formType = null)
66 111 {
112 + // bitform-js-{postId}.js is disk-cached per post ID with no language key.
113 + // Display strings must stay out of it and travel in bf_globals per request.
67 114 // return true;
68 115 $isFormPreview = get_transient('bitform_form_preview');
69 116 if ($isFormPreview && !$formID) {
70 117 delete_transient('bitform_form_preview');
@@ -124,8 +171,10 @@
124 171 if (!$regenerateScriptFlag) {
125 172 $regenerateScriptFlag = $this->deleteUnusedFormPageIds($postId, $bfUniqFormIds);
126 173 }
127 174 $isJsGenerating = get_option('bitforms_frontend_js_generating');
175 + // The fast path also requires the cached bundle to exist on disk, not just be flagged in the DB.
176 + $regenerateScriptFlag = $this->needsScriptGeneration($postId, $regenerateScriptFlag);
128 177 if (!$regenerateScriptFlag && !$isJsGenerating && !empty($formIDs)) {
129 178 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
130 179 return;
131 180 }
@@ -158,8 +207,13 @@
158 207 $frontendScriptGenObj->generateJsFile($formContents, $allFields, $contentIds, $postId, $formIDs, $previewMode);
159 208 if ('preview' === $previewMode) {
160 209 return;
161 210 }
211 + // Only mark the page as generated once the bundle is verifiably on disk; otherwise the
212 + // next request must retry generation instead of fast-pathing to a stale/missing file.
213 + if (!empty($bfUniqFormIds) && file_exists($this->getJSFilePath($postId))) {
214 + $this->markScriptGenerated($bfUniqFormIds, $postId);
215 + }
162 216 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
163 217 }
164 218
165 219 private function deleteUnusedFormPageIds($postId, $formIDs)
@@ -175,9 +229,9 @@
175 229 );
176 230 $regenerateScriptFlag = false;
177 231 foreach ($forms as $form) {
178 232 $formId = $form->id;
179 - $generatedScriptPageIdsDecoded = json_decode($form->generated_script_page_ids, true);
233 + $generatedScriptPageIdsDecoded = json_decode((string) $form->generated_script_page_ids, true);
180 234 $generatedScriptPageIds = is_array($generatedScriptPageIdsDecoded) ? array_keys($generatedScriptPageIdsDecoded) : [];
181 235 if (!empty($generatedScriptPageIds) && !in_array($formId, $formIDs) && in_array($postId, $generatedScriptPageIds)) {
182 236 unset($generatedScriptPageIdsDecoded[$postId]);
183 237 if (empty($generatedScriptPageIdsDecoded)) {
@@ -205,10 +259,11 @@
205 259 if (!is_a($post, 'WP_Post') && !isset($post->ID)) {
206 260 return;
207 261 }
208 262 $postId = $post->ID;
209 - $regenerateScriptFlag = false;
210 - $formModel = new FormModel();
263 + // Read-only check. Marking the page as generated is deferred to markScriptGenerated(),
264 + // called only after the bundle file is actually written — marking here left the DB
265 + // saying "generated" while the file stayed stale whenever generation failed mid-way.
211 266 foreach ($formsIds as $formId) {
212 267 $formInstance = FormManager::getInstance($formId);
213 268 if (!$formInstance->isExist()) {
214 269 continue;
@@ -214,18 +269,35 @@
214 269 continue;
215 270 }
216 271 $generatedPages = $formInstance->getFormData('generated_script_page_ids');
217 272 if (empty($generatedPages)) {
218 - $regenerateScriptFlag = true;
219 - } elseif (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || (isset($generatedPages->{$postId}) && false === $generatedPages->{$postId}))) {
220 - $regenerateScriptFlag = true;
273 + return true;
221 274 }
222 - if (!$regenerateScriptFlag) {
275 + if (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || false === $generatedPages->{$postId})) {
276 + return true;
277 + }
278 + }
279 + return false;
280 + }
281 +
282 + private function markScriptGenerated($formsIds, $postId)
283 + {
284 + // Fetched via FormModel rather than FormManager: FormManager keeps its row in a static
285 + // property shared across instances, so after the render loop it holds the last form's
286 + // data regardless of which instance is asked.
287 + $formModel = new FormModel();
288 + foreach ($formsIds as $formId) {
289 + $form = $formModel->get(['generated_script_page_ids'], ['id' => $formId]);
290 + if (is_wp_error($form) || empty($form)) {
223 291 continue;
224 292 }
293 + $generatedPages = Utilities::jsonObj($form[0]->generated_script_page_ids ?? '');
225 294 if (!is_object($generatedPages)) {
226 295 $generatedPages = (object) [];
227 296 }
297 + if (!empty($generatedPages->{$postId})) {
298 + continue;
299 + }
228 300 $generatedPages->{$postId} = true;
229 301 $formModel->update(
230 302 [
231 303 'generated_script_page_ids' => \wp_json_encode($generatedPages)
@@ -234,9 +306,8 @@
234 306 'id' => $formId,
235 307 ]
236 308 );
237 309 }
238 - return $regenerateScriptFlag;
239 310 }
240 311
241 312 private function addInlineScript($code, $handle = '', $position = 'after')
242 313 {
@@ -346,10 +417,13 @@
346 417 /* translators: %s: form ID */
347 418 return sprintf(__('#%s no. Form doesn\'t exists', 'bit-form'), $formID);
348 419 }
349 420
350 - // Add-ons may detect whether the current visitor is resuming an abandoned entry.
351 - $isAbandoned = (bool) apply_filters('bitform_is_abandoned_entry', false, $formID, $entryId, $atts);
421 + // Add-ons return the id of the abandoned entry this visitor can resume. A bare
422 + // true (older Pro) carries no id, so nothing is restored rather than entry #1.
423 + $abandonedEntryId = apply_filters('bitform_is_abandoned_entry', false, $formID, $entryId, $atts);
424 + $abandonedEntryId = (!is_bool($abandonedEntryId) && is_numeric($abandonedEntryId)) ? (int) $abandonedEntryId : 0;
425 + $isAbandoned = $abandonedEntryId > 0;
352 426
353 427 FrontendHelpers::setBfFrontendFormIds($formID);
354 428 $bfFrontendFormIds = FrontendHelpers::$bfFrontendFormIds;
355 429 $shortCodeCounter = count($bfFrontendFormIds);
@@ -369,9 +443,13 @@
369 443 }
370 444
371 445 // Read-only: password reset token from URL for display-time validation. No state written until form is submitted.
372 446 if (!empty($_GET['token']) && !empty($_GET['id'])) {
373 - $this->validPassowordResetToken(sanitize_text_field(wp_unslash($_GET['token'])), sanitize_text_field(wp_unslash($_GET['id'])), $formID);
447 + $resetNotice = $this->invalidPasswordResetNotice(sanitize_text_field(wp_unslash($_GET['token'])), sanitize_text_field(wp_unslash($_GET['id'])), $formID);
448 + if ('' !== $resetNotice) {
449 + ob_end_clean();
450 + return $resetNotice;
451 + }
374 452 }
375 453
376 454 $previousValue = $this->getValuesFromQueryParams();
377 455 $errorMessages = []; // delete
@@ -545,8 +623,9 @@
545 623 ];
546 624
547 625 if ($entryId) {
548 626 $bitFormFrontArr['entryId'] = $entryId;
627 + self::markResponseUncacheable();
549 628 }
550 629
551 630 if (isset($additional->enabled->validateFocusLost)) {
552 631 $bitFormFrontArr['validateFocusLost'] = true;
@@ -551,12 +630,19 @@
551 630 if (isset($additional->enabled->validateFocusLost)) {
552 631 $bitFormFrontArr['validateFocusLost'] = true;
553 632 }
554 633
555 - if (!empty($isAbandoned)) {
556 - $bitFormFrontArr['oldValues'] = $this->getFieldsValue($formID, $isAbandoned);
634 + if ($isAbandoned) {
635 + // One visitor's typed values, so this response must not be page-cached.
636 + $bitFormFrontArr['oldValues'] = $this->getFieldsValue($formID, $abandonedEntryId);
637 + self::markResponseUncacheable();
557 638 if (empty($entryId)) {
558 - $bitFormFrontArr['entryId'] = $entryId;
639 + // Later draft saves must update this entry, not start a new one each time.
640 + $bitFormFrontArr['entryId'] = $abandonedEntryId;
641 + $entryToken = Cryptography::encrypt($abandonedEntryId, Helpers::getBitformSalt());
642 + if (is_string($entryToken)) {
643 + $bitFormFrontArr['entryToken'] = $entryToken;
644 + }
559 645 }
560 646 }
561 647
562 648 $formInfo = $FrontendFormManager->getFormInfo();
@@ -591,27 +677,31 @@
591 677 $layout = wp_json_encode($layout);
592 678 $buttons = wp_json_encode($buttons);
593 679 $frontArr = wp_json_encode($bitFormFrontArr);
594 680
595 - $bfGlobals = sprintf('
596 - if(!window.bf_globals) {
597 - window.bf_globals = {}
598 - } if(!window.bf_globals.%1$s) {
599 - window.bf_globals.%1$s = {}
681 + $bfGlobals = sprintf('
682 + if(!window.bf_globals) {
683 + window.bf_globals = {}
684 + } if(!window.bf_globals.%1$s) {
685 + window.bf_globals.%1$s = {}
600 686 }
601 - if(document.getElementById("%1$s")) {
602 - window.bf_globals.%1$s = {
603 - ...window.bf_globals.%1$s,
604 - ...%2$s
605 - };
606 - }', $FormIdentifier, $frontArr);
687 + window.bf_globals.%1$s = {
688 + ...window.bf_globals.%1$s,
689 + ...%2$s
690 + };
691 + if (typeof window.bitformInit === "function") { window.bitformInit("%1$s"); }', $FormIdentifier, $frontArr);
607 692
693 + // Inert copy of the config. Optimizers only rewrite executable scripts, so
694 + // this survives and travels with the markup; the runtime hydrates from it
695 + // whenever bf_globals is missing.
696 + $configTag = self::buildFormConfigTag($FormIdentifier, $bitFormFrontArr);
697 +
608 698 if ('conversational' === $formType
609 699 && isset($formContent->formInfo->conversationalSettings->enable)
610 700 && $formContent->formInfo->conversationalSettings->enable) {
611 - $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages);
701 + $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages, null, !empty($entryId));
612 702 } else {
613 - $html = $FrontendFormManager->formView($fields, $file, $errorMessages);
703 + $html = $FrontendFormManager->formView($fields, $file, $errorMessages, null, !empty($entryId));
614 704 }
615 705
616 706 // if form preview then return html otherwise echo with output buffer
617 707 if ($formPreview) {
@@ -619,8 +709,9 @@
619 709 $formViewObject = new \stdClass();
620 710 $formViewObject->html = $html;
621 711 $formViewObject->font = $font;
622 712 $formViewObject->bfGlobals = $bfGlobals;
713 + $formViewObject->configTag = $configTag;
623 714 $formViewObject->formContent = $formContent;
624 715 return $formViewObject;
625 716 }
626 717
@@ -627,13 +718,60 @@
627 718 $bfGlobalsHandle = 'bitform-bf-globals-' . sanitize_key($FormIdentifier);
628 719 $this->addInlineScript($bfGlobals, $bfGlobalsHandle, 'after');
629 720 $this->emitShowPickerBridge();
630 721
722 + // Printed outside wp_kses rather than allowing <script> in form markup.
723 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built by buildFormConfigTag(), JSON_HEX_* escaped.
724 + echo $configTag;
631 725 echo wp_kses(trim($html), EscapingHelper::getFormAllowedHtml($formContent));
632 726 return ob_get_clean();
633 727 }
634 728
635 729 /**
730 + * Keep per-visitor config (oldValues, entryId) out of full-page caches.
731 + *
732 + * @return void
733 + */
734 + public static function markResponseUncacheable()
735 + {
736 + // DONOTCACHEPAGE does the work; caches read it at shutdown. Rendering
737 + // usually runs after headers are sent, so nocache_headers() is a bonus.
738 + if (!defined('DONOTCACHEPAGE')) {
739 + define('DONOTCACHEPAGE', true);
740 + }
741 + if (!headers_sent() && function_exists('nocache_headers')) {
742 + nocache_headers();
743 + }
744 + }
745 +
746 + /**
747 + * Build the inert JSON config block for a rendered form.
748 + *
749 + * JSON_HEX_* escapes < > & as \u00XX so no field value can close the script
750 + * element or inject markup.
751 + *
752 + * @param string $formIdentifier
753 + * @param array $config
754 + *
755 + * @return string
756 + */
757 + public static function buildFormConfigTag($formIdentifier, $config)
758 + {
759 + $json = wp_json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
760 + if (false === $json) {
761 + return '';
762 + }
763 + // Some optimizers wrap any inline <script>, including application/json,
764 + // in DOMContentLoaded boilerplate that corrupts the JSON. These attributes
765 + // make the common ones skip it; the JS side also salvage-parses.
766 + return sprintf(
767 + '<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>',
768 + esc_attr($formIdentifier),
769 + $json
770 + );
771 + }
772 +
773 + /**
636 774 * Build the smart-tag map exposed to the browser in window.bf_globals[formId].smartTags.
637 775 *
638 776 * Security: the legacy code shipped the ENTIRE ~43-tag map to every visitor, leaking
639 777 * PII (admin/user/author email) and freezing per-visitor request data (IP, time,
@@ -698,8 +836,15 @@
698 836 $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(_){}}});}';
699 837 $this->addInlineScript($code, 'bitform-show-picker-bridge', 'after');
700 838 }
701 839
840 + /**
841 + * Does this form row exist?
842 + *
843 + * @param int $formID
844 + *
845 + * @return bool
846 + */
702 847 private function isExist($formID)
703 848 {
704 849 $formModel = new FormModel();
705 850 $form = $formModel->get(
@@ -709,12 +854,32 @@
709 854 [
710 855 'id' => $formID,
711 856 ]
712 857 );
713 - if (!is_wp_error($form)) {
714 - return true;
858 +
859 + if (is_wp_error($form)) {
860 + if ('result_empty' !== $form->get_error_code()) {
861 + Log::debug_log([
862 + 'message' => 'Form lookup failed — reported to the visitor as a missing form',
863 + 'formID' => $formID,
864 + 'code' => $form->get_error_code(),
865 + 'error' => $form->get_error_message(),
866 + ]);
867 + }
868 +
869 + return false;
715 870 }
716 - return false;
871 +
872 + if (empty($form)) {
873 + Log::debug_log([
874 + 'message' => 'Form lookup returned no rows without an error (is the form table present?)',
875 + 'formID' => $formID,
876 + ]);
877 +
878 + return false;
879 + }
880 +
881 + return true;
717 882 }
718 883
719 884 private function getFieldsValue($formID, $entryID)
720 885 {
@@ -744,8 +909,12 @@
744 909 } else {
745 910 $metaVal = implode(BITFORMS_BF_SEPARATOR, $metaVal);
746 911 }
747 912 }
913 + // A restored draft never gets the password back; the visitor types it again.
914 + if (isset($formFields[$metaKey]['type']) && 'password' === $formFields[$metaKey]['type']) {
915 + continue;
916 + }
748 917 if (!isset($fldsData->{$metaKey})) {
749 918 $fldsData->{$metaKey} = '';
750 919 }
751 920 $fldsData->{$metaKey} = $metaVal;
@@ -798,8 +967,16 @@
798 967 } else {
799 968 $metaVal = implode(BITFORMS_BF_SEPARATOR, $metaVal);
800 969 }
801 970 }
971 + if (property_exists($fields, $metaKey) && 'password' === $fields->{$metaKey}->typ) {
972 + // Never hand a stored password back to the browser; blank keeps it on update.
973 + $fields->{$metaKey}->val = '';
974 + if ('' !== (string) $metaValue->meta_value && isset($fields->{$metaKey}->valid) && is_object($fields->{$metaKey}->valid)) {
975 + $fields->{$metaKey}->valid->req = false;
976 + }
977 + continue;
978 + }
802 979 if (property_exists($fields, $metaKey)) {
803 980 $fields->{$metaKey}->val = $metaVal;
804 981 if ('file-up' === $fields->{$metaKey}->typ || 'advanced-file-up' === $fields->{$metaKey}->typ) {
805 982 $fields->{$metaKey}->val = $metaValue->meta_value;
@@ -804,8 +981,11 @@
804 981 if ('file-up' === $fields->{$metaKey}->typ || 'advanced-file-up' === $fields->{$metaKey}->typ) {
805 982 $fields->{$metaKey}->val = $metaValue->meta_value;
806 983 $fields->{$metaKey}->config->oldFiles = $metaValue->meta_value;
807 984 }
985 + if ('signature' === $fields->{$metaKey}->typ) {
986 + $this->setOldSignature($fields->{$metaKey}, $formID, $entryID, $metaValue->meta_value);
987 + }
808 988 }
809 989 }
810 990 }
811 991 return $fields;
@@ -810,8 +990,51 @@
810 990 }
811 991 return $fields;
812 992 }
813 993
994 + /** Give the signature field its stored signature: a data URI to redraw, and the name it posts back as `_old`. */
995 + private function setOldSignature($field, $formID, $entryID, $storedValue)
996 + {
997 + $fileName = is_string($storedValue) ? trim($storedValue) : '';
998 + $decoded = json_decode($fileName, true);
999 + if (is_array($decoded)) {
1000 + $fileName = empty($decoded) ? '' : trim((string) reset($decoded));
1001 + }
1002 + // signature-failed.png means the stored signature was never usable.
1003 + if ('' === $fileName || 'signature-failed.png' === $fileName) {
1004 + return;
1005 + }
1006 + $fileName = sanitize_file_name($fileName);
1007 + if (!isset($field->config)) {
1008 + $field->config = (object) [];
1009 + } elseif (is_array($field->config)) {
1010 + $field->config = (object) $field->config;
1011 + }
1012 + $field->config->oldSignatureFile = $fileName;
1013 +
1014 + $filePath = FileHandler::getEntriesFileUploadDir($formID, $entryID) . DIRECTORY_SEPARATOR . $fileName;
1015 + if (!is_file($filePath) || !is_readable($filePath)) {
1016 + return;
1017 + }
1018 + // The types getSignatureFilePath() writes; wp_check_filetype() reports none for SVG.
1019 + $signatureMimeTypes = ['png' => 'image/png', 'jpg' => 'image/jpeg', 'svg' => 'image/svg+xml'];
1020 + $extension = strtolower((string) pathinfo($fileName, PATHINFO_EXTENSION));
1021 + if (!isset($signatureMimeTypes[$extension])) {
1022 + return;
1023 + }
1024 + $mimeType = $signatureMimeTypes[$extension];
1025 + // A hand-drawn signature is a few KB; a larger file is not worth inlining.
1026 + if (filesize($filePath) > self::MAX_INLINE_SIGNATURE_BYTES) {
1027 + return;
1028 + }
1029 + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_get_contents -- local upload dir read, inlined as a data URI for the signature pad.
1030 + $contents = file_get_contents($filePath);
1031 + if (false === $contents || '' === $contents) {
1032 + return;
1033 + }
1034 + $field->config->oldSignature = 'data:' . $mimeType . ';base64,' . base64_encode($contents);
1035 + }
1036 +
814 1037 public function loadAssets($formID = 0, $fromType = 'classic')
815 1038 {
816 1039 $bfUniqFormIds = FrontendHelpers::getAllFormIdsInPage();
817 1040 $isPageBuilder = FrontendHelpers::$isPageBuilder;
@@ -835,9 +1058,9 @@
835 1058 $formUpdateVersion = get_option('bitform_form_update_version');
836 1059 if (!wp_style_is('bitform-style-' . $newFormId) && is_readable(BITFORMS_CONTENT_DIR . '/form-styles/bitform-' . $newFormId . '.css')) {
837 1060 wp_enqueue_style(
838 1061 'bitform-style-' . $newFormId,
839 - BITFORMS_UPLOAD_BASE_URL . "/form-styles/bitform-{$newFormId}.css",
1062 + FrontendHelpers::styleSrc("form-styles/bitform-{$newFormId}.css"),
840 1063 [],
841 1064 $formUpdateVersion
842 1065 );
843 1066 if ($isPageBuilder) {
@@ -847,9 +1070,9 @@
847 1070 }
848 1071 if (!wp_style_is('bitform-style-custom-' . $formID) && is_readable(BITFORMS_CONTENT_DIR . '/form-styles/bitform-custom-' . $formID . '.css')) {
849 1072 wp_enqueue_style(
850 1073 'bitform-style-custom-' . $formID,
851 - BITFORMS_UPLOAD_BASE_URL . "/form-styles/bitform-custom-{$formID}.css",
1074 + FrontendHelpers::styleSrc("form-styles/bitform-custom-{$formID}.css"),
852 1075 [],
853 1076 $formUpdateVersion
854 1077 );
855 1078 if ($isPageBuilder) {
@@ -862,9 +1085,9 @@
862 1085 if (!wp_style_is('bitform-conversational-style-' . $formID) &&
863 1086 is_readable(BITFORMS_CONTENT_DIR . "/form-styles/bitform-conversational-{$formID}.css")) {
864 1087 wp_enqueue_style(
865 1088 'bitform-conversational-style',
866 - BITFORMS_UPLOAD_BASE_URL . "/form-styles/bitform-conversational-{$formID}.css",
1089 + FrontendHelpers::styleSrc("form-styles/bitform-conversational-{$formID}.css"),
867 1090 [],
868 1091 $formUpdateVersion
869 1092 );
870 1093 }