PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.0
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.0
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
bit-form / includes / Frontend / Form / FrontendFormManager.php

FrontendFormManager.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.0, at includes/Frontend/Form/FrontendFormManager.php

758 lines 30.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Get set Form,fields
5 */
6
7 namespace BitCode\BitForm\Frontend\Form;
8
9 /**
10 * FrontendFormManager class
11 */
12
13 use BitCode\BitForm\Admin\Form\Helpers;
14 use BitCode\BitForm\Core\Database\FormEntryModel;
15 use BitCode\BitForm\Core\Form\FormManager;
16 use BitCode\BitForm\Core\Form\Validator\FormFieldValidator;
17 use BitCode\BitForm\Core\Integration\IntegrationHandler;
18 use BitCode\BitForm\Core\Messages\SuccessMessageHandler;
19 use BitCode\BitForm\Core\Util\ApiResponse as UtilApiResponse;
20 use BitCode\BitForm\Core\Util\DateTimeHelper;
21 use BitCode\BitForm\Core\Util\HttpHelper;
22 use BitCode\BitForm\Core\Util\IpTool;
23 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
24 use BitCode\BitForm\Core\WorkFlow\WorkFlowHandler;
25 use BitCode\BitForm\Frontend\Form\View\FormViewer;
26 use WP_Error;
27
28 final class FrontendFormManager extends FormManager {
29 private $_form_identifier;
30 private $_form_token;
31 private $_form_id;
32 private $_work_flows;
33 private $_conf_messages;
34
35 // private $_has_upload = false;
36 public function __construct($form_id, $shortCodeCounter = null) {
37 parent::__construct($form_id);
38 $this->_form_identifier = 'bitforms_' . $form_id;
39 $this->_form_identifier .= !empty(get_post()->ID) ? '_' . get_post()->ID : '';
40 $this->_form_identifier .= !empty($shortCodeCounter) ? "_$shortCodeCounter" : '';
41 $this->_form_token = wp_create_nonce('bitforms_' . $form_id);
42 $this->_form_id = $form_id;
43 }
44
45 public function getFormIdentifier() {
46 return $this->_form_identifier;
47 }
48
49 public function getFormID() {
50 return $this->_form_id;
51 }
52
53 public function getFormToken() {
54 return $this->_form_token;
55 }
56
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) {
63 unset($submitted_data[$this->_form_identifier]);
64 // unset($submitted_data['bit-form-submit-btn']);
65 return array_keys($submitted_data);
66 }
67
68 public function formView($fields = null, $hasFile = false, $errorMessages = null, $previousValue = null) {
69 $formContents = $this->getFormContent();
70 $formAtomicClsMap = $this->getAtomicClsMap();
71 if (!empty($fields)) {
72 $formContents->fields = is_string($fields) ? json_decode($fields) : $fields;
73 } else {
74 $workFlowRunHelper = new WorkFlow($this->form_id);
75 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
76 'create',
77 $formContents->fields
78 );
79 $formContents->fields = empty($workFlowreturnedOnLoad['fields']) ? $formContents->fields : $workFlowreturnedOnLoad['fields'];
80 }
81 $formViewer = new FormViewer($this, $formContents, $formAtomicClsMap, $errorMessages, $previousValue);
82 return $formViewer->getView($hasFile);
83 }
84
85 private function checkEmptySubmission($data, $file) {
86 $formFields = $this->getFields();
87 foreach ($formFields as $key => $field) {
88 $fieldType = $field['type'];
89 $fileUploadFieldTypes = ['file-up', 'advanced-file-up'];
90 $isFileType = in_array($fieldType, $fileUploadFieldTypes);
91 if (!$isFileType && !empty($data[$key])) {
92 return false;
93 }
94 if ($isFileType && !empty($file[$key]['name']) && is_string($file[$key]['name'])) {
95 return false;
96 }
97 if ($isFileType && is_array($file[$key]['name']) && !empty($file[$key]['name'][0])) {
98 return false;
99 }
100 }
101 return true;
102 }
103
104 private function getParams() {
105 $url = parse_url(wp_get_referer());
106 $parameter = [];
107 if (isset($url['query'])) {
108 $queries = explode('&', $url['query']);
109 foreach ($queries as $query) {
110 list($field, $value) = explode('=', $query);
111 $parameter[$field] = $value;
112 }
113 }
114 return $parameter;
115 }
116
117 public function handleSubmission() {
118 $this->fieldNameReplaceOfPost();
119 $validated = $this->beforeSubmittedValidate();
120
121 if (true === $validated) {
122 unset($_POST['hidden_fields']);
123
124 $redirectPage = '';
125 $regSuccMsg = '';
126
127 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
128 if (!is_wp_error($existAuth) && count($existAuth) > 0) {
129 $parameter = $this->getParams();
130 $existAuthFilter = has_filter('bf_wp_user_auth');
131
132 if (true === $existAuthFilter) {
133 $result = apply_filters('bf_wp_user_auth', $existAuth[0], $_POST, $parameter);
134
135 if (isset($result['auth_type']) && 'register' === $result['auth_type']) {
136 if (!$result['success']) {
137 return new WP_Error('errors', __($result['message'], 'bit-form'));
138 } elseif (isset($result['success'])) {
139 $redirectPage = $result['redirect_url'];
140 $regSuccMsg = $result['message'];
141 $newNonce = wp_create_nonce('bitforms_' . $this->_form_id);
142 }
143 } else {
144 if (!$result['success']) {
145 return new WP_Error('errors', __($result['message'], 'bit-form'));
146 } else {
147 return $result;
148 }
149 }
150 }
151 }
152
153 $saveResponse = $this->saveFormEntry($_POST);
154 if (is_wp_error($saveResponse)) {
155 return $saveResponse;
156 }
157
158 $entryID = $saveResponse['entry_id'];
159 do_action('bitform_submit_success', $this->_form_id, $entryID, $_POST);
160
161 $captchaV3Settings = $this->getCaptchaV3Settings();
162 if ($captchaV3Settings) {
163 $token = $_POST['g-recaptcha-response'];
164 $integrationHandler = new IntegrationHandler(0);
165 $allFormIntegrations = $integrationHandler->getAllIntegration('app', 'gReCaptchaV3');
166 if (!is_wp_error($allFormIntegrations)) {
167 foreach ($allFormIntegrations as $integration) {
168 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;
172 }
173 }
174 }
175 if (!empty($reCAPTCHA->secretKey)) {
176 $gRecaptchaResponse = HttpHelper::post(
177 'https://www.google.com/recaptcha/api/siteverify',
178 ['secret' => $reCAPTCHA->secretKey, 'response' => $token]
179 );
180 if ($captchaV3Settings && !empty($saveResponse['triggerData'])) {
181 $logID = $saveResponse['triggerData']['logID'];
182 $integId = $reCAPTCHA->id;
183 $saveApiResponse = new UtilApiResponse();
184 $saveApiResponse->apiResponse($logID, $integId, ['type_name' => 'ReCaptcha', 'type' => 'v3'], 'success', $gRecaptchaResponse);
185 }
186 }
187 unset($_POST['g-recaptcha-response']);
188 }
189 if (!empty($redirectPage) && empty($saveResponse['redirectPage']) || null === $saveResponse['redirectPage']) {
190 $saveResponse['redirectPage'] = $redirectPage;
191 }
192 if (!empty($regSuccMsg) && isset($saveResponse['dflt_message'])) {
193 $saveResponse['message'] = $regSuccMsg;
194 }
195 $saveResponse = IntegrationHandler::maybeSetCronForIntegration($saveResponse, 'create');
196 $entryId = $saveResponse['entry_id'];
197
198 $responseMsg = is_array($saveResponse) && !empty($saveResponse) ? $saveResponse : __('Form Submitted Successfully', 'bit-form');
199 if (isset($newNonce)) {
200 $responseMsg['new_nonce'] = $newNonce;
201 }
202 $_POST = [];
203 $responseMsg['entry_id'] = $entryId;
204 return $responseMsg;
205 }
206 do_action('bitform_validation_error', $this->_form_id, $validated);
207 return $validated;
208 }
209
210 public function handleUpdateEntry() {
211 $this->fieldNameReplaceOfPost();
212 $validated = $this->beforeSubmittedValidate();
213
214 $entryID = $_POST['entryID'];
215 if (is_null($entryID)) {
216 return new WP_Error('empty_form', __('Entries id is invalid', 'bit-form'));
217 }
218 if (true === $validated) {
219 unset($_POST['hidden_fields'], $_POST['entryID']);
220
221 $redirectPage = '';
222 $regSuccMsg = '';
223
224 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
225 if (!is_wp_error($existAuth) && count($existAuth) > 0) {
226 $parameter = $this->getParams();
227 $existAuthFilter = has_filter('bf_wp_user_auth');
228
229 if (true === $existAuthFilter) {
230 $result = apply_filters('bf_wp_user_auth', $existAuth[0], $_POST, $parameter);
231
232 if (isset($result['auth_type']) && 'register' === $result['auth_type']) {
233 if (!$result['success']) {
234 return new WP_Error('errors', __($result['message'], 'bit-form'));
235 } elseif (isset($result['success'])) {
236 $redirectPage = $result['redirect_url'];
237 $regSuccMsg = $result['message'];
238 $newNonce = wp_create_nonce('bitforms_' . $this->_form_id);
239 }
240 } else {
241 if (!$result['success']) {
242 return new WP_Error('errors', __($result['message'], 'bit-form'));
243 } else {
244 return $result;
245 }
246 }
247 }
248 }
249
250 $updateResponse = $this->updateFormEntry($_POST, $this->getFormID(), $entryID);
251 if (is_wp_error($updateResponse)) {
252 return $updateResponse;
253 }
254
255 do_action('bitform_submit_success', $this->_form_id, $entryID, $_POST);
256
257 $captchaV3Settings = $this->getCaptchaV3Settings();
258 if ($captchaV3Settings) {
259 $token = $_POST['g-recaptcha-response'];
260 $integrationHandler = new IntegrationHandler(0);
261 $allFormIntegrations = $integrationHandler->getAllIntegration('app', 'gReCaptchaV3');
262 if (!is_wp_error($allFormIntegrations)) {
263 foreach ($allFormIntegrations as $integration) {
264 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;
268 }
269 }
270 }
271 if (!empty($reCAPTCHA->secretKey)) {
272 $gRecaptchaResponse = HttpHelper::post(
273 'https://www.google.com/recaptcha/api/siteverify',
274 ['secret' => $reCAPTCHA->secretKey, 'response' => $token]
275 );
276 if ($captchaV3Settings && !empty($updateResponse['triggerData'])) {
277 $logID = $updateResponse['triggerData']['logID'];
278 $integId = $reCAPTCHA->id;
279 $saveApiResponse = new UtilApiResponse();
280 $saveApiResponse->apiResponse($logID, $integId, ['type_name' => 'ReCaptcha', 'type' => 'v3'], 'success', $gRecaptchaResponse);
281 }
282 }
283 unset($_POST['g-recaptcha-response']);
284 }
285 if (!empty($redirectPage) && empty($updateResponse['redirectPage']) || null === $updateResponse['redirectPage']) {
286 $updateResponse['redirectPage'] = $redirectPage;
287 }
288 if (!empty($regSuccMsg) && isset($updateResponse['dflt_message'])) {
289 $updateResponse['message'] = $regSuccMsg;
290 }
291 $updateResponse = IntegrationHandler::maybeSetCronForIntegration($updateResponse, 'create');
292 $entryId = $updateResponse['entry_id'];
293
294 $responseMsg = is_array($updateResponse) && !empty($updateResponse) ? $updateResponse : __('Entry Update Successfully', 'bit-form');
295 if (isset($newNonce)) {
296 $responseMsg['new_nonce'] = $newNonce;
297 }
298 $_POST = [];
299 $responseMsg['entry_id'] = $entryId;
300 return $responseMsg;
301 }
302 do_action('bitform_validation_error', $this->_form_id, $validated);
303 return $validated;
304 }
305
306 public function validateFormSubmission($submitted_data) {
307 $hidden_fields = isset($submitted_data['hidden_fields']) ? $submitted_data['hidden_fields'] : '';
308 $submitted_fields = $this->getSubmittedFields($submitted_data);
309 $form_fields = $this->getFields();
310 $form_fields_names = array_keys($form_fields);
311 if ($this->isGCLIDEnabled()) {
312 array_push($form_fields_names, 'GCLID');
313 }
314 foreach ($submitted_fields as $key => $field) {
315 if ('hidden_fields' !== $field && !in_array($field, $form_fields_names) || false !== strpos($hidden_fields, $field)) {
316 unset($submitted_data[$field]);
317 }
318 }
319 return $submitted_data;
320 }
321
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() {
341 if ($this->verifySubmissionNonce()) {
342 if ($this->isExist()) {
343 $isRestricted = $this->checkSubmissionRestriction();
344 if ($isRestricted && !empty($isRestricted)) {
345 return new WP_Error('spam_detection', $isRestricted[0]);
346 }
347 if ($this->isTrappedInHoneypot()) {
348 return new WP_Error('spam_detection', __('Token verification failed', 'bit-form'));
349 }
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'));
356 }
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 }
367 }
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 }
393 }
394 }
395 $existAuth = (new IntegrationHandler($this->_form_id))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
396
397 // check if user is already logged in and form has auth integration
398 do_action('bitform_checked_exist_auth', $this->_form_id, $existAuth);
399 if (!is_wp_error($existAuth) && count($existAuth) > 0 && is_user_logged_in()) {
400 return new WP_Error('auth_error', __('You are already logged in', 'bit-form'));
401 }
402 $validateForm = $this->validateFormSubmission($_POST);
403 $validateFormFiles = $this->validateFormSubmission($_FILES);
404 $validateForm = array_merge($validateForm, $validateFormFiles);
405 $form_fields = $this->getFields();
406 $formFieldValidator = new FormFieldValidator($form_fields, $_POST, $_FILES);
407 $validUniuqFields = [];
408 $existFilter = has_filter('bf_check_duplicate_entry');
409 if (true === $existFilter) {
410 $validUniuqFields = apply_filters('bf_check_duplicate_entry', $form_fields, $_POST);
411
412 $fieldKeys = array_keys($validUniuqFields);
413 $form_fields_keys = array_keys($form_fields);
414 $uniqueFields = [];
415 foreach ($fieldKeys as $key) {
416 if (in_array($key, $form_fields_keys)) {
417 $uniqueFields[] = $form_fields[$key];
418 }
419 }
420 do_action('bitform_Unique_entry', $uniqueFields, $validUniuqFields, $this->_form_id, $_POST);
421 }
422 $validateField = $formFieldValidator->validate('create', $this->_form_id);
423
424 if ($validateForm && $validateField && 0 === count($validUniuqFields)) {
425 return true;
426 } else {
427 $error = __('Please submit form with valid fields', 'bit-form');
428 if (!$validateForm) {
429 $errorMessages = $error;
430 } elseif (count($formFieldValidator->getMessage()) > 0) {
431 $errorMessages = $formFieldValidator->getMessage();
432 } else {
433 $errorMessages = 0 === count($validUniuqFields) ? $error : $validUniuqFields;
434 }
435 return new WP_Error('validation_error', $errorMessages);
436 }
437 }
438 return new WP_Error('unknown_form', __('Form does not exist', 'bit-form'));
439 } else {
440 return new WP_Error('token_expired', __('Token expired', 'bit-form'));
441 }
442 }
443
444 public function verifySubmissionNonce() {
445 if (!isset($_POST['t_identy']) && !isset($_POST['csrf'])) {
446 return false;
447 }
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']);
451 return Helpers::csrfDecrypted($tIdenty, $csrf);
452 }
453
454 public function setViewCount() {
455 if (!current_user_can('manage_options')) {
456 $update_status = $this->formModel->update(
457 [
458 'views' => intval(static::$form[0]->views) + 1
459 ],
460 [
461 'id' => $this->form_id
462 ]
463 );
464 }
465 }
466
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 }
490 }
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;
500
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;
518
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 }
563
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 }
576
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;
594 break;
595 }
596 }
597 if ($isIpBlocked) {
598 $restrictionMessage[] = sprintf(__('Sorry!! Your IP address is %s, Blocked from submitting the form', 'bit-form'), $ipAddress);
599 }
600 }
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 }
612 }
613 }
614 }
615 return $restrictionMessage;
616 }
617
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;
625
626 if (!$this->isHoneypotActive()) {
627 return false;
628 }
629
630 $token = $_POST['b_h_t'];
631 $pattern = '/^([a-zA-Z0-9]*_[a-zA-Z0-9]*){4}$/';
632 $decryptedToken = base64_decode(base64_decode($token));
633
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;
641 }
642 } else {
643 $isHoneyPot = true;
644 }
645
646 if (isset($_POST[$token])) {
647 unset($_POST[$token]);
648 }
649 unset($_POST['b_h_t']);
650 return $isHoneyPot;
651 }
652
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;
660 }
661
662 public function checkPaymentFields() {
663 $formContents = $this->getFormContent();
664 $fields = $formContents->fields;
665
666 $payments = [];
667 foreach ($fields as $fldData) {
668 if ('paypal' === $fldData->typ && property_exists($fldData, 'payIntegID')) {
669 $payments['paypalKey'] = $this->getClientKey($fldData->payIntegID, 'clientID');
670 } elseif ('razorpay' === $fldData->typ && property_exists($fldData->options, 'payIntegID')) {
671 $payments['razorpayKey'] = $this->getClientKey($fldData->options->payIntegID, 'apiKey');
672 }
673 }
674
675 return $payments;
676 }
677
678 private function getClientKey($integID, $keyName) {
679 $client = '';
680 if (!empty($integID)) {
681 $integrationHandler = new IntegrationHandler(0);
682 $integration = $integrationHandler->getAIntegration($integID, 'app', 'payments');
683 if (!is_wp_error($integration)) {
684 $integration_details = json_decode($integration[0]->integration_details);
685 $client = base64_encode($integration_details->{$keyName});
686 }
687 }
688 return $client;
689 }
690
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);
719 if (is_null($this->_conf_messages)) {
720 $successMsgHandler = new SuccessMessageHandler($this->form_id);
721 $this->_conf_messages = $successMsgHandler->getMessages($ids);
722 }
723
724 $messageMarkups = '';
725 if (is_wp_error($this->_conf_messages)) {
726 return $messageMarkups;
727 }
728
729 foreach ($this->_conf_messages as $msgItem) {
730 $messageMarkups .= $this->messageMarkup($msgItem);
731 }
732
733 return $messageMarkups;
734 }
735
736 private function messageMarkup($msg) {
737 $msgId = $msg->id;
738 $msgConfig = json_decode($msg->message_config);
739 $scrollClass = 'below' === $msgConfig->msgType ? 'scroll' : '';
740
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;
756 }
757 }
758