PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 3.1.2
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v3.1.2
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 / Admin / Form / FrontEndScriptGenerator.php

FrontEndScriptGenerator.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 3.1.2, at includes/Admin/Form/FrontEndScriptGenerator.php

586 lines 20.5 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\Admin\Form;
4
5 if (!defined('ABSPATH')) {
6 exit;
7 }
8
9 use BitCode\BitForm\Core\Util\FileHandler;
10 use BitCode\BitForm\Core\Util\Log;
11 use WP_Error;
12
13 class FrontEndScriptGenerator
14 {
15 private $_scriptAddedFlags;
16 private $_fields;
17 private $_formContents;
18 private $_jsFilesNeeded;
19 private $_loadedScriptsList;
20 private $_validationJsFilesNeeded;
21
22 public function __construct()
23 {
24 $this->_scriptAddedFlags = [];
25 $this->_fields = [];
26 $this->_jsFilesNeeded = [];
27 $this->_loadedScriptsList = [];
28 $this->_validationJsFilesNeeded = ScriptFilePriorityManager::validationAndOtherScriptFile();
29 }
30
31 private static function generateBfGlobalObjJS($contentIds = [])
32 {
33 $contentidArray = wp_json_encode($contentIds);
34 return ' if(!window.bf_globals){ window.bf_globals = {};}
35 ' . $contentidArray . '.forEach(function(contentId){
36 const form = document.getElementById(contentId);
37 if(!form){
38 delete window.bf_globals[contentId];
39 return;
40 }
41 if(!window.bf_globals[contentId]){
42 window.bf_globals[contentId] = {inits: {}, contentId: contentId};
43 }else{
44 window.bf_globals[contentId].inits = {};
45 window.bf_globals[contentId].contentId = contentId;
46 }
47
48 });';
49 }
50
51 private static function isValidationNeeded($fldData)
52 {
53 $validationsToCheck = ['valid->req', 'valid->regexr', 'mn', 'mx', 'opt', 'err->invalid->show', 'err->notVerified->show'];
54 foreach ($validationsToCheck as $property) {
55 $needValidation = Helpers::property_exists_nested($fldData, $property);
56 if ($needValidation) {
57 return true;
58 }
59 }
60 return false;
61 }
62
63 public function generateJsFile($formContents, $fields, $contentIds, $postId, $formIDs = null, $preview = 'classic')
64 {
65 add_option('bitforms_frontend_js_generating', true);
66 $this->_formContents = $formContents;
67 $this->_fields = $fields;
68
69 $this->appendJs(self::generateBfGlobalObjJS($contentIds), $postId, $preview, 'w');
70 $this->_jsFilesNeeded = ScriptFilePriorityManager::jsFile();
71
72 // helper js files for whole form
73 foreach ($this->_jsFilesNeeded['helperScript'] as $jsFile) {
74 $this->addScriptInLoadedScriptsList($jsFile);
75 }
76
77 // for add validation js files
78 $this->jsValidationNeededFile();
79
80 // js files for all fields
81 $this->jsFieldsNeededFile();
82
83 // for frontend helper js files
84 $this->jsFrontendScript();
85
86 // for hidden Field when cache plugin on
87 $this->jsHiddenFieldScript();
88
89 // for recaptcha v3 (form-level setting)
90 $this->jsRecaptchaV3Scripts();
91
92 // for form abandonment scripts
93 $this->jsFormAbandonmentScripts();
94
95 // multi step form scripts
96 $this->multiStepFormScripts();
97
98 // conversational form scripts
99 $this->conversationalFormScripts();
100
101 //⚠👆 every script file generate method call before this method
102 $this->appendJs($this->getScript(), $postId, $preview);
103 $this->appendJs($this->generateFieldConfigsJs($contentIds), $postId, $preview);
104 // init all js events and functions at last
105 $this->appendJs(self::getFileFromAssetsJs('bitform-init.min.js'), $postId, $preview);
106 if (defined('ELEMENTOR_PRO_VERSION')) {
107 $this->appendJs(self::getFileFromAssetsJs('bitform-elementor.min.js'), $postId, $preview);
108 }
109
110 // for js file minification
111 $this->appendJs(self::getCustomJsCodes($contentIds), $postId, $preview);
112 delete_option('bitforms_frontend_js_generating');
113 return true;
114 }
115
116 private function multiStepFormScripts()
117 {
118 foreach ($this->_formContents as $formContent) {
119 $layout = $formContent->layout;
120 if (is_array($layout) && count($layout) > 1) {
121 $files = ScriptFilePriorityManager::multiStepFiles();
122 foreach ($files as $file) {
123 $this->addScriptInLoadedScriptsList($file);
124 }
125 }
126 }
127 }
128
129 private function conversationalFormScripts()
130 {
131 foreach ($this->_formContents as $formContent) {
132 if (!empty($formContent->formInfo->conversationalSettings) && $formContent->formInfo->conversationalSettings->enable) {
133 $files = ScriptFilePriorityManager::conversationalFormFiles();
134 foreach ($files as $file) {
135 $this->addScriptInLoadedScriptsList($file);
136 }
137 }
138 }
139 }
140
141 private function jsFormAbandonmentScripts()
142 {
143 /**
144 * Add-ons can inject required script files here.
145 *
146 * @param array $files Array of file arrays: ['priority' => int, 'filename' => string]
147 * @param array $formContents
148 * @param array $fields
149 */
150 $files = apply_filters('bitform_form_abandonment_script_files', [], $this->_formContents, $this->_fields);
151 if (empty($files) || !is_array($files)) {
152 return;
153 }
154 foreach ($files as $jsFile) {
155 if (!empty($jsFile['filename']) && !empty($jsFile['priority'])) {
156 $this->addScriptInLoadedScriptsList($jsFile);
157 }
158 }
159 }
160
161 private function appendJs($script, $postId, $previewMode, $mode = 'a')
162 {
163 $fileName = '';
164 $path = '';
165
166 if ('conversational' === $previewMode) {
167 $fileName = "bitform-conversational-{$postId}.js";
168 $path = 'form-scripts';
169 } elseif ('preview' === $previewMode) {
170 $fileName = "preview-{$postId}.js";
171 $path = 'form-scripts';
172 } else {
173 $fileName = "bitform-js-$postId.js";
174 $path = "form-scripts/{$postId}";
175 }
176 Helpers::saveFile($path, $fileName, Helpers::minifyJs($script), $mode);
177 }
178
179 private function getScript()
180 {
181 usort($this->_loadedScriptsList, function ($a, $b) {
182 return $a['priority'] - $b['priority'];
183 });
184
185 $script = '';
186 foreach ($this->_loadedScriptsList as $scriptFileArr) {
187 $fileNam = $scriptFileArr['filename'];
188 $fileContent = self::getFileFromAssetsJs($fileNam);
189 if ($fileContent) {
190 $script .= $fileContent;
191 }
192 }
193 return $script;
194 }
195
196 private function jsValidationNeededFile()
197 {
198 foreach ($this->_fields as $flds) {
199 foreach ($flds as $fld) {
200 $fldData = $fld['field'];
201 // for validation js files
202 if (self::isValidationNeeded($fldData)) {
203 $validation = $this->_validationJsFilesNeeded['validation'];
204 $this->addScriptInLoadedScriptsList($validation);
205 }
206 // for required
207 if (Helpers::property_exists_nested($fldData, 'valid->req')) {
208 $fileArr = $this->_validationJsFilesNeeded['requiredFldValidation'];
209 $this->addScriptInLoadedScriptsList($fileArr);
210 }
211 // for regex
212 if (Helpers::property_exists_nested($fldData, 'valid->regexr')) {
213 $patternFile = $this->_validationJsFilesNeeded['generateBackslashPattern'];
214 $rgx = $this->_validationJsFilesNeeded['regexPatternValidation'];
215 $this->addScriptInLoadedScriptsList($patternFile);
216 $this->addScriptInLoadedScriptsList($rgx);
217 }
218
219 $validationScriptFileMapping = ScriptFilePriorityManager::validationScriptFileMapping($fldData->typ);
220 if ($validationScriptFileMapping) {
221 foreach ($validationScriptFileMapping as $key => $value) {
222 $paths = $value['paths'] ?? [];
223 $hasMatchingPath = false;
224 foreach ($paths as $path) {
225 if (Helpers::property_exists_nested($fldData, $path)) {
226 $hasMatchingPath = true;
227 break; // one match is enough
228 }
229 }
230
231 if (!$hasMatchingPath) {
232 continue;
233 }
234
235 // Add the main script once
236 if (!empty($this->_validationJsFilesNeeded[$key])) {
237 $this->addScriptInLoadedScriptsList($this->_validationJsFilesNeeded[$key]);
238 }
239
240 // Add dependencies once each
241 foreach (($value['dependencies'] ?? []) as $dep) {
242 if (!empty($this->_validationJsFilesNeeded[$dep])) {
243 $this->addScriptInLoadedScriptsList($this->_validationJsFilesNeeded[$dep]);
244 }
245 }
246 }
247 }
248 }
249 }
250 }
251
252 private function jsFieldsNeededFile()
253 {
254 $filePondPluginList = apply_filters('bitform_filepond_plugins_list', []);
255 foreach ($this->_fields as $typ => $flds) {
256 if (!array_key_exists($typ, $this->_jsFilesNeeded)) {
257 continue;
258 }
259 $fldScriptArr = $this->_jsFilesNeeded[$typ];
260
261 foreach ($flds as $fld) {
262 if ('advanced-file-up' === $typ) {
263 $configs = $fld['field']->config;
264 foreach ($configs as $configKey => $config) {
265 if ($configs->$configKey) {
266 if (array_key_exists($configKey, $filePondPluginList)) {
267 $this->addScriptInLoadedScriptsList($filePondPluginList[$configKey]);
268 }
269 }
270 }
271 }
272 foreach ($fldScriptArr as $scriptFile) {
273 if (isset($scriptFile['paths']) && is_array($scriptFile['paths'])) {
274 $pathMatched = false;
275 foreach ($scriptFile['paths'] as $path) {
276 if (Helpers::property_exists_nested($fld['field'], $path)) {
277 $pathMatched = true;
278 break;
279 }
280 }
281 if (!$pathMatched) {
282 continue;
283 }
284 } elseif (isset($scriptFile['path']) && !Helpers::property_exists_nested($fld['field'], $scriptFile['path'])) {
285 continue;
286 }
287 $this->addScriptInLoadedScriptsList($scriptFile);
288 }
289 }
290 }
291 }
292
293 private static function getCustomJsCodes($contentIds = [])
294 {
295 $script = 'let bfContentId = "", bfSlNo = "1", bfVars= "";';
296 foreach ($contentIds as $contentId) {
297 $contentIdArr = explode('_', $contentId);
298 $jsCode = self::getCustomCodes($contentIdArr[1])['JavaScript'];
299 $bfSlNo = array_key_exists(3, $contentIdArr) ? $contentIdArr[3] : '1';
300 if (!empty($jsCode)) {
301 $script .= " if(bfSelect('#{$contentId}')){ bfContentId = '{$contentId}'; bfSlNo = '{$bfSlNo}'; bfVars = window.bf_globals.{$contentId}.smartTags; {$jsCode}}";
302 }
303 }
304
305 return $script;
306 }
307
308 private static function getFileFromAssetsJs($fileName)
309 {
310 $sourceJsFile = BITFORMS_PLUGIN_DIR_PATH . 'assets' . DIRECTORY_SEPARATOR . $fileName;
311 if (file_exists($sourceJsFile)) {
312 return file_get_contents($sourceJsFile);
313 }
314 Log::debug_log('file not found: ' . $fileName);
315 return false;
316 }
317
318 public static function saveCssFile($formId, $atomicCssText)
319 {
320 $path = 'form-styles';
321 $fileName = "bitform-$formId.css";
322 if (!isset($formId) || '' === $formId) {
323 return new WP_Error('missing_form_id', __('Error Occurred, Please Reload', 'bit-form'));
324 }
325 return Helpers::saveFile($path, $fileName, $atomicCssText, 'w');
326 }
327
328 public static function customCodeFile($formId, $customCodes)
329 {
330 // for js file
331 $path = 'form-scripts';
332 $fileName = "bitform-custom-$formId.js";
333 $filteredJs = Helpers::removeJsSingleLineComments($customCodes->JavaScript);
334 self::customCodeFileSaveOrDelete($filteredJs, $path, $fileName);
335
336 // for css file
337 $path = 'form-styles';
338 $fileName = "bitform-custom-$formId.css";
339 self::customCodeFileSaveOrDelete($customCodes->CSS, $path, $fileName);
340
341 return true;
342 }
343
344 public static function customCodeFileSaveOrDelete($script, $path, $fileName)
345 {
346 if ($script) {
347 Helpers::saveFile($path, $fileName, $script, 'w');
348 } else {
349 $uploadPath = "$path/$fileName";
350 $uploadFilePath = Helpers::generatePathDirOrFile($uploadPath);
351 FileHandler::deleteIsFileExists($uploadFilePath);
352 }
353 return true;
354 }
355
356 public static function getCustomCodes($formId)
357 {
358 $customCodes = ['JavaScript' => '', 'CSS' => ''];
359 $customJsPath = Helpers::generatePathDirOrFile("form-scripts/bitform-custom-$formId.js");
360 $customCodes['JavaScript'] = Helpers::fileRead($customJsPath);
361
362 $customCSSPath = Helpers::generatePathDirOrFile("form-styles/bitform-custom-$formId.css");
363 $customCodes['CSS'] = Helpers::fileRead($customCSSPath);
364
365 return $customCodes;
366 }
367
368 private $fldContainersByType = [
369 'address' => '.__$fk__-parent-fld-wrp',
370 'select' => '.__$fk__-dpd-fld-wrp',
371 'country' => '.__$fk__-country-fld-wrp',
372 'currency' => '.__$fk__-currency-fld-wrp',
373 'phone-number' => '.__$fk__-phone-fld-wrp',
374 'file-up' => '.__$fk__-file-up-wrpr',
375 'advanced-file-up' => '#filepond-__$fk__-container',
376 'paypal' => '.__$fk__-paypal-wrp',
377 'razorpay' => '.__$fk__-razorpay-wrp',
378 'recaptcha' => '.__$fk__-recaptcha-wrp',
379 'stripe' => '.__$fk__-stripe-fld',
380 'mollie' => '.__$fk__-mollie-wrp',
381 'repeater' => '.__$fk__-rpt-fld-wrp',
382 'signature' => '.__$fk__-inp-fld-wrp',
383 'rating' => '.__$fk__-inp-fld-wrp',
384 'email-otp' => '.__$fk__-inp-fld-wrp',
385 'hcaptcha' => '.__$fk__-h-captcha-wrp',
386 'advanced-datetime' => '.__$fk__-advanced-datetime',
387 ];
388
389 private function generateFieldConfigsJs()
390 {
391 $customFlds = ['address', 'select', 'country', 'currency', 'phone-number', 'file-up', 'advanced-file-up', 'paypal', 'razorpay', 'stripe', 'mollie', 'recaptcha', 'repeater', 'signature', 'rating', 'turnstile', 'hcaptcha', 'advanced-datetime', 'email-otp'];
392 $allFieldTypes = array_keys($this->_fields);
393 $customFldsInForms = array_intersect($allFieldTypes, $customFlds);
394 $formContents = $this->_formContents;
395 $recaptchaV3Enabled = false;
396 foreach ($formContents as $content) {
397 if (isset($content->additional->enabled->recaptchav3) && $content->additional->enabled->recaptchav3) {
398 $recaptchaV3Enabled = true;
399 break;
400 }
401 }
402 if (empty($customFldsInForms) && !$recaptchaV3Enabled) {
403 return '';
404 }
405
406 $containers = [];
407 foreach ($customFldsInForms as $customFldTyp) {
408 if (isset($this->fldContainersByType[$customFldTyp])) {
409 $containers[$customFldTyp] = $this->fldContainersByType[$customFldTyp];
410 }
411 }
412
413 $customFldConfigPaths = [];
414
415 $allConfs = ScriptFilePriorityManager::getAllFldConfs();
416 foreach ($customFldsInForms as $customFldTyp) {
417 if (isset($allConfs[$customFldTyp])) {
418 $customFldConfigPaths[$customFldTyp] = $allConfs[$customFldTyp];
419 } else {
420 $customFldConfigPaths[$customFldTyp] = (object) [];
421 }
422 }
423
424 $customFldConfigPaths = wp_json_encode($customFldConfigPaths);
425 $containers = wp_json_encode($containers);
426
427 $script = ' const customFldConfigPaths = ' . $customFldConfigPaths . ';
428 const fldContainers = ' . $containers . ';
429
430 function initAllCustomFlds (formContentId = null) {
431 const allContendIds = formContentId ? [formContentId] : Object.keys(bf_globals);
432 allContendIds.forEach((contentId) => {
433 const contentData = bf_globals[contentId];
434 if(!contentData?.inits) contentData.inits = {};
435 const flds = bf_globals[contentId]?.fields || {};
436 const fldKeys = Object.keys(flds).reverse();
437 fldKeys.forEach((fldKey) => {
438 const fldData = flds[fldKey];
439 const fldType = fldData.typ;
440 if(fldType === \'paypal\') {
441 initPaypalFld(contentId, fldKey, fldData, fldType);
442 } else if(fldType === \'razorpay\') {
443 initRazorpayFld(contentId, fldKey, fldType);
444 } else if(fldType === \'recaptcha\') {
445 initRecaptchaFld(contentId, fldKey, fldType);
446 } else if(fldType === \'turnstile\') {
447 initTurnstileFld(contentId, fldKey);
448 } else if(fldType === \'hcaptcha\') {
449 initHCaptchaFld(contentId, fldKey, fldType);
450 } else if(fldType === \'stripe\' || fldType === \'mollie\') {
451 initStripeFld(contentId, fldKey, fldType);
452 } else if (customFldConfigPaths[fldType]) {
453 contentData.inits[fldKey] = getFldInstance(contentId, fldKey, fldType);
454 }
455 });
456 if(contentData.gRecaptchaVersion === \'v3\' && contentData.gRecaptchaSiteKey){
457 initRecaptchaV3Fld(contentId, contentData);
458 }
459 });
460 };
461 function getFldInstance(contentId, fldKey, fldTyp, nestedSelector = \'\') {
462 const fldClass = this[\'bit_\'+fldTyp.replace(/-/g, \'_\')+\'_field\'];
463 const selector = \'#form-\'+contentId+\' \'+nestedSelector+fldContainers[fldTyp].replace("__$fk__", fldKey);
464 if(!fldClass || !bfSelect(selector)) return;
465 return new fldClass(selector, getFldConf(contentId, fldKey, fldTyp));
466 };
467 function getFldConf(contentId, fieldKey, fldTyp) {
468 const fldData = bf_globals[contentId].fields[fieldKey];
469 const fldConfPaths = Object.entries(customFldConfigPaths[fldTyp]);
470 let fldConf = {};
471 const { formId } = bf_globals[contentId];
472 if (!("config" in customFldConfigPaths[fldTyp]) && "config" in fldData) fldConf = fldData.config;
473 const varData = { contentId, fieldKey, formId };
474 fldConfPaths.forEach(([ confPath, fldPath ]) => {
475 let value = "";
476 if (fldPath.var) value = varData[fldPath.var];
477 if (!value && fldPath.path) {
478 if(Array.isArray(fldPath.path)) {
479 fldPath.path.forEach((path) => {
480 if(!value) value = getDataFromNestedPath(fldData, path);
481 });
482 } else {
483 value = getDataFromNestedPath(fldData, fldPath.path);
484 }
485 }
486 if (!value && "val" in fldPath) {
487 value = fldPath.val;
488 if(typeof value === \'string\') {
489 Object.entries(varData).forEach(([key, val]) => {
490 value = value.replace("__$"+key+"__", val);
491 });
492 }
493 }
494 fldConf = setDataToNestedPath(fldConf, confPath, value);
495 });
496 return fldConf;
497 };
498 function getDataFromNestedPath(data, key) {
499 const keys = key.split("->");
500 const lastKey = keys.pop();
501 let current = {...data};
502 for (const k of keys) {
503 if (!(k in current)) return null;
504 current = current[k];
505 }
506 return current[lastKey] || null;
507 }
508 function setDataToNestedPath(data, key, value) {
509 const keys = key.split("->");
510 const lastKey = keys.pop();
511 let current = {...data};
512 keys.forEach((k) => {
513 if (!current[k]) current[k] = {};
514 current = current[k];
515 });
516 current[lastKey] = value;
517 return current;
518 }';
519
520 return $script;
521 }
522
523 private function addScriptInLoadedScriptsList($fileArr)
524 {
525 $fileName = $fileArr['filename'];
526 if (!in_array($fileName, $this->_scriptAddedFlags)) {
527 $this->_loadedScriptsList[] = $fileArr;
528 $this->_scriptAddedFlags[] = $fileName;
529 }
530 return true;
531 }
532
533 private function jsFrontendScript()
534 {
535 foreach ($this->_formContents as $formContent) {
536 if (Helpers::property_exists_nested($formContent, 'workFlowExist->oninput', true)) {
537 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['conditionalLogic'];
538 $this->addScriptInLoadedScriptsList($fileArr);
539 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['resetPlaceholders'];
540 $this->addScriptInLoadedScriptsList($fileArr);
541 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['bfResetDefaultValue'];
542 $this->addScriptInLoadedScriptsList($fileArr);
543 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['validateFocusLost'];
544 $this->addScriptInLoadedScriptsList($fileArr);
545 $fileArr = ScriptFilePriorityManager::frontendScriptFile()['observeElm'];
546 $this->addScriptInLoadedScriptsList($fileArr);
547 }
548 if (Helpers::property_exists_nested($formContent, 'additional->enabled->validateFocusLost', true)) {
549 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['validateFocusLost'];
550 $this->addScriptInLoadedScriptsList($fileArr);
551 }
552 }
553 }
554
555 private function jsHiddenFieldScript()
556 {
557 $appConfig = get_option('bitform_app_config');
558 if (Helpers::property_exists_nested($appConfig, 'cache_plugin', true)) {
559 $fileArr = ScriptFilePriorityManager::frontendScriptFile()['hidden-token-field'];
560 $this->addScriptInLoadedScriptsList($fileArr);
561 return;
562 }
563 }
564
565 private function jsRecaptchaV3Scripts()
566 {
567 foreach ($this->_formContents as $content) {
568 if (isset($content->additional->enabled->recaptchav3) && $content->additional->enabled->recaptchav3) {
569 $this->addScriptInLoadedScriptsList(['priority' => 302, 'filename' => 'scriptLoader.min.js']);
570 $this->addScriptInLoadedScriptsList(['priority' => 303, 'filename' => 'initRecaptchaV3Fld.min.js']);
571 return;
572 }
573 }
574 }
575
576 public function dd($data, $exit = false)
577 {
578 echo '+++++++++++++';
579 echo '<pre>';
580 var_dump($data);
581 echo '</pre>';
582 echo '+++++++++++++';
583 $exit ? exit : '';
584 }
585 }
586