PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.9.1
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.9.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 2.10.2 All 137 releases
bit-form / includes / Frontend / Form / FrontendFormHandler.php

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

693 lines 26.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace BitCode\BitForm\Frontend\Form;
4
5 use BitCode\BitForm\Admin\Form\FrontEndScriptGenerator;
6 use BitCode\BitForm\Core\Database\FormEntryMetaModel;
7 use BitCode\BitForm\Core\Database\FormModel;
8 use BitCode\BitForm\Core\Form\FormManager;
9 use BitCode\BitForm\Core\Integration\IntegrationHandler;
10 use BitCode\BitForm\Core\Util\FieldValueHandler;
11 use BitCode\BitForm\Core\Util\FileDownloadProvider;
12 use BitCode\BitForm\Core\Util\FrontendHelpers;
13 use BitCode\BitForm\Core\Util\Utilities;
14 use BitCode\BitForm\Core\WorkFlow\WorkFlow;
15 use BitCode\BitFormPro\Admin\FormSettings\FormAbandonment;
16
17 final class FrontendFormHandler
18 {
19 public function __construct()
20 {
21 // before markup load - formids [], posts [1,2]
22 add_action('wp_enqueue_scripts', [$this, 'loadAssets']);
23 // markup loads - formids []
24 add_shortcode('bitform', [$this, 'handleFrontendRenderRequest']);
25 // after markup load - formids [1,35,3]
26 add_action('wp_footer', [$this, 'generateJS']);
27 }
28
29 private function validPassowordResetToken($token, $userID, $formId)
30 {
31 $existResetInteg = (new IntegrationHandler($formId))->getAllIntegration('wp_user_auth', 'wp_auth', 1);
32 if (!is_wp_error($existResetInteg) && count($existResetInteg) > 0) {
33 if ('reset' === $existResetInteg[0]->integration_name) {
34 $user = get_userdata($userID);
35 if ($user) {
36 $validKey = check_password_reset_key($token, $user->user_login);
37 if (is_wp_error($validKey)) {
38 echo "<div id='bf-resp' style='display:grid;justify-content:center;color:#860000;'>This password reset token is invalid.</div>";
39 exit();
40 }
41 } else {
42 echo "<div id='bf-resp' style='display:grid;justify-content:center;color:#860000;'>Invalid User!!</div>";
43 exit();
44 }
45 }
46 }
47 }
48
49 private function getJSFileSrc($postId)
50 {
51 $formUpdateVersion = get_option('bit-form_form_update_version');
52 $formScriptSrc = BITFORMS_UPLOAD_BASE_URL . "/form-scripts/$postId/bitform-js-$postId.js?bfv=$formUpdateVersion";
53
54 return $formScriptSrc;
55 }
56
57 public function generateJs($formID = null, $entryID = null)
58 {
59 $isFormPreview = get_transient('bitform_form_preview');
60 if ($isFormPreview && !$formID) {
61 delete_transient('bitform_form_preview');
62 return;
63 }
64 $isPageBuilder = FrontendHelpers::checkIsPageBuilder($_SERVER);
65 $bfFrontendFormIds = FrontendHelpers::$bfFrontendFormIds;
66 if ($isPageBuilder || empty($bfFrontendFormIds)) {
67 return;
68 }
69 // for unique fields ids in the same form (e.g. multiple forms in the same page)
70 $allFields = [];
71 $formContents = [];
72 $contentIds = [];
73 $formIDs = [];
74 $preview = false;
75 $postId = '';
76
77 $formUpdateVersion = get_option('bit-form_form_update_version');
78 if ($formID) {
79 $formIDs[] = $formID;
80 $FrontendFormManager = new FrontendFormManager($formID, 1);
81 $FormIdentifier = esc_js($FrontendFormManager->getFormIdentifier());
82 $formContent = $FrontendFormManager->getFormContentWithValue($this->getValuesFromQueryParams());
83 $formContent->formId = $formID;
84 $formContents[] = $formContent;
85 $workFlowRunType = $entryID ? 'edit' : 'create';
86 $fields = $formContent->fields;
87 if ($entryID) {
88 $fields = $this->setFieldsValue($fields, $formID, $entryID);
89 }
90 $fields = $this->triggerWorkflowOnLoad($formID, 1, $fields, $workFlowRunType);
91 array_push($contentIds, $FormIdentifier);
92 foreach ($fields as $fk => $field) {
93 $allFields[$field->typ][] = ['fk' => $fk, 'field' => $field, 'formID' => $formID, 'contentId' => $FormIdentifier];
94 }
95 $preview = true;
96 $postId = $formID;
97 } else {
98 global $post;
99 if (!is_object($post) && !isset($post->ID)) {
100 return;
101 }
102 $bfFrontendFormIds = FrontendHelpers::$bfFrontendFormIds;
103 $bfUniqFormIds = FrontendHelpers::getAllUniqFormIdsInPage();
104 $formIDs = $bfUniqFormIds;
105 $regenerateScriptFlag = $this->regenerateScriptChecker($bfUniqFormIds);
106
107 $postId = $post->ID;
108 if (!$regenerateScriptFlag) {
109 $regenerateScriptFlag = $this->deleteUnusedFormPageIds($postId, $bfUniqFormIds);
110 }
111 $isJsGenerating = get_option('bitforms_frontend_js_generating');
112 if (!$regenerateScriptFlag && !$isJsGenerating && !empty($formIDs)) {
113 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
114 return;
115 }
116
117 foreach ($bfFrontendFormIds as $index => $formId) {
118 $shortCodeCounter = $index + 1;
119 $FrontendFormManager = new FrontendFormManager($formId, $shortCodeCounter);
120 $FormIdentifier = esc_js($FrontendFormManager->getFormIdentifier());
121 $formContent = $FrontendFormManager->getFormContentWithValue($this->getValuesFromQueryParams());
122 $formContent->formId = $formId;
123 $formContents[] = $formContent;
124 $fields = $this->triggerWorkflowOnLoad($formId, $shortCodeCounter, $formContent->fields);
125 $contentIds[] = $FormIdentifier;
126 foreach ($fields as $fk => $field) {
127 $allFields[$field->typ][] = ['fk' => $fk, 'field' => $field, 'formID' => $formId, 'contentId' => $FormIdentifier];
128 }
129 }
130 }
131 if (empty($formIDs)) {
132 return;
133 }
134 (new FrontEndScriptGenerator())->generateJsFile($formContents, $allFields, $contentIds, $postId, $formIDs, $preview);
135 wp_enqueue_script('bit-form-all-script-test', $this->getJSFileSrc($postId), [], $formUpdateVersion, true);
136 }
137
138 private function deleteUnusedFormPageIds($postId, $formIDs)
139 {
140 global $post;
141 if (!is_object($post) && !isset($post->ID)) {
142 return;
143 }
144 $postId = $post->ID;
145 $formModel = new FormModel();
146 $forms = $formModel->get(
147 ['id', 'generated_script_page_ids']
148 );
149 $regenerateScriptFlag = false;
150 foreach ($forms as $form) {
151 $formId = $form->id;
152 $generatedScriptPageIdsDecoded = json_decode($form->generated_script_page_ids, true);
153 $generatedScriptPageIds = is_array($generatedScriptPageIdsDecoded) ? array_keys($generatedScriptPageIdsDecoded) : [];
154 if (!empty($generatedScriptPageIds) && !in_array($formId, $formIDs) && in_array($postId, $generatedScriptPageIds)) {
155 unset($generatedScriptPageIdsDecoded[$postId]);
156 if (empty($generatedScriptPageIdsDecoded)) {
157 $generatedScriptPageIdsDecoded = new \stdClass();
158 }
159 $regenerateScriptFlag = true;
160 $formModel->update(['generated_script_page_ids' => wp_json_encode($generatedScriptPageIdsDecoded)], ['id' => $formId]);
161 }
162 }
163 if ($regenerateScriptFlag) {
164 $formUpdateVersion = get_option('bit-form_form_update_version');
165 if (!$formUpdateVersion) {
166 $formUpdateVersion = 1;
167 } else {
168 $formUpdateVersion = (int) $formUpdateVersion + 1;
169 }
170 update_option('bit-form_form_update_version', $formUpdateVersion);
171 }
172 return $regenerateScriptFlag;
173 }
174
175 private function regenerateScriptChecker($formsIds)
176 {
177 global $post;
178 if (!is_a($post, 'WP_Post') && !isset($post->ID)) {
179 return;
180 }
181 $postId = $post->ID;
182 $regenerateScriptFlag = false;
183 $formModel = new FormModel();
184 foreach ($formsIds as $formId) {
185 $formInstance = new FormManager($formId);
186 if (!$formInstance->isExist()) {
187 continue;
188 }
189 $generatedPages = $formInstance->getFormData('generated_script_page_ids');
190 if (empty($generatedPages)) {
191 $regenerateScriptFlag = true;
192 } elseif (is_object($generatedPages) && (!isset($generatedPages->{$postId}) || (isset($generatedPages->{$postId}) && false === $generatedPages->{$postId}))) {
193 $regenerateScriptFlag = true;
194 }
195 if (!$regenerateScriptFlag) {
196 continue;
197 }
198 if (!is_object($generatedPages)) {
199 $generatedPages = (object) [];
200 }
201 $generatedPages->{$postId} = true;
202 $formModel->update(
203 [
204 'generated_script_page_ids' => \wp_json_encode($generatedPages)
205 ],
206 [
207 'id' => $formId,
208 ]
209 );
210 }
211 return $regenerateScriptFlag;
212 }
213
214 private function addInlineScript($code, $handle = '', $position = 'after')
215 {
216 $scriptHandle = !empty($handle) ? $handle : 'bf-inline-script';
217 if (!wp_script_is($scriptHandle)) {
218 wp_register_script($scriptHandle, '', [], '', true);
219 wp_enqueue_script($scriptHandle);
220 }
221 wp_add_inline_script($scriptHandle, $code, $position);
222 }
223
224 private function addInlineStyle($code, $handle = '')
225 {
226 $styleHandle = !empty($handle) ? $handle : 'bf-inline-style';
227 if (!wp_style_is($styleHandle)) {
228 wp_register_style($styleHandle, '', [], '', true);
229 wp_enqueue_style($styleHandle);
230 }
231 wp_add_inline_style($styleHandle, $code);
232 }
233
234 private function triggerWorkflowOnLoad($formID, $shortCodeCounter, $fields, $workFlowRunType = 'create')
235 {
236 $FrontendFormManager = new FrontendFormManager($formID, $shortCodeCounter);
237 $previousValue = $this->getValuesFromQueryParams();
238 $formContent = $FrontendFormManager->getFormContentWithValue($previousValue);
239 if (!empty($formContent->workFlowExist)) {
240 $workFlowRunHelper = new WorkFlow($formID);
241 if (!empty($formContent->workFlowExist->onload)) {
242 $workFlowreturnedOnLoad = $workFlowRunHelper->executeOnLoad(
243 $workFlowRunType,
244 $fields
245 );
246
247 if (!empty($workFlowreturnedOnLoad['fields'])) {
248 return $workFlowreturnedOnLoad['fields'];
249 }
250 }
251 }
252
253 return $fields;
254 }
255
256 private function executeOnUserInput($formID, $shortCodeCounter, $fields)
257 {
258 $FrontendFormManager = new FrontendFormManager($formID, $shortCodeCounter);
259 $previousValue = $this->getValuesFromQueryParams();
260 $formContent = $FrontendFormManager->getFormContentWithValue($previousValue);
261 $customCodesExist = strpos(FrontEndScriptGenerator::getCustomCodes($formID)['JavaScript'], 'bfVars');
262 if ($customCodesExist || (!empty($formContent->workFlowExist) && !empty($formContent->workFlowExist->oninput))) {
263 $workFlowRunHelper = new WorkFlow($formID);
264 return $workFlowRunHelper->executeOnUserInput('create', $fields);
265 }
266 }
267
268 private function getValuesFromQueryParams()
269 {
270 $reqField = $_SERVER['QUERY_STRING'];
271 $queryParamsValue = [];
272 if (!empty($reqField)) {
273 foreach (explode('&', $reqField) as $keyValue) {
274 // $pattern = '/([a-zA-Z0-9])([a-zA-Z])\=+/';
275 $pattern = '/([^.]+)=(.*?)([^.]+)/';
276 $matches = preg_match($pattern, $keyValue, $matchFormat);
277 if ($matches) {
278 list($field, $value) = explode('=', $keyValue, 2);
279
280 if (!trim($value)) {
281 continue;
282 }
283
284 $queryParamsValue[$field][] = sanitize_text_field(urldecode($value));
285 }
286 }
287 }
288
289 return $queryParamsValue;
290 }
291
292 public function handleFrontendRenderRequest($atts)
293 {
294 $formPreview = isset($atts['form_preview']) ? $atts['form_preview'] : false;
295 if (isset($atts['form_id'])) {
296 $formID = intval($atts['form_id']);
297 }
298 if (isset($atts['entry_id'])) {
299 $entryId = intval($atts['entry_id']);
300 } else {
301 $entryId = false;
302 }
303 if (isset($atts['id'])) {
304 $atts = shortcode_atts(['id' => 0], $atts);
305 $formID = intval($atts['id']);
306 }
307
308 if (!$formID) {
309 return __('Form ID cannot be empty', 'bit-form');
310 }
311
312 if (!$this->isExist($formID)) {
313 return sprintf(__('#%s no. Form doesn\'t exists', 'bit-form'), $formID);
314 }
315
316 // check for abandoned form entry id
317 $isAbandoned = false;
318 if (empty($entryId) && Utilities::isPro() && class_exists('\BitCode\BitFormPro\Admin\FormSettings\FormAbandonment')) {
319 $FormAbandonment = new FormAbandonment($formID);
320 $isAbandoned = $FormAbandonment->checkAbandonedFormEntryId();
321 }
322
323 FrontendHelpers::setBfFrontendFormIds($formID);
324 $bfFrontendFormIds = FrontendHelpers::$bfFrontendFormIds;
325 $shortCodeCounter = count($bfFrontendFormIds);
326 $FrontendFormManager = new FrontendFormManager($formID, $shortCodeCounter);
327
328 if (!$FrontendFormManager->checkStatus()) {
329 return sprintf(__('#%s no. Form is not active', 'bit-form'), $formID);
330 }
331 ob_start();
332 $this->loadAssets($formID);
333
334 $font = $FrontendFormManager->getFont();
335
336 if ($font && !$formPreview) {
337 wp_enqueue_style('bf-google-font', $font, '1.0.0', true);
338 }
339
340 if (!empty($_GET['token']) && !empty($_GET['id'])) {
341 $this->validPassowordResetToken($_GET['token'], $_GET['id'], $formID);
342 }
343
344 $previousValue = $this->getValuesFromQueryParams();
345 $errorMessages = []; // delete
346 $FormIdentifier = esc_js($FrontendFormManager->getFormIdentifier());
347 $nonce = $FrontendFormManager->getFormToken();
348 $file = count($FrontendFormManager->getUploadFields()) > 0 ? $FrontendFormManager->getUploadFields() : false;
349
350 $FrontendFormManager->setViewCount();
351
352 $formContent = $FrontendFormManager->getFormContentWithValue($previousValue);
353 $fields = $formContent->fields;
354 $layout = $formContent->layout;
355 $nestedLayout = isset($formContent->nestedLayout) ? $formContent->nestedLayout : (object) [];
356 $buttons = !empty($formContent->buttons) ? $formContent->buttons : '';
357 $additional = $formContent->additional;
358
359 $workFlowRunType = $entryId ? 'edit' : 'create';
360 if ($entryId) {
361 $fields = $this->setFieldsValue($fields, $formID, $entryId);
362 }
363
364 $fields = $this->triggerWorkflowOnLoad($formID, $shortCodeCounter, $fields, $workFlowRunType);
365 $workFlowreturnedOnUserInput = $this->executeOnUserInput($formID, $shortCodeCounter, $fields);
366
367 // test for form before remove
368 $noLabel = ['decision-box', 'html', 'button', 'paypal', 'razorpay', 'recaptcha'];
369 foreach ($fields as $fldKey => $field) {
370 if (!in_array($field->typ, $noLabel) && isset($field->lbl)) {
371 $lblReplaceToBackslash = str_replace('$_bf_$', '\\', $field->lbl);
372 $fields->{$fldKey}->lbl = FieldValueHandler::replaceSmartTagWithValue($lblReplaceToBackslash);
373 }
374 }
375 $fieldsKey = $FrontendFormManager->getFieldsKey();
376
377 $captchaV3Settings = $FrontendFormManager->getCaptchaV3Settings();
378 if ($FrontendFormManager->getCaptchaSettings() || $captchaV3Settings || $FrontendFormManager->getTurnstileSettings()) {
379 $integrationHandler = new IntegrationHandler(0);
380 $allFormIntegrations = $integrationHandler->getAllIntegration('app');
381 if (!is_wp_error($allFormIntegrations)) {
382 foreach ($allFormIntegrations as $integration) {
383 if (
384 $FrontendFormManager->getCaptchaSettings()
385 && !is_null($integration->integration_type)
386 && 'gReCaptcha' === $integration->integration_type
387 ) {
388 $integrationDetails = json_decode($integration->integration_details);
389 $integrationDetails->id = $integration->id;
390 $reCAPTCHA = $integrationDetails;
391 $reCAPTCHAVersion = 'v2';
392 }
393
394 if (
395 $FrontendFormManager->getTurnstileSettings()
396 && !is_null($integration->integration_type)
397 && 'turnstileCaptcha' === $integration->integration_type
398 ) {
399 $integrationDetails = json_decode($integration->integration_details);
400 $turnstileSiteKey = $integrationDetails->siteKey;
401 }
402
403 if ($captchaV3Settings) {
404 if (!is_null($integration->integration_type) && 'gReCaptchaV3' === $integration->integration_type) {
405 $integrationDetails = json_decode($integration->integration_details);
406 $integrationDetails->id = $integration->id;
407 $reCAPTCHA = $integrationDetails;
408 $reCAPTCHAVersion = 'v3';
409 }
410 }
411 }
412 }
413 }
414
415 if ($captchaV3Settings && !empty($reCAPTCHA->siteKey)) {
416 // DANGER: no matter what, DONT CHANGE THE SCRIPT ID OF THIS SCRIPT
417 $scriptId = BITFORMS_PREFIX . 'recaptcha';
418 wp_enqueue_script($scriptId, "https://www.google.com/recaptcha/api.js?render={$reCAPTCHA->siteKey}");
419 }
420
421 $configs = [
422 'bf_separator' => BITFORMS_BF_SEPARATOR,
423 ];
424
425 // check if fields has paypal or razorpay
426 $paymentFields = ['paypal', 'razorpay', 'stripe'];
427 $paymentFieldData = [];
428 foreach ($fields as $key => $field) {
429 if (in_array($field->typ, $paymentFields)) {
430 $paymentFieldData[$key] = $field;
431 }
432 }
433
434 if (!empty($paymentFieldData)) {
435 $integrationHandler = new IntegrationHandler(0);
436 foreach ($paymentFieldData as $fldKey => $fldData) {
437 if ('paypal' === $fldData->typ) {
438 $paypalIntegration = $integrationHandler->getAIntegration($fldData->payIntegID);
439 $integrationDetails = json_decode($paypalIntegration[0]->integration_details);
440 $clientID = $integrationDetails->clientID;
441 $fields->{$fldKey}->clientId = $clientID;
442 } elseif ('razorpay' === $fldData->typ) {
443 $razorpayIntegration = $integrationHandler->getAIntegration($fldData->payIntegID);
444 $integrationDetails = json_decode($razorpayIntegration[0]->integration_details);
445 $clientID = $integrationDetails->apiKey;
446 $fields->{$fldKey}->clientId = $clientID;
447 } elseif ('stripe' === $fldData->typ) {
448 $stripeIntegration = $integrationHandler->getAIntegration($fldData->payIntegID);
449 $integrationDetails = json_decode($stripeIntegration[0]->integration_details);
450 $publishableKey = $integrationDetails->publishableKey;
451 $fields->{$fldKey}->publishableKey = $publishableKey;
452 }
453 }
454 }
455
456 $bitFormFrontArr = [
457 'ajaxURL' => admin_url('admin-ajax.php'),
458 'nonce' => $nonce,
459 'version' => BITFORMS_VERSION,
460 'layout' => $layout,
461 'nestedLayout' => $nestedLayout,
462 'fields' => $fields,
463 'buttons' => $buttons,
464 'fieldsKey' => $fieldsKey,
465 'file' => $file,
466 'configs' => $configs,
467 'formId' => $formID,
468 'appID' => "bitforms_{$formID}",
469 'GCLID' => $FrontendFormManager->isGCLIDEnabled(),
470 'assetUrl' => BITFORMS_ASSET_URI,
471 'onfieldCondition' => !empty($workFlowreturnedOnUserInput['onfield_input_conditions']) ? $workFlowreturnedOnUserInput['onfield_input_conditions'] : false,
472 'smartTags' => !empty($workFlowreturnedOnUserInput['smart_tags']) ? $workFlowreturnedOnUserInput['smart_tags'] : [],
473 'paymentCallbackUrl' => get_rest_url() . 'bitform/v1/payments/razorpay',
474 'gRecaptchaSiteKey' => !empty($reCAPTCHA->siteKey) ? $reCAPTCHA->siteKey : null,
475 'gRecaptchaVersion' => !empty($reCAPTCHAVersion) ? $reCAPTCHAVersion : null,
476 'turnstileSiteKey' => !empty($turnstileSiteKey) ? $turnstileSiteKey : null
477 ];
478
479 if ($entryId) {
480 $bitFormFrontArr['entryId'] = $entryId;
481 }
482
483 if (isset($additional->enabled->validateFocusLost)) {
484 $bitFormFrontArr['validateFocusLost'] = true;
485 }
486
487 if (!empty($isAbandoned)) {
488 $bitFormFrontArr['oldValues'] = $this->getFieldsValue($formID, $isAbandoned);
489 if (empty($entryId)) {
490 $bitFormFrontArr['entryId'] = $isAbandoned;
491 }
492 }
493
494 if (is_array($layout) && count($layout) > 1) {
495 $formInfo = $FrontendFormManager->getFormInfo();
496 $multiStepSettings = isset($formInfo->multiStepSettings) ? $formInfo->multiStepSettings : null;
497 $newTempSettings = (object) [
498 'validateOnStepChange' => isset($multiStepSettings->validateOnStepChange) ? $multiStepSettings->validateOnStepChange : false,
499 'maintainStepHistory' => isset($multiStepSettings->maintainStepHistory) ? $multiStepSettings->maintainStepHistory : false,
500 'saveProgress' => isset($multiStepSettings->saveProgress) ? $multiStepSettings->saveProgress : false,
501 'showPercentage' => isset($multiStepSettings->progressSettings->showPercentage) ? $multiStepSettings->progressSettings->showPercentage : false,
502 ];
503 $bitFormFrontArr['formInfo'] = (object) [
504 'multiStepSettings' => $newTempSettings
505 ];
506 }
507
508 $bitFormsFront = apply_filters(
509 'bitforms_localized_script',
510 $bitFormFrontArr
511 );
512
513 $layout = \json_encode($layout);
514 $buttons = \json_encode($buttons);
515 $frontArr = json_encode($bitFormFrontArr);
516
517 $bfGlobals = <<<BFGLOBALS
518 if(!window.bf_globals) {
519 window.bf_globals = {}
520 } if(!window.bf_globals.{$FormIdentifier}) {
521 window.bf_globals.{$FormIdentifier} = {}
522 }
523 if(document.getElementById('{$FormIdentifier}')) {
524 window.bf_globals.{$FormIdentifier} = {...window.bf_globals.{$FormIdentifier}, ...{$frontArr}};
525 }
526 BFGLOBALS;
527 // $this->addInlineScript($bfGlobals, 'bit-form-all-script', 'before');
528
529 $html = $FrontendFormManager->formView($fields, $file, $errorMessages);
530
531 // if form preview then return html otherwise echo with output buffer
532 if ($formPreview) {
533 ob_clean();
534 $formViewObject = new \stdClass();
535 $formViewObject->html = $html;
536 $formViewObject->font = $font;
537 $formViewObject->bfGlobals = $bfGlobals;
538 return $formViewObject;
539 }
540 $html .= <<<BFGLOBALSSCRIPT
541 <script id="bit-form-bf-globals-{$FormIdentifier}">{$bfGlobals}</script>
542 BFGLOBALSSCRIPT;
543 echo trim($html);
544 return ob_get_clean();
545 }
546
547 private function isExist($formID)
548 {
549 $formModel = new FormModel();
550 $form = $formModel->get(
551 [
552 'id'
553 ],
554 [
555 'id' => $formID,
556 ]
557 );
558 if (!is_wp_error($form)) {
559 return true;
560 }
561 return false;
562 }
563
564 private function getFieldsValue($formID, $entryID)
565 {
566 $formEntryModel = new FormEntryMetaModel();
567 $metaValues = $formEntryModel->get(
568 [
569 'meta_key',
570 'meta_value'
571 ],
572 [
573 'bitforms_form_entry_id' => $entryID,
574 ]
575 );
576 $fldsData = (object) [];
577 if (!is_wp_error($metaValues)) {
578 foreach ($metaValues as $metaValue) {
579 $metaKey = $metaValue->meta_key;
580 $metaVal = $metaValue->meta_value;
581 // if meta value is array then convert to string
582 if (preg_match('/^\[.*\]$/', $metaVal)) {
583 $metaVal = json_decode($metaVal);
584 //check is it array of objects
585 if (is_array($metaVal) && is_object($metaVal[0])) {
586 $metaVal = $metaValue->meta_value;
587 } else {
588 $metaVal = implode(BITFORMS_BF_SEPARATOR, $metaVal);
589 }
590 }
591 if (!isset($fldsData->{$metaKey})) {
592 $fldsData->{$metaKey} = '';
593 }
594 $fldsData->{$metaKey} = $metaVal;
595 }
596 }
597
598 return $fldsData;
599 }
600
601 public function setFieldsValue($fields, $formID, $entryID)
602 {
603 $formEntryModel = new FormEntryMetaModel();
604 $metaValues = $formEntryModel->get(
605 [
606 'meta_key',
607 'meta_value'
608 ],
609 [
610 'bitforms_form_entry_id' => $entryID,
611 ]
612 );
613 if (!is_wp_error($metaValues)) {
614 foreach ($metaValues as $metaValue) {
615 $metaKey = $metaValue->meta_key;
616 $metaVal = $metaValue->meta_value;
617 // if meta value is array then convert to string
618 if (preg_match('/^\[.*\]$/', $metaVal)) {
619 $metaVal = json_decode($metaVal);
620 //check is it array of objects
621 if (is_array($metaVal) && is_object($metaVal[0])) {
622 $metaVal = $metaValue->meta_value;
623 } else {
624 $metaVal = implode(BITFORMS_BF_SEPARATOR, $metaVal);
625 }
626 }
627 if (property_exists($fields, $metaKey)) {
628 $fields->{$metaKey}->val = $metaVal;
629 if ('file-up' === $fields->{$metaKey}->typ || 'advanced-file-up' === $fields->{$metaKey}->typ) {
630 $fields->{$metaKey}->val = $metaValue->meta_value;
631 $fields->{$metaKey}->config->oldFiles = $metaValue->meta_value;
632 $urlQuery = parse_url(FileDownloadProvider::getBaseDownloadURL(), PHP_URL_QUERY);
633 $baseDLURL = FileDownloadProvider::getBaseDownloadURL();
634 $baseDLURL = empty($urlQuery) ? $baseDLURL . '?' : $baseDLURL . '&';
635 $fields->{$metaKey}->config->baseDLURL = $baseDLURL . "formID={$formID}&entryID={$entryID}";
636 }
637 }
638 }
639 }
640
641 return $fields;
642 }
643
644 public function loadAssets($formID = 0)
645 {
646 $bfUniqFormIds = FrontendHelpers::getAllFormIdsInPage();
647 $isPageBuilder = FrontendHelpers::$isPageBuilder;
648 $bfMultipleFormsExists = $isPageBuilder ? true : count($bfUniqFormIds) > 1;
649
650 if (!empty($formID)) {
651 $formIds = [$formID];
652 } else {
653 $formIds = $bfUniqFormIds;
654 }
655 foreach ($formIds as $formID) {
656 global $bitform_dequeued_styles;
657 if (is_array($bitform_dequeued_styles) && in_array($formID, $bitform_dequeued_styles)) {
658 continue;
659 }
660 if ($bfMultipleFormsExists) {
661 $newFormId = $formID . '-formid';
662 } else {
663 $newFormId = $formID;
664 }
665 $formUpdateVersion = get_option('bit-form_form_update_version');
666 if (!wp_style_is('bitform-style-' . $newFormId) && is_readable(BITFORMS_CONTENT_DIR . '/form-styles/bitform-' . $newFormId . '.css')) {
667 wp_enqueue_style(
668 'bitform-style-' . $newFormId,
669 BITFORMS_UPLOAD_BASE_URL . "/form-styles/bitform-{$newFormId}.css",
670 [],
671 $formUpdateVersion
672 );
673 if ($isPageBuilder) {
674 $formStyle = file_get_contents(BITFORMS_CONTENT_DIR . '/form-styles/bitform-' . $newFormId . '.css');
675 echo sprintf("<style id='bitform-style-{$newFormId}'>%s</style>", $formStyle);
676 }
677 }
678 if (!wp_style_is('bitform-style-custom-' . $formID) && is_readable(BITFORMS_CONTENT_DIR . '/form-styles/bitform-custom-' . $formID . '.css')) {
679 wp_enqueue_style(
680 'bitform-style-custom-' . $formID,
681 BITFORMS_UPLOAD_BASE_URL . "/form-styles/bitform-custom-{$formID}.css",
682 [],
683 $formUpdateVersion
684 );
685 if ($isPageBuilder) {
686 $formStyle = file_get_contents(BITFORMS_CONTENT_DIR . '/form-styles/bitform-custom-' . $formID . '.css');
687 echo sprintf("<style id='bitform-style-custom-{$formID}'>%s</style>", $formStyle);
688 }
689 }
690 }
691 }
692 }
693