PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.21.13
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.21.13
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 / Core / Integration / IntegrationHandler.php

IntegrationHandler.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.21.13, at includes/Core/Integration/IntegrationHandler.php

629 lines 21.8 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\Core\Integration;
4
5 use BitCode\BitForm\Admin\Form\AdminFormManager;
6 use BitCode\BitForm\Admin\Form\Helpers;
7 use BitCode\BitForm\Core\Database\FormEntryLogModel;
8 use BitCode\BitForm\Core\Database\FormEntryModel;
9 use BitCode\BitForm\Core\Database\IntegrationModel;
10 use BitCode\BitForm\Core\Form\FormManager;
11 use BitCode\BitForm\Core\Util\FieldValueHandler;
12 use BitCode\BitForm\Core\Util\MailNotifier;
13 use BitCode\BitForm\Frontend\Form\FrontendFormManager;
14
15 final class IntegrationHandler
16 {
17 private static $_formID;
18 private static $_integrationModel;
19 private $_user_details;
20
21 /**
22 * Constructor of Integration Handler
23 *
24 * @param Integer $formID If Integration is accessible globally then
25 * $formID will be 0 and category app
26 * @param Array $user_details Details of user accessing data
27 * @return void
28 */
29 public function __construct($formID, $user_details = null)
30 {
31 static::$_formID = $formID;
32 static::$_integrationModel = new IntegrationModel();
33 $this->_user_details = $user_details;
34 }
35
36 public function getAIntegration($integrationID, $integrationCategory = null, $integrationType = null)
37 {
38 $conditions = [
39 'form_id' => static::$_formID,
40 'id' => $integrationID,
41 ];
42 if (!is_null($integrationType)) {
43 $conditions = array_merge($conditions, ['integration_type' => $integrationType]);
44 }
45 if (!is_null($integrationCategory)) {
46 $conditions = array_merge($conditions, ['category' => $integrationCategory]);
47 }
48 return static::$_integrationModel->get(
49 [
50 'id',
51 'integration_name',
52 'integration_type',
53 'integration_details',
54 'form_id',
55 ],
56 $conditions
57 );
58 }
59
60 public function getAllIntegration($integrationCategory = null, $integrationType = null, $status = null, $id = null)
61 {
62 $conditions = [
63 'form_id' => static::$_formID,
64 ];
65 if (!is_null($integrationType)) {
66 $conditions = array_merge($conditions, ['integration_type' => $integrationType]);
67 }
68
69 if (!is_null($integrationCategory)) {
70 $conditions = array_merge($conditions, ['category' => $integrationCategory]);
71 }
72 if (!is_null($status)) {
73 $conditions = array_merge($conditions, ['status' => 1]);
74 }
75 if (!is_null($id)) {
76 $conditions = array_merge($conditions, ['id' => $id]);
77 }
78 return static::$_integrationModel->get(
79 [
80 'id',
81 'form_id',
82 'integration_name',
83 'integration_type',
84 'integration_details',
85 'status',
86 ],
87 $conditions
88 );
89 }
90
91 public function getIntegrationWithoutFormId($integrationCategory = null, $integrationType = null, $status = null, $id = null)
92 {
93 $conditions = [];
94 if (!is_null($integrationType)) {
95 $conditions = array_merge($conditions, ['integration_type' => $integrationType]);
96 }
97
98 if (!is_null($integrationCategory)) {
99 $conditions = array_merge($conditions, ['category' => $integrationCategory]);
100 }
101 if (!is_null($status)) {
102 $conditions = array_merge($conditions, ['status' => 1]);
103 }
104 if (!is_null($id)) {
105 $conditions = array_merge($conditions, ['id' => $id]);
106 }
107 return static::$_integrationModel->get(
108 [
109 'id',
110 'form_id',
111 'integration_name',
112 'integration_type',
113 'integration_details',
114 'status',
115 ],
116 $conditions
117 );
118 }
119
120 public function saveIntegration($integrationName, $integrationType, $integrationDetails, $integrationCategory, $status = null)
121 {
122 if (null === $status) {
123 $status = 1;
124 }
125 return static::$_integrationModel->insert(
126 [
127 'integration_name' => $integrationName,
128 'integration_type' => $integrationType,
129 'integration_details' => $integrationDetails,
130 'category' => $integrationCategory,
131 'form_id' => static::$_formID,
132 'user_id' => $this->_user_details['id'],
133 'user_ip' => $this->_user_details['ip'],
134 'status' => $status,
135 'created_at' => $this->_user_details['time'],
136 'updated_at' => $this->_user_details['time'],
137 ]
138 );
139 }
140
141 public function updateIntegration($integrationID, $integrationName, $integrationType, $integrationDetails, $integrationCategory, $status = null)
142 {
143 if (null === $status) {
144 $status = 1;
145 }
146 return static::$_integrationModel->update(
147 [
148 'integration_name' => $integrationName,
149 'integration_type' => $integrationType,
150 'integration_details' => $integrationDetails,
151 'category' => $integrationCategory,
152 'form_id' => static::$_formID,
153 'user_id' => $this->_user_details['id'],
154 'user_ip' => $this->_user_details['ip'],
155 'status' => $status,
156 'updated_at' => $this->_user_details['time'],
157 ],
158 [
159 'id' => $integrationID,
160 ]
161 );
162 }
163
164 public function duplicateAllInAForm($oldFormId)
165 {
166 $integCols = ['integration_name', 'integration_type', 'integration_details', 'category', 'form_id', 'user_id', 'user_ip', 'status', 'created_at', 'updated_at'];
167 $integDupData = [
168 'integration_name',
169 'integration_type',
170 'integration_details',
171 'category',
172 static::$_formID,
173 $this->_user_details['id'],
174 $this->_user_details['ip'],
175 'status',
176 $this->_user_details['time'],
177 $this->_user_details['time'],
178 ];
179 return static::$_integrationModel->duplicate($integCols, $integDupData, ['form_id' => $oldFormId]);
180 }
181
182 public function deleteIntegration($integrationID)
183 {
184 return static::$_integrationModel->delete(
185 [
186 'id' => $integrationID,
187 'form_id' => static::$_formID,
188 ]
189 );
190 }
191
192 public static function replaceFieldWithValue($dataToReplaceField, $fieldValues)
193 {
194 if (empty($dataToReplaceField)) {
195 return false;
196 }
197 if (is_string($dataToReplaceField)) {
198 $dataToReplaceField = static::replaceFieldWithValueHelper($dataToReplaceField, $fieldValues);
199 } elseif (is_array($dataToReplaceField)) {
200 foreach ($dataToReplaceField as $field => $value) {
201 if (is_array($value) && 1 === count($value)) {
202 $dataToReplaceField[$field] = static::replaceFieldWithValueHelper($value[0], $fieldValues);
203 } elseif (is_array($value)) {
204 $dataToReplaceField[$field] = static::replaceFieldWithValue($value, $fieldValues);
205 } else {
206 $dataToReplaceField[$field] = static::replaceFieldWithValueHelper($value, $fieldValues);
207 }
208 }
209 }
210 return $dataToReplaceField;
211 }
212
213 private static function replaceFieldWithValueHelper($stringToReplaceField, $fieldValues)
214 {
215 if (empty($stringToReplaceField)) {
216 return $stringToReplaceField;
217 }
218 $fieldPattern = '/\${\w[^ ${}]*}/';
219 preg_match_all($fieldPattern, $stringToReplaceField, $matchedField);
220 $uniqueFieldsInStr = array_unique($matchedField[0]);
221
222 foreach ($uniqueFieldsInStr as $value) {
223 $fieldName = substr($value, 2, strlen($value) - 3);
224
225 $repeaterArr = explode('.', $fieldName);
226 if (isset($fieldValues[$fieldName])) {
227 $stringToReplaceField = is_string($fieldValues[$fieldName])
228 ? str_replace($value, $fieldValues[$fieldName], $stringToReplaceField)
229 : wp_json_encode($fieldValues[$fieldName]);
230 } elseif (2 === count($repeaterArr) && isset($fieldValues[$repeaterArr[0]])) {
231 $repeaterValues = [];
232 $repeaterFieldValues = $fieldValues[$repeaterArr[0]];
233 foreach ($repeaterFieldValues as $value) {
234 if (isset($value[$repeaterArr[1]])) {
235 $repeaterValues[] = $value[$repeaterArr[1]];
236 }
237 }
238
239 $stringToReplaceField = $repeaterValues;
240 } else {
241 $stringToReplaceField = FieldValueHandler::replaceSmartTagWithValue($value);
242 }
243 }
244 return $stringToReplaceField;
245 }
246
247 public static function updatedHiddenFieldValue($formID)
248 {
249 $hiddenFields = [];
250 $frontendFormManger = FrontendFormManager::getInstance($formID);
251
252 if ($frontendFormManger->isHoneypotActive()) {
253 $str = '_bitform' . '_' . $formID . '_' . time() . '_';
254 $honpotToken = Helpers::honeypotEncryptedToken($str);
255 $hiddenFields[] = [
256 'name' => 'b_h_t',
257 'value' => $honpotToken
258 ];
259 }
260 $csrfTokens = Helpers::csrfEecrypted();
261 $hiddenFields[] = [
262 'name' => 't_identity',
263 'value' => $csrfTokens['t_identity'],
264 ];
265 $hiddenFields[] = [
266 'name' => 'csrf',
267 'value' => $csrfTokens['csrf']
268 ];
269 return $hiddenFields;
270 }
271
272 public static function maybeSetCronForIntegration($workFlowReturnedData, $opType, $isFormRequest = true)
273 {
274 $responseData = [];
275 $entryId = $workFlowReturnedData['triggerData']['entryID'];
276 $responseData['entry_id'] = $entryId;
277 if (isset($workFlowReturnedData['message'])) {
278 $formID = $workFlowReturnedData['triggerData']['formID'];
279 $responseData['message'] = $workFlowReturnedData['message'];
280 $responseData['hidden_fields'] = self::updatedHiddenFieldValue($formID);
281 $responseData['msg_id'] = isset($workFlowReturnedData['msg_id']) ? $workFlowReturnedData['msg_id'] : 0;
282 if (isset($workFlowReturnedData['msg_duration'])) {
283 $responseData['msg_duration'] = $workFlowReturnedData['msg_duration'];
284 }
285 }
286 if (isset($workFlowReturnedData['redirectPage'])) {
287 $responseData['redirectPage'] = $workFlowReturnedData['redirectPage'];
288 }
289 if ('update' === $opType && isset($workFlowReturnedData['updatedData'])) {
290 $responseData['updatedData'] = $workFlowReturnedData['updatedData'];
291 }
292 if (isset($workFlowReturnedData['new_nonce'])) {
293 $responseData['new_nonce'] = $workFlowReturnedData['new_nonce'];
294 }
295 if (!isset($workFlowReturnedData['triggerData'])) {
296 return $responseData;
297 }
298
299 $triggerData = $workFlowReturnedData['triggerData'];
300
301 $trnasientData = get_transient("bitform_trigger_transient_{$entryId}");
302 $trnasientData = is_string($trnasientData) ? json_decode($trnasientData) : $trnasientData;
303
304 if (!empty($trnasientData['fields'])) {
305 $fieldData = isset($workFlowReturnedData['fields']) ? $workFlowReturnedData['fields'] : $workFlowReturnedData['updatedData'];
306 $workFlowReturnedData['fields'] = array_merge($fieldData, $trnasientData['fields']);
307 }
308
309 if (function_exists('fastcgi_finish_request') || !wp_doing_ajax()) {
310 if (!headers_sent()) {
311 header('Connection: close');
312 $contentType = wp_doing_ajax() || defined('REST_REQUEST') ? 'application/json' : 'text/html';
313 header('Content-Type: ' . $contentType . '; charset=' . get_option('blog_charset'));
314 status_header(200);
315 if (!$isFormRequest) {
316 $response = [
317 'status' => 200,
318 'code' => 4000,
319 'message' => 'Data Added Successfully!!',
320 'success' => true
321 ];
322 } else {
323 $response = [
324 'success' => true,
325 'data' => $responseData,
326 ];
327 }
328 }
329 ob_start();
330 // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $response contains wp_json_encode() output intended for JSON context and $workFlowReturnedData['message'] is escaped internally and safe to output.
331 echo wp_doing_ajax() || defined('REST_REQUEST') ? wp_json_encode($response) : $workFlowReturnedData['message'];
332 ob_end_flush();
333 flush();
334 session_write_close();
335
336 if (isset($workFlowReturnedData['integrationRun']) && !$workFlowReturnedData['integrationRun']) {
337 $entryModel = new FormEntryModel();
338 $updatedStatus = $entryModel->update(
339 [
340 'status' => 2,
341 ],
342 [
343 'form_id' => $triggerData['formID'],
344 'id' => $triggerData['entryID'],
345 ]
346 );
347
348 $triggerData['fields'] = $workFlowReturnedData['fields'];
349 if (!is_wp_error($updatedStatus)) {
350 if ($workFlowReturnedData['dflt_template']) {
351 // $triggerData['fields'] = $workFlowReturnedData['fields'];
352 do_action('bf_double_optin_confirmation', $workFlowReturnedData['integrationDetails'], $triggerData); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
353 } elseif (isset($triggerData['dblOptin'])) {
354 foreach ($triggerData['dblOptin'] as $value) {
355 MailNotifier::notify($value, $triggerData['formID'], $triggerData['fields'], $triggerData['entryID'], true, $triggerData['logID']);
356 }
357 }
358 }
359 if (function_exists('fastcgi_finish_request')) {
360 fastcgi_finish_request();
361 }
362
363 if (defined('REST_REQUEST') || wp_doing_ajax()) {
364 die;
365 }
366 return $workFlowReturnedData;
367 }
368
369 if (isset($triggerData['mail']) && !empty($triggerData['mail'])) {
370 $formManager = new AdminFormManager($triggerData['formID']);
371 $formContent = $formManager->getFormContent();
372 $submitted_fields = $formContent->fields;
373 $fieldValueForMail = FieldValueHandler::formatFieldValueForMail($submitted_fields, $workFlowReturnedData['fields']);
374 foreach ($triggerData['mail'] as $value) {
375 MailNotifier::notify($value, $triggerData['formID'], $fieldValueForMail, $triggerData['entryID'], false, $triggerData['logID']);
376 }
377 }
378 do_action('bitforms_exec_integrations', $triggerData['integrations'], $workFlowReturnedData['fields'], $triggerData['formID'], $triggerData['entryID'], $triggerData['logID']);
379
380 if (function_exists('fastcgi_finish_request')) {
381 fastcgi_finish_request();
382 }
383
384 if (defined('REST_REQUEST') || wp_doing_ajax()) {
385 die;
386 }
387 return $workFlowReturnedData;
388 }
389
390 $entryID = $triggerData['entryID'];
391 if (isset($workFlowReturnedData['cron']) && $workFlowReturnedData['cron'] && !isset($triggerData['mail']) && isset($workFlowReturnedData['integrationRun']) && $workFlowReturnedData['integrationRun']) {
392 $eventScheuled = wp_schedule_single_event(time(), 'bitforms_exec_integrations', [$triggerData['integrations'], $workFlowReturnedData['fields'], $triggerData['formID'], $triggerData['entryID'], $triggerData['logID']]);
393 $scheduleTime = wp_next_scheduled('bitforms_exec_integrations', [$triggerData['integrations'], $workFlowReturnedData['fields'], $triggerData['formID'], $triggerData['entryID'], $triggerData['logID']]);
394 $responseData['cron'] = get_site_url(null, "/wp-cron.php?doing_wp_cron&{$scheduleTime}");
395 } elseif (!empty($triggerData['integrations']) || !empty($triggerData['mail']) || isset($workFlowReturnedData['integrationRun']) && !$workFlowReturnedData['integrationRun']) {
396 $triggerData['fields'] = $workFlowReturnedData['fields'];
397 if (!$workFlowReturnedData['integrationRun'] && isset($workFlowReturnedData['integrationDetails'])) {
398 $triggerData['dbl_opt_donf'] = $workFlowReturnedData['integrationDetails'];
399 $triggerData['dbl_opt_dflt_template'] = $workFlowReturnedData['dflt_template'];
400 $triggerData['integrationRun'] = $workFlowReturnedData['integrationRun'];
401 }
402
403 // Generate one-time trigger token for security
404 $triggerToken = wp_hash($triggerData['entryID'] . $triggerData['logID'] . time() . wp_rand(), 'nonce');
405 $triggerData['trigger_token'] = $triggerToken;
406
407 set_transient("bitform_trigger_transient_{$entryID}", $triggerData, HOUR_IN_SECONDS);
408 $entryLog = new FormEntryLogModel();
409 $queueuEntry = $entryLog->log_history_insert(
410 [
411 'log_id' => $triggerData['logID'],
412 'integration_id' => 0,
413 'api_type' => wp_json_encode(['type' => 'trigger', 'type_name' => 'Workflow', 'on' => $opType]),
414 'response_type' => 'queued',
415 'response_obj' => wp_json_encode(['status' => 'queued']),
416 'created_at' => current_time('mysql'),
417 ]
418 );
419 $responseData['cronNotOk'] = [
420 $triggerData['entryID'],
421 $triggerData['logID'],
422 $queueuEntry,
423 $triggerToken, // Add one-time token as 4th element
424 ];
425 }
426 return $responseData;
427 }
428
429 public static function repeaterFieldValueFormatter($fieldValues)
430 {
431 $formattedArray = [];
432
433 foreach ($fieldValues as $key => $value) {
434 if (is_array($value)) {
435 foreach ($value as $index => $v) {
436 if (is_array($v)) {
437 foreach ($v as $k1 => $v1) {
438 $formattedArray[$k1][] = $v1;
439 }
440 } else {
441 $formattedArray[$key][] = $v;
442 }
443 }
444 } else {
445 $formattedArray[$key] = $value;
446 }
447 }
448
449 return $formattedArray;
450 }
451
452 /**
453 *
454 * @param mixed $fieldValues
455 * @param mixed $returnRepeaterValue default is array
456 * @return array and repeater field value as array or string
457 */
458 public static function formattedRepeaterValue($fieldValues, $returnRepeaterValue = '')
459 {
460 // get the repeater field and store it in an array
461 $repeaterField = [];
462 foreach ($fieldValues as $key => $value) {
463 if (!preg_match('/\./', $key)) {
464 continue;
465 }
466 $repeaterField[] = $key;
467 }
468
469 // put the value of the child key to the parent repeater field\
470 foreach ($repeaterField as $key) {
471 list($parentKey, $childKey) = explode('.', $key);
472 $repeatValues = isset($fieldValues[$parentKey]) ? $fieldValues[$parentKey] : $key;
473
474 if (!is_array($repeatValues)) {
475 $fieldValues[$key] = $fieldValues[$childKey];
476 continue;
477 }
478
479 foreach ($repeatValues as $value) {
480 if (isset($value[$childKey])) {
481 if (!isset($fieldValues[$key]) || !is_array($fieldValues[$key])) {
482 $fieldValues[$key] = [];
483 }
484 if (!empty($value[$childKey])) {
485 $fieldValues[$key][] = $value[$childKey];
486 }
487 }
488 }
489 }
490
491 // convert the array to string repeater field value
492 if ('string' === $returnRepeaterValue) {
493 $form = new FormManager(static::$_formID);
494 foreach ($repeaterField as $key) {
495 if (isset($fieldValues[$key]) && is_array($fieldValues[$key])) {
496 $fieldValues[$key] = implode(', ', self::flattenArray($fieldValues[$key]));
497 }
498 }
499
500 foreach ($fieldValues as $key=>$value) {
501 if (!$form->isRepeaterField($key)) {
502 continue;
503 }
504 $repeaterValues = $fieldValues[$key];
505
506 $newFieldValues = self::constructRepeaterValue($repeaterValues, static::$_formID);
507
508 $fieldValues[$key] = json_encode(array_values($newFieldValues), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
509 }
510 }
511
512 return $fieldValues;
513 }
514
515 private static function flattenArray($array)
516 {
517 return array_map(function ($val) {
518 if (is_array($val)) {
519 return count($val) > 1 ? ('[' . implode(', ') . ']') : implode(', ', $val);
520 } else {
521 return $val;
522 }
523 }, $array);
524 }
525
526 /**
527 * Replace file field value with web url
528 * @param mixed $fieldValues
529 * @param number $formId
530 * @param number $entryId
531 * @return mixed $fieldValues
532 */
533 public static function replaceFileWithUrl($fieldValues, $formId, $entryId)
534 {
535 if (!$formId || !$entryId) {
536 return $fieldValues;
537 }
538 $form = new FormManager($formId);
539 $formFields = $form->getFields();
540 $webPath = Helpers::getWebPathWithEncryptedEntryId($formId, $entryId);
541
542 $fldsIncludeFile = ['file-up', 'advanced-file-up', 'repeater', 'signature'];
543 foreach ($fieldValues as $key =>$value) {
544 $fldTyp = $formFields[$key]['type'] ?? null;
545 if (!in_array($fldTyp, $fldsIncludeFile)) {
546 continue;
547 }
548
549 if ('repeater' === $fldTyp) {
550 foreach ($value as $rIndex => $rValue) {
551 foreach ($rValue as $subKey=>$subValue) {
552 if (!in_array($formFields[$subKey]['type'], $fldsIncludeFile)) {
553 continue;
554 }
555 // for file fields inside repeater
556 if (is_array($subValue)) {
557 foreach ($subValue as $fileIndex=>$fileValue) {
558 $fieldValues[$key][$rIndex][$subKey][$fileIndex] = $webPath . '/' . $fileValue;
559 }
560 } else {
561 // for signature field inside repeater;
562 $fieldValues[$key][$rIndex][$subKey] = $webPath . '/' . $subValue;
563 }
564 }
565 }
566 }
567
568 if ('file-up' === $fldTyp || 'advanced-file-up' === $fldTyp || 'signature' === $fldTyp) {
569 if (is_array($value)) {
570 foreach ($value as $fldIndex=>$fldValue) {
571 $fieldValues[$key][$fldIndex] = $webPath . '/' . $fldValue;
572 }
573 } else {
574 $fieldValues[$key] = $webPath . '/' . $value;
575 }
576 }
577 }
578
579 return $fieldValues;
580 }
581
582 public static function assignRepeaterFieldValue($fieldValues, $formId)
583 {
584 if (!$formId) {
585 return $fieldValues;
586 }
587 $form = new FormManager($formId);
588 $formFields = $form->getFields();
589
590 foreach ($fieldValues as $key=>$value) {
591 if (!$form->isRepeaterField($key)) {
592 continue;
593 }
594
595 if ('repeater' === $formFields[$key]['type']) {
596 if (is_array($value)) {
597 foreach ($value as $rIndex=>$rValue) {
598 foreach ($rValue as $subKey =>$subValue) {
599 $fieldValues[$subKey] = $subValue;
600 }
601 }
602 }
603 }
604 }
605
606 return $fieldValues;
607 }
608
609 public static function constructRepeaterValue($repeaterValues, $formId)
610 {
611 if (!$formId) {
612 return $repeaterValues;
613 }
614 $form = new FormManager($formId);
615 $formFields = $form->getFields();
616 $newRptrValue = [];
617 foreach ($repeaterValues as $key=>$value) {
618 $newRepeatedValue = [];
619 foreach ($value as $rKey =>$rValue) {
620 $fldLbl = isset($formFields[$rKey]) ? $formFields[$rKey]['label'] : $rKey;
621 $newRepeatedValue[$fldLbl] = $rValue;
622 }
623 $newRptrValue[$key] = $newRepeatedValue;
624 }
625
626 return $newRptrValue;
627 }
628 }
629