Bootstrap.php 0000644 00000011022 15073231424 0007227 0 ustar 00 exist()) {
$migratorLinks[] = [
'name' => 'Caldera Forms',
'key' => 'caldera',
];
}
if ((new NinjaFormsMigrator())->exist()) {
$migratorLinks[] = [
'name' => 'Ninja Forms',
'key' => 'ninja_forms',
];
}
if ((new GravityFormsMigrator())->exist()) {
$migratorLinks[] = [
'name' => 'Gravity Forms',
'key' => 'gravityform',
];
}
if ((new WpFormsMigrator())->exist()) {
$migratorLinks[] = [
'name' => 'WPForms',
'key' => 'wpforms',
];
}
if ((new ContactForm7Migrator())->exist()) {
$migratorLinks[] = [
'name' => 'Contact Form 7',
'key' => 'contactform7',
];
}
return $migratorLinks;
}
public function setImporterType()
{
$formType = sanitize_text_field(wpFluentForm('request')->get('form_type'));
switch ($formType) {
case 'caldera':
$this->importer = new CalderaMigrator();
break;
case 'ninja_forms':
$this->importer = new NinjaFormsMigrator();
break;
case 'gravityform':
$this->importer = new GravityFormsMigrator();
break;
case 'wpforms':
$this->importer = new WpFormsMigrator();
break;
case 'contactform7':
$this->importer = new ContactForm7Migrator();
break;
default:
wp_send_json([
'message' => __('Unsupported Form Type!'),
'success' => false,
]);
}
}
public function getMigratorData()
{
\FluentForm\App\Modules\Acl\Acl::verify(['fluentform_settings_manager', 'fluentform_forms_manager']);
wp_send_json([
'status' => true,
'migrator_data' => $this->availableMigrations()
], 200);
}
public function importForms()
{
\FluentForm\App\Modules\Acl\Acl::verify(['fluentform_settings_manager', 'fluentform_forms_manager']);
$formIds = wpFluentForm('request')->get('form_ids');
$formIds = array_map('sanitize_text_field', $formIds);
$this->setImporterType();
$this->importer->import_forms($formIds);
}
public function importEntries()
{
\FluentForm\App\Modules\Acl\Acl::verify(['fluentform_settings_manager', 'fluentform_forms_manager']);
$fluentFormId = intval(wpFluentForm('request')->get('imported_fluent_form_id'));
$importFormId = sanitize_text_field(wpFluentForm('request')->get('source_form_id'));
$this->setImporterType();
$this->importer->insertEntries($fluentFormId, $importFormId);
}
public function hasOtherForms()
{
\FluentForm\App\Modules\Acl\Acl::verify(['fluentform_settings_manager', 'fluentform_forms_manager']);
$migrationData = $this->availableMigrations();
if (is_array($migrationData) && !empty($migrationData)) {
return true;
}
return false;
}
public function getFormsByKey()
{
\FluentForm\App\Modules\Acl\Acl::verify(['fluentform_settings_manager', 'fluentform_forms_manager']);
$this->setImporterType();
$forms = $this->importer->getFormsFormatted();
wp_send_json([
'forms' => $forms,
'success' => true,
]);
}
}
Classes/GravityFormsMigrator.php 0000644 00000111532 15073231424 0013017 0 ustar 00 key = 'gravityform';
$this->title = 'Gravity Forms';
$this->shortcode = 'gravity_form';
$this->hasStep = false;
}
public function exist()
{
return class_exists('GFForms');
}
/**
* @param $form
* @return array
*/
public function getFields($form)
{
$fluentFields = [];
$fields = $form['fields'];
foreach ($fields as $name => $field) {
$field = (array)$field;
list($type, $args) = $this->formatFieldData($field);
if ($value = $this->getFluentClassicField($type, $args)) {
$fluentFields[$field['id']] = $value;
} else {
$this->unSupportFields[] = ArrayHelper::get($field, 'label');
}
}
$submitBtn = $this->getSubmitBttn([
'uniqElKey' => time(),
'class' => '',
'label' => ArrayHelper::get($form, 'button.text', 'Submit'),
'type' => ArrayHelper::get($form, 'button.type') == 'text' ? 'default' : 'image',
'img_url' => ArrayHelper::get($form, 'button.imageUrl'),
]);
$returnData = [
'fields' => $this->getContainer($fields, $fluentFields),
'submitButton' => $submitBtn
];
if ($this->hasStep && defined('FLUENTFORMPRO')) {
$returnData['stepsWrapper'] = $this->getStepWrapper();
}
return $returnData;
}
private function formatFieldData(array $field)
{
$args = [
'uniqElKey' => $field['id'],
'index' => $field['id'],
'required' => $field['isRequired'],
'label' => $field['label'],
'label_placement' => $this->getLabelPlacement($field),
'admin_field_label' => ArrayHelper::get($field, 'adminLabel'),
'name' => $this->getInputName($field),
'placeholder' => ArrayHelper::get($field, 'placeholder'),
'class' => $field['cssClass'],
'value' => ArrayHelper::get($field, 'defaultValue'),
'help_message' => ArrayHelper::get($field, 'description'),
];
$type = ArrayHelper::get($this->fieldTypes(), $field['type'], '');
switch ($type) {
case 'input_name':
$args['input_name_args'] = $field['inputs'];
$args['input_name_args']['first_name']['name'] = $this->getInputName($field['inputs'][1]);
$args['input_name_args']['middle_name']['name'] = $this->getInputName($field['inputs'][2]);
$args['input_name_args']['last_name']['name'] = $this->getInputName($field['inputs'][3]);
$args['input_name_args']['first_name']['label'] = ArrayHelper::get($field['inputs'][1], 'label');
$args['input_name_args']['middle_name']['label'] = ArrayHelper::get($field['inputs'][2], 'label');
$args['input_name_args']['last_name']['label'] = ArrayHelper::get($field['inputs'][3], 'label');
$args['input_name_args']['first_name']['visible'] = ArrayHelper::get($field, 'inputs.1.isHidden', true);
$args['input_name_args']['middle_name']['visible'] = ArrayHelper::get($field, 'inputs.2.isHidden',
true);
$args['input_name_args']['last_name']['visible'] = ArrayHelper::get($field, 'inputs.3.isHidden', true);
break;
case 'input_textarea':
$args['maxlength'] = $field['maxLength'];
break;
case 'input_text':
$args['maxlength'] = $field['maxLength'];
$args['is_unique'] = ArrayHelper::isTrue($field, 'noDuplicates');
if (ArrayHelper::isTrue($field, 'inputMask')) {
$type = 'input_mask';
$args['temp_mask'] = 'custom';
$args['mask'] = $field['inputMaskValue'];
}
if (ArrayHelper::isTrue($field, 'enablePasswordInput')) {
$type = 'input_password';
}
break;
case 'address':
$args['address_args'] = $this->getAddressArgs($field);
break;
case 'select':
case 'input_radio':
$optionData = $this->getOptions(ArrayHelper::get($field, 'choices'));
$args['options'] = ArrayHelper::get($optionData, 'options');
$args['value'] = ArrayHelper::get($optionData, 'selectedOption.0');
case 'multi_select':
case 'input_checkbox':
$optionData = $this->getOptions(ArrayHelper::get($field, 'choices'));
$args['options'] = ArrayHelper::get($optionData, 'options');
$args['value'] = ArrayHelper::get($optionData, 'selectedOption');
break;
case 'input_date':
if ($field['type'] == 'time') {
$args['format'] = 'H:i';
$args['is_time_enabled'] = true;
}
break;
case 'input_number':
$args['min'] = $field['rangeMin'];
$args['max'] = $field['rangeMax'];
break;
case 'repeater_field':
$repeaterFields = ArrayHelper::get($field, 'choices', []);
$args['fields'] = $this->getRepeaterFields($repeaterFields, $field['label']);;
case 'input_file':
$args['allowed_file_types'] = $this->getFileTypes($field, 'allowedExtensions');
$args['max_size_unit'] = 'MB';
$args['max_file_size'] = $this->getFileSize($field);;
$args['max_file_count'] = ArrayHelper::isTrue($field,
'multipleFiles') ? $field['maxFiles'] : 1;
$args['upload_btn_text'] = 'File Upload';
break;
case 'custom_html':
$args['html_codes'] = $field['content'];
break;
case 'section_break':
$args['section_break_desc'] = $field['description'];
break;
case 'terms_and_condition':
$args['tnc_html'] = $field['description'];
break;
case 'form_step':
$this->hasStep = true;
$args['next_btn'] = $field['nextButton'];
$args['next_btn']['type'] = $field['nextButton']['type'] == 'text' ? 'default' : 'img';
$args['next_btn']['img_url'] = $field['nextButton']['imageUrl'];
$args['prev_btn'] = $field['previousButton'];
$args['prev_btn']['type'] = $field['previousButton']['type'] == 'text' ? 'default' : 'img';
$args['prev_btn']['img_url'] = $field['previousButton']['imageUrl'];
break;
}
return array($type, $args);
}
private function getInputName($field)
{
return str_replace('-', '_', sanitize_title($field['label'] . '-' . $field['id']));
}
private function getLabelPlacement($field)
{
if ($field['labelPlacement'] == 'hidden_label') {
return 'hide_label';
}
return 'top';
}
/**
* @param $field
* @return filesize in MB
*/
private function getFileSize($field)
{
$fileSizeByte = ArrayHelper::get($field, 'maxFileSize', 10);
if (empty($fileSizeByte)) {
$fileSizeByte = 1;
}
$fileSizeMB = ceil($fileSizeByte * 1048576); // 1MB = 1048576 Bytes
return $fileSizeMB;
}
/**
* @return array
*/
public function fieldTypes()
{
$fieldTypes = [
'email' => 'email',
'text' => 'input_text',
'name' => 'input_name',
'hidden' => 'input_hidden',
'textarea' => 'input_textarea',
'website' => 'input_url',
'phone' => 'phone',
'select' => 'select',
'list' => 'repeater_field',
'multiselect' => 'multi_select',
'checkbox' => 'input_checkbox',
'radio' => 'input_radio',
'date' => 'input_date',
'time' => 'input_date',
'number' => 'input_number',
'fileupload' => 'input_file',
'consent' => 'terms_and_condition',
'captcha' => 'reCaptcha',
'html' => 'custom_html',
'section' => 'section_break',
'page' => 'form_step',
'address' => 'address',
];
//todo pro fields remove
return $fieldTypes;
}
/**
* @param array $field
* @return array[]
*/
private function getAddressArgs(array $field)
{
$required = ArrayHelper::isTrue($field, 'isRequired');
return [
'address_line_1' => [
'name' => $this->getInputName($field['inputs'][0]),
'label' => $field['inputs'][0]['label'],
'visible' => ArrayHelper::get($field, 'inputs.0.isHidden', true),
'required' => $required,
],
'address_line_2' => [
'name' => $this->getInputName($field['inputs'][1]),
'label' => $field['inputs'][1]['label'],
'visible' => ArrayHelper::get($field, 'inputs.1.isHidden', true),
'required' => $required,
],
'city' => [
'name' => $this->getInputName($field['inputs'][2]),
'label' => $field['inputs'][2]['label'],
'visible' => ArrayHelper::get($field, 'inputs.2.isHidden', true),
'required' => $required,
],
'state' => [
'name' => $this->getInputName($field['inputs'][3]),
'label' => $field['inputs'][3]['label'],
'visible' => ArrayHelper::get($field, 'inputs.3.isHidden', true),
'required' => $required,
],
'zip' => [
'name' => $this->getInputName($field['inputs'][4]),
'label' => $field['inputs'][4]['label'],
'visible' => ArrayHelper::get($field, 'inputs.4.isHidden', true),
'required' => $required,
],
'country' => [
'name' => $this->getInputName($field['inputs'][5]),
'label' => $field['inputs'][5]['label'],
'visible' => ArrayHelper::get($field, 'inputs.5.isHidden', true),
'required' => $required,
],
];
}
/**
* @param $options
* @return array
*/
public function getOptions($options = [])
{
$formattedOptions = [];
$selectedOption = [];
foreach ($options as $key => $option) {
$arr = [
'label' => ArrayHelper::get($option, 'text', 'Item -' . $key),
'value' => ArrayHelper::get($option, 'value'),
'id' => ArrayHelper::get($option, $key)
];
if (ArrayHelper::isTrue($option, 'isSelected')) {
$selectedOption[] = ArrayHelper::get($option, 'value', '');
}
$formattedOptions[] = $arr;
}
return ['options' => $formattedOptions, 'selectedOption' => $selectedOption];
}
/**
* @param $repeaterFields
* @param $label
* @return array
*/
protected function getRepeaterFields($repeaterFields, $label)
{
$arr = [];
if (empty($repeaterFields)) {
$arr[] = [
'element' => 'input_text',
'attributes' => array(
'type' => 'text',
'value' => '',
'placeholder' => '',
),
'settings' => array(
'label' => $label,
'help_message' => '',
'validation_rules' => array(
'required' => array(
'value' => false,
'message' => __('This field is required', 'fluentform'),
),
)
)
];
} else {
foreach ($repeaterFields as $serial => $repeaterField) {
$arr[] = [
'element' => 'input_text',
'attributes' => array(
'type' => 'text',
'value' => '',
'placeholder' => '',
),
'settings' => array(
'label' => ArrayHelper::get($repeaterField, 'label', ''),
'help_message' => '',
'validation_rules' => array(
'required' => array(
'value' => false,
'message' => __('This field is required', 'fluentform'),
),
)
)
];
}
}
return $arr;
}
private function getContainer($fields, $fluentFields)
{
$layoutGroupIds = array_column($fields, 'layoutGroupId');
$cols = array_count_values($layoutGroupIds); // if inputs has more then one duplicate layoutGroupIds then it has container
if (intval($cols) < 2) {
return $fluentFields;
}
$final = [];
//get fields array for inserting into containers
$containers = self::getLayout($fields);
//set fields array map for inserting into containers
foreach ($containers as $index => $fields) {
$final[$index][] = array_map(function ($id) use ($fluentFields) {
if (isset($fluentFields[$id])) {
return $fluentFields[$id];
}
}, $fields);
}
$final = self::arrayFlat($final);
$withContainer = [];
foreach ($final as $row => $columns) {
$colsCount = count($columns);
$containerConfig = [];
//with container
if ($colsCount != 1) {
$fields = [];
foreach ($columns as $col) {
$fields[]['fields'] = [$col];
}
$containerConfig[] = [
'index' => $row,
'element' => 'container',
"attributes" => [],
'settings' => [
'container_class',
'conditional_logics'
],
'editor_options' => [
'title' => $colsCount . ' Column Container',
'icon_class' => 'ff-edit-column-' . $colsCount
],
'columns' => $fields,
'uniqElKey' => 'col' . '_' . md5(uniqid(mt_rand(), true))
];
} else {
//without container
$containerConfig = $columns;
}
$withContainer[] = $containerConfig;
}
return (array_filter(self::arrayFlat($withContainer)));
}
protected static function getLayout($fields, $id = '')
{
$layoutGroupIds = array_column($fields, 'layoutGroupId');
$rows = array_count_values($layoutGroupIds);
$layout = [];
foreach ($rows as $key => $value) {
$layout[] = self::getInputIdsFromLayoutGrp($key, $fields);
}
return $layout;
}
public static function getInputIdsFromLayoutGrp($id, $array)
{
$keys = [];
foreach ($array as $key => $val) {
if ($val['layoutGroupId'] === $id) {
$keys[] = $val['id'];
}
}
return $keys;
}
/**
* @param null $array
* @param int $depth
* @return array
*/
public static function arrayFlat($array = null, $depth = 1)
{
$result = [];
if (!is_array($array)) {
$array = func_get_args();
}
foreach ($array as $key => $value) {
if (is_array($value) && $depth) {
$result = array_merge($result, self::arrayFlat($value, $depth - 1));
} else {
$result = array_merge($result, [$key => $value]);
}
}
return $result;
}
/**
* @return array
*/
private function getStepWrapper()
{
return [
'stepStart' => [
'element' => 'step_start',
'attributes' => [
'id' => '',
'class' => '',
],
'settings' => [
'progress_indicator' => 'progress-bar',
'step_titles' => [],
'disable_auto_focus' => 'no',
'enable_auto_slider' => 'no',
'enable_step_data_persistency' => 'no',
'enable_step_page_resume' => 'no',
],
'editor_options' => [
'title' => 'Start Paging'
],
],
'stepEnd' => [
'element' => 'step_end',
'attributes' => [
'id' => '',
'class' => '',
],
'settings' => [
'prev_btn' => [
'type' => 'default',
'text' => 'Previous',
'img_url' => ''
]
],
'editor_options' => [
'title' => 'End Paging'
],
]
];
}
/**
* @param $form
* @return array default parsed form metas
* @throws \Exception
*/
public function getFormMetas($form)
{
$formObject = new Form(wpFluentForm());
$defaults = $formObject->getFormsDefaultSettings();
$confirmationsFormatted = $this->getConfirmations($form, $defaults['confirmation']);
$defaultConfirmation = array_shift($confirmationsFormatted);
$notifications = $this->getNotifications($form);
$defaults['restrictions']['requireLogin']['enabled'] = ArrayHelper::isTrue($form, 'requireLogin');
$defaults['restrictions']['requireLogin']['requireLoginMsg'] = ArrayHelper::isTrue($form,
'requireLoginMessage');
$defaults['restrictions']['limitNumberOfEntries']['enabled'] = ArrayHelper::isTrue($form, 'limitEntries');
$defaults['restrictions']['limitNumberOfEntries']['numberOfEntries'] = ArrayHelper::isTrue($form,
'limitEntriesCount');
$defaults['restrictions']['limitNumberOfEntries']['period'] = ArrayHelper::isTrue($form, 'limitEntriesPeriod');
$defaults['restrictions']['limitNumberOfEntries']['limitReachedMsg'] = ArrayHelper::isTrue($form,
'limitEntriesMessage');
$defaults['restrictions']['scheduleForm']['enabled'] = ArrayHelper::isTrue($form, 'scheduleForm');
$defaults['restrictions']['scheduleForm']['start'] = ArrayHelper::isTrue($form, 'scheduleStart');
$defaults['restrictions']['scheduleForm']['end'] = ArrayHelper::isTrue($form, 'scheduleEnd');
$defaults['restrictions']['scheduleForm']['pendingMsg'] = ArrayHelper::isTrue($form, 'schedulePendingMessage');
$defaults['restrictions']['scheduleForm']['expiredMsg'] = ArrayHelper::isTrue($form, 'scheduleMessage');
$advancedValidation = [
'status' => false,
'type' => 'all',
'conditions' => [
[
'field' => '',
'operator' => '=',
'value' => ''
]
],
'error_message' => '',
'validation_type' => 'fail_on_condition_met'
];
return [
'formSettings' => [
'confirmation' => $defaultConfirmation,
'restrictions' => $defaults['restrictions'],
'layout' => $defaults['layout'],
],
'advancedValidationSettings' => $advancedValidation,
'delete_entry_on_submission' => 'no',
'confirmations' => $confirmationsFormatted,
'notifications' => $notifications
];
}
private function getNotifications($form)
{
$notificationsFormatted = [];
foreach (ArrayHelper::get($form, 'notifications', []) as $notification) {
$fieldType = ArrayHelper::get($notification, 'toType', 'email');
$sendTo = [
'type' => $fieldType,
'email' => '',
'field' => '',
'routing' => [],
];
if ('field' == $fieldType) {
$sendTo['field'] = $this->getFormFieldName(ArrayHelper::get($notification, 'to', ''), $form);
} elseif('routing' == $fieldType) {
foreach (ArrayHelper::get($notification, 'routing', []) as $route) {
$fieldName = $this->getFormFieldName(ArrayHelper::get($route, 'fieldId'), $form);
$routeEmail = ArrayHelper::get($route, 'email');
if (!$fieldName || !$routeEmail) {
continue;
}
if ($operator = $this->getResolveOperator(ArrayHelper::get($route, 'operator', ''))) {
$sendTo['routing'][] = [
'field' => $fieldName,
'operator' => $operator,
'input_value' => $routeEmail,
'value' => ArrayHelper::get($route, 'value', '')
];
}
}
} else {
$sendTo['email'] = $this->getResolveShortcodes(ArrayHelper::get($notification, 'to', ''), $form);
}
$message = $this->getResolveShortcodes(ArrayHelper::get($notification, 'message', ''), $form);
$replyTo = $this->getResolveShortcodes(ArrayHelper::get($notification, 'replyTo', ''), $form);
$notificationsFormatted[] = [
'sendTo' => $sendTo,
'enabled' => ArrayHelper::get($notification, 'isActive', true),
'name' => ArrayHelper::get($notification, 'name', 'Admin Notification'),
'subject' => $this->getResolveShortcodes(ArrayHelper::get($notification, 'subject', 'Notification'), $form),
'to' => $sendTo['email'],
'replyTo' => $replyTo ?: '{wp.admin_email}',
'message' => str_replace("\n", "
", $message),
'fromName' => $this->getResolveShortcodes(ArrayHelper::get($notification, 'fromName', ''), $form),
'fromEmail' => $this->getResolveShortcodes(ArrayHelper::get($notification, 'from', ''), $form),
'bcc' => $this->getResolveShortcodes(ArrayHelper::get($notification, 'bcc', ''), $form),
'conditionals' => $this->getConditionals($notification,'notification', $form)
];
}
return $notificationsFormatted;
}
private function getConditionals($notification, $key, $form)
{
$conditionals = ArrayHelper::get($notification, 'conditionalLogic', []);
$conditions = [];
if (!$conditionals) {
$conditionals = ArrayHelper::get($notification, $key.'_conditional_logic_object', []);
}
$type = 'any';
if ($conditionals) {
$type = ArrayHelper::get($conditionals, 'logicType', 'any');
foreach (ArrayHelper::get($conditionals, 'rules', []) as $rule) {
$fieldName = $this->getFormFieldName(ArrayHelper::get($rule, 'fieldId'), $form);
if (!$fieldName) {
continue;
}
if ($operator = $this->getResolveOperator(ArrayHelper::get($rule, 'operator', ''))) {
$conditions[] = [
'field' => $fieldName,
'operator' => $operator,
'value' => ArrayHelper::get($rule, 'value', '')
];
}
}
}
return [
"status" => ArrayHelper::isTrue($notification, $key . '_conditional_logic'),
"type" => $type,
'conditions' => $conditions
];
}
private function getConfirmations($form, $defaultValues)
{
$confirmationsFormatted = [];
foreach (ArrayHelper::get($form, 'confirmations', []) as $confirmation) {
$type = ArrayHelper::get($confirmation, 'type');
$queryString = "";
if ($type == 'redirect') {
$redirectTo = 'customUrl';
$queryString = $this->getResolveShortcodes(ArrayHelper::get($confirmation, 'queryString', ''), $form);
} elseif ($type == 'page') {
$queryString = $this->getResolveShortcodes(ArrayHelper::get($confirmation, 'queryString', ''), $form);
$redirectTo = 'customPage';
} else {
$redirectTo = 'samePage';
}
$format = [
'name' => ArrayHelper::get($confirmation, 'name', 'Confirmation'),
'messageToShow' => str_replace("\n", "
", $this->getResolveShortcodes(ArrayHelper::get($confirmation, 'message', ''), $form)),
'samePageFormBehavior' => 'hide_form',
'redirectTo' => $redirectTo,
'customPage' => intval(ArrayHelper::get($confirmation, 'page')),
'customUrl' => ArrayHelper::get($confirmation, 'url'),
'active' => ArrayHelper::get($confirmation, 'isActive', true),
'enable_query_string' => $queryString ? 'yes' : 'no',
'query_strings' => $queryString,
];
$isDefault = ArrayHelper::isTrue($confirmation, 'isDefault');
if (!$isDefault) {
$format['conditionals'] = $this->getConditionals($confirmation,'confirmation', $form);
}
$confirmationsFormatted[] = wp_parse_args($format, $defaultValues);
}
return $confirmationsFormatted;
}
/**
* Get form field name in fluentforms format
*
* @param string $str
* @param array $form
* @return string
*/
private function getFormFieldName($str, $form)
{
preg_match('/[0-9]+[.]?[0-9]*/', $str, $fieldId);
$fieldId = ArrayHelper::get($fieldId, 0, '0');
if (!$fieldId) {
return '';
}
$fieldIds = [];
if (strpos($fieldId, '.') !== false) {
$fieldIds = explode('.', $fieldId);
$fieldId = $fieldId[0];
}
$field = [];
foreach (ArrayHelper::get($form, 'fields', []) as $formField) {
if (isset($formField->id) && $formField->id == $fieldId) {
$field = (array)$formField;
break;
}
}
list($type, $args) = $this->formatFieldData($field);
$name = ArrayHelper::get($args, 'name', '');
if ($fieldIds && ArrayHelper::get($fieldIds, 1)) {
foreach (ArrayHelper::get($field, "inputs", []) as $input) {
if (ArrayHelper::get($input, 'id') != join('.', $fieldIds)) {
continue;
}
if ($subName = $this->getInputName($input)) {
$name .= ".$subName";
}
break;
}
}
return $name;
}
/**
* Resolve shortcode in fluentforms format
*
* @param string $message
* @param array $form
* @return string
*/
private function getResolveShortcodes($message, $form)
{
if (!$message) {
return $message;
}
preg_match_all('/{(.*?)}/', $message, $matches);
if (!$matches[0]) {
return $message;
}
$shortcodes = $this->dynamicShortcodes();
foreach ($matches[0] as $match) {
$replace = '';
if (isset($shortcodes[$match])) {
$replace = $shortcodes[$match];
} elseif ($this->isFormField($match) && $name = $this->getFormFieldName($match, $form)) {
$replace = "{inputs.$name}";
}
$message = str_replace($match, $replace, $message);
}
return $message;
}
/**
* Get bool value depend on shortcode is form inputs or not
*
* @param string $shortcode
* @return boolean
*/
private function isFormField($shortcode)
{
preg_match('/:[0-9]+[.]?[0-9]*/', $shortcode, $fieldId);
return ArrayHelper::isTrue($fieldId, '0');
}
/**
* Get shortcode in fluentforms format
* @return array
*/
private function dynamicShortcodes()
{
return [
'{all_fields}' => '{all_data}',
'{admin_email}' => '{wp.admin_email}',
'{ip}' => '{ip}',
'{date_mdy}' => '{date.m/d/Y}',
'{date_dmy}' => '{date.d/m/Y}',
'{embed_post:ID}' => '{embed_post.ID}',
'{embed_post:post_title}' => '{embed_post.post_title}',
'{embed_url}' => '{embed_post.permalink}',
'{user:id}' => '{user.ID}',
'{user:first_name}' => '{user.first_name}',
'{user:last_name}' => '{user.last_name}',
'{user:user_login}' => '{user.user_login}',
'{user:display_name}' => '{user.display_name}',
'{user_full_name}' => '{user.first_name} {user.last_name}',
'{user:user_email}' => '{user.user_email}',
'{entry_id}' => '{submission.id}',
'{entry_url}' => '{submission.admin_view_url}',
'{referer}' => '{http_referer}',
'{user_agent}' => '{browser.name}'
];
}
public function getFormsFormatted()
{
$forms = [];
$items = $this->getForms();
foreach ($items as $item) {
$forms[] = [
'name' => $this->getFormName($item),
'id' => $this->getFormId($item),
'imported_ff_id' => $this->isAlreadyImported($item),
];
}
return $forms;
}
protected function getForms()
{
$forms = \GFAPI::get_forms();
return $forms;
}
protected function getForm($id)
{
if ($form = \GFAPI::get_form($id)) {
return $form;
}
return false;
}
protected function getFormName($form)
{
return $form['title'];
}
public function getEntries($formId)
{
$form = $this->getForm($formId);
if (empty($form)) {
return false;
}
/**
* Note - more-then 5000/6000 (based on sever) entries process make timout response / set default limit 1000
* @todo need silently async processing for support all entries migrate at a time, and improve frontend entry-migrate with more settings options
*/
$totalEntries = \GFAPI::count_entries($formId);
$perPage = apply_filters('fluentform/entry_migration_max_limit', static::DEFAULT_ENTRY_MIGRATION_MAX_LIMIT, $this->key , $totalEntries, $formId);
$offset = 0;
$paging = [
'offset' => $offset,
'page_size' => $perPage
];
$shorting = [
'key' => 'id',
'direction' => 'ASC',
];
$submissions = \GFAPI::get_entries($formId, [], $shorting, $paging);
$entries = [];
if (!is_array($submissions)) {
return $entries;
}
$fieldsMap = $this->getFields($form);
foreach ($submissions as $submission) {
$entry = [];
foreach ($fieldsMap['fields'] as $id => $field) {
$name = ArrayHelper::get($field, 'attributes.name');
if (!$name) {
continue;
}
$type = ArrayHelper::get($field, 'element');
$fieldModel = \GFFormsModel::get_field($form, $id);
// format entry value by field name
$finalValue = null;
if ("input_file" == $type && $value = $this->getSubmissionValue($id, $submission)) {
$finalValue = $this->migrateFilesAndGetUrls($value);
} elseif ("repeater_field" == $type && $value = $this->getSubmissionValue($id, $submission)) {
if ($repeatData = (array)maybe_unserialize($value)) {
$finalValue = [];
foreach ($repeatData as $data) {
$finalValue[] = array_values($data);
}
}
} elseif (
"select" == $type &&
ArrayHelper::isTrue($field, 'attributes.multiple') &&
$value = $this->getSubmissionValue($id, $submission)
) {
$finalValue = \json_decode($value);
} elseif (
in_array($type, ["input_checkbox", "address", "input_name", "terms_and_condition"]) &&
isset($fieldModel['inputs'])
) {
$finalValue = $this->getSubmissionArrayValue($type, $field, $fieldModel['inputs'], $submission);
if ("input_checkbox" == $type) {
$finalValue = array_values($finalValue);
} elseif ("terms_and_condition" == $type) {
$finalValue = $finalValue ? 'on' : 'off';
}
}
if (!$finalValue) {
$finalValue = is_object($fieldModel) ? $fieldModel->get_value_export($submission, $id) : '';
}
$entry[$name] = $finalValue;
}
if ($created_at = ArrayHelper::get($submission, 'date_created')) {
$entry['created_at'] = $created_at;
}
if ($updated_at = ArrayHelper::get($submission, 'date_updated')) {
$entry['updated_at'] = $updated_at;
}
if ($is_favourite = ArrayHelper::get($submission, 'is_starred')) {
$entry['is_favourite'] = $is_favourite;
}
if ($status = ArrayHelper::get($submission, 'status')) {
if ('trash' == $status || 'spam' == $status) {
$entry['status'] = 'trashed';
} elseif ('active' == $status && ArrayHelper::isTrue($submission, 'is_read')) {
$entry['status'] = 'read';
}
}
$entries[] = $entry;
}
return $entries;
}
/**
* @param $form
* @return mixed
*/
protected function getFormId($form)
{
if (isset($form['id'])) {
return $form['id'];
}
return false;
}
protected function getSubmissionArrayValue($type, $field, $inputs, $submission)
{
$arrayValue = [];
foreach ($inputs as $input) {
if (!isset($submission[$input['id']])) {
continue;
}
if ("input_name" == $type && $subFields = ArrayHelper::get($field, 'fields')) {
foreach ($subFields as $subField) {
if (
$input['label'] == ArrayHelper::get($subField, 'settings.label') &&
$subName = ArrayHelper::get($subField, 'attributes.name', '')
) {
$arrayValue[$subName] = $submission[$input['id']];
}
}
} else {
$arrayValue[] = $submission[$input['id']];
}
}
if ('address' == $type) {
$arrayValue = array_combine([
"address_line_1",
"address_line_2",
"city",
"state",
"zip",
"country"
], $arrayValue);
}
return array_filter($arrayValue);
}
protected function getSubmissionValue($id, $submission)
{
return isset($submission[$id]) ? $submission[$id] : "";
}
}
Classes/ContactForm7Migrator.php 0000644 00000047204 15073231424 0012675 0 ustar 00 key = 'contactform7';
$this->title = 'Contact Form 7';
$this->shortcode = 'contact_form_7';
}
public function exist()
{
return !!defined('WPCF7_PLUGIN');
}
protected function getForms()
{
$forms = [];
$postItems = get_posts(['post_type' => 'wpcf7_contact_form', 'posts_per_page' => -1]);
foreach ($postItems as $form) {
$forms[] = [
'ID' => $form->ID,
'name' => $form->post_title,
];
}
return $forms;
}
public function getFields($form)
{
$formPostMeta = get_post_meta($form['ID'], '_form', true);
$formMetaDataArray = preg_split('/\r\n|\r|\n/', $formPostMeta);
//remove all label and empty line
$formattedArray = $this->removeLabelsAndNewLine($formMetaDataArray);
//format array with field label and remove quiz field
$fieldStringArray = $this->formatFieldArray($formattedArray);
// format fields as fluent forms field
return $this->formatAsFluentField($fieldStringArray);
}
public function getSubmitBttn($args)
{
return [
'uniqElKey' => 'submit-' . time(),
'element' => 'button',
'attributes' => [
'type' => 'submit',
'class' => '',
'id' => ''
],
'settings' => [
'align' => 'left',
'button_style' => 'default',
'container_class' => '',
'help_message' => '',
'background_color' => '#1a7efb',
'button_size' => 'md',
'color' => '#ffffff',
'button_ui' => [
'type' => 'default',
'text' => $args['label'],
'img_url' => ''
],
'normal_styles' => [
'backgroundColor' => '#1a7efb',
'borderColor' => '#1a7efb',
'color' => '#ffffff',
'borderRadius' => '',
'minWidth' => ''
],
'hover_styles' => [
'backgroundColor' => '#1a7efb',
'borderColor' => '#1a7efb',
'color' => '#ffffff',
'borderRadius' => '',
'minWidth' => ''
],
'current_state' => "normal_styles"
],
'editor_options' => [
'title' => 'Submit Button',
],
];
}
private function fieldTypeMap()
{
return [
'email' => 'email',
'text' => 'input_text',
'url' => 'input_url',
'tel' => 'phone',
'textarea' => 'input_textarea',
'number' => 'input_number',
'range' => 'rangeslider',
'date' => 'input_date',
'checkbox' => 'input_checkbox',
'radio' => 'input_radio',
'select' => 'select',
'multi_select' => 'multi_select',
'file' => 'input_file',
'acceptance' => 'terms_and_condition'
];
}
protected function formatFieldData($args, $type)
{
switch ($type) {
case 'input_number':
$args['min'] = ArrayHelper::get($args, 'min', 0);
$args['max'] = ArrayHelper::get($args, 'max');
break;
case 'rangeslider':
$args['min'] = ArrayHelper::get($args, 'min', 0);
$args['max'] = ArrayHelper::get($args, 'max', 10);
$args['step'] = ArrayHelper::get($args, 'step',1);
break;
case 'input_date':
$args['format'] = "Y-m-d H:i";
break;
case 'select':
case 'input_radio':
case 'input_checkbox':
list($options, $defaultVal) = $this->getOptions(ArrayHelper::get($args, 'choices', []),
ArrayHelper::get($args, 'default', '')
);;
$args['options'] = $options;
if ($type == 'select') {
$isMulti = ArrayHelper::isTrue($args, 'multiple');
if ($isMulti) {
$args['multiple'] = true;
$args['value'] = $defaultVal;
} else {
$args['value'] = is_array($defaultVal) ? array_shift($defaultVal) : "";
}
} elseif ($type == 'input_checkbox') {
$args['value'] = $defaultVal;
} elseif ($type == 'input_radio') {
$args['value'] = is_array($defaultVal) ? array_shift($defaultVal) : "";
}
break;
case 'input_file':
$args['allowed_file_types'] = $this->getFileTypes($args, 'allowed_file_types');
$args['max_size_unit'] = ArrayHelper::get($args, 'max_size_unit');
$max_size = ArrayHelper::get($args, 'max_file_size') ?: 1;
if ($args['max_size_unit'] === 'MB') {
$args['max_file_size'] = ceil($max_size * 1048576); // 1MB = 1048576 Bytes
}
$args['max_file_count'] = '1';
$args['upload_btn_text'] = 'File Upload';
break;
case 'terms_and_condition':
if (ArrayHelper::get($args, 'tnc_html') !== '') {
$args['tnc_html'] = ArrayHelper::get($args, 'tnc_html',
'I have read and agree to the Terms and Conditions and Privacy Policy.'
);
$args['required'] = true;
}
break;
default :
break;
}
return $args;
}
protected function getOptions($options, $default)
{
$formattedOptions = [];
$defaults = [];
foreach ($options as $key => $option) {
$formattedOption = [
'label' => $option,
'value' => $option,
'image' => '',
'calc_value' => '',
'id' => $key + 1,
];
if (strpos($default, '_') !== false) {
$defaults = explode('_', $default);
foreach ($defaults as $defaultValue) {
if ($formattedOption['id'] == $defaultValue) {
$defaults[] = $formattedOption['value'];
}
}
} else {
$defaults = $default;
}
$formattedOptions[] = $formattedOption;
}
return [$formattedOptions, $defaults];
}
protected function getFileTypes($field, $arg)
{
// All Supported File Types in Fluent Forms
$allFileTypes = [
"image/*|jpg|jpeg|gif|png|bmp",
"audio/*|mp3|wav|ogg|oga|wma|mka|m4a|ra|mid|midi|mpga",
"video/*|avi|divx|flv|mov|ogv|mkv|mp4|m4v|mpg|mpeg|mpe|video/quicktime|qt",
"pdf",
"text/*|doc|ppt|pps|xls|mdb|docx|xlsx|pptx|odt|odp|ods|odg|odc|odb|odf|rtf|txt",
"zip|gz|gzip|rar|7z",
"exe",
"csv"
];
$formattedTypes = explode('|', ArrayHelper::get($field, $arg, ''));
$fileTypeOptions = [];
foreach ($formattedTypes as $format) {
foreach ($allFileTypes as $fileTypes) {
if (!empty($format) && strpos($fileTypes, $format) !== false) {
if (strpos($fileTypes, '/*|') !== false) {
$fileTypes = explode('/*|', $fileTypes)[1];
}
$fileTypeOptions[] = $fileTypes;
}
}
}
return array_unique($fileTypeOptions);
}
protected function getFormName($form)
{
return $form['name'];
}
protected function getFormMetas($form)
{
$formObject = new Form(wpFluentForm());
$defaults = $formObject->getFormsDefaultSettings();
return [
'formSettings' => [
'confirmation' => ArrayHelper::get($defaults, 'confirmation'),
'restrictions' => ArrayHelper::get($defaults, 'restrictions'),
'layout' => ArrayHelper::get($defaults, 'layout'),
],
'advancedValidationSettings' => $this->getAdvancedValidation(),
'delete_entry_on_submission' => 'no',
'notifications' => $this->getNotifications(),
'step_data_persistency_status' => 'no',
'form_save_state_status' => 'no'
];
}
protected function getFormId($form)
{
return $form['ID'];
}
public function getFormsFormatted()
{
$forms = [];
$items = $this->getForms();
foreach ($items as $item) {
$forms[] = [
'name' => $item['name'],
'id' => $item['ID'],
'imported_ff_id' => $this->isAlreadyImported($item),
];
}
return $forms;
}
private function getNotifications()
{
return [
'name' => __('Admin Notification Email', 'fluentform'),
'sendTo' => [
'type' => 'email',
'email' => '{wp.admin_email}',
'field' => '',
'routing' => [],
],
'fromName' => '',
'fromEmail' => '',
'replyTo' => '',
'bcc' => '',
'subject' => __('New Form Submission', 'fluentform'),
'message' => '
{all_data}
This form submitted at: {embed_post.permalink}
', 'conditionals' => [], 'enabled' => false ]; } private function getAdvancedValidation() { return [ 'status' => false, 'type' => 'all', 'conditions' => [ [ 'field' => '', 'operator' => '=', 'value' => '' ] ], 'error_message' => '', 'validation_type' => 'fail_on_condition_met' ]; } private function removeLabelsAndNewLine($formMetaDataArray) { $formattedArray = []; foreach ($formMetaDataArray as $formMetaString) { if (!empty($formMetaString)) { if (strpos($formMetaString, '') !== false) { $formMetaString = trim(str_replace([''], '', $formMetaString)); } $formattedArray[] = $formMetaString; } } return $formattedArray; } private function formatFieldArray($formattedArray) { $fieldStringArray = []; foreach ($formattedArray as $formattedKey => &$formattedValue) { preg_match_all('/\[[^\]]*\]/', $formattedValue, $fieldStringMatches); $fieldString = isset($fieldStringMatches[0][0]) ? $fieldStringMatches[0][0] : ''; if (preg_match('/\[(.*?)\](.*?)\[.*?\]/', $formattedValue, $withoutBracketMatches)) { $withoutBracketString = isset($withoutBracketMatches[2]) ? trim($withoutBracketMatches[2]) : ''; $fieldString = str_replace(']', ' "' . $withoutBracketString . '"]', $fieldString); } if (strpos($formattedValue, '[quiz') !== 0) { if (strpos($formattedValue, '[') === false) { if ( isset($formattedArray[$formattedKey + 1]) && strpos($formattedArray[$formattedKey + 1], '[') !== false ) { $fieldStringArray[] = $formattedValue . $formattedArray[$formattedKey + 1]; unset($formattedArray[$formattedKey + 1]); } } else { $fieldStringArray[] = $fieldString; unset($formattedArray[$formattedKey]); } } } return $fieldStringArray; } private function formatAsFluentField($fieldStringArray) { $fluentFields = []; $submitBtn = []; foreach ($fieldStringArray as $fieldKey => &$fieldValue) { $fieldLabel = ''; $fieldPlaceholder = ''; $fieldAutoComplete = ''; $fieldMinLength = ''; $fieldMaxLength = ''; $fieldSize = ''; $fieldStep = ''; $fieldMultipleValues = []; $fieldMin = ''; $fieldMax = ''; $fieldDefault = ''; $fieldMultiple = false; $fieldFileTypes = ''; $fieldMaxFileSize = ''; $fieldFileSizeUnit = 'KB'; $tncHtml = ''; $fieldString = ''; if (preg_match('/^(.*?)\[/', $fieldValue, $matches)) { $fieldLabel = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/\[([^]]+)\]/', $fieldValue, $matches)) { $fieldString = isset($matches[1]) ? $matches[1] : ''; } $words = preg_split('/\s+/', $fieldString); $fieldRequired = isset($words[0]) && strpos($words[0], '*') !== false ?? true; $fieldElement = isset($words[0]) ? trim($words[0], '*') : ''; $fieldName = isset($words[1]) ? trim($words[1]) : ''; if ($fieldElement === 'submit') { preg_match_all('/(["\'])(.*?)\1/', $fieldString, $matches); $submitBtn = $this->getSubmitBttn([ 'uniqElKey' => $fieldElement . '-' . time(), 'label' => isset($matches[2][0]) ? $matches[2][0] : 'Submit' ]); continue; } if ($fieldElement === 'select' && strpos($fieldString, 'multiple') !== false) { $fieldMultiple = true; } if (preg_match('/min:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldMin = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/max:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldMax = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/minlength:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldMinLength = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/maxlength:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldMaxLength = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/size:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldSize = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/step:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldStep = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/(?:placeholder|watermark) "([a-zA-Z0-9]+)"/', $fieldString, $matches)) { $fieldPlaceholder = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/filetypes:([a-zA-Z0-9|]+)/', $fieldString, $matches)) { $fieldFileTypes = isset($matches[1]) ? $matches[1] : ''; } if (preg_match_all('/(["\'])(.*?)\1/', $fieldString, $matches)) { if (isset($matches[2])) { if (count($matches[2]) > 1) { $fieldMultipleValues = $matches[2]; } else { if (count($matches[2]) === 1) { $fieldAutoComplete = isset($matches[2][0]) ? $matches[2][0] : ''; } } } } if (preg_match('/default:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldDefault = isset($matches[1]) ? $matches[1] : ''; } if (preg_match('/limit:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldMaxFileSize = isset($matches[1]) ? $matches[1] : '1mb'; if (strpos($fieldMaxFileSize, 'mb') !== false) { $fieldFileSizeUnit = 'MB'; } $fieldMaxFileSize = str_replace(['mb', 'kb'], '', $fieldMaxFileSize); } if (preg_match('/autocomplete:([a-zA-Z0-9]+)/', $fieldString, $matches)) { $fieldAutoComplete = isset($matches[1]) ? $matches[1] : ''; } if ($fieldElement === 'acceptance') { $tncHtml = $fieldAutoComplete; } if (!$fieldLabel) { $fieldLabel = $fieldElement; } $fieldType = ArrayHelper::get($this->fieldTypeMap(), $fieldElement); $args = [ 'uniqElKey' => 'el_' . $fieldKey . time(), 'type' => $fieldType, 'index' => $fieldKey, 'required' => $fieldRequired, 'label' => $fieldLabel, 'name' => $fieldName, 'placeholder' => $fieldPlaceholder, 'class' => '', 'value' => $fieldAutoComplete, 'help_message' => '', 'container_class' => '', 'prefix' => '', 'suffix' => '', 'min' => $fieldMin, 'max' => $fieldMax, 'minlength' => $fieldMinLength, 'maxlength' => $fieldMaxLength, 'size' => $fieldSize, 'step' => $fieldStep, 'choices' => $fieldMultipleValues, 'default' => $fieldDefault, 'multiple' => $fieldMultiple, 'allowed_file_types' => $fieldFileTypes, 'max_file_size' => $fieldMaxFileSize, 'max_size_unit' => $fieldFileSizeUnit, 'tnc_html' => $tncHtml ]; $fields = $this->formatFieldData($args, $fieldType); if ($fieldMultiple) { $fieldType = 'multi_select'; } if ($fieldData = $this->getFluentClassicField($fieldType, $fields)) { $fluentFields['fields'][$args['index']] = $fieldData; } } $fluentFields['submitButton'] = $submitBtn; return $fluentFields; } public function getEntries($formId) { if (class_exists('Flamingo_Inbound_Message')) { $post = get_post($formId); $formName = $post->post_name; $allPosts = \Flamingo_Inbound_Message::find(['channel' => $formName]); $entries = []; foreach ($allPosts as $post) { $entries[] = $post->fields; } return $entries; } wp_send_json_error([ 'message' => __("Please install and active Flamingo", 'fluentform') ], 422); } } Classes/CalderaMigrator.php 0000644 00000051550 15073231424 0011721 0 ustar 00 key = 'caldera'; $this->title = 'Caldera Forms'; $this->shortcode = 'caldera_form'; $this->hasStep = false; } /** * @return bool */ public function exist() { return defined('CFCORE_VER'); } /** * @return array */ public function getForms() { $forms = []; $items = \Caldera_Forms_Forms::get_forms(); foreach ($items as $item) { $forms[] = \Caldera_Forms_Forms::get_form($item); } return $forms; } public function getForm($id) { return \Caldera_Forms_Forms::get_form($id); } public function getFormsFormatted() { $forms = []; $items = \Caldera_Forms_Forms::get_forms(); foreach ($items as $item) { $item = \Caldera_Forms_Forms::get_form($item); $forms[] = [ 'name' => $this->getFormName($item), 'id' => $this->getFormId($item), 'imported_ff_id' => $this->isAlreadyImported($item), 'entryImportSupported' => true ]; } return $forms; } /** * @param $form * @return array */ public function getFields($form) { $fluentFields = []; $fields = \Caldera_Forms_Forms::get_fields($form); foreach ($fields as $name => $field) { $field = (array)$field; list($type, $args) = $this->formatFieldData($field, $form); if ($value = $this->getFluentClassicField($type, $args)) { $fluentFields[$field['ID']] = $value; } else { //submit button is imported separately if (ArrayHelper::get($field, 'type') != 'button') { $this->unSupportFields[] = ArrayHelper::get($field, 'label'); } } } $returnData = [ 'fields' => $this->getContainer($form, $fluentFields), 'submitButton' => $this->submitBtn ]; if ($this->hasStep && defined('FLUENTFORMPRO')) { $returnData['stepsWrapper'] = $this->getStepWrapper(); } return $returnData; } private function formatFieldData($field, $form) { if (ArrayHelper::get($field, 'config.type_override')) { $field['type'] = $field['config']['type_override']; } $args = [ 'uniqElKey' => $field['ID'], 'index' => $field['ID'], // get the order id from order array 'required' => isset($field['required']), 'label' => $field['label'], 'label_placement' => $this->getLabelPlacement($field), 'name' => $field['slug'], 'placeholder' => ArrayHelper::get($field, 'config.placeholder'), 'class' => $field['config']['custom_class'], 'value' => ArrayHelper::get($field, 'config.default'), 'help_message' => ArrayHelper::get($field, 'caption'), ]; $type = ArrayHelper::get($this->fieldTypes(), $field['type'], ''); switch ($type) { case 'phone': case 'input_text': if (ArrayHelper::isTrue($field, 'config.masked')) { $type = 'input_mask'; $args['temp_mask'] = 'custom'; $args['mask'] = str_replace('9', '0', $field['config']['mask']);//replace mask 9 with 0 for numbers } break; case 'email': case 'input_textarea': $args['rows'] = ArrayHelper::get($field, 'config.rows'); break; case 'input_url': case 'color_picker': case 'section_break': case 'select': case 'input_radio': case 'input_checkbox': case 'dropdown': if ($args['placeholder'] == '') { $args['placeholder'] = __('-Select-', 'fluentform'); } $args['options'] = $this->getOptions(ArrayHelper::get($field, 'config.option', [])); $args['calc_value_status'] = (bool)ArrayHelper::get($field, 'config.show_values'); // Toggle switch field in Caldera $isBttnType = ArrayHelper::get($field, 'type') == 'toggle_switch'; if ($isBttnType) { $args['layout_class'] = 'ff_list_buttons'; //for btn type radio } if ($type == 'section_break') { $args['label'] = ''; } break; case 'multi_select': $args['options'] = $this->getOptions(ArrayHelper::get($field, 'config.option', [])); $args['calc_value_status'] = ArrayHelper::get($field, 'config.show_values') ? true : false; break; case 'input_date': $args['format'] = Arrayhelper::get($field, 'config.format'); break; case 'input_number': $args['step'] = ArrayHelper::get($field, 'config.step'); $args['min'] = ArrayHelper::get($field, 'config.min'); $args['max'] = ArrayHelper::get($field, 'config.max'); // Caldera Calculation field if (ArrayHelper::get($field, 'type') == 'calculation') { $args['prefix'] = $field['config']['before']; $args['suffix'] = $field['config']['after']; if (ArrayHelper::isTrue($field, 'config.manual') || !empty(Arrayhelper::get($field, 'config.formular'))) { $args['enable_calculation'] = true; $args['calculation_formula'] = $this->convertFormulas($field, $form); } } break; case 'rangeslider': $args['step'] = $field['config']['step']; $args['min'] = $field['config']['min']; $args['max'] = $field['config']['max']; break; case 'ratings': $number = ArrayHelper::get($field, 'config.number', 5); $args['options'] = array_combine(range(1, $number), range(1, $number)); break; case 'input_file': $args['help_message'] = $field['caption']; $args['allowed_file_types'] = $this->getFileTypes($field, 'config.allowed'); $args['max_size_unit'] = 'KB'; $args['max_file_size'] = $this->getFileSize($field); $args['max_file_count'] = ArrayHelper::isTrue($field, 'config.multi_upload') ? 5 : 1; //limit 5 for unlimited files $args['upload_btn_text'] = ArrayHelper::get($field, 'config.multi_upload_text') ?: 'File Upload'; break; case 'custom_html': $args['html_codes'] = $field['config']['default']; $args['container_class'] = $field['config']['custom_class']; break; case 'gdpr_agreement': $args['tnc_html'] = $field['config']['agreement']; break; case 'button': $pageLength = count(ArrayHelper::get($form, 'page_names')); if ($field['config']['type'] == 'next' && $pageLength > 1) { $this->hasStep = true; $type = 'form_step'; break; //skipped prev button ,only one is required } elseif ($field['config']['type'] != 'submit') { break; } $this->submitBtn = $this->getSubmitBttn([ 'uniqElKey' => $field['ID'], 'label' => $field['label'], 'class' => $field['config']['custom_class'], ]); break; } return array($type, $args); } private function getLabelPlacement($field) { if (ArrayHelper::get($field, 'hide_label') == 1) { return 'hide_label'; } return ''; } // Function to convert shortcodes in numeric field calculations (todo) private function convertFormulas($calculationField, $form) { $calderaFormula = ''; $fieldSlug = []; $fieldID = []; foreach ($form['fields'] as $field) { $prefixTypes = ArrayHelper::get($this->fieldPrefix(), $field['type'], ''); // FieldSlug for Manual Formula $fieldSlug[$field['slug']] = '{' . $prefixTypes . '.' . $field['slug'] . '}'; // FieldID for Direct Formula $fieldID[$field['ID']] = '{' . $prefixTypes . '.' . $field['slug'] . '}'; } // Check if Manual Formula Enabled in Caldera Otherwise get Direct Formula if (!empty($calculationField['config']['manual'])) { $calderaFormula = $calculationField['config']['manual_formula']; $refactorShortcode = str_replace("%", "", $calderaFormula); $refactoredFormula = str_replace(array_keys($fieldSlug), array_values($fieldSlug), $refactorShortcode); } else { if (!empty($calculationField['config']['formular'])) { $calderaFormula = $calculationField['config']['formular']; $refactoredFormula = str_replace(array_keys($fieldID), array_values($fieldID), $calderaFormula); } } return $refactoredFormula; } /** * @param $field * @return int */ private function getFileSize($field) { $fileSizeByte = ArrayHelper::get($field, 'config.max_upload', 6000); $fileSizeKilobyte = ceil(($fileSizeByte * 1024) / 1000); return $fileSizeKilobyte; } /** * @return array */ public function fieldPrefix() { $fieldPrefix = [ 'number' => 'input', 'hidden' => 'input', 'range_slider' => 'input', 'calculation' => 'input', 'checkbox' => 'checkbox', 'radio' => 'radio', 'toggle_switch' => 'radio', 'dropdown' => 'select', 'filtered_select2' => 'select' ]; return $fieldPrefix; } /** * @return array */ public function fieldTypes() { $fieldTypes = [ 'email' => 'email', 'text' => 'input_text', 'hidden' => 'input_hidden', 'textarea' => 'input_textarea', 'paragraph' => 'input_textarea', 'wysiwyg' => 'input_textarea', 'url' => 'input_url', 'color_picker' => 'color_picker', 'phone_better' => 'phone', 'phone' => 'phone', 'select' => 'select', 'dropdown' => 'select', 'filtered_select2' => 'multi_select', 'radio' => 'input_radio', 'checkbox' => 'input_checkbox', 'toggle_switch' => 'input_radio', 'date_picker' => 'input_date', 'date' => 'input_date', 'range' => 'input_number', 'number' => 'input_number', 'calculation' => 'input_number', 'range_slider' => 'rangeslider', 'star_rating' => 'ratings', 'file' => 'input_file', 'cf2_file' => 'input_file', 'advanced_file' => 'input_file', 'html' => 'custom_html', 'section_break' => 'section_break', 'gdpr' => 'gdpr_agreement', 'button' => 'button', ]; return $fieldTypes; } /** * @param $options * @return array */ public function getOptions($options) { $formattedOptions = []; foreach ($options as $key => $option) { $formattedOptions[] = [ 'label' => ArrayHelper::get($option, 'label', 'Item -' . $key), 'value' => $key, 'calc_value' => ArrayHelper::get($option, 'calc_value'), 'id' => $key ]; } return $formattedOptions; } /** * @param $form * @param $fluentFields * @return array */ private function getContainer($form, $fluentFields) { $containers = []; if (empty($form['layout_grid']['fields'])) { return $fluentFields; } //set fields array map for inserting into containers foreach ($form['layout_grid']['fields'] as $field_id => $location) { if (isset($fluentFields[$field_id])) { $location = explode(':', $location); $containers[$location[0]][$location[1]]['fields'][] = $fluentFields[$field_id]; } } $withContainer = []; foreach ($containers as $row => $columns) { $colsCount = count($columns); $containerConfig = []; if ($colsCount != 1) { //with container $containerConfig[] = [ 'index' => $row, 'element' => 'container', 'attributes' => [], 'settings' => [ 'container_class', 'conditional_logics' ], 'editor_options' => [ 'title' => $colsCount . ' Column Container', 'icon_class' => $colsCount . 'dashicons dashicons-align-center' ], 'columns' => $columns, 'uniqElKey' => 'col' . '_' . md5(uniqid(mt_rand(), true)) ]; } else { //without container $containerConfig = $columns[1]['fields']; } $withContainer[] = $containerConfig; } array_filter($withContainer); return (self::arrayFlat($withContainer)); } /** * @param null $array * @param int $depth * @return array */ public static function arrayFlat($array = null, $depth = 1) { $result = []; if (!is_array($array)) { $array = func_get_args(); } foreach ($array as $key => $value) { if (is_array($value) && $depth) { $result = array_merge($result, self::arrayFlat($value, $depth - 1)); } else { $result = array_merge($result, [$key => $value]); } } return $result; } /** * @return array */ private function getStepWrapper() { return [ 'stepStart' => [ 'element' => 'step_start', 'attributes' => [ 'id' => '', 'class' => '', ], 'settings' => [ 'progress_indicator' => 'progress-bar', 'step_titles' => [], 'disable_auto_focus' => 'no', 'enable_auto_slider' => 'no', 'enable_step_data_persistency' => 'no', 'enable_step_page_resume' => 'no', ], 'editor_options' => [ 'title' => 'Start Paging' ], ], 'stepEnd' => [ 'element' => 'step_end', 'attributes' => [ 'id' => '', 'class' => '', ], 'settings' => [ 'prev_btn' => [ 'type' => 'default', 'text' => 'Previous', 'img_url' => '' ] ], 'editor_options' => [ 'title' => 'End Paging' ], ] ]; } /** * @param $form * @return array default parsed form metas * @throws \Exception */ public function getFormMetas($form) { $formObject = new Form(wpFluentForm()); $defaults = $formObject->getFormsDefaultSettings(); $confirmation = wp_parse_args( [ 'messageToShow' => $form['success'], 'samePageFormBehavior' => isset($form['hide_form']) ? 'hide_form' : 'reset_form', ], $defaults['confirmation'] ); $advancedValidation = [ 'status' => false, 'type' => 'all', 'conditions' => [ [ 'field' => '', 'operator' => '=', 'value' => '' ] ], 'error_message' => '', 'validation_type' => 'fail_on_condition_met' ]; $notifications = [ 'sendTo' => [ 'type' => 'email', 'email' => ArrayHelper::get($form, 'mailer.recipients'), 'field' => '', 'routing' => [], ], 'enabled' => $form['mailer']['on_insert'] ? true : false, 'name' => 'Admin Notification', 'subject' => ArrayHelper::get($form, 'mailer.email_subject', 'Admin Notification'), 'to' => ArrayHelper::get($form, 'mailer.recipients', '{wp.admin_email}'), 'replyTo' => ArrayHelper::get($form, 'mailer.reply_to', '{wp.admin_email}'), 'message' => str_replace('{summary}', '{all_data}', ArrayHelper::get($form, 'mailer.email_message')), 'fromName' => ArrayHelper::get($form, 'mailer.sender_name'), 'fromEmail' => ArrayHelper::get($form, 'mailer.sender_email'), 'bcc' => ArrayHelper::get($form, 'mailer.bcc_to'), ]; return [ 'formSettings' => [ 'confirmation' => $confirmation, 'restrictions' => $defaults['restrictions'], 'layout' => $defaults['layout'], ], 'advancedValidationSettings' => $advancedValidation, 'delete_entry_on_submission' => 'no', 'notifications' => [$notifications] ]; } /** * @param $form * @return mixed */ protected function getFormId($form) { return $form['ID']; } /** * @param $form * @return mixed */ protected function getFormName($form) { return $form['name']; } public function getEntries($formId) { $form = \Caldera_Forms::get_form($formId); $totalEntries = (new \Caldera_Forms_Entry_Entries($form, 9999))->get_total('active'); $max_limit = apply_filters('fluentform/entry_migration_max_limit', static::DEFAULT_ENTRY_MIGRATION_MAX_LIMIT, $this->key, $totalEntries, $formId); $data = \Caldera_Forms_Admin::get_entries($form, 1, $max_limit); $nameKeyMap = $this->getFieldsNameMap($form); $entries = []; if (!is_array(ArrayHelper::get($data, 'entries'))) { return $entries; } foreach ($data['entries'] as $entry) { $entryId = ArrayHelper::get($entry, '_entry_id'); $entryFields = ArrayHelper::get(\Caldera_Forms::get_entry($entryId, $form), 'data'); $formattedEntry = []; foreach ($entryFields as $key => $field) { $value = $field['value']; if (is_array($value)) { $selectedOption = array_pop($value); $value = \json_decode($selectedOption, true); $value = array_keys($value); } $inputName = $nameKeyMap[$key]; $formattedEntry[$inputName] = $value; } $entries[] = $formattedEntry; } return array_reverse($entries); } /** * Map Field key with its name to insert entry with input name * * @param array|null $form * @return array|mixed */ public function getFieldsNameMap($form) { $fields = \Caldera_Forms_Forms::get_fields($form); $map = []; if (is_array($fields) && !empty($fields)) { foreach ($fields as $key => $field) { $map[$key] = $field['slug']; } } return $map; } } Classes/WpFormsMigrator.php 0000644 00000107473 15073231424 0011771 0 ustar 00 key = 'wpforms'; $this->title = 'WPForms'; $this->shortcode = 'wp_form'; $this->hasStep = false; } protected function getForms() { $forms = []; if (function_exists('wpforms')) { $formItems = wpforms()->form->get(''); foreach ($formItems as $form) { $formData = json_decode($form->post_content, true); $forms[] = [ 'ID' => $form->ID, 'name' => $form->post_title, 'fields' => ArrayHelper::get($formData, 'fields'), 'settings' => ArrayHelper::get($formData, 'settings'), ]; } } return $forms; } public function getFields($form) { $fluentFields = []; $fields = ArrayHelper::get($form, 'fields'); foreach ($fields as $field) { if ( "pagebreak" == ArrayHelper::get($field, 'type') && $position = ArrayHelper::get($field, 'position') ) { if ("top" == $position || "bottom" == $position) { continue; } } $fieldType = ArrayHelper::get($this->fieldTypeMap(), ArrayHelper::get($field, 'type')); $args = $this->formatFieldData($field, $fieldType); if ('select' == $fieldType && ArrayHelper::isTrue($field, 'multiple')) { $fieldType = 'multi_select'; } if ($fieldData = $this->getFluentClassicField($fieldType, $args)) { $fluentFields[$field['id']] = $fieldData; } else { $this->unSupportFields[] = ArrayHelper::get($field, 'label'); } } $submitBtn = $this->getSubmitBttn([ 'uniqElKey' => 'button_' . time(), 'label' => ArrayHelper::get($form, 'settings.submit_text'), 'class' => ArrayHelper::get($form, 'settings.submit_class'), ]); if (empty($fluentFields)) { return false; } $returnData = [ 'fields' => $fluentFields, 'submitButton' => $submitBtn ]; if ($this->hasStep && defined('FLUENTFORMPRO')) { $returnData['stepsWrapper'] = $this->getStepWrapper(); } return $returnData; } public function getSubmitBttn($args) { return [ 'uniqElKey' => $args['uniqElKey'], 'element' => 'button', 'attributes' => [ 'type' => 'submit', 'class' => $args['class'] ], 'settings' => [ 'container_class' => '', 'align' => 'left', 'button_style' => 'default', 'button_size' => 'md', 'color' => '#ffffff', 'background_color' => '#409EFF', 'button_ui' => [ 'type' => ArrayHelper::get($args, 'type', 'default'), 'text' => $args['label'], 'img_url' => ArrayHelper::get($args, 'img_url', '') ], 'normal_styles' => [], 'hover_styles' => [], 'current_state' => "normal_styles" ], 'editor_options' => [ 'title' => 'Submit Button', ], ]; } protected function getFormName($form) { return $form['name']; } protected function getFormMetas($form) { $formObject = new Form(wpFluentForm()); $defaults = $formObject->getFormsDefaultSettings(); $confirmationsFormatted = $this->getConfirmations($form, $defaults['confirmation']); $defaultConfirmation = array_pop($confirmationsFormatted); $notifications = $this->getNotifications($form); $metas = [ 'formSettings' => [ 'confirmation' => $defaultConfirmation, 'restrictions' => $defaults['restrictions'], 'layout' => $defaults['layout'], ], 'advancedValidationSettings' => $this->getAdvancedValidation(), 'delete_entry_on_submission' => 'no', 'notifications' => $notifications, 'confirmations' => $confirmationsFormatted, ]; if ($webhooks = $this->getWebhooks($form)) { $metas['webhooks'] = $webhooks; } return $metas; } protected function getFormId($form) { return $form['ID']; } protected function getForm($id) { if (function_exists('wpforms') && $form = wpforms()->form->get($id)) { $formData = json_decode($form->post_content, true); return [ 'ID' => $form->ID, 'name' => $form->post_title, 'fields' => ArrayHelper::get($formData, 'fields'), 'settings' => ArrayHelper::get($formData, 'settings'), ]; } return false; } public function getEntries($formId) { if(!wpforms()->is_pro()){ wp_send_json([ 'message' => __("Entries not available in WPForms Lite",'fluentform') ], 200); } $form = $this->getForm($formId); if (empty($form)) { return false; } $formFields = $this->getFields($form); if ($formFields) { $formFields = $formFields['fields']; } $args = [ 'form_id' => $form['ID'], 'order' => 'asc', ]; $totalEntries = wpforms()->entry->get_entries($args, true);// 2nd parameter 'true' means return total entries count $args['number'] = apply_filters('fluentform/entry_migration_max_limit', static::DEFAULT_ENTRY_MIGRATION_MAX_LIMIT, $this->key, $totalEntries, $formId); $submissions = wpforms()->entry->get_entries($args); $entries = []; if (!$submissions || !is_array($submissions)) { return $entries; } foreach ($submissions as $submission) { $fields = \json_decode( $submission->fields , true); if (!$fields) { continue; } $entry = []; foreach ($fields as $fieldId => $field) { if (!isset($formFields[$fieldId])) { continue; } $formField = $formFields[$fieldId]; $name = ArrayHelper::get($formField, 'attributes.name'); if (!$name) { continue; } $type = ArrayHelper::get($formField, 'element'); // format entry value by field name $finalValue = ArrayHelper::get($field, 'value'); if ("input_name" == $type) { $finalValue = $this->getSubmissionNameValue($formField['fields'], $field); } elseif ( "input_checkbox" == $type || ( "select" == $type && ArrayHelper::isTrue($formField, 'attributes.multiple') ) ) { $finalValue = explode("\n", $finalValue); } elseif ("address" == $type) { $finalValue = [ "address_line_1" => ArrayHelper::get($field, 'address1', ''), "address_line_2" => ArrayHelper::get($field, 'address2', ''), "city" => ArrayHelper::get($field, 'city', ''), "state" => ArrayHelper::get($field, 'state', ''), "zip" => ArrayHelper::get($field, 'postal', ''), "country" => ArrayHelper::get($field, 'country', ''), ]; } elseif ("input_file" == $type && $value = ArrayHelper::get($field, 'value')) { $finalValue = $this->migrateFilesAndGetUrls($value); } if (null == $finalValue) { $finalValue = ""; } $entry[$name] = $finalValue; } if ($submission->date) { $entry['created_at'] = $submission->date; } if ($submission->date_modified) { $entry['updated_at'] = $submission->date_modified; } if ($submission->starred) { $entry['is_favourite'] = $submission->starred; } if ($submission->viewed) { $entry['status'] = 'read'; } $entries[] = $entry; } return $entries; } protected function getSubmissionNameValue($nameFields, $submissionField) { $finalValue = []; foreach ($nameFields as $key => $field) { if ($name = ArrayHelper::get($field, 'attributes.name')) { $value = ""; if ("first_name" == $key) { $value = ArrayHelper::get($submissionField, 'first'); } elseif ("middle_name" == $key) { $value = ArrayHelper::get($submissionField, 'middle'); } elseif ("last_name" == $key) { $value = ArrayHelper::get($submissionField, 'last'); } $finalValue[$name] = $value; } } return $finalValue; } public function getFormsFormatted() { $forms = []; $items = $this->getForms(); foreach ($items as $item) { $forms[] = [ 'name' => $item['name'], 'id' => $item['ID'], 'imported_ff_id' => $this->isAlreadyImported($item), ]; } return $forms; } public function exist() { return !!defined('WPFORMS_VERSION'); } protected function formatFieldData($field, $type) { $args = [ 'uniqElKey' => $field['id'] . '-' . time(), 'index' => $field['id'], 'required' => ArrayHelper::isTrue($field, 'required'), 'label' => ArrayHelper::get($field, 'label', ''), 'name' => ArrayHelper::get($field, 'type') . '_' . $field['id'], 'placeholder' => ArrayHelper::get($field, 'placeholder', ''), 'class' => '', 'value' => ArrayHelper::get($field, 'default_value') ?: "", 'help_message' => ArrayHelper::get($field, 'description', ''), 'container_class' => ArrayHelper::get($field, 'css', ''), ]; switch ($type) { case 'input_text': if (ArrayHelper::isTrue($field, 'limit_enabled')) { $max_length = ArrayHelper::get($field, 'limit_count', ''); $mode = ArrayHelper::get($field, 'limit_mode', ''); if ("words" == $mode && $max_length) { $max_length = (int)$max_length * 6; // average 6 characters is a word } $args['maxlength'] = $max_length; } break; case 'phone': $args['valid_phone_number'] = "1"; break; case 'input_name': $args['input_name_args'] = []; $fields = ArrayHelper::get($field, 'format'); if (!$fields) { break; } $fields = explode('-', $fields); $required = ArrayHelper::isTrue($field, 'required'); foreach ($fields as $subField) { if ($subField == 'simple') { $label = $args['label']; $subName = 'first_name'; $hideLabel = ArrayHelper::isTrue($field, 'label_hide'); } else { $subName = $subField . '_name'; $label = ucfirst($subField); $hideLabel = ArrayHelper::isTrue($field, 'sublabel_hide'); } $placeholder = ArrayHelper::get($field, $subField . "_placeholder" , ''); $default = ArrayHelper::get($field, $subField . "_default" , ''); $args['input_name_args'][$subName] = [ "visible" => true, "required" => $required, "name" => $subName, "default" => $default, ]; if (!$hideLabel) { $args['input_name_args'][$subName]['label'] = $label; } if ($placeholder) { $args['input_name_args'][$subName]['placeholder'] = $placeholder; } } break; case 'select': case 'input_radio': case 'input_checkbox': list($options, $defaultVal) = $this->getOptions(ArrayHelper::get($field, 'choices', [])); $args['options'] = $options; $args['randomize_options'] = ArrayHelper::isTrue($field, 'random'); if ($type == 'select') { $isMulti = ArrayHelper::isTrue($field, 'multiple'); if ($isMulti) { $args['multiple'] = true; $args['value'] = $defaultVal; } else { $args['value'] = array_shift($defaultVal) ?: ""; } } elseif ($type == 'input_checkbox') { $args['value'] = $defaultVal; } elseif ($type == 'input_radio') { $args['value'] = array_shift($defaultVal) ?: ""; } break; case 'input_date': $format = ArrayHelper::get($field, 'format'); if ("date" == $format) { $format = ArrayHelper::get($field, 'date_format', 'd/m/Y'); } elseif ("time" == $format) { $format = ArrayHelper::get($field, 'time_format', 'H:i'); } else { $format = ArrayHelper::get($field, 'date_format', 'd/m/Y') . ' ' .ArrayHelper::get($field, 'time_format', 'H:i'); } $args['format'] = $format; break; case 'rangeslider': $args['step'] = $field['step']; $args['min'] = $field['min']; $args['max'] = $field['max']; break; case 'ratings': $number = ArrayHelper::get($field, 'scale', 5); $args['options'] = array_combine(range(1, $number), range(1, $number)); break; case 'input_file': $args['allowed_file_types'] = $this->getFileTypes($field, 'extensions'); $args['max_size_unit'] = 'MB'; $max_size = ArrayHelper::get($field, 'max_size') ?: 1; $args['max_file_size'] = ceil( $max_size * 1048576); // 1MB = 1048576 Bytes $args['max_file_count'] = ArrayHelper::get($field, 'max_file_number', 1); $args['upload_btn_text'] = ArrayHelper::get($field, 'label', 'File Upload'); break; case 'custom_html': $args['html_codes'] = ArrayHelper::get($field, 'code', ''); break; case 'form_step': $this->hasStep = true; break; case 'address': $args['address_args'] = $this->getAddressArgs($field, $args); break; case 'rich_text_input': $size = ArrayHelper::get($field, 'size'); if ('small' == $size) { $rows = 2; } elseif ('large' == $size) { $rows = 5; } else { $rows =3; } $args['rows'] = $rows; break; case 'section_break': $args['section_break_desc'] = ArrayHelper::get($field, 'description'); break; case 'input_number': $args['min'] = ''; $args['max'] = ''; break; default : break; } return $args; } private function fieldTypeMap() { return [ 'email' => 'email', 'text' => 'input_text', 'name' => 'input_name', 'hidden' => 'input_hidden', 'textarea' => 'input_textarea', 'select' => 'select', 'radio' => 'input_radio', 'checkbox' => 'input_checkbox', 'number' => 'input_number', 'layout' => 'container', 'date-time' => 'input_date', 'address' => 'address', 'password' => 'input_password', 'html' => 'custom_html', 'rating' => 'ratings', 'divider' => 'section_break', 'url' => 'input_url', 'multi_select' => 'multi_select', 'number-slider' => 'rangeslider', 'richtext' => 'rich_text_input', 'phone' => 'phone', 'file-upload' => 'input_file', 'pagebreak' => 'form_step', ]; } private function getConfirmations($form, $defaultValues) { $confirmations = ArrayHelper::get($form, 'settings.confirmations'); $confirmationsFormatted = []; if (!empty($confirmations)) { foreach ($confirmations as $confirmation) { $type = $confirmation['type']; if ($type == 'redirect') { $redirectTo = 'customUrl'; } else { if ($type == 'page') { $redirectTo = 'customPage'; } else { $redirectTo = 'samePage'; } } $confirmationsFormatted[] = wp_parse_args( [ 'name' => ArrayHelper::get($confirmation, 'name'), 'messageToShow' => $this->getResolveShortcode(ArrayHelper::get($confirmation, 'message'), $form), 'samePageFormBehavior' => 'hide_form', 'redirectTo' => $redirectTo, 'customPage' => intval(ArrayHelper::get($confirmation, 'page')), 'customUrl' => ArrayHelper::get($confirmation, 'redirect'), 'active' => true, 'conditionals' => $this->getConditionals($confirmation, $form) ], $defaultValues ); } } return $confirmationsFormatted; } private function getConditionals($notification, $form) { $conditionals = ArrayHelper::get($notification, 'conditionals', []); $status = ArrayHelper::isTrue($notification, 'conditional_logic'); if ('stop' == ArrayHelper::get($notification, 'conditional_type')) { $status = false; } $type = 'all'; $conditions = []; if ($conditionals) { if (count($conditionals) > 1) { $type = 'any'; $conditionals = array_filter(array_column($conditionals, 0)); } else { $conditionals = ArrayHelper::get($conditionals, 0, []); } foreach ($conditionals as $condition) { $fieldId = ArrayHelper::get($condition, 'field'); list ($fieldName, $fieldType) = $this->getFormFieldName($fieldId, $form); if (!$fieldName) { continue; } if ($operator = $this->getResolveOperator(ArrayHelper::get($condition, 'operator', ''))) { $value = ArrayHelper::get($condition, 'value', ''); if ( in_array($fieldType, ['select', 'multi_select', 'input_radio', 'input_checkbox']) && $choices = ArrayHelper::get($form, "fields.$fieldId.choices") ) { $choiceValue = ArrayHelper::get($choices, "$value.value", ''); if (!$choiceValue) { $choiceValue = ArrayHelper::get($choices, "$value.label", ''); } $value = $choiceValue; } $conditions[] = [ 'field' => $fieldName, 'operator' => $operator, 'value' => $value ]; } } } return [ "status" => $status, "type" => $type, 'conditions' => $conditions ]; } private function getAdvancedValidation(): array { return [ 'status' => false, 'type' => 'all', 'conditions' => [ [ 'field' => '', 'operator' => '=', 'value' => '' ] ], 'error_message' => '', 'validation_type' => 'fail_on_condition_met' ]; } private function getNotifications($form) { $notificationsFormatted = []; $enabled = ArrayHelper::isTrue($form, 'settings.notification_enable'); $notifications = ArrayHelper::get($form, 'settings.notifications'); foreach ($notifications as $notification) { $email = ArrayHelper::get($notification, 'email', ''); $sendTo = [ 'type' => 'email', 'email' => '{wp.admin_email}', 'field' => '', 'routing' => [], ]; if ($this->isFormField($email)) { list($fieldName) = $this->getFormFieldName($email, $form); $sendTo['type'] = 'field'; $sendTo['field'] = $fieldName; $sendTo['email'] = ''; } else { if ($email) { $sendTo['email'] = $this->getResolveShortcode($email, $form); } } $message = $this->getResolveShortcode(ArrayHelper::get($notification, 'message', ''), $form); $replyTo = $this->getResolveShortcode(ArrayHelper::get($notification, 'replyto', ''), $form); $notificationsFormatted[] = [ 'sendTo' => $sendTo, 'enabled' => $enabled, 'name' => ArrayHelper::get($notification, 'notification_name', 'Admin Notification'), 'subject' => $this->getResolveShortcode(ArrayHelper::get($notification, 'subject', 'Notification'), $form), 'to' => $sendTo['email'], 'replyTo' => $replyTo ?: '{wp.admin_email}', 'message' => str_replace("\n", "