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/FrontendFormManager.php +778 -362 2.03.3.1 View file →
@@ -9,8 +9,9 @@
9 9 /**
10 10 * FrontendFormManager class
11 11 */
12 12
13 +use BitCode\BitForm\Admin\Form\AdminFormHandler;
13 14 use BitCode\BitForm\Admin\Form\Helpers;
14 15 use BitCode\BitForm\Core\Database\FormEntryModel;
15 16 use BitCode\BitForm\Core\Form\FormManager;
16 17 use BitCode\BitForm\Core\Form\Validator\FormFieldValidator;
@@ -16,25 +17,30 @@
16 17 use BitCode\BitForm\Core\Form\Validator\FormFieldValidator;
17 18 use BitCode\BitForm\Core\Integration\IntegrationHandler;
18 19 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
19 20 use BitCode\BitForm\Core\Util\ApiResponse as UtilApiResponse;
20 -use BitCode\BitForm\Core\Util\DateTimeHelper;
21 +use BitCode\BitForm\Core\Util\EscapingHelper;
22 +use BitCode\BitForm\Core\Util\FieldValueHandler;
23 +use BitCode\BitForm\Core\Util\FrontendHelpers;
21 24 use BitCode\BitForm\Core\Util\HttpHelper;
22 25 use BitCode\BitForm\Core\Util\IpTool;
26 +use BitCode\BitForm\Core\Util\Utilities;
23 27 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
24 -use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
25 28 use BitCode\BitForm\Frontend\Form\View\FormViewer;
29 +use BitCode\BitForm\GlobalHelper;
26 30 use WP_Error;
27 31
28 -final class FrontendFormManager extends FormManager {
32 +final class FrontendFormManager extends FormManager
33 +{
29 34 private $_form_identifier;
30 35 private $_form_token;
31 36 private $_form_id;
32 - private $_work_flows;
33 37 private $_conf_messages;
38 + private static $_instance = [];
34 39
35 40 // private $_has_upload = false;
36 - public function __construct($form_id, $shortCodeCounter = null) {
41 + public function __construct($form_id, $shortCodeCounter = null)
42 + {
37 43 parent::__construct($form_id);
38 44 $this->_form_identifier = 'bitforms_' . $form_id;
39 45 $this->_form_identifier .= !empty(get_post()->ID) ? '_' . get_post()->ID : '';
40 46 $this->_form_identifier .= !empty($shortCodeCounter) ? "_$shortCodeCounter" : '';
@@ -41,32 +47,43 @@
41 47 $this->_form_token = wp_create_nonce('bitforms_' . $form_id);
42 48 $this->_form_id = $form_id;
43 49 }
44 50
45 - public function getFormIdentifier() {
51 + public static function getInstance($form_id, $shortCodeCounter = null)
52 + {
53 + $key = $form_id . ':' . ($shortCodeCounter ?? 'default');
54 +
55 + if (!isset(self::$_instance[$key])) {
56 + self::$_instance[$key] = new self($form_id, $shortCodeCounter);
57 + }
58 +
59 + return self::$_instance[$key];
60 + }
61 +
62 + public function getFormIdentifier()
63 + {
46 64 return $this->_form_identifier;
47 65 }
48 66
49 - public function getFormID() {
67 + public function getFormID()
68 + {
50 69 return $this->_form_id;
51 70 }
52 71
53 - public function getFormToken() {
72 + public function getFormToken()
73 + {
54 74 return $this->_form_token;
55 75 }
56 76
57 - public function isSubmitted() {
58 - // return isset($_POST[$this->_form_identifier]) ? true : false;
59 - return (isset($_POST['bitforms_id']) && $_POST['bitforms_id'] === $this->_form_identifier) ? true : false;
60 - }
61 -
62 - public function getSubmittedFields($submitted_data) {
77 + public function getSubmittedFields($submitted_data)
78 + {
63 79 unset($submitted_data[$this->_form_identifier]);
64 80 // unset($submitted_data['bit-form-submit-btn']);
65 81 return array_keys($submitted_data);
66 82 }
67 83
68 - public function formView($fields = null, $hasFile = false, $errorMessages = null, $previousValue = null) {
84 + public function formView($fields = null, $hasFile = false, $errorMessages = null, $previousValue = null, $isEntryEdit = false)
85 + {
69 86 $formContents = $this->getFormContent();
70 87 $formAtomicClsMap = $this->getAtomicClsMap();
71 88 if (!empty($fields)) {
72 89 $formContents->fields = is_string($fields) ? json_decode($fields) : $fields;
@@ -78,24 +95,69 @@
78 95 );
79 96 $formContents->fields = empty($workFlowreturnedOnLoad['fields']) ? $formContents->fields : $workFlowreturnedOnLoad['fields'];
80 97 }
81 98 $formViewer = new FormViewer($this, $formContents, $formAtomicClsMap, $errorMessages, $previousValue);
82 - return $formViewer->getView($hasFile);
99 + $isRestricted = $this->checkSubmissionRestriction(false, $isEntryEdit);
100 + $msg = !empty($isRestricted) ? $isRestricted[0] : '';
101 + return $formViewer->getView($hasFile, $msg);
83 102 }
84 103
85 - private function checkEmptySubmission($data, $file) {
104 + public function conversationalFormView($fields = null, $hasFile = false, $errorMessages = null, $previousValue = null, $isEntryEdit = false)
105 + {
106 + $formContents = $this->getFormContent();
107 + $formAtomicClsMap = $this->getAtomicClsMap();
108 + if (!empty($fields)) {
109 + $formContents->fields = is_string($fields) ? json_decode($fields) : $fields;
110 + } else {
111 + $workFlowRunHelper = new WorkFlow($this->form_id);
112 + $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
113 + 'create',
114 + $formContents->fields
115 + );
116 + $formContents->fields = empty($workFlowreturnedOnLoad['fields']) ? $formContents->fields : $workFlowreturnedOnLoad['fields'];
117 + }
118 + $formViewer = new FormViewer($this, $formContents, $formAtomicClsMap, $errorMessages, $previousValue);
119 + $isRestricted = $this->checkSubmissionRestriction(false, $isEntryEdit);
120 + $msg = !empty($isRestricted) ? $isRestricted[0] : '';
121 + return $formViewer->getConversationalView($hasFile, $msg);
122 + }
123 +
124 + public function checkEmptySubmission($data, $file, $isEntryEdit = false)
125 + {
86 126 $formFields = $this->getFields();
87 127 foreach ($formFields as $key => $field) {
88 128 $fieldType = $field['type'];
129 + if ('button' === $fieldType) {
130 + continue;
131 + }
89 132 $fileUploadFieldTypes = ['file-up', 'advanced-file-up'];
133 + if ('decision-box' === $fieldType || 'gdpr' === $fieldType) {
134 + continue;
135 + }
90 136 $isFileType = in_array($fieldType, $fileUploadFieldTypes);
91 - if (!$isFileType && !empty($data[$key])) {
137 + // An edit keeps an untouched file/signature as `<fieldKey>_old`, not as an upload.
138 + if (
139 + $isEntryEdit
140 + && ($isFileType || 'signature' === $fieldType)
141 + && !empty(FieldValueHandler::retainedOldValues($data, $key))
142 + ) {
92 143 return false;
93 144 }
145 + if ($this->isRepeatedField($key)) {
146 + $fileData = !empty($file[$key]) ? $file[$key] : [];
147 + $dataVal = !empty($data[$key]) ? $data[$key] : [];
148 + if (!$this->checkRepeatedFieldEmptySubmission($isFileType, $dataVal, $fileData)) {
149 + return false;
150 + }
151 + continue;
152 + }
153 + if (!$isFileType && (!empty($data[$key]) || (isset($data[$key]) && is_numeric($data[$key])))) {
154 + return false;
155 + }
94 156 if ($isFileType && !empty($file[$key]['name']) && is_string($file[$key]['name'])) {
95 157 return false;
96 158 }
97 - if ($isFileType && is_array($file[$key]['name']) && !empty($file[$key]['name'][0])) {
159 + if ($isFileType && !empty($file[$key]['name'][0])) {
98 160 return false;
99 161 }
100 162 }
101 163 return true;
@@ -100,10 +162,33 @@
100 162 }
101 163 return true;
102 164 }
103 165
104 - private function getParams() {
105 - $url = parse_url(wp_get_referer());
166 + private function checkRepeatedFieldEmptySubmission($isFileType, $data, $file = [])
167 + {
168 + if (!$isFileType) {
169 + foreach ($data as $value) {
170 + if (!empty($value)) {
171 + return false;
172 + }
173 + }
174 + }
175 + if ($isFileType) {
176 + foreach ($file['name'] as $value) {
177 + if (!empty($value) && is_string($value)) {
178 + return false;
179 + }
180 + if (is_array($value) && !empty($value[0])) {
181 + return false;
182 + }
183 + }
184 + }
185 + return true;
186 + }
187 +
188 + private function getParams()
189 + {
190 + $url = wp_parse_url(wp_get_referer());
106 191 $parameter = [];
107 192 if (isset($url['query'])) {
108 193 $queries = explode('&', $url['query']);
109 194 foreach ($queries as $query) {
@@ -113,37 +198,146 @@
113 198 }
114 199 return $parameter;
115 200 }
116 201
117 - public function handleSubmission() {
202 + private function getFormFields($formID)
203 + {
204 + $adminFormHandler = new AdminFormHandler();
205 + $post = new \stdClass();
206 + $post = (object) [
207 + 'id' => $formID
208 + ];
209 + $getForm = $adminFormHandler->getAForm('', $post);
210 + $formContainer = $getForm['form_content'];
211 +
212 + return $formContainer['fields'];
213 + }
214 +
215 + private function transformDrpdwnValue($post)
216 + {
217 + $formFields = $this->getFormFields($this->_form_id);
218 +
219 + foreach ($post as $key => $value) {
220 + if (!str_starts_with($key, 'repeater') && isset($formFields->{$key}) && 'select' === $formFields->{$key}->typ) {
221 + if (is_array($value)) {
222 + foreach ($value as $k => $v) {
223 + $post[$key][$k] = !is_array($v) && is_string($v) ? explode(BITFORMS_BF_SEPARATOR, $v) : $v;
224 + }
225 + } else {
226 + $post[$key] = explode(BITFORMS_BF_SEPARATOR, $value);
227 + }
228 + };
229 + }
230 +
231 + return $post;
232 + }
233 +
234 + /**
235 + * WP auth errors carry markup and the confirmation box paints them with innerHTML,
236 + * so esc_html() would show the tags as text. kses keeps only the safe markup.
237 + *
238 + * @param mixed $message
239 + *
240 + * @return string
241 + */
242 + private static function authErrorMessage($message)
243 + {
244 + return wp_kses(is_string($message) ? $message : '', EscapingHelper::getAllowedHtmlTags());
245 + }
246 +
247 + /**
248 + * A confirm-enabled email/password field posts as one composite and the validator collapses it
249 + * to the primary value, so the confirm child's own field key never reaches $_POST. WP auth
250 + * integrations map fields by key, so fill those child keys on a copy for the auth filter.
251 + *
252 + * @param mixed $postData
253 + *
254 + * @return mixed
255 + */
256 + private function resolveConfirmChildValues($postData)
257 + {
258 + if (!is_array($postData)) {
259 + return $postData;
260 + }
261 + $fields = $this->getFields();
262 + foreach ($fields as $fieldKey => $fieldData) {
263 + if (
264 + empty($fieldData['childFields'])
265 + || !isset($fieldData['type'])
266 + || !in_array($fieldData['type'], ['email', 'password'], true)
267 + || !empty($fieldData['repeated'])
268 + || !isset($postData[$fieldKey])
269 + ) {
270 + continue;
271 + }
272 + $parentValue = $postData[$fieldKey];
273 + foreach ((array) $fieldData['childFields'] as $childFieldRef) {
274 + $childKey = is_object($childFieldRef) && isset($childFieldRef->fldKey) ? $childFieldRef->fldKey : '';
275 + if (
276 + empty($childKey)
277 + || !isset($fields[$childKey])
278 + || !empty($fields[$childKey]['isDeactive'])
279 + || isset($postData[$childKey])
280 + ) {
281 + continue;
282 + }
283 + if (is_array($parentValue)) {
284 + if (array_key_exists('confirm', $parentValue)) {
285 + $postData[$childKey] = $parentValue['confirm'];
286 + }
287 + continue;
288 + }
289 + // Validation matched primary against confirm before collapsing, so this is that value.
290 + $postData[$childKey] = $parentValue;
291 + }
292 + if (is_array($parentValue) && array_key_exists('primary', $parentValue)) {
293 + $postData[$fieldKey] = $parentValue['primary'];
294 + }
295 + }
296 +
297 + return $postData;
298 + }
299 +
300 + public function handleSubmission()
301 + {
302 + // CSRF verified via verifySubmissionNonce() before this method is called. All $_POST reads below occur after that verification.
118 303 $this->fieldNameReplaceOfPost();
304 +
119 305 $validated = $this->beforeSubmittedValidate();
120 306
307 + $validated = apply_filters('bitform_filter_form_validation', $validated, $this->_form_id);
308 +
121 309 if (true === $validated) {
122 - unset($_POST['hidden_fields']);
310 + do_action('bitform_validation_success', $this->_form_id);
311 + $this->discardHiddenFieldValues();
123 312
124 313 $redirectPage = '';
125 314 $regSuccMsg = '';
126 315
127 316 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
317 + $unslashed_post = wp_unslash($_POST);
128 318 if (!is_wp_error($existAuth) && count($existAuth) > 0) {
129 319 $parameter = $this->getParams();
130 - $existAuthFilter = has_filter('bf_wp_user_auth');
320 + $existAuthFilter = has_filter('bitform_wp_user_auth');
131 321
132 322 if (true === $existAuthFilter) {
133 - $result = apply_filters('bf_wp_user_auth', $existAuth[0], $_POST, $parameter);
323 + $authPostData = $this->resolveConfirmChildValues($unslashed_post);
324 + $result = apply_filters('bitform_wp_user_auth', $existAuth[0], $authPostData, $parameter);
134 325
326 + $result = apply_filters('bitform_filter_wp_user_auth_response', $result, $this->_form_id, $authPostData, $parameter);
327 +
328 + do_action('bitform_wp_user_auth_response', $result, $this->_form_id, $authPostData, $parameter);
329 +
135 330 if (isset($result['auth_type']) && 'register' === $result['auth_type']) {
136 331 if (!$result['success']) {
137 - return new WP_Error('errors', __($result['message'], 'bit-form'));
332 + return new WP_Error('errors', self::authErrorMessage($result['message']));
138 333 } elseif (isset($result['success'])) {
139 - $redirectPage = $result['redirect_url'];
334 + $redirectPage = $result['redirectPage'];
140 335 $regSuccMsg = $result['message'];
141 - $newNonce = wp_create_nonce('bitforms_' . $this->_form_id);
142 336 }
143 337 } else {
144 338 if (!$result['success']) {
145 - return new WP_Error('errors', __($result['message'], 'bit-form'));
339 + return new WP_Error('errors', self::authErrorMessage($result['message']));
146 340 } else {
147 341 return $result;
148 342 }
149 343 }
@@ -149,27 +343,33 @@
149 343 }
150 344 }
151 345 }
152 346
153 - $saveResponse = $this->saveFormEntry($_POST);
347 + $saveResponse = $this->saveFormEntry($unslashed_post);
154 348 if (is_wp_error($saveResponse)) {
155 349 return $saveResponse;
156 350 }
157 351
158 352 $entryID = $saveResponse['entry_id'];
159 - do_action('bitform_submit_success', $this->_form_id, $entryID, $_POST);
160 353
354 + // transformed dropdown value from string to array
355 + $newPost = $this->transformDrpdwnValue($unslashed_post);
356 + $filesData = GlobalHelper::sanitize_files_input($_FILES);
357 + do_action('bitform_submit_success', $this->_form_id, $entryID, $newPost, $filesData);
358 +
161 359 $captchaV3Settings = $this->getCaptchaV3Settings();
162 360 if ($captchaV3Settings) {
163 - $token = $_POST['g-recaptcha-response'];
361 + $token = isset($_POST['g-recaptcha-response']) ? sanitize_text_field(wp_unslash($_POST['g-recaptcha-response'])) : '';
164 362 $integrationHandler = new IntegrationHandler(0);
165 363 $allFormIntegrations = $integrationHandler->getAllIntegration('app', 'gReCaptchaV3');
166 364 if (!is_wp_error($allFormIntegrations)) {
167 365 foreach ($allFormIntegrations as $integration) {
168 366 if (!is_null($integration->integration_type) && 'gReCaptchaV3' === $integration->integration_type) {
169 - $integrationDetails = json_decode($integration->integration_details);
170 - $integrationDetails->id = $integration->id;
171 - $reCAPTCHA = $integrationDetails;
367 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
368 + if ($integrationDetails) {
369 + $integrationDetails->id = $integration->id;
370 + $reCAPTCHA = $integrationDetails;
371 + }
172 372 }
173 373 }
174 374 }
175 375 if (!empty($reCAPTCHA->secretKey)) {
@@ -191,15 +391,14 @@
191 391 }
192 392 if (!empty($regSuccMsg) && isset($saveResponse['dflt_message'])) {
193 393 $saveResponse['message'] = $regSuccMsg;
194 394 }
395 + $saveResponse['new_nonce'] = wp_create_nonce('bitforms_' . $this->_form_id);
396 +
195 397 $saveResponse = IntegrationHandler::maybeSetCronForIntegration($saveResponse, 'create');
196 398 $entryId = $saveResponse['entry_id'];
197 399
198 400 $responseMsg = is_array($saveResponse) && !empty($saveResponse) ? $saveResponse : __('Form Submitted Successfully', 'bit-form');
199 - if (isset($newNonce)) {
200 - $responseMsg['new_nonce'] = $newNonce;
201 - }
202 401 $_POST = [];
203 402 $responseMsg['entry_id'] = $entryId;
204 403 return $responseMsg;
205 404 }
@@ -206,41 +405,48 @@
206 405 do_action('bitform_validation_error', $this->_form_id, $validated);
207 406 return $validated;
208 407 }
209 408
210 - public function handleUpdateEntry() {
409 + public function handleUpdateEntry()
410 + {
411 + // Entry token or capability verified by caller (FrontendAjax::update_entry). All $_POST reads occur after that check.
211 412 $this->fieldNameReplaceOfPost();
212 - $validated = $this->beforeSubmittedValidate();
413 + $validated = $this->beforeSubmittedValidate(true, true);
414 + $validated = apply_filters('bitform_filter_form_validation', $validated, $this->_form_id);
213 415
214 - $entryID = $_POST['entryID'];
416 + $entryID = isset($_REQUEST['entryID']) ? sanitize_text_field(wp_unslash($_REQUEST['entryID'])) : null;
417 + $GLOBALS['bitform_entry_id'] = $entryID;
215 418 if (is_null($entryID)) {
216 419 return new WP_Error('empty_form', __('Entries id is invalid', 'bit-form'));
217 420 }
218 421 if (true === $validated) {
219 - unset($_POST['hidden_fields'], $_POST['entryID']);
422 + do_action('bitform_validation_success', $this->_form_id);
423 + $this->discardHiddenFieldValues();
424 + unset($_POST['entryID']);
220 425
221 426 $redirectPage = '';
222 427 $regSuccMsg = '';
428 + $postData = wp_unslash($_POST);
223 429
224 430 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
225 431 if (!is_wp_error($existAuth) && count($existAuth) > 0) {
226 432 $parameter = $this->getParams();
227 - $existAuthFilter = has_filter('bf_wp_user_auth');
433 + $existAuthFilter = has_filter('bitform_wp_user_auth');
228 434
229 435 if (true === $existAuthFilter) {
230 - $result = apply_filters('bf_wp_user_auth', $existAuth[0], $_POST, $parameter);
436 + $authPostData = $this->resolveConfirmChildValues($postData);
437 + $result = apply_filters('bitform_wp_user_auth', $existAuth[0], $authPostData, $parameter);
231 438
232 439 if (isset($result['auth_type']) && 'register' === $result['auth_type']) {
233 440 if (!$result['success']) {
234 - return new WP_Error('errors', __($result['message'], 'bit-form'));
441 + return new WP_Error('errors', self::authErrorMessage($result['message']));
235 442 } elseif (isset($result['success'])) {
236 - $redirectPage = $result['redirect_url'];
443 + $redirectPage = $result['redirectPage'];
237 444 $regSuccMsg = $result['message'];
238 - $newNonce = wp_create_nonce('bitforms_' . $this->_form_id);
239 445 }
240 446 } else {
241 447 if (!$result['success']) {
242 - return new WP_Error('errors', __($result['message'], 'bit-form'));
448 + return new WP_Error('errors', self::authErrorMessage($result['message']));
243 449 } else {
244 450 return $result;
245 451 }
246 452 }
@@ -246,26 +452,34 @@
246 452 }
247 453 }
248 454 }
249 455
250 - $updateResponse = $this->updateFormEntry($_POST, $this->getFormID(), $entryID);
456 + $updateResponse = $this->updateFormEntry(wp_unslash($_POST), $this->getFormID(), $entryID);
251 457 if (is_wp_error($updateResponse)) {
252 458 return $updateResponse;
253 459 }
254 460
255 - do_action('bitform_submit_success', $this->_form_id, $entryID, $_POST);
461 + // transformed dropdown value from string to array
462 + $newPost = $this->transformDrpdwnValue($postData);
463 + $filesData = GlobalHelper::sanitize_files_input($_FILES);
256 464
465 + //TO DO:: submit success action temporarily added for solution of a issue
466 + do_action('bitform_submit_success', $this->_form_id, $entryID, $newPost, $filesData);
467 + do_action('bitform_update_success', $this->_form_id, $entryID, $newPost, $filesData);
468 +
257 469 $captchaV3Settings = $this->getCaptchaV3Settings();
258 470 if ($captchaV3Settings) {
259 - $token = $_POST['g-recaptcha-response'];
471 + $token = isset($_POST['g-recaptcha-response']) ? sanitize_text_field(wp_unslash($_POST['g-recaptcha-response'])) : '';
260 472 $integrationHandler = new IntegrationHandler(0);
261 473 $allFormIntegrations = $integrationHandler->getAllIntegration('app', 'gReCaptchaV3');
262 474 if (!is_wp_error($allFormIntegrations)) {
263 475 foreach ($allFormIntegrations as $integration) {
264 476 if (!is_null($integration->integration_type) && 'gReCaptchaV3' === $integration->integration_type) {
265 - $integrationDetails = json_decode($integration->integration_details);
266 - $integrationDetails->id = $integration->id;
267 - $reCAPTCHA = $integrationDetails;
477 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
478 + if ($integrationDetails) {
479 + $integrationDetails->id = $integration->id;
480 + $reCAPTCHA = $integrationDetails;
481 + }
268 482 }
269 483 }
270 484 }
271 485 if (!empty($reCAPTCHA->secretKey)) {
@@ -287,15 +501,14 @@
287 501 }
288 502 if (!empty($regSuccMsg) && isset($updateResponse['dflt_message'])) {
289 503 $updateResponse['message'] = $regSuccMsg;
290 504 }
291 - $updateResponse = IntegrationHandler::maybeSetCronForIntegration($updateResponse, 'create');
505 + $updateResponse['new_nonce'] = wp_create_nonce('bitforms_' . $this->_form_id);
506 + $updateResponse = IntegrationHandler::maybeSetCronForIntegration($updateResponse, 'update');
292 507 $entryId = $updateResponse['entry_id'];
293 508
294 509 $responseMsg = is_array($updateResponse) && !empty($updateResponse) ? $updateResponse : __('Entry Update Successfully', 'bit-form');
295 - if (isset($newNonce)) {
296 - $responseMsg['new_nonce'] = $newNonce;
297 - }
510 +
298 511 $_POST = [];
299 512 $responseMsg['entry_id'] = $entryId;
300 513 return $responseMsg;
301 514 }
@@ -302,10 +515,96 @@
302 515 do_action('bitform_validation_error', $this->_form_id, $validated);
303 516 return $validated;
304 517 }
305 518
306 - public function validateFormSubmission($submitted_data) {
307 - $hidden_fields = isset($submitted_data['hidden_fields']) ? $submitted_data['hidden_fields'] : '';
519 + /**
520 + * Drop the posted `hidden_fields` transport key and, when the form opts in, the values of
521 + * the fields it names.
522 + *
523 + * A hidden field keeps its typed value in the DOM, so the browser still submits it. Runs
524 + * here because it is the last point before entry, notifications and integrations are built
525 + * from $_POST.
526 + *
527 + * @return void
528 + */
529 + private function discardHiddenFieldValues()
530 + {
531 + // CSRF verified upstream via verifySubmissionNonce(); $_POST is only being narrowed here.
532 + $rawHiddenFields = isset($_POST['hidden_fields']) ? wp_unslash($_POST['hidden_fields']) : '';
533 + unset($_POST['hidden_fields']);
534 +
535 + if (!$this->shouldDiscardHiddenFieldValues()) {
536 + return;
537 + }
538 + $hiddenFieldKeys = FrontendHelpers::parseHiddenFieldKeys($rawHiddenFields);
539 + if (empty($hiddenFieldKeys)) {
540 + return;
541 + }
542 +
543 + $formFields = $this->getFields();
544 + foreach ($hiddenFieldKeys as $fieldKey) {
545 + if (!isset($formFields[$fieldKey])) {
546 + continue;
547 + }
548 + $field = $formFields[$fieldKey];
549 + // The posted list also names builder-hidden and hidden-type fields, which carry a value
550 + // on purpose. Only what conditional logic hid is discarded.
551 + if ('hidden' === $field['type'] || !empty($field['valid']['hide'])) {
552 + continue;
553 + }
554 + // Hiding flags a repeater child once, not per row, so discarding would wipe the column
555 + // in every row.
556 + if (!empty($field['repeated'])) {
557 + continue;
558 + }
559 + // Calculation and tracking fields opt out.
560 + if (!empty($field['valid']['keepValueWhenHidden'])) {
561 + continue;
562 + }
563 + // A composite child (name/address/confirm) posts nested under its parent key.
564 + if (!empty($field['parentFieldKey'])) {
565 + $this->discardCompositeChildValue($formFields, $field, $fieldKey);
566 + continue;
567 + }
568 + unset($_POST[$fieldKey], $_FILES[$fieldKey]);
569 + }
570 + }
571 +
572 + /**
573 + * @param array $formFields
574 + * @param array $field the child field's config
575 + * @param string $fieldKey the child field's key
576 + *
577 + * @return void
578 + */
579 + private function discardCompositeChildValue($formFields, $field, $fieldKey)
580 + {
581 + $parentKey = $field['parentFieldKey'];
582 + if (!isset($_POST[$parentKey]) || !is_array($_POST[$parentKey])) {
583 + return;
584 + }
585 + $parentName = isset($formFields[$parentKey]['name']) ? $formFields[$parentKey]['name'] : '';
586 + $childName = FieldValueHandler::deriveChildName(isset($field['name']) ? $field['name'] : '', $parentName);
587 + unset($_POST[$parentKey][$childName], $_POST[$parentKey][$fieldKey]);
588 + }
589 +
590 + /**
591 + * @return bool
592 + */
593 + private function shouldDiscardHiddenFieldValues()
594 + {
595 + $formInfo = $this->getFormInfo();
596 + if (!is_object($formInfo) || !isset($formInfo->submissionSettings)) {
597 + return false;
598 + }
599 + $submissionSettings = (object) $formInfo->submissionSettings;
600 +
601 + return !empty($submissionSettings->discardHiddenFieldValues);
602 + }
603 +
604 + public function validateFormSubmission($submitted_data)
605 + {
606 + $hidden_fields = FrontendHelpers::parseHiddenFieldKeys(isset($submitted_data['hidden_fields']) ? $submitted_data['hidden_fields'] : '');
308 607 $submitted_fields = $this->getSubmittedFields($submitted_data);
309 608 $form_fields = $this->getFields();
310 609 $form_fields_names = array_keys($form_fields);
311 610 if ($this->isGCLIDEnabled()) {
@@ -310,10 +609,10 @@
310 609 $form_fields_names = array_keys($form_fields);
311 610 if ($this->isGCLIDEnabled()) {
312 611 array_push($form_fields_names, 'GCLID');
313 612 }
314 - foreach ($submitted_fields as $key => $field) {
315 - if ('hidden_fields' !== $field && !in_array($field, $form_fields_names) || false !== strpos($hidden_fields, $field)) {
613 + foreach ($submitted_fields as $field) {
614 + if ('hidden_fields' !== $field && !in_array($field, $form_fields_names) || FrontendHelpers::isFieldHidden($hidden_fields, $field)) {
316 615 unset($submitted_data[$field]);
317 616 }
318 617 }
319 618 return $submitted_data;
@@ -318,81 +617,41 @@
318 617 }
319 618 return $submitted_data;
320 619 }
321 620
322 - public function fieldNameReplaceOfPost() {
323 - $fields = $this->getFields();
324 - foreach ($fields as $fieldKey => $fieldData) {
325 - if (array_key_exists('name', $fieldData)) {
326 - $fldName = $fieldData['name'];
327 - if (array_key_exists($fldName, $_POST)) {
328 - $temp = $_POST[$fldName];
329 - unset($_POST[$fldName]);
330 - $_POST[$fieldKey] = $temp;
331 - } elseif (array_key_exists($fldName, $_FILES)) {
332 - $temp = $_FILES[$fldName];
333 - unset($_FILES[$fldName]);
334 - $_FILES[$fieldKey] = $temp;
335 - }
336 - }
337 - }
338 - }
339 -
340 - public function beforeSubmittedValidate() {
621 + public function beforeSubmittedValidate($verifyCaptcha = true, $isEntryEdit = false)
622 + {
341 623 if ($this->verifySubmissionNonce()) {
342 624 if ($this->isExist()) {
343 - $isRestricted = $this->checkSubmissionRestriction();
625 + $isRestricted = $this->checkSubmissionRestriction(true, $isEntryEdit);
344 626 if ($isRestricted && !empty($isRestricted)) {
345 627 return new WP_Error('spam_detection', $isRestricted[0]);
346 628 }
347 - if ($this->isTrappedInHoneypot()) {
629 + $postData = wp_unslash($_POST);
630 + $filesData = GlobalHelper::sanitize_files_input($_FILES);
631 + $isHoneypot = apply_filters('bitform_check_honeypot', false, $this->_form_id, $postData);
632 + if ($isHoneypot) {
348 633 return new WP_Error('spam_detection', __('Token verification failed', 'bit-form'));
349 634 }
350 - $captchaSettings = $this->getCaptchaSettings();
351 - $captchaV3Settings = $this->getCaptchaV3Settings();
352 - if ($captchaSettings || $captchaV3Settings) {
353 - $token = $_POST['g-recaptcha-response'];
354 - if (!isset($_POST['g-recaptcha-response'])) {
355 - return new WP_Error('spam_detection', __('Please verify reCAPTCHA', 'bit-form'));
635 + $formCurrentStep = isset($_POST['form-current-step']) ? sanitize_text_field(wp_unslash($_POST['form-current-step'])) : null;
636 + // TODO: Temporary parameter to skip captcha verification in step change of multi step form
637 + if ($verifyCaptcha) {
638 + $verifyGRecaptchaResult = $this->verifyGRecaptcha();
639 + if (is_wp_error($verifyGRecaptchaResult)) {
640 + return $verifyGRecaptchaResult;
356 641 }
357 - $integrationHandler = new IntegrationHandler(0);
358 - $allFormIntegrations = $integrationHandler->getAllIntegration('app', $captchaSettings ? 'gReCaptcha' : 'gReCaptchaV3');
359 - if (!is_wp_error($allFormIntegrations)) {
360 - foreach ($allFormIntegrations as $integration) {
361 - if (!is_null($integration->integration_type) && $integration->integration_type === ($captchaSettings ? 'gReCaptcha' : 'gReCaptchaV3')) {
362 - $integrationDetails = json_decode($integration->integration_details);
363 - $integrationDetails->id = $integration->id;
364 - $reCAPTCHA = $integrationDetails;
365 - }
366 - }
642 + $verifyHCaptchaResult = $this->verifyHCaptcha();
643 + if (is_wp_error($verifyHCaptchaResult)) {
644 + return $verifyHCaptchaResult;
367 645 }
368 - if (!empty($reCAPTCHA->secretKey)) {
369 - $gRecaptchaResponse = HttpHelper::post(
370 - 'https://www.google.com/recaptcha/api/siteverify',
371 - ['secret' => $reCAPTCHA->secretKey, 'response' => $token]
372 - );
373 - $isgReCaptchaVerified = false;
374 - if (!is_wp_error($gRecaptchaResponse)) {
375 - if (
376 - $captchaV3Settings
377 - && !empty($gRecaptchaResponse->score)
378 - && ((float) $gRecaptchaResponse->score < (float) $captchaV3Settings->score)
379 - ) {
380 - wp_send_json_error(
381 - __(
382 - $captchaV3Settings->message,
383 - 'bit-form'
384 - )
385 - );
386 - }
387 -
388 - $isgReCaptchaVerified = $gRecaptchaResponse->success;
389 - }
390 - if (!$isgReCaptchaVerified) {
391 - return new WP_Error('spam_detection', __('Please verify reCAPTCHA', 'bit-form'));
392 - }
646 + /* Implement Turnstile Captcha start */
647 + $verifyTurnstileCaptchaResult = $this->verifyTurnstileCaptcha();
648 + if (is_wp_error($verifyTurnstileCaptchaResult)) {
649 + return $verifyTurnstileCaptchaResult;
393 650 }
394 651 }
652 + /* Implement Turnstile Captcha end */
653 +
395 654 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
396 655
397 656 // check if user is already logged in and form has auth integration
398 657 do_action('bitform_checked_exist_auth', $this->_form_id, $existAuth);
@@ -398,17 +657,80 @@
398 657 do_action('bitform_checked_exist_auth', $this->_form_id, $existAuth);
399 658 if (!is_wp_error($existAuth) && count($existAuth) > 0 && is_user_logged_in()) {
400 659 return new WP_Error('auth_error', __('You are already logged in', 'bit-form'));
401 660 }
402 - $validateForm = $this->validateFormSubmission($_POST);
403 - $validateFormFiles = $this->validateFormSubmission($_FILES);
661 + $validateForm = $this->validateFormSubmission($postData);
662 + $validateFormFiles = $this->validateFormSubmission($filesData);
404 663 $validateForm = array_merge($validateForm, $validateFormFiles);
405 - $form_fields = $this->getFields();
406 - $formFieldValidator = new FormFieldValidator($form_fields, $_POST, $_FILES);
664 + // Validate only provably-rendered fields: a field stranded in form_content->fields
665 + // with no layout entry (orphan) is never shown to the user and must not block
666 + // submission. getRenderedFields() unions ALL breakpoints × steps × nested layouts
667 + // + childFields of rendered parents, derives only from DB-stored form_content,
668 + // and fails closed (returns all fields) when the layout is unusable.
669 + $form_fields = $this->getRenderedFields();
670 + // check if form-current-step is set and form is multi-step
671 + $formCurrentStep = isset($_POST['form-current-step']) ? sanitize_text_field(wp_unslash($_POST['form-current-step'])) : null;
672 + if (!is_null($formCurrentStep)) {
673 + // Narrow validation to the current step's fields. SECURITY: the step
674 + // key set unions ALL breakpoints (lg/md/sm) — an md/sm-only field was
675 + // previously null-skipped by the validator (silent bypass). A forged
676 + // step index or malformed layout skips the narrowing entirely so every
677 + // rendered field stays validated (fail closed).
678 + $formContents = $this->getFormContent();
679 + $layout = isset($formContents->layout) ? $formContents->layout : null;
680 + $stepIndex = (int) $formCurrentStep - 1;
681 + if (is_array($layout) && isset($layout[$stepIndex]->layout) && is_object($layout[$stepIndex]->layout)) {
682 + $stepLayout = $layout[$stepIndex]->layout;
683 + $nestedLayout = isset($formContents->nestedLayout) && is_object($formContents->nestedLayout)
684 + ? $formContents->nestedLayout : null;
685 + $stepKeys = [];
686 + foreach (['lg', 'md', 'sm'] as $brkpnt) {
687 + if (!isset($stepLayout->{$brkpnt}) || !is_array($stepLayout->{$brkpnt})) {
688 + continue;
689 + }
690 + foreach ($stepLayout->{$brkpnt} as $lay) {
691 + if (!is_object($lay) || !isset($lay->i)) {
692 + continue;
693 + }
694 + $fk = $lay->i;
695 + $stepKeys[$fk] = true;
696 + if (!is_null($nestedLayout) && isset($nestedLayout->{$fk})) {
697 + foreach (['lg', 'md', 'sm'] as $nBrkpnt) {
698 + if (!isset($nestedLayout->{$fk}->{$nBrkpnt}) || !is_array($nestedLayout->{$fk}->{$nBrkpnt})) {
699 + continue;
700 + }
701 + foreach ($nestedLayout->{$fk}->{$nBrkpnt} as $nestedLay) {
702 + if (is_object($nestedLay) && isset($nestedLay->i)) {
703 + $stepKeys[$nestedLay->i] = true;
704 + }
705 + }
706 + }
707 + }
708 + }
709 + }
710 + // Name/Address/Email/Password children live outside layouts; a child
711 + // is part of this step iff its parent is.
712 + self::expandChildFieldKeys($stepKeys, $form_fields);
713 + if (!empty($stepKeys)) {
714 + $step_fields = [];
715 + foreach (array_keys($stepKeys) as $fk) {
716 + if (isset($form_fields[$fk])) {
717 + $step_fields[$fk] = $form_fields[$fk];
718 + }
719 + }
720 + $form_fields = $step_fields;
721 + }
722 + }
723 + }
724 + // Only an edit may satisfy a required upload/signature from a `_old` marker.
725 + $editedEntryID = $isEntryEdit && isset($_REQUEST['entryID'])
726 + ? sanitize_text_field(wp_unslash($_REQUEST['entryID']))
727 + : null;
728 + $formFieldValidator = new FormFieldValidator($form_fields, $postData, $filesData, $editedEntryID);
407 729 $validUniuqFields = [];
408 - $existFilter = has_filter('bf_check_duplicate_entry');
730 + $existFilter = has_filter('bitform_check_duplicate_entry');
409 731 if (true === $existFilter) {
410 - $validUniuqFields = apply_filters('bf_check_duplicate_entry', $form_fields, $_POST);
732 + $validUniuqFields = apply_filters('bitform_check_duplicate_entry', $form_fields, $postData);
411 733
412 734 $fieldKeys = array_keys($validUniuqFields);
413 735 $form_fields_keys = array_keys($form_fields);
414 736 $uniqueFields = [];
@@ -416,9 +738,9 @@
416 738 if (in_array($key, $form_fields_keys)) {
417 739 $uniqueFields[] = $form_fields[$key];
418 740 }
419 741 }
420 - do_action('bitform_Unique_entry', $uniqueFields, $validUniuqFields, $this->_form_id, $_POST);
742 + do_action('bitform_Unique_entry', $uniqueFields, $validUniuqFields, $this->_form_id, $postData);
421 743 }
422 744 $validateField = $formFieldValidator->validate('create', $this->_form_id);
423 745
424 746 if ($validateForm && $validateField && 0 === count($validUniuqFields)) {
@@ -440,23 +762,163 @@
440 762 return new WP_Error('token_expired', __('Token expired', 'bit-form'));
441 763 }
442 764 }
443 765
444 - public function verifySubmissionNonce() {
445 - if (!isset($_POST['t_identy']) && !isset($_POST['csrf'])) {
766 + private function verifyGRecaptcha()
767 + {
768 + $captchaSettings = $this->getCaptchaSettings();
769 + $captchaV3Settings = $this->getCaptchaV3Settings();
770 + if ($captchaSettings || $captchaV3Settings) {
771 + $token = isset($_POST['g-recaptcha-response']) ? sanitize_text_field(wp_unslash($_POST['g-recaptcha-response'])) : '';
772 + if (!isset($_POST['g-recaptcha-response'])) {
773 + return new WP_Error('spam_detection', __('Please recheck your reCaptcha Configuration', 'bit-form'));
774 + }
775 + $integrationHandler = new IntegrationHandler(0);
776 + $allFormIntegrations = $integrationHandler->getAllIntegration('app', $captchaSettings ? 'gReCaptcha' : 'gReCaptchaV3');
777 + if (!is_wp_error($allFormIntegrations)) {
778 + foreach ($allFormIntegrations as $integration) {
779 + if (!is_null($integration->integration_type) && $integration->integration_type === ($captchaSettings ? 'gReCaptcha' : 'gReCaptchaV3')) {
780 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
781 + if ($integrationDetails) {
782 + $integrationDetails->id = $integration->id;
783 + $reCAPTCHA = $integrationDetails;
784 + }
785 + }
786 + }
787 + }
788 + if (!empty($reCAPTCHA->secretKey)) {
789 + $gRecaptchaResponse = HttpHelper::post(
790 + 'https://www.google.com/recaptcha/api/siteverify',
791 + ['secret' => $reCAPTCHA->secretKey, 'response' => $token]
792 + );
793 + $isgReCaptchaVerified = false;
794 + if (!is_wp_error($gRecaptchaResponse)) {
795 + if (
796 + $captchaV3Settings
797 + && !empty($gRecaptchaResponse->score)
798 + && ((float) $gRecaptchaResponse->score < (float) $captchaV3Settings->score)
799 + ) {
800 + wp_send_json_error(
801 + sanitize_text_field((string) $captchaV3Settings->message)
802 + );
803 + }
804 +
805 + $isgReCaptchaVerified = $gRecaptchaResponse->success;
806 + }
807 + if (!$isgReCaptchaVerified) {
808 + return new WP_Error('spam_detection', __('Please verify reCAPTCHA', 'bit-form'));
809 + }
810 + }
811 + }
812 + }
813 +
814 + private function verifyHCaptcha()
815 + {
816 + $hCaptchaExist = $this->isFieldTypeExist('hcaptcha'); // You can rename this to getHCaptchaSettings() if needed
817 + if ($hCaptchaExist) {
818 + if (!isset($_POST['h-captcha-response'])) {
819 + return new WP_Error('spam_detection', __('Please verify hCaptcha', 'bit-form'));
820 + }
821 +
822 + $token = sanitize_text_field(wp_unslash($_POST['h-captcha-response']));
823 +
824 + $integrationHandler = new IntegrationHandler(0);
825 + $allFormIntegrations = $integrationHandler->getAllIntegration('app', 'hcaptcha');
826 +
827 + if (!is_wp_error($allFormIntegrations)) {
828 + foreach ($allFormIntegrations as $integration) {
829 + if (!is_null($integration->integration_type) && 'hcaptcha' === $integration->integration_type) {
830 + $integrationDetails = Utilities::jsonObj($integration->integration_details);
831 + if ($integrationDetails) {
832 + $integrationDetails->id = $integration->id;
833 + $hCaptcha = $integrationDetails;
834 + }
835 + }
836 + }
837 + }
838 +
839 + if (!empty($hCaptcha->secretKey)) {
840 + $hCaptchaResponse = HttpHelper::post(
841 + 'https://api.hcaptcha.com/siteverify',
842 + [
843 + 'secret' => $hCaptcha->secretKey,
844 + 'response' => $token,
845 + 'remoteip' => (isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '')
846 + ]
847 + );
848 +
849 + $isVerified = false;
850 + if (!is_wp_error($hCaptchaResponse)) {
851 + $isVerified = $hCaptchaResponse->success;
852 + }
853 +
854 + if (!$isVerified) {
855 + return new WP_Error('spam_detection', __('hCaptcha verification failed', 'bit-form'));
856 + }
857 + }
858 + }
859 + }
860 +
861 + private function verifyTurnstileCaptcha()
862 + {
863 + $turnstileExist = $this->isFieldTypeExist('turnstile');
864 + if ($turnstileExist) {
865 + if (!isset($_POST['cf-turnstile-response'])) {
866 + return new WP_Error('spam_detection', __('Please verify Cloudflare Turnstile Captcha', 'bit-form'));
867 + }
868 + $token = sanitize_text_field(wp_unslash($_POST['cf-turnstile-response']));
869 + $turnstileCaptcha = null;
870 + $integrationHandler = new IntegrationHandler(0);
871 + $turnstileIntegration = $integrationHandler->getAllIntegration('app', 'turnstileCaptcha')[0];
872 + if (!is_wp_error($turnstileIntegration && !is_null($turnstileIntegration->integration_type))) {
873 + $turnstileCaptcha = json_decode($turnstileIntegration->integration_details);
874 + // $integrationDetails->id = $turnstileIntegration->id;
875 + // $turnstileCaptcha = $integrationDetails;
876 + }
877 + if (!is_null($turnstileCaptcha)) {
878 + $isTurnstileCaptchaVerified = false;
879 + $turnstileRecaptchaResponse = HttpHelper::post(
880 + 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
881 + ['secret' => $turnstileCaptcha->secretKey, 'response' => $token]
882 + );
883 + if (!is_wp_error($turnstileRecaptchaResponse)) {
884 + if (!$turnstileRecaptchaResponse->success) {
885 + $errorCodes = implode(', ', (array) ($turnstileRecaptchaResponse->{'error-codes'} ?? []));
886 + wp_send_json_error(
887 + sprintf(
888 + /* translators: %s: dynamic value. */
889 + __('Cloudflare Turnstile Validation Error: %s', 'bit-form'),
890 + $errorCodes
891 + )
892 + );
893 + }
894 +
895 + $isTurnstileCaptchaVerified = $turnstileRecaptchaResponse->success;
896 + }
897 + if (!$isTurnstileCaptchaVerified) {
898 + return new WP_Error('spam_detection', __('Please verify Cloudflare Turnstile Captcha', 'bit-form'));
899 + }
900 + }
901 + }
902 + }
903 +
904 + public function verifySubmissionNonce()
905 + {
906 + if (!isset($_POST['t_identity']) || !isset($_POST['csrf'])) {
446 907 return false;
447 908 }
448 - $tIdenty = sanitize_text_field($_POST['t_identy']);
449 - $csrf = sanitize_text_field($_POST['csrf']);
450 - unset($_POST['t_identy'], $_POST['action'], $_POST['bitforms_id'], $_POST['csrf']);
909 + $tIdenty = sanitize_text_field(wp_unslash($_POST['t_identity']));
910 + $csrf = sanitize_text_field(wp_unslash($_POST['csrf']));
911 + unset($_POST['t_identity'], $_POST['action'], $_POST['bitforms_id'], $_POST['csrf']);
451 912 return Helpers::csrfDecrypted($tIdenty, $csrf);
452 913 }
453 914
454 - public function setViewCount() {
915 + public function setViewCount()
916 + {
455 917 if (!current_user_can('manage_options')) {
456 918 $update_status = $this->formModel->update(
457 919 [
458 - 'views' => intval(static::$form[0]->views) + 1
920 + 'views' => intval($this->form[0]->views) + 1
459 921 ],
460 922 [
461 923 'id' => $this->form_id
462 924 ]
@@ -463,212 +925,161 @@
463 925 );
464 926 }
465 927 }
466 928
467 - public function checkSubmissionRestriction() {
468 - $formContents = $this->getFormContent();
469 - $fromRestrictionSetitingsEnabled = empty($formContents->additional->enabled) ? [] : $formContents->additional->enabled;
470 - $fromRestrictionSetitings = empty($formContents->additional->settings) ? null : $formContents->additional->settings;
471 - if (is_null($formContents->additional->enabled) || is_null($formContents->additional->settings)) {
472 - return false;
473 - }
474 - $restrictionMessage = [];
475 - $ipTool = new IpTool();
476 - $ipAddress = $ipTool->getIP();
477 - foreach ($fromRestrictionSetitingsEnabled as $restrictionKey => $isEnabled) {
478 - if ($isEnabled) {
479 - if ('entry_limit' === $restrictionKey && isset($fromRestrictionSetitings->{$restrictionKey})) {
480 - $formEntry = new FormEntryModel();
481 - $countResult = $formEntry->count(
482 - [
483 - 'form_id' => $this->form_id
484 - ]
485 - );
486 - $count = !empty($countResult[0]) && !empty($countResult[0]->count) ? $countResult[0]->count : false;
487 - if ($count && $count >= intval($fromRestrictionSetitings->{$restrictionKey})) {
488 - $restrictionMessage[] = __('Sorry!! Entry limit exceeded', 'bit-form');
489 - }
929 + /**
930 + * @param bool $checkedEmptySubmitted whether the empty-submission rule applies here
931 + * @param bool $isEntryEdit true when an existing entry is being updated
932 + */
933 + public function checkSubmissionRestriction($checkedEmptySubmitted = true, $isEntryEdit = false)
934 + {
935 + $formContents = $this->getFormContent();
936 + $additionalSettings = isset($formContents->additional) ? $formContents->additional : null;
937 + $fromRestrictionSetitingsEnabled = empty($additionalSettings->enabled) ? [] : $additionalSettings->enabled;
938 + $fromRestrictionSetitings = empty($additionalSettings->settings) ? null : $additionalSettings->settings;
939 +
940 + if (is_null($additionalSettings) || is_null($fromRestrictionSetitings) || empty((array) $fromRestrictionSetitingsEnabled)) {
941 + return false;
942 + }
943 +
944 + $restrictionMessage = [];
945 + $ipTool = new IpTool();
946 + $ipAddress = $ipTool->getIP();
947 + $currentUserId = get_current_user_id();
948 +
949 + foreach ($fromRestrictionSetitingsEnabled as $restrictionKey => $isEnabled) {
950 + if ($isEnabled) {
951 + // Quota rules gate creating an entry, so an edit skips them; access-control keys stay.
952 + $skippableOnEdit = ['onePerIp', 'entry_limit', 'entry_limit_by_user', 'restrict_form'];
953 + if ($isEntryEdit && in_array($restrictionKey, $skippableOnEdit, true)) {
954 + $skipOnEdit = apply_filters(
955 + 'bitform_skip_restriction_on_entry_edit',
956 + true,
957 + $restrictionKey,
958 + $this->form_id
959 + );
960 + if ($skipOnEdit) {
961 + continue;
490 962 }
491 - if ('onePerIp' === $restrictionKey) {
492 - $formEntry = new FormEntryModel();
493 - $countResult = $formEntry->count(
494 - [
495 - 'form_id' => $this->form_id,
496 - 'user_ip' => ip2long($ipAddress)
497 - ]
498 - );
499 - $count = !empty($countResult[0]) && !empty($countResult[0]->count) ? $countResult[0]->count : false;
963 + }
964 + /**
965 + * Allow add-ons to handle any restriction key (Pro-only restrictions
966 + * should be implemented in the add-on, not shipped in the free plugin).
967 + *
968 + * Return a non-null string to block submission.
969 + */
970 + $addonMsg = apply_filters(
971 + 'bitform_submission_restriction',
972 + null,
973 + $restrictionKey,
974 + $this->form_id,
975 + $fromRestrictionSetitingsEnabled,
976 + $fromRestrictionSetitings,
977 + $ipAddress,
978 + $currentUserId
979 + );
500 980
501 - if ($count && $count > 0) {
502 - $restrictionMessage[] = __('Sorry!! You have already submitted', 'bit-form');
503 - }
504 - }
505 - if ('is_login' === $restrictionKey && 0 === get_current_user_id()) {
506 - $restrictionMessage[] = __($fromRestrictionSetitings->is_login->message, 'bit-form');
507 - }
508 - if ('empty_submission' === $restrictionKey) {
509 - $isEmpty = $this->checkEmptySubmission($_POST, $_FILES);
510 - if ($isEmpty) {
511 - $restrictionMessage[] = __($fromRestrictionSetitings->empty_submission->message, 'bit-form');
512 - }
513 - }
514 - if ('restrict_form' === $restrictionKey && isset($fromRestrictionSetitings->{$restrictionKey})) {
515 - $day = empty($fromRestrictionSetitings->{$restrictionKey}->day) ? null : $fromRestrictionSetitings->{$restrictionKey}->day;
516 - $date = empty($fromRestrictionSetitings->{$restrictionKey}->date) ? null : $fromRestrictionSetitings->{$restrictionKey}->date;
517 - $time = empty($fromRestrictionSetitings->{$restrictionKey}->time) ? null : $fromRestrictionSetitings->{$restrictionKey}->time;
981 + if (!is_null($addonMsg) && '' !== $addonMsg) {
982 + $restrictionMessage[] = $addonMsg;
983 + continue;
984 + }
518 985
519 - $isdayOk = $isdateOk = $istimeOk = true;
520 - $dayNotOkMsg = $dateNotOkMsg = $timeNotOkMsg = '';
521 - $dateTimeHelper = new DateTimeHelper();
522 - if (
523 - !empty($day)
524 - && is_array($day)
525 - && (in_array('Friday', $day)
526 - || in_array('Saturday', $day)
527 - || in_array('Sunday', $day)
528 - || in_array('Monday', $day)
529 - || in_array('Tuesday', $day)
530 - || in_array('Wednesday', $day)
531 - || in_array('Thursday', $day))
532 - && (!in_array($dateTimeHelper->getDay('full-name'), $day))
533 - ) {
534 - $isdayOk = false;
535 - $dayMsgVarsFormat = '';
536 - foreach ($day as $dayIndex => $dayValue) {
537 - if ($dayIndex > 0) {
538 - $dayMsgVarsFormat .= ', ';
539 - }
540 - $dayMsgVarsFormat .= '%s';
541 - }
542 - $dayNotOkMsg = vsprintf(__("in $dayMsgVarsFormat", 'bit-form'), $day);
543 - }
544 - if (
545 - !empty($day)
546 - && is_array($day)
547 - && (in_array('Custom', $day))
548 - ) {
549 - $startDate = empty($date->from) ? '00-00-0000' : $date->from;
550 - $endDate = empty($date->to) ? '00-00-0000' : $date->to;
551 - if (!empty($date->from) && false !== strpos($startDate, 'T')) {
552 - $startDate = $dateTimeHelper->getDate($startDate, false, null, 'm-d-Y');
553 - }
554 - if (!empty($date->to) && false !== strpos($endDate, 'T')) {
555 - $endDate = $dateTimeHelper->getDate($endDate, false, null, 'm-d-Y');
556 - }
557 - $currentDate = $dateTimeHelper->getDate(null, null, null, 'm-d-Y');
558 - if (!($currentDate >= $startDate && $currentDate <= $endDate)) {
559 - $isdateOk = false;
560 - $dateNotOkMsg = sprintf(__('within %s to %s', 'bit-form'), $startDate, $endDate);
561 - }
562 - }
986 + if ('onePerIp' === $restrictionKey) {
987 + $formEntry = new FormEntryModel();
563 988
564 - if (!empty($time)) {
565 - $startTime = empty($time->from) ? '00:00' : $time->from;
566 - $endTime = empty($time->to) ? '23:59.999' : $time->to;
567 - $currentTime = $dateTimeHelper->getTime(null, null, null, 'H:i');
568 - if (!($currentTime >= $startTime && $currentTime <= $endTime)) {
569 - $istimeOk = false;
570 - $startTime = $dateTimeHelper->getTime($startTime, 'H:i', null);
571 - $endTime = $dateTimeHelper->getTime($endTime, 'H:i', null);
572 - $isTimeOk = false;
573 - $timeNotOkMsg = sprintf(__('%s to %s', 'bit-form'), $startTime, $endTime);
574 - }
575 - }
989 + $getResult = $formEntry->get(
990 + ['user_ip', 'status'],
991 + [
992 + 'form_id' => $this->form_id,
993 + 'user_ip' => (int) ip2long((string) $ipAddress)
994 + ],
995 + );
576 996
577 - if (!($isdateOk && $isdayOk && $istimeOk)) {
578 - if (!$isdayOk) {
579 - $restrictionMessage[] = !empty($timeNotOkMsg) ? sprintf(__('Form is available %s From %s', 'bit-form'), $dayNotOkMsg, $timeNotOkMsg) :
580 - sprintf(__('Form is available %s', 'bit-form'), $dayNotOkMsg, $timeNotOkMsg);
581 - } elseif (!$isdateOk) {
582 - $restrictionMessage[] = !empty($timeNotOkMsg) ? sprintf(__('Form is available %s From %s', 'bit-form'), $dateNotOkMsg, $timeNotOkMsg) :
583 - sprintf(__('Form is available %s', 'bit-form'), $dateNotOkMsg, $timeNotOkMsg);
584 - } elseif (!$istimeOk) {
585 - $restrictionMessage[] = sprintf(__('Form is available on %s', 'bit-form'), $timeNotOkMsg);
586 - }
587 - }
588 - }
589 - if ('blocked_ip' === $restrictionKey && isset($fromRestrictionSetitings->{$restrictionKey})) {
590 - $isIpBlocked = false;
591 - foreach ($fromRestrictionSetitings->{$restrictionKey} as $ipIndex => $ipDetails) {
592 - if (!empty($ipDetails->status) && $ipDetails->status && !empty($ipDetails->ip) && $ipDetails->ip === $ipAddress) {
593 - $isIpBlocked = true;
997 + $count = 0;
998 + $status = 0;
999 +
1000 + if (!is_wp_error($getResult) && count($getResult) > 0) {
1001 + $count = count($getResult);
1002 +
1003 + foreach ($getResult as $row) {
1004 + if (9 === (int) $row->status) {
1005 + $status = 9;
594 1006 break;
595 1007 }
596 1008 }
597 - if ($isIpBlocked) {
598 - $restrictionMessage[] = sprintf(__('Sorry!! Your IP address is %s, Blocked from submitting the form', 'bit-form'), $ipAddress);
599 - }
600 1009 }
601 - if ('private_ip' === $restrictionKey && isset($fromRestrictionSetitings->{$restrictionKey})) {
602 - $isIpWhiteListed = false;
603 - foreach ($fromRestrictionSetitings->{$restrictionKey} as $ipIndex => $ipDetails) {
604 - if (!empty($ipDetails->status) && $ipDetails->status && !empty($ipDetails->ip) && $ipDetails->ip === $ipAddress) {
605 - $isIpWhiteListed = true;
606 - break;
607 - }
608 - }
609 - if (!$isIpWhiteListed) {
610 - $restrictionMessage[] = sprintf(__('Sorry!! Your IP address is %s, Blocked from submitting the form', 'bit-form'), $ipAddress);
611 - }
1010 +
1011 + if ($count > 0 && 9 !== (int) $status) {
1012 + $onePerIp = __('Sorry!! You have already submitted from this IP address', 'bit-form');
1013 +
1014 + $onePerIp = apply_filters(
1015 + 'bitform_filter_restriction_one_per_ip_message',
1016 + $onePerIp,
1017 + $this->form_id
1018 + );
1019 +
1020 + $restrictionMessage[] = $onePerIp;
612 1021 }
613 1022 }
614 - }
615 - return $restrictionMessage;
616 - }
1023 + if ('is_login' === $restrictionKey && 0 === get_current_user_id()) {
1024 + $is_login_messages = $fromRestrictionSetitings->is_login->message;
617 1025
618 - /**
619 - * Will check if form is submitted by a bot
620 - *
621 - * @return Boolean true - if submitted by bot else false
622 - */
623 - public function isTrappedInHoneypot() {
624 - $isHoneyPot = false;
1026 + $is_login_messages = apply_filters(
1027 + 'bitform_filter_restriction_is_login_message',
1028 + $is_login_messages,
1029 + $this->form_id
1030 + );
625 1031
626 - if (!$this->isHoneypotActive()) {
627 - return false;
628 - }
1032 + $restrictionMessage[] = $is_login_messages;
1033 + }
1034 + if ($checkedEmptySubmitted && 'empty_submission' === $restrictionKey) {
1035 + $isEmpty = $this->checkEmptySubmission(wp_unslash($_POST), GlobalHelper::sanitize_files_input($_FILES), $isEntryEdit);
1036 + if ($isEmpty) {
1037 + $restriction = $fromRestrictionSetitings->empty_submission->message;
629 1038
630 - $token = $_POST['b_h_t'];
631 - $pattern = '/^([a-zA-Z0-9]*_[a-zA-Z0-9]*){4}$/';
632 - $decryptedToken = base64_decode(base64_decode($token));
1039 + $restriction = apply_filters(
1040 + 'bitform_filter_restriction_empty_submission_message',
1041 + $restriction,
1042 + $this->form_id
1043 + );
633 1044
634 - preg_match($pattern, $decryptedToken, $validToken);
635 -
636 - if ($validToken) {
637 - if (isset($_POST[$token]) && empty($_POST[$token])) {
638 - $isHoneyPot = false;
639 - } else {
640 - $isHoneyPot = true;
1045 + $restrictionMessage[] = $restriction;
1046 + }
1047 + }
641 1048 }
642 - } else {
643 - $isHoneyPot = true;
644 1049 }
1050 + return $restrictionMessage;
1051 + }
645 1052
646 - if (isset($_POST[$token])) {
647 - unset($_POST[$token]);
648 - }
649 - unset($_POST['b_h_t']);
650 - return $isHoneyPot;
1053 + /**
1054 + * Will check if form is submitted by a bot
1055 + *
1056 + * @return Boolean true - if submitted by bot else false
1057 + */
1058 + public function isTrappedInHoneypot()
1059 + {
1060 + // Honeypot is implemented by add-ons (e.g. Pro) via filter.
1061 + return (bool) apply_filters('bitform_check_honeypot', false, $this->_form_id, wp_unslash($_POST));
651 1062 }
652 1063
653 - public function isHoneypotActive() {
654 - $formContents = $this->getFormContent();
655 - $enabled = empty($formContents->additional->enabled) ? null : $formContents->additional->enabled;
656 - if (!empty($enabled->honeypot) && $enabled->honeypot) {
657 - return true;
658 - }
659 - return false;
1064 + public function isHoneypotActive()
1065 + {
1066 + return (bool) apply_filters('bitform_is_honeypot_active', false, $this->_form_id, $this->getFormContent());
660 1067 }
661 1068
662 - public function checkPaymentFields() {
1069 + public function checkPaymentFields()
1070 + {
663 1071 $formContents = $this->getFormContent();
664 1072 $fields = $formContents->fields;
665 1073
666 1074 $payments = [];
667 1075 foreach ($fields as $fldData) {
1076 + if (!is_object($fldData)) {
1077 + continue;
1078 + }
668 1079 if ('paypal' === $fldData->typ && property_exists($fldData, 'payIntegID')) {
669 1080 $payments['paypalKey'] = $this->getClientKey($fldData->payIntegID, 'clientID');
670 - } elseif ('razorpay' === $fldData->typ && property_exists($fldData->options, 'payIntegID')) {
1081 + } elseif ('razorpay' === $fldData->typ && isset($fldData->options) && is_object($fldData->options) && property_exists($fldData->options, 'payIntegID')) {
671 1082 $payments['razorpayKey'] = $this->getClientKey($fldData->options->payIntegID, 'apiKey');
672 1083 }
673 1084 }
674 1085
@@ -674,52 +1085,30 @@
674 1085
675 1086 return $payments;
676 1087 }
677 1088
678 - private function getClientKey($integID, $keyName) {
1089 + private function getClientKey($integID, $keyName)
1090 + {
679 1091 $client = '';
680 1092 if (!empty($integID)) {
681 1093 $integrationHandler = new IntegrationHandler(0);
682 1094 $integration = $integrationHandler->getAIntegration($integID, 'app', 'payments');
683 1095 if (!is_wp_error($integration)) {
684 - $integration_details = json_decode($integration[0]->integration_details);
685 - $client = base64_encode($integration_details->{$keyName});
1096 + $integrationRow = Utilities::firstRow($integration);
1097 + $integration_details = Utilities::jsonObj($integrationRow->integration_details ?? '');
1098 + if ($integration_details && isset($integration_details->{$keyName})) {
1099 + $client = base64_encode($integration_details->{$keyName});
1100 + }
686 1101 }
687 1102 }
688 1103 return $client;
689 1104 }
690 1105
691 - public function getSuccessMessageMarkups() {
692 - if (is_null($this->_work_flows)) {
693 - $workFlowManager = new WorkFlowHandler($this->form_id);
694 - $this->_work_flows = $workFlowManager->getAllworkFlow();
695 - }
696 -
697 - $ids = [];
698 - foreach ($this->_work_flows as $msgItem) {
699 - foreach ($msgItem['conditions'] as $condition) {
700 - if (isset($condition->actions->success)) {
701 - foreach ($condition->actions->success as $msg) {
702 - if ('successMsg' === $msg->type && isset($msg->details->id)) {
703 - $idObj = json_decode(stripslashes($msg->details->id));
704 - if (is_object($idObj) && !empty($idObj->id)) {
705 - array_push($ids, $idObj->id);
706 - }
707 - }
708 - }
709 - }
710 - if (isset($condition->actions->failure)) {
711 - $idObj = json_decode(stripslashes($condition->actions->failure));
712 - if (is_object($idObj) && !empty($idObj->id)) {
713 - array_push($ids, $idObj->id);
714 - }
715 - }
716 - }
717 - }
718 - $ids = array_unique($ids);
1106 + public function getSuccessMessageMarkups()
1107 + {
719 1108 if (is_null($this->_conf_messages)) {
720 1109 $successMsgHandler = new SuccessMessageHandler($this->form_id);
721 - $this->_conf_messages = $successMsgHandler->getMessages($ids);
1110 + $this->_conf_messages = $successMsgHandler->getAllMessage();
722 1111 }
723 1112
724 1113 $messageMarkups = '';
725 1114 if (is_wp_error($this->_conf_messages)) {
@@ -726,8 +1115,12 @@
726 1115 return $messageMarkups;
727 1116 }
728 1117
729 1118 foreach ($this->_conf_messages as $msgItem) {
1119 + $msgConfig = json_decode($msgItem->message_config);
1120 + if (is_object($msgConfig) && property_exists($msgConfig, 'status') && empty($msgConfig->status)) {
1121 + continue;
1122 + }
730 1123 $messageMarkups .= $this->messageMarkup($msgItem);
731 1124 }
732 1125
733 1126 return $messageMarkups;
@@ -732,26 +1125,49 @@
732 1125
733 1126 return $messageMarkups;
734 1127 }
735 1128
736 - private function messageMarkup($msg) {
1129 + public function getFormAbandonmentMessage()
1130 + {
1131 + $msg = apply_filters('bitform_form_abandonment_warning_markup', '', $this->form_id);
1132 + return is_string($msg) ? $msg : '';
1133 + }
1134 +
1135 + public function getFormAbandonmentSettings()
1136 + {
1137 + return apply_filters('bitform_form_abandonment_settings', null, $this->form_id);
1138 + }
1139 +
1140 + private function messageMarkup($msg)
1141 + {
737 1142 $msgId = $msg->id;
738 1143 $msgConfig = json_decode($msg->message_config);
739 - $scrollClass = 'below' === $msgConfig->msgType ? 'scroll' : '';
1144 + $msgType = (is_object($msgConfig) && isset($msgConfig->msgType)) ? $msgConfig->msgType : 'below';
1145 + $scrollClass = 'below' === $msgType ? 'scroll' : '';
740 1146
741 - return <<<SUCCESSMSG
742 - <div role="dialog" aria-hidden="true" data-modal-backdrop="true" class="{$this->getAtomicCls("msg-container-{$msgId}")} deactive {$scrollClass}">
743 - <div data-contentid="{$this->getFormIdentifier()}" data-msgid="{$msgId}" role="button" class="{$this->getAtomicCls("msg-background-{$msgId}")} msg-backdrop">
744 - <div class="{$this->getAtomicCls("msg-content-{$msgId}")}">
745 - <button data-contentid="{$this->getFormIdentifier()}" data-msgid="{$msgId}" class="{$this->getAtomicCls("close-{$msgId}")} msg-close" type="button">
746 - <svg class="{$this->getAtomicCls("close-icn-{$msgId}")}" viewBox="0 0 30 30">
747 - <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
748 - <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
749 - </svg>
750 - </button>
751 - <div class="msg-content"></div>
752 - </div>
753 - </div>
754 - </div>
755 -SUCCESSMSG;
1147 + return '<div
1148 + role="dialog"
1149 + aria-hidden="true"
1150 + data-modal-backdrop="true"
1151 + class="' . $this->getAtomicCls("msg-container-{$msgId}") . ' deactive ' . $scrollClass . '">
1152 + <div
1153 + data-contentid="' . $this->getFormIdentifier() . '"
1154 + data-msgid="' . $msgId . '"
1155 + role="button"
1156 + class="' . $this->getAtomicCls("msg-background-{$msgId}") . ' msg-backdrop">
1157 + <div class="bf-msg-content ' . $this->getAtomicCls("msg-content-{$msgId}") . '">
1158 + <button
1159 + data-contentid="' . $this->getFormIdentifier() . '"
1160 + data-msgid="' . $msgId . '"
1161 + class="' . $this->getAtomicCls("close-{$msgId}") . ' bf-msg-close"
1162 + type="button">
1163 + <svg class="' . $this->getAtomicCls("close-icn-{$msgId}") . '" viewBox="0 0 30 30">
1164 + <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="4" y1="3.88" x2="26" y2="26.12"></line>
1165 + <line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" x1="26" y1="3.88" x2="4" y2="26.12"></line>
1166 + </svg>
1167 + </button>
1168 + <div class="msg-content"></div>
1169 + </div>
1170 + </div>
1171 + </div>';
756 1172 }
757 1173 }