PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / V3.0.3
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder vV3.0.3
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 V3.0.3, at includes/Admin/Form/FrontEndScriptGenerator.php

585 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 'select' => '.__$fk__-dpd-fld-wrp',
370 'country' => '.__$fk__-country-fld-wrp',
371 'currency' => '.__$fk__-currency-fld-wrp',
372 'phone-number' => '.__$fk__-phone-fld-wrp',
373 'file-up' => '.__$fk__-file-up-wrpr',
374 'advanced-file-up' => '#filepond-__$fk__-container',
375 'paypal' => '.__$fk__-paypal-wrp',
376 'razorpay' => '.__$fk__-razorpay-wrp',
377 'recaptcha' => '.__$fk__-recaptcha-wrp',
378 'stripe' => '.__$fk__-stripe-fld',
379 'mollie' => '.__$fk__-mollie-wrp',
380 'repeater' => '.__$fk__-rpt-fld-wrp',
381 'signature' => '.__$fk__-inp-fld-wrp',
382 'rating' => '.__$fk__-inp-fld-wrp',
383 'email-otp' => '.__$fk__-inp-fld-wrp',
384 'hcaptcha' => '.__$fk__-h-captcha-wrp',
385 'advanced-datetime' => '.__$fk__-advanced-datetime',
386 ];
387
388 private function generateFieldConfigsJs()
389 {
390 $customFlds = ['select', 'country', 'currency', 'phone-number', 'file-up', 'advanced-file-up', 'paypal', 'razorpay', 'stripe', 'mollie', 'recaptcha', 'repeater', 'signature', 'rating', 'turnstile', 'hcaptcha', 'advanced-datetime', 'email-otp'];
391 $allFieldTypes = array_keys($this->_fields);
392 $customFldsInForms = array_intersect($allFieldTypes, $customFlds);
393 $formContents = $this->_formContents;
394 $recaptchaV3Enabled = false;
395 foreach ($formContents as $content) {
396 if (isset($content->additional->enabled->recaptchav3) && $content->additional->enabled->recaptchav3) {
397 $recaptchaV3Enabled = true;
398 break;
399 }
400 }
401 if (empty($customFldsInForms) && !$recaptchaV3Enabled) {
402 return '';
403 }
404
405 $containers = [];
406 foreach ($customFldsInForms as $customFldTyp) {
407 if (isset($this->fldContainersByType[$customFldTyp])) {
408 $containers[$customFldTyp] = $this->fldContainersByType[$customFldTyp];
409 }
410 }
411
412 $customFldConfigPaths = [];
413
414 $allConfs = ScriptFilePriorityManager::getAllFldConfs();
415 foreach ($customFldsInForms as $customFldTyp) {
416 if (isset($allConfs[$customFldTyp])) {
417 $customFldConfigPaths[$customFldTyp] = $allConfs[$customFldTyp];
418 } else {
419 $customFldConfigPaths[$customFldTyp] = (object) [];
420 }
421 }
422
423 $customFldConfigPaths = wp_json_encode($customFldConfigPaths);
424 $containers = wp_json_encode($containers);
425
426 $script = ' const customFldConfigPaths = ' . $customFldConfigPaths . ';
427 const fldContainers = ' . $containers . ';
428
429 function initAllCustomFlds (formContentId = null) {
430 const allContendIds = formContentId ? [formContentId] : Object.keys(bf_globals);
431 allContendIds.forEach((contentId) => {
432 const contentData = bf_globals[contentId];
433 if(!contentData?.inits) contentData.inits = {};
434 const flds = bf_globals[contentId]?.fields || {};
435 const fldKeys = Object.keys(flds).reverse();
436 fldKeys.forEach((fldKey) => {
437 const fldData = flds[fldKey];
438 const fldType = fldData.typ;
439 if(fldType === \'paypal\') {
440 initPaypalFld(contentId, fldKey, fldData, fldType);
441 } else if(fldType === \'razorpay\') {
442 initRazorpayFld(contentId, fldKey, fldType);
443 } else if(fldType === \'recaptcha\') {
444 initRecaptchaFld(contentId, fldKey, fldType);
445 } else if(fldType === \'turnstile\') {
446 initTurnstileFld(contentId, fldKey);
447 } else if(fldType === \'hcaptcha\') {
448 initHCaptchaFld(contentId, fldKey, fldType);
449 } else if(fldType === \'stripe\' || fldType === \'mollie\') {
450 initStripeFld(contentId, fldKey, fldType);
451 } else if (customFldConfigPaths[fldType]) {
452 contentData.inits[fldKey] = getFldInstance(contentId, fldKey, fldType);
453 }
454 });
455 if(contentData.gRecaptchaVersion === \'v3\' && contentData.gRecaptchaSiteKey){
456 initRecaptchaV3Fld(contentId, contentData);
457 }
458 });
459 };
460 function getFldInstance(contentId, fldKey, fldTyp, nestedSelector = \'\') {
461 const fldClass = this[\'bit_\'+fldTyp.replace(/-/g, \'_\')+\'_field\'];
462 const selector = \'#form-\'+contentId+\' \'+nestedSelector+fldContainers[fldTyp].replace("__$fk__", fldKey);
463 if(!fldClass || !bfSelect(selector)) return;
464 return new fldClass(selector, getFldConf(contentId, fldKey, fldTyp));
465 };
466 function getFldConf(contentId, fieldKey, fldTyp) {
467 const fldData = bf_globals[contentId].fields[fieldKey];
468 const fldConfPaths = Object.entries(customFldConfigPaths[fldTyp]);
469 let fldConf = {};
470 const { formId } = bf_globals[contentId];
471 if (!("config" in customFldConfigPaths[fldTyp]) && "config" in fldData) fldConf = fldData.config;
472 const varData = { contentId, fieldKey, formId };
473 fldConfPaths.forEach(([ confPath, fldPath ]) => {
474 let value = "";
475 if (fldPath.var) value = varData[fldPath.var];
476 if (!value && fldPath.path) {
477 if(Array.isArray(fldPath.path)) {
478 fldPath.path.forEach((path) => {
479 if(!value) value = getDataFromNestedPath(fldData, path);
480 });
481 } else {
482 value = getDataFromNestedPath(fldData, fldPath.path);
483 }
484 }
485 if (!value && "val" in fldPath) {
486 value = fldPath.val;
487 if(typeof value === \'string\') {
488 Object.entries(varData).forEach(([key, val]) => {
489 value = value.replace("__$"+key+"__", val);
490 });
491 }
492 }
493 fldConf = setDataToNestedPath(fldConf, confPath, value);
494 });
495 return fldConf;
496 };
497 function getDataFromNestedPath(data, key) {
498 const keys = key.split("->");
499 const lastKey = keys.pop();
500 let current = {...data};
501 for (const k of keys) {
502 if (!(k in current)) return null;
503 current = current[k];
504 }
505 return current[lastKey] || null;
506 }
507 function setDataToNestedPath(data, key, value) {
508 const keys = key.split("->");
509 const lastKey = keys.pop();
510 let current = {...data};
511 keys.forEach((k) => {
512 if (!current[k]) current[k] = {};
513 current = current[k];
514 });
515 current[lastKey] = value;
516 return current;
517 }';
518
519 return $script;
520 }
521
522 private function addScriptInLoadedScriptsList($fileArr)
523 {
524 $fileName = $fileArr['filename'];
525 if (!in_array($fileName, $this->_scriptAddedFlags)) {
526 $this->_loadedScriptsList[] = $fileArr;
527 $this->_scriptAddedFlags[] = $fileName;
528 }
529 return true;
530 }
531
532 private function jsFrontendScript()
533 {
534 foreach ($this->_formContents as $formContent) {
535 if (Helpers::property_exists_nested($formContent, 'workFlowExist->oninput', true)) {
536 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['conditionalLogic'];
537 $this->addScriptInLoadedScriptsList($fileArr);
538 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['resetPlaceholders'];
539 $this->addScriptInLoadedScriptsList($fileArr);
540 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['bfResetDefaultValue'];
541 $this->addScriptInLoadedScriptsList($fileArr);
542 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['validateFocusLost'];
543 $this->addScriptInLoadedScriptsList($fileArr);
544 $fileArr = ScriptFilePriorityManager::frontendScriptFile()['observeElm'];
545 $this->addScriptInLoadedScriptsList($fileArr);
546 }
547 if (Helpers::property_exists_nested($formContent, 'additional->enabled->validateFocusLost', true)) {
548 $fileArr = ScriptFilePriorityManager::validationAndOtherScriptFile()['validateFocusLost'];
549 $this->addScriptInLoadedScriptsList($fileArr);
550 }
551 }
552 }
553
554 private function jsHiddenFieldScript()
555 {
556 $appConfig = get_option('bitform_app_config');
557 if (Helpers::property_exists_nested($appConfig, 'cache_plugin', true)) {
558 $fileArr = ScriptFilePriorityManager::frontendScriptFile()['hidden-token-field'];
559 $this->addScriptInLoadedScriptsList($fileArr);
560 return;
561 }
562 }
563
564 private function jsRecaptchaV3Scripts()
565 {
566 foreach ($this->_formContents as $content) {
567 if (isset($content->additional->enabled->recaptchav3) && $content->additional->enabled->recaptchav3) {
568 $this->addScriptInLoadedScriptsList(['priority' => 302, 'filename' => 'scriptLoader.min.js']);
569 $this->addScriptInLoadedScriptsList(['priority' => 303, 'filename' => 'initRecaptchaV3Fld.min.js']);
570 return;
571 }
572 }
573 }
574
575 public function dd($data, $exit = false)
576 {
577 echo '+++++++++++++';
578 echo '<pre>';
579 var_dump($data);
580 echo '</pre>';
581 echo '+++++++++++++';
582 $exit ? exit : '';
583 }
584 }
585