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 +217 -25 3.2.03.3.1 View file →
@@ -15,9 +15,11 @@
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;
20 22 use BitCode\BitForm\Core\Util\SmartTagRegistry;
21 23 use BitCode\BitForm\Core\Util\SmartTags;
22 24 use BitCode\BitForm\Core\Util\Utilities;
23 25 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
@@ -23,8 +25,11 @@
23 25 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
24 26
25 27 final class FrontendFormHandler
26 28 {
29 + /** Largest stored signature inlined into the page as a data URI. */
30 + private const MAX_INLINE_SIGNATURE_BYTES = 2097152;
31 +
27 32 public function __construct()
28 33 {
29 34 // before markup load - formids [], posts [1,2]
30 35 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
@@ -30,9 +35,11 @@
30 35 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
31 36 // markup loads - formids []
32 37 add_shortcode('bitform', [$this, 'handleFrontendRenderRequest']);
33 38 // after markup load - formids [1,35,3]
34 - 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);
35 42 }
36 43
37 44 private function validPassowordResetToken($token, $userID, $formId)
38 45 {
@@ -61,10 +68,43 @@
61 68
62 69 return $formScriptSrc;
63 70 }
64 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 +
65 103 public function generateJs($formID = null, $entryID = null, $formType = null)
66 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.
67 107 // return true;
68 108 $isFormPreview = get_transient('bitform_form_preview');
69 109 if ($isFormPreview && !$formID) {
70 110 delete_transient('bitform_form_preview');
@@ -124,8 +164,10 @@
124 164 if (!$regenerateScriptFlag) {
125 165 $regenerateScriptFlag = $this->deleteUnusedFormPageIds($postId, $bfUniqFormIds);
126 166 }
127 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);
128 170 if (!$regenerateScriptFlag && !$isJsGenerating && !empty($formIDs)) {
129 171 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
130 172 return;
131 173 }
@@ -158,8 +200,13 @@
158 200 $frontendScriptGenObj->generateJsFile($formContents, $allFields, $contentIds, $postId, $formIDs, $previewMode);
159 201 if ('preview' === $previewMode) {
160 202 return;
161 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 + }
162 209 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
163 210 }
164 211
165 212 private function deleteUnusedFormPageIds($postId, $formIDs)
@@ -175,9 +222,9 @@
175 222 );
176 223 $regenerateScriptFlag = false;
177 224 foreach ($forms as $form) {
178 225 $formId = $form->id;
179 - $generatedScriptPageIdsDecoded = json_decode($form->generated_script_page_ids, true);
226 + $generatedScriptPageIdsDecoded = json_decode((string) $form->generated_script_page_ids, true);
180 227 $generatedScriptPageIds = is_array($generatedScriptPageIdsDecoded) ? array_keys($generatedScriptPageIdsDecoded) : [];
181 228 if (!empty($generatedScriptPageIds) && !in_array($formId, $formIDs) && in_array($postId, $generatedScriptPageIds)) {
182 229 unset($generatedScriptPageIdsDecoded[$postId]);
183 230 if (empty($generatedScriptPageIdsDecoded)) {
@@ -205,10 +252,11 @@
205 252 if (!is_a($post, 'WP_Post') && !isset($post->ID)) {
206 253 return;
207 254 }
208 255 $postId = $post->ID;
209 - $regenerateScriptFlag = false;
210 - $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.
211 259 foreach ($formsIds as $formId) {
212 260 $formInstance = FormManager::getInstance($formId);
213 261 if (!$formInstance->isExist()) {
214 262 continue;
@@ -214,18 +262,35 @@
214 262 continue;
215 263 }
216 264 $generatedPages = $formInstance->getFormData('generated_script_page_ids');
217 265 if (empty($generatedPages)) {
218 - $regenerateScriptFlag = true;
219 - } elseif (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || (isset($generatedPages->{$postId}) && false === $generatedPages->{$postId}))) {
220 - $regenerateScriptFlag = true;
266 + return true;
221 267 }
222 - 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)) {
223 284 continue;
224 285 }
286 + $generatedPages = Utilities::jsonObj($form[0]->generated_script_page_ids ?? '');
225 287 if (!is_object($generatedPages)) {
226 288 $generatedPages = (object) [];
227 289 }
290 + if (!empty($generatedPages->{$postId})) {
291 + continue;
292 + }
228 293 $generatedPages->{$postId} = true;
229 294 $formModel->update(
230 295 [
231 296 'generated_script_page_ids' => \wp_json_encode($generatedPages)
@@ -234,9 +299,8 @@
234 299 'id' => $formId,
235 300 ]
236 301 );
237 302 }
238 - return $regenerateScriptFlag;
239 303 }
240 304
241 305 private function addInlineScript($code, $handle = '', $position = 'after')
242 306 {
@@ -545,8 +609,9 @@
545 609 ];
546 610
547 611 if ($entryId) {
548 612 $bitFormFrontArr['entryId'] = $entryId;
613 + self::markResponseUncacheable();
549 614 }
550 615
551 616 if (isset($additional->enabled->validateFocusLost)) {
552 617 $bitFormFrontArr['validateFocusLost'] = true;
@@ -552,9 +617,11 @@
552 617 $bitFormFrontArr['validateFocusLost'] = true;
553 618 }
554 619
555 620 if (!empty($isAbandoned)) {
621 + // One visitor's typed values, so this response must not be page-cached.
556 622 $bitFormFrontArr['oldValues'] = $this->getFieldsValue($formID, $isAbandoned);
623 + self::markResponseUncacheable();
557 624 if (empty($entryId)) {
558 625 $bitFormFrontArr['entryId'] = $entryId;
559 626 }
560 627 }
@@ -591,27 +658,31 @@
591 658 $layout = wp_json_encode($layout);
592 659 $buttons = wp_json_encode($buttons);
593 660 $frontArr = wp_json_encode($bitFormFrontArr);
594 661
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 = {}
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 = {}
600 667 }
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);
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);
607 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 +
608 679 if ('conversational' === $formType
609 680 && isset($formContent->formInfo->conversationalSettings->enable)
610 681 && $formContent->formInfo->conversationalSettings->enable) {
611 - $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages);
682 + $html = $FrontendFormManager->conversationalFormView($fields, $file, $errorMessages, null, !empty($entryId));
612 683 } else {
613 - $html = $FrontendFormManager->formView($fields, $file, $errorMessages);
684 + $html = $FrontendFormManager->formView($fields, $file, $errorMessages, null, !empty($entryId));
614 685 }
615 686
616 687 // if form preview then return html otherwise echo with output buffer
617 688 if ($formPreview) {
@@ -619,8 +690,9 @@
619 690 $formViewObject = new \stdClass();
620 691 $formViewObject->html = $html;
621 692 $formViewObject->font = $font;
622 693 $formViewObject->bfGlobals = $bfGlobals;
694 + $formViewObject->configTag = $configTag;
623 695 $formViewObject->formContent = $formContent;
624 696 return $formViewObject;
625 697 }
626 698
@@ -627,13 +699,60 @@
627 699 $bfGlobalsHandle = 'bitform-bf-globals-' . sanitize_key($FormIdentifier);
628 700 $this->addInlineScript($bfGlobals, $bfGlobalsHandle, 'after');
629 701 $this->emitShowPickerBridge();
630 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;
631 706 echo wp_kses(trim($html), EscapingHelper::getFormAllowedHtml($formContent));
632 707 return ob_get_clean();
633 708 }
634 709
635 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 + /**
636 755 * Build the smart-tag map exposed to the browser in window.bf_globals[formId].smartTags.
637 756 *
638 757 * Security: the legacy code shipped the ENTIRE ~43-tag map to every visitor, leaking
639 758 * PII (admin/user/author email) and freezing per-visitor request data (IP, time,
@@ -698,8 +817,15 @@
698 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(_){}}});}';
699 818 $this->addInlineScript($code, 'bitform-show-picker-bridge', 'after');
700 819 }
701 820
821 + /**
822 + * Does this form row exist?
823 + *
824 + * @param int $formID
825 + *
826 + * @return bool
827 + */
702 828 private function isExist($formID)
703 829 {
704 830 $formModel = new FormModel();
705 831 $form = $formModel->get(
@@ -709,12 +835,32 @@
709 835 [
710 836 'id' => $formID,
711 837 ]
712 838 );
713 - if (!is_wp_error($form)) {
714 - 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;
715 851 }
716 - 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;
717 863 }
718 864
719 865 private function getFieldsValue($formID, $entryID)
720 866 {
@@ -804,12 +950,58 @@
804 950 if ('file-up' === $fields->{$metaKey}->typ || 'advanced-file-up' === $fields->{$metaKey}->typ) {
805 951 $fields->{$metaKey}->val = $metaValue->meta_value;
806 952 $fields->{$metaKey}->config->oldFiles = $metaValue->meta_value;
807 953 }
954 + if ('signature' === $fields->{$metaKey}->typ) {
955 + $this->setOldSignature($fields->{$metaKey}, $formID, $entryID, $metaValue->meta_value);
956 + }
808 957 }
809 958 }
810 959 }
811 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);
812 1004 }
813 1005
814 1006 public function loadAssets($formID = 0, $fromType = 'classic')
815 1007 {