# e2pdf/1.05.03/classes/extension/e2pdf-caldera.php

E2Pdf – Export Pdf Tool for WordPress, version 1.05.03. 1,426 lines.

- Page: https://pluginprobe.com/plugins/e2pdf/1.05.03/code/classes/extension/e2pdf-caldera.php
- Raw: https://pluginprobe.com/plugins/e2pdf/1.05.03/raw/classes/extension/e2pdf-caldera.php
- Modified: 2019-03-12T13:29:06+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/e2pdf/1.05.03/code/classes/extension/e2pdf-caldera.php#L10-L20`.

```php
<?php

/**
 * E2pdf Caldera Extension
 * 
 * @copyright  Copyright 2017 https://e2pdf.com
 * @license    GPL v2
 * @version    1
 * @link       https://e2pdf.com
 * @since      0.01.47
 */
if (!defined('ABSPATH')) {
    die('Access denied.');
}

class Extension_E2pdf_Caldera extends Model_E2pdf_Model {

    private $options;
    private $info = array(
        'key' => 'caldera',
        'title' => 'Caldera Forms'
    );

    function __construct() {
        parent::__construct();
    }

    /**
     * Get info about extension
     * 
     * @param string $key - Key to get assigned extension info value
     * 
     * @return array|string - Extension Key and Title or Assigned extension info value
     */
    public function info($key = false) {
        if ($key && isset($this->info[$key])) {
            return $this->info[$key];
        } else {
            return array(
                $this->info['key'] => $this->info['title']
            );
        }
    }

    /**
     * Check if needed plugin active
     * 
     * @return bool - Activated/Not Activated plugin
     */
    public function active() {

        if (!function_exists('is_plugin_active')) {
            include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        }

        if (is_plugin_active('caldera-forms/caldera-core.php')) {
            return true;
        }
        return false;
    }

    /**
     * Set option
     * 
     * @param string $key - Key of option
     * @param string $value - Value of option
     * 
     * @return bool - Status of setting option
     */
    public function set($key, $value) {
        if (!isset($this->options)) {
            $this->options = new stdClass();
        }

        $this->options->$key = $value;
        return true;
    }

    /**
     * Get option by key
     * 
     * @param string $key - Key to get assigned option value
     * 
     * @return mixed
     */
    public function get($key) {
        if (isset($this->options->$key)) {
            $value = $this->options->$key;
            return $value;
        } else {
            return false;
        }
    }

    /**
     * Get items to work with
     * 
     * @return array() - List of available items
     */
    public function items() {
        $content = array();
        if (class_exists("Caldera_Forms_Forms")) {
            $forms = Caldera_Forms_Forms::get_forms(true);
            if ($forms) {
                foreach ($forms as $key => $value) {
                    $content[] = $this->item($value['ID']);
                }
            }
        }
        return $content;
    }

    /**
     * Get entries for export
     * 
     * @param int $item - Form ID
     * @param string $name - Entries names
     * 
     * @return array() - Entries list
     */
    public function datasets($item = false, $name = false) {

        $datasets = array();

        if (class_exists("Caldera_Forms_Admin") && $item) {

            $form = Caldera_Forms_Admin::get_entries($item, 1, 9999999999);

            if ($form && isset($form['entries']) && is_array($form['entries'])) {
                foreach ($form['entries'] as $key => $dataset) {
                    $this->set('item', $item);
                    $this->set('dataset', $dataset['_entry_id']);

                    $dataset_title = $this->render($name);
                    if (!$dataset_title) {
                        $dataset_title = $dataset['_date'];
                    }
                    $datasets[] = array(
                        'key' => $dataset['_entry_id'],
                        'value' => $dataset_title
                    );
                }
            }
        }


        return $datasets;
    }

    /**
     * Get dataset
     * 
     * @param int $dataset - Dataset ID
     * 
     * @return object - Dataset
     */
    public function dataset($dataset = false) {
        $dataset = (int) $dataset;

        if (!$dataset) {
            return false;
        }

        $data = new stdClass();
        $data->url = false;

        return $data;
    }

    /**
     * Get item
     * 
     * @param string $item - Item ID
     * 
     * @return object - Item
     */
    public function item($item = false) {

        $form = new stdClass();

        if (!$item && $this->get('item')) {
            $item = $this->get('item');
        }

        $caldera_form = false;
        if (class_exists('Caldera_Forms_Forms')) {
            $caldera_form = Caldera_Forms_Forms::get_form($item);
        }

        if ($caldera_form) {
            $form->id = (string) $caldera_form['ID'];
            $form->url = $this->helper->get_url(array('page' => 'caldera-forms', 'edit' => $caldera_form['ID']));
            $form->name = $caldera_form['name'];
        } else {
            $form->id = '';
            $form->url = 'javascript:void(0);';
            $form->name = '';
        }
        return $form;
    }

    /**
     * Render value according to content
     * 
     * @param string $value - Content
     * @param string $type - Type of rendering value
     * @param array $field - Field details
     * 
     * @return string - Fully rendered value
     */
    public function render($value, $type = false, $field = array()) {

        $value = $this->render_shortcodes($value, $type, $field);
        $value = $this->strip_shortcodes($value);

        if ($type === 'value' && isset($field['type']) && $field['type'] === 'e2pdf-checkbox' && isset($field['properties']['option'])) {
            $option = $this->render($field['properties']['option']);
            $options = explode(', ', $value);
            $option_options = explode(', ', $option);
            if (is_array($options) && is_array($option_options) && !array_diff($option_options, $options)) {
                return $option;
            } else {
                return "";
            }
        }

        if ($type === 'value') {
            $value = $this->convert_shortcodes($value, true);
        }

        return $value;
    }

    /**
     * Render shortcodes which available in this extension
     * 
     * @param string $value - Content
     * @param string $type - Type of rendering value
     * @param array $field - Field details
     * 
     * @return string - Value with rendered shortcodes
     */
    public function render_shortcodes($value, $type = false, $field = array()) {

        $dataset = $this->get('dataset');

        if ($this->verify()) {
            if (false !== strpos($value, '[')) {

                $shortcode_tags = array(
                    'e2pdf-format-number',
                    'e2pdf-format-date',
                    'e2pdf-format-output',
                );
                preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $value, $matches);
                $tagnames = array_intersect($shortcode_tags, $matches[1]);

                if (!empty($tagnames)) {

                    $pattern = get_shortcode_regex($tagnames);
                    preg_match_all("/$pattern/", $value, $shortcodes);
                    foreach ($shortcodes[0] as $key => $shortcode_value) {
                        $shortcode = array();
                        $shortcode[1] = $shortcodes[1][$key];
                        $shortcode[2] = $shortcodes[2][$key];
                        $shortcode[3] = $shortcodes[3][$key];
                        $shortcode[4] = $shortcodes[4][$key];
                        $shortcode[5] = $shortcodes[5][$key];
                        $shortcode[6] = $shortcodes[6][$key];

                        if (isset($shortcode['5'])) {
                            if (isset($field['type']) && ($field['type'] === 'e2pdf-image' || $field['type'] === 'e2pdf-signature')) {
                                $sub_value = $this->render($shortcode['5'], $type);
                            } else {
                                $sub_value = $this->render($shortcode['5'], $type, $field);
                            }
                            $value = str_replace($shortcode_value, "[" . $shortcode['2'] . $shortcode['3'] . "]" . $sub_value . "[/" . $shortcode['2'] . "]", $value);
                        }
                    }
                }
            }

            $value = do_shortcode($value);

            add_filter('caldera_forms_magic_form', array($this, 'filter_caldera_forms_magic_form'), 30, 2);
            add_filter('caldera_forms_render_get_field', array($this, 'filter_caldera_forms_render_get_field'), 30, 2);
            add_filter('caldera_forms_do_field_magic_value', array($this, 'filter_caldera_forms_do_field_magic_value'), 30, 4);

            global $form;
            $tmp_form = false;
            if ($form && isset($form['ID'])) {
                $tmp_form = $form;
                if ($form['ID'] != $this->get('item')) {
                    $form = Caldera_Forms_Forms::get_form($this->get('item'));
                }
                if (!empty($form['is_connected_form'])) {
                    $form['processors']['_connected_form'] = array(
                        'type' => 'form-connector',
                        'runtimes' => array(
                            'insert' => true
                        ),
                        'config' => array()
                    );

                    // setup fields
                    $form_fields = array();
                    // get meta
                    $meta = Caldera_Forms::get_entry_meta((int) $dataset, $form);

                    if (!empty($meta['form-connector']['data']['_connected_form']['entry']['form']['meta_value'])) {
                        foreach ((array) $meta['form-connector']['data']['_connected_form']['entry']['form']['meta_value'] as $form_meta) {
                            $form_fields = array_merge($form_fields, $form_meta);
                        }
                    }

                    if (!empty($form['condition_points']['forms'])) {
                        $form['fields'] = array();
                        foreach ($form['condition_points']['forms'] as $connected_id => $connected_form) {
                            if (!empty($form_fields[$connected_id]) && !empty($connected_form['fields'])) {
                                $form['fields'] = array_merge($form['fields'], $connected_form['fields']);
                            }
                        }

                        if (function_exists('cf_form_connector_setup_processors_meta')) {
                            add_filter('caldera_forms_get_entry_detail', 'cf_form_connector_setup_processors_meta', 10, 3);
                        }
                    }
                }
            }

            $value = Caldera_Forms::do_magic_tags($value, $dataset);

            if ($tmp_form) {
                $form = $tmp_form;
            }

            if (isset($field['type']) && ($field['type'] === 'e2pdf-image' || $field['type'] === 'e2pdf-signature')) {
                $esig = isset($field['properties']['esig']) && $field['properties']['esig'] ? true : false;
                if ($esig) {
                    //process e-signature
                    $value = "";
                } else {
                    if (!$this->helper->load('image')->get_image($value)) {
                        $value = $this->strip_shortcodes($value);
                        if (
                                $value &&
                                trim($value) != "" &&
                                extension_loaded('gd') &&
                                function_exists('imagettftext')
                        ) {
                            if (isset($field['properties']['text_color']) && $field['properties']['text_color']) {
                                $penColour = $this->helper->load('convert')->to_hex_color($field['properties']['text_color']);
                            } else {
                                $penColour = array(0x14, 0x53, 0x94);
                            }

                            $default_options = array(
                                'imageSize' => array(isset($field['width']) ? $field['width'] : '400', isset($field['height']) ? $field['height'] : '150'),
                                'bgColour' => 'transparent',
                                'penColour' => $penColour
                            );

                            $options = array();
                            $options = array_merge($default_options, $options);

                            $model_e2pdf_font = new Model_E2pdf_Font();

                            $font = false;
                            if (isset($field['properties']['text_font']) && $field['properties']['text_font']) {
                                $font = $model_e2pdf_font->get_font_path($field['properties']['text_font']);
                            }
                            if (!$font) {
                                $font = $model_e2pdf_font->get_font_path('Noto Sans');
                            }

                            $size = 150;
                            if (isset($field['properties']['text_font_size']) && $field['properties']['text_font_size']) {
                                $size = $field['properties']['text_font_size'];
                            }

                            $model_e2pdf_signature = new Model_E2pdf_Signature();
                            $value = $model_e2pdf_signature->ttf_signature($value, $size, $font, $options);
                        } else {
                            $value = "";
                        }
                    }
                }
            } else {
                $value = $this->convert_shortcodes($value);
            }

            remove_filter('caldera_forms_magic_form', array($this, 'filter_caldera_forms_magic_form'), 30);
            remove_filter('caldera_forms_render_get_field', array($this, 'filter_caldera_forms_render_get_field'), 30);
            remove_filter('caldera_forms_do_field_magic_value', array($this, 'filter_caldera_forms_do_field_magic_value'), 30);
        }

        return $value;
    }

    /**
     * Strip unused shortcodes
     * 
     * @param string $value - Content
     * 
     * @return string - Value with removed unused shortcodes
     */
    public function strip_shortcodes($value) {
        $value = preg_replace('~(?:\[/?)[^/\]]+/?\]~s', "", $value);
        $value = preg_replace('~(?:%/?)[^/%]+/?%~s', "", $value);
        return $value;
    }

    public function convert_shortcodes($value, $to = false) {
        if ($value) {
            if ($to) {
                $value = str_replace("&#91;", "[", $value);
                //$value = str_replace("&#37;", "%", $value);
            } else {
                $value = str_replace("[", "&#91;", $value);
                //$value = str_replace("%", "&#37;", $value);
            }
        }
        return $value;
    }

    public function verify() {
        $item = $this->get('item');
        $dataset = $this->get('dataset');

        if ($item && $dataset && class_exists('Caldera_Forms_Entry') && class_exists('Caldera_Forms_Forms') && class_exists("Caldera_Forms")) {
            $form = Caldera_Forms_Forms::get_form($item);
            if ($form && isset($form['_last_updated'])) {
                $entry = new Caldera_Forms_Entry($form, $dataset);
                if ($entry->found()) {
                    return true;
                }
            }
        }
        return false;
    }

    public function add_form($template) {
        if ($template->get('ID')) {

            $form = array(
                'success' => sprintf(__('Success. [e2pdf-download id="%s"]', 'e2pdf'), $template->get('ID')),
                'name' => $template->get('title'),
                'fields' => array(),
                'layout_grid' => array(
                    'fields' => array(),
                    'strucutre' => ''
                )
            );

            $pages = $template->get('pages');
            $checkboxes = array();
            $radios = array();

            foreach ($pages as $page_key => $page) {
                if (isset($page['elements']) && !empty($page['elements'])) {

                    foreach ($page['elements'] as $element_key => $element) {
                        if ($element['type'] == 'e2pdf-input' || $element['type'] == 'e2pdf-signature') {

                            $field_id = 'fld_' . $this->random();
                            $form['fields'][$field_id] = array(
                                'ID' => $field_id,
                                'slug' => 'element_' . $element['element_id'],
                                'type' => 'text',
                                'label' => $element['value'] ? '%element_' . $element['element_id'] . '% ' . $element['value'] : '%element_' . $element['element_id'] . '%',
                            );
                            $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $element['element_id'] . '%';
                            if (isset($element['properties']['esig'])) {
                                unset($pages[$page_key]['elements'][$element_key]['properties']['esig']);
                            }
                        } elseif ($element['type'] == 'e2pdf-textarea') {

                            $field_id = 'fld_' . $this->random();
                            $form['fields'][$field_id] = array(
                                'ID' => $field_id,
                                'slug' => 'element_' . $element['element_id'],
                                'type' => 'paragraph',
                                'label' => $element['value'] ? '%element_' . $element['element_id'] . '% ' . $element['value'] : '%element_' . $element['element_id'] . '%',
                            );
                            $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $element['element_id'] . '%';
                        } elseif ($element['type'] == 'e2pdf-select') {

                            $options = array();
                            $field_options = array();

                            if (isset($element['properties']['options'])) {
                                $field_options = explode("\n", $element['properties']['options']);
                                foreach ($field_options as $option) {
                                    $option_id = 'opt' . $this->random();
                                    $options[$option_id] = array(
                                        'calc_value' => '',
                                        'label' => $option,
                                        'value' => $option
                                    );
                                }
                            }

                            $field_id = 'fld_' . $this->random();
                            $form['fields'][$field_id] = array(
                                'ID' => $field_id,
                                'slug' => 'element_' . $element['element_id'],
                                'type' => 'dropdown',
                                'label' => '%element_' . $element['element_id'] . '%',
                                'config' => array(
                                    'option' => $options
                                )
                            );

                            $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $element['element_id'] . '%';
                        } elseif ($element['type'] == 'e2pdf-checkbox') {
                            $field_key = array_search($element['name'], array_column($checkboxes, 'name'));
                            if ($field_key !== false) {
                                $option_id = 'opt' . $this->random();
                                $checkboxes[$field_key]['options'][$option_id] = array(
                                    'calc_value' => $element['properties']['option'],
                                    'label' => $element['properties']['option'],
                                    'value' => $element['properties']['option'],
                                );
                                $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $checkboxes[$field_key]['element_id'] . '%';
                            } else {

                                $option_id = 'opt' . $this->random();

                                $checkboxes[] = array(
                                    'name' => $element['name'],
                                    'element_id' => $element['element_id'],
                                    'options' => array(
                                        $option_id => array(
                                            'calc_value' => $element['properties']['option'],
                                            'label' => $element['properties']['option'],
                                            'value' => $element['properties']['option'],
                                        ),
                                    )
                                );

                                $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $element['element_id'] . '%';
                            }
                        } elseif ($element['type'] == 'e2pdf-radio') {
                            $field_key = array_search($element['name'], array_column($radios, 'name'));
                            if ($field_key !== false) {
                                $option_id = 'opt' . $this->random();
                                $radios[$field_key]['options'][$option_id] = array(
                                    'calc_value' => $element['properties']['option'],
                                    'label' => $element['properties']['option'],
                                    'value' => $element['properties']['option'],
                                );
                                $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $radios[$field_key]['element_id'] . '%';
                            } else {

                                $option_id = 'opt' . $this->random();

                                $radios[] = array(
                                    'name' => $element['name'],
                                    'element_id' => $element['element_id'],
                                    'options' => array(
                                        $option_id => array(
                                            'calc_value' => $element['properties']['option'],
                                            'label' => $element['properties']['option'],
                                            'value' => $element['properties']['option'],
                                        ),
                                    )
                                );

                                $pages[$page_key]['elements'][$element_key]['value'] = '%element_' . $element['element_id'] . '%';
                            }
                        }
                    }
                }
            }

            foreach ($checkboxes as $element) {
                $field_id = 'fld_' . $this->random();
                $form['fields'][$field_id] = array(
                    'ID' => $field_id,
                    'slug' => 'element_' . $element['element_id'],
                    'type' => 'checkbox',
                    'label' => '%element_' . $element['element_id'] . '%',
                    'config' => array(
                        'option' => $element['options']
                    )
                );
            }

            foreach ($radios as $element) {
                $field_id = 'fld_' . $this->random();
                $form['fields'][$field_id] = array(
                    'ID' => $field_id,
                    'slug' => 'element_' . $element['element_id'],
                    'type' => 'radio',
                    'label' => '%element_' . $element['element_id'] . '%',
                    'config' => array(
                        'option' => $element['options']
                    )
                );
            }

            $fields = array_keys($form['fields']);
            $x = 1;
            foreach ($fields as $field) {
                $form['layout_grid']['fields'][$field] = $x . ':1';
                if ($x == 1) {
                    $form['layout_grid']['structure'] .= '12';
                } else {
                    $form['layout_grid']['structure'] .= '|12';
                }
                $x++;
            }

            if ($item = Caldera_Forms_Forms::create_form($form)) {
                $template->set('item', $item['ID']);
                $template->set('pages', $pages);
            }
        }
        return $template;
    }

    private function random() {
        return round((float) rand() / (float) getrandmax() * 10000000);
    }

    public function visual_mapper() {

        $item = $this->get('item');
        $forms = array();
        $source = '';
        $html = '';

        if ($item && class_exists("Caldera_Forms") && class_exists("Caldera_Forms_Forms") && class_exists("Caldera_Forms_Field_Util")) {

            $form = Caldera_Forms_Forms::get_form($item);
            if (!empty($form['is_connected_form']) && isset($form['node']) && !empty($form['node'])) {
                foreach ($form['node'] as $node) {
                    if (isset($node['form']) && $node['form']) {
                        $source .= Caldera_Forms::render_form($node['form']);
                        $forms[] = Caldera_Forms_Forms::get_form($node['form']);
                    }
                }
            } else {
                $source = Caldera_Forms::render_form($item);
            }

            if ($source) {
                libxml_use_internal_errors(true);
                $dom = new DOMDocument();
                if (function_exists('mb_convert_encoding')) {
                    $html = $dom->loadHTML(mb_convert_encoding($source, 'HTML-ENTITIES', 'UTF-8'));
                } else {
                    $html = $dom->loadHTML('<?xml encoding="UTF-8">' . $source);
                }
                libxml_clear_errors();
            }

            if (!$source) {
                return __('Form source is empty', 'e2pdf');
            } elseif (!$html) {
                return __('Form could not be parsed due incorrect HTML', 'e2pdf');
            } else {

                $xpath = new DomXPath($dom);

                $remove_by_class = array(
                    'live-gravatar',
                );
                foreach ($remove_by_class as $key => $class) {
                    $elements = $xpath->query("//*[contains(@class, '{$class}')]");
                    foreach ($elements as $element) {
                        $element->parentNode->removeChild($element);
                    }
                }

                $remove_by_tag = array(
                    'script'
                );
                foreach ($remove_by_tag as $key => $tag) {
                    $elements = $xpath->query("//{$tag}");
                    foreach ($elements as $element) {
                        $element->parentNode->removeChild($element);
                    }
                }

                // Replace names
                $fields = $xpath->query("//*[contains(@name, 'fld_')]");
                foreach ($fields as $element) {
                    if ($element->attributes->getNamedItem("type")->nodeValue == 'checkbox') {
                        preg_match("/(.*?)\[(.*?)\]/i", $element->attributes->getNamedItem("name")->nodeValue, $matches);
                        if (isset($matches[1])) {
                            $field_id = $matches[1];
                        }
                    } else {
                        $field_id = $element->attributes->getNamedItem("name")->nodeValue;
                    }

                    // Modify Star field
                    if ($element->attributes->getNamedItem("data-type")->nodeValue == 'star') {
                        if ($element->attributes->getNamedItem("style")) {
                            $element->attributes->getNamedItem("style")->nodeValue = '';
                        }
                    }

                    // Modify Range field
                    if ($element->attributes->getNamedItem("type")->nodeValue == 'range') {

                        if ($element->parentNode->attributes->getNamedItem("style")) {
                            $element->parentNode->attributes->getNamedItem("style")->nodeValue = '';
                        }

                        if ($element->parentNode->attributes->getNamedItem("class")) {
                            $element->parentNode->attributes->getNamedItem("class")->nodeValue = 'col-xs-12';
                        }

                        $next_element = $xpath->query(".//following-sibling::div[1]", $element->parentNode)->item(0);
                        $next_element->parentNode->removeChild($next_element);
                    }

                    if (!empty($form['is_connected_form'])) {
                        foreach ($forms as $sub_form) {
                            $field = Caldera_Forms_Field_Util::get_field($field_id, $sub_form);
                            if ($field && isset($field['slug'])) {
                                if ($element->attributes->getNamedItem("name")) {
                                    $element->attributes->getNamedItem("name")->nodeValue = "%" . $field['slug'] . "%";
                                }
                                break;
                            }
                        }
                    } else {
                        $field = Caldera_Forms_Field_Util::get_field($field_id, $form);
                        if ($field && isset($field['slug'])) {
                            if ($element->attributes->getNamedItem("name")) {
                                $element->attributes->getNamedItem("name")->nodeValue = "%" . $field['slug'] . "%";
                            }
                        }
                    }
                }

                // Convert Calculation Fields
                $calculation_fields = $xpath->query("//input[@data-type='calculation']");
                foreach ($calculation_fields as $calculation_field) {

                    if ($calculation_field->attributes->getNamedItem("type")) {
                        $calculation_field->attributes->getNamedItem("type")->nodeValue = 'text';
                    }

                    $calculation_text = $xpath->query(".//h3", $calculation_field->parentNode)->item(0);
                    $calculation_field->parentNode->removeChild($calculation_text);
                }

                // Modify Toggle Fields
                $toggle_gorups = $xpath->query("//*[contains(@class, 'cf-toggle-switch')]");
                foreach ($toggle_gorups as $toogle_group) {
                    $toggle_elements = $xpath->query(".//*[contains(@class, 'cf-toggle-group-buttons')]//a", $toogle_group);
                    foreach ($toggle_elements as $toggle_element) {
                        $toggle_id = $toggle_element->attributes->getNamedItem("id")->nodeValue;

                        $radio = $toggle_elements = $xpath->query(".//input[@id='{$toggle_id}']", $toogle_group)->item(0);

                        if ($radio) {
                            $radio_cloned = $radio->cloneNode(true);

                            $attr = $dom->createAttribute('style');
                            $attr->value = 'position: absolute;width: 100%;top: 0;left: 0;height: 100%; opacity: 0;';
                            $radio_cloned->appendChild($attr);

                            $toggle_element->appendChild($radio_cloned);
                        }
                    }
                }

                // Modify Advanced File Upload
                $advanced_uploaders = $xpath->query("//*[contains(@class, 'cf-uploader-trigger')]");
                foreach ($advanced_uploaders as $advanced_uploader) {
                    $input = $xpath->query(".//input[@type='hidden']", $advanced_uploader->parentNode)->item(0);

                    $attr = $dom->createAttribute('style');
                    $attr->value = 'position: relative;';
                    $advanced_uploader->appendChild($attr);

                    if ($input) {
                        $input_cloned = $input->cloneNode(true);
                        $attr = $dom->createAttribute('style');
                        $attr->value = 'position: absolute;width: 100%;top: 0;left: 0;height: 100%; opacity: 0;';
                        $input_cloned->appendChild($attr);

                        if ($input_cloned->attributes->getNamedItem('type')) {
                            $input_cloned->attributes->getNamedItem('type')->nodeValue = 'text';
                        }

                        $advanced_uploader->appendChild($input_cloned);
                    }
                }

                // Remove unecessary elements
                $submit_buttons = $xpath->query("//input[@type='submit']");
                foreach ($submit_buttons as $submit_button) {
                    $submit_button->parentNode->removeChild($submit_button);
                }
                return $dom->saveHTML();
            }
        }
        return false;
    }

    /**
     * Auto Generate of Template for this extension
     * 
     * @return array - List of elements
     */
    public function auto() {

        $response = array();
        $elements = array();
        $fields = array();
        $forms = array();

        $item = $this->get('item');

        if (class_exists("Caldera_Forms_Forms")) {
            $form = Caldera_Forms_Forms::get_form($item);
            if (!empty($form['is_connected_form']) && isset($form['node']) && !empty($form['node'])) {
                foreach ($form['node'] as $node) {
                    if (isset($node['form']) && $node['form']) {
                        $sub_form = Caldera_Forms_Forms::get_form($node['form']);
                        $forms[] = $sub_form;
                        if ($sub_form && isset($sub_form['fields']) && is_array($sub_form['fields'])) {
                            $fields = array_merge($fields, $sub_form['fields']);
                        }
                    }
                }
            } else {
                $forms[] = $form;
                $fields = $form['fields'];
            }

            foreach ($forms as $sub_form) {
                if ($sub_form && isset($sub_form['layout_grid']['structure']) && isset($sub_form['layout_grid']['fields'])) {
                    $struct = explode('|', $sub_form['layout_grid']['structure']);
                    foreach ($struct as $row_num => $row) {

                        $float = false;
                        $columns = explode(':', $row);
                        foreach ($columns as $column_num => $column) {
                            $column_fields = array_keys($sub_form['layout_grid']['fields'], ( $row_num + 1) . ':' . ( $column_num + 1));

                            $width = 100 / (12 / $column) . "%";

                            foreach ($column_fields as $column_field_key) {
                                if (isset($fields[$column_field_key])) {
                                    $field = $fields[$column_field_key];

                                    switch ($field['type']) {
                                        case 'text':
                                        case 'email':
                                        case 'phone_better':
                                        case 'phone_better':
                                        case 'number':
                                        case 'phone':
                                        case 'url':
                                        case 'date_picker':
                                        case 'color_picker':
                                        case 'credit_card_number':
                                        case 'credit_card_exp':
                                        case 'credit_card_cvc':
                                        case 'calculation':
                                        case 'range_slider':
                                        case 'star_rating':
                                        case 'utm':
                                        case 'file':
                                        case 'advanced_file':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-input',
                                                'properties' => array(
                                                    'top' => '5',
                                                    'width' => '100%',
                                                    'height' => 'auto',
                                                    'value' => "%{$field['slug']}%",
                                                )
                                            ));
                                            break;

                                        case 'paragraph':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-textarea',
                                                'properties' => array(
                                                    'top' => '5',
                                                    'width' => '100%',
                                                    'height' => '150',
                                                    'value' => "%{$field['slug']}%",
                                                )
                                            ));
                                            break;

                                        case 'wysiwyg':
                                        case 'html':
                                        case 'summary':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'properties' => array(
                                                    'top' => '5',
                                                    'width' => '100%',
                                                    'height' => '150',
                                                    'value' => "%{$field['slug']}%",
                                                )
                                            ));
                                            break;

                                        case 'dropdown':
                                        case 'filtered_select2':
                                        case 'states':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            $options_tmp = array();

                                            if (isset($field['config']['option']) && is_array($field['config']['option'])) {
                                                foreach ($field['config']['option'] as $opt_key => $option) {
                                                    if (is_array($option)) {
                                                        $options_tmp[] = $option['value'];
                                                    }
                                                }
                                            }

                                            if ($field['type'] == 'states' && defined("CFCORE_PATH")) {
                                                if (file_exists(CFCORE_PATH . "fields/states/field.php")) {
                                                    $contents = file_get_contents(CFCORE_PATH . "fields/states/field.php");
                                                    preg_match_all('/<option value="(.*?)">(.*?)<\/option>/', $contents, $matches);
                                                    if (isset($matches[1])) {
                                                        foreach ($matches[1] as $state) {
                                                            $options_tmp[] = $state;
                                                        }
                                                    }
                                                }
                                            }

                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-select',
                                                'properties' => array(
                                                    'top' => '5',
                                                    'width' => '100%',
                                                    'height' => 'auto',
                                                    'options' => implode("\n", $options_tmp),
                                                    'value' => "%{$field['slug']}%",
                                                )
                                            ));
                                            break;

                                        case 'checkbox':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            if (isset($field['config']['option']) && is_array($field['config']['option'])) {
                                                foreach ($field['config']['option'] as $opt_key => $option) {
                                                    if (is_array($option)) {
                                                        $elements[] = $this->auto_field($field, array(
                                                            'type' => 'e2pdf-checkbox',
                                                            'properties' => array(
                                                                'top' => '5',
                                                                'width' => 'auto',
                                                                'height' => 'auto',
                                                                'value' => "%{$field['slug']}%",
                                                                'option' => $option['label']
                                                            )
                                                        ));
                                                        $elements[] = $this->auto_field($field, array(
                                                            'type' => 'e2pdf-html',
                                                            'float' => true,
                                                            'properties' => array(
                                                                'left' => '5',
                                                                'width' => '100%',
                                                                'height' => 'auto',
                                                                'value' => $option['label']
                                                            )
                                                        ));
                                                    }
                                                }
                                            }
                                            break;

                                        case 'radio':
                                        case 'toggle_switch':
                                            $elements[] = $this->auto_field($field, array(
                                                'type' => 'e2pdf-html',
                                                'block' => true,
                                                'float' => $float,
                                                'properties' => array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'width' => $width,
                                                    'height' => 'auto',
                                                    'value' => $field['label'],
                                                )
                                            ));

                                            if (isset($field['config']['option']) && is_array($field['config']['option'])) {
                                                foreach ($field['config']['option'] as $opt_key => $option) {
                                                    if (is_array($option)) {
                                                        $elements[] = $this->auto_field($field, array(
                                                            'type' => 'e2pdf-radio',
                                                            'properties' => array(
                                                                'top' => '5',
                                                                'width' => 'auto',
                                                                'height' => 'auto',
                                                                'value' => "%{$field['slug']}%",
                                                                'option' => $option['label'],
                                                                'group' => "group_" . $field['slug'],
                                                            )
                                                        ));
                                                        $elements[] = $this->auto_field($field, array(
                                                            'type' => 'e2pdf-html',
                                                            'float' => true,
                                                            'properties' => array(
                                                                'left' => '5',
                                                                'width' => '100%',
                                                                'height' => 'auto',
                                                                'value' => $option['label']
                                                            )
                                                        ));
                                                    }
                                                }
                                            }
                                            break;
                                        default:
                                            /*
                                             *  Unsupported fields: section_break, live_gravatar, button 
                                             */
                                            break;
                                    }
                                }
                            }

                            $float = true;
                        }
                    }
                }
            }
        }

        $response['page'] = array(
            'bottom' => '20',
            'top' => '20',
        );

        $response['elements'] = $elements;
        return $response;
    }

    public function auto_field($field = false, $element = array()) {

        if (!$field) {
            return false;
        }

        if (!isset($element['block'])) {
            $element['block'] = false;
        }

        if (!isset($element['float'])) {
            $element['float'] = false;
        }

        return $element;
    }

    /**
     * Load actions for this extension
     */
    public function load_actions() {
        add_action('caldera_forms_submit_complete', array($this, 'action_caldera_forms_submit_complete'), 99, 3);
        add_action('caldera_forms_mailer_complete', array($this, 'action_caldera_forms_mailer_complete'), 99, 3);
    }

    /**
     * Delete attachments that were sent by email
     */
    public function action_caldera_forms_mailer_complete() {

        $files = $this->helper->get('caldera_attachments');

        if (is_array($files) && !empty($files)) {
            foreach ($files as $key => $file) {
                $this->helper->delete_dir(dirname($file) . '/');
            }
            $this->helper->deset('caldera_attachments');
        }
    }

    /**
     * Convert file and advanced_file field type to not rendered
     * 
     * @param array $field - Field
     * @param array $form - Current form 
     * 
      @return array - Updated field
     */
    public function filter_caldera_forms_render_get_field($field, $form) {
        if (isset($field['type']) && ($field['type'] == 'file' || $field['type'] == 'advanced_file')) {
            $field['config']['media_lib'] = false;
        }
        return $field;
    }

    /**
     * Fix for {entry_id}
     * 
     * @param array $form - Current form
     * @param int $entry_id - Current entry_id
     * 
      @return array - Updated form
     */
    public function filter_caldera_forms_magic_form($form, $entry_id) {
        if (class_exists("Caldera_Forms") && $entry_id) {
            Caldera_Forms::set_field_data('_entry_id', $entry_id, $form);
        }
        return $form;
    }

    /**
     * Render file and advanced_file field types to url instead image and link
     * 
     * @param string $value - Text value
     * @param array $matches - List of matches of magic tags
     * @param int $entry_id - Current entry
     * @param array $form - Current form  
     * 
     * @return string - Updated value
     */
    public function filter_caldera_forms_do_field_magic_value($value, $matches, $entry_id, $form) {

        if (class_exists('Caldera_Forms') && class_exists('Caldera_Forms_Field_Util')) {
            if (isset($matches[1])) {
                foreach ($matches[1] as $key => $tag) {

                    $part_tags = explode(':', $tag);
                    if (!empty($part_tags[1])) {
                        $tag = $part_tags[0];
                    }
                    $entry = Caldera_Forms::get_slug_data($tag, $form, $entry_id);

                    $field = false;
                    if ($entry !== null) {
                        $field = Caldera_Forms_Field_Util::get_field_by_slug($tag, $form);
                    }

                    if (Caldera_Forms_Field_Util::is_file_field($field, $form)) {
                        if (filter_var($entry, FILTER_VALIDATE_URL)) {
                            $value = $entry;
                        }
                        continue;
                    }
                    $value = str_replace($matches[0][$key], $entry, $value);
                }
            }
        }

        return $value;
    }

    /**
     * [e2pdf-view] shortcode fix
     * 
     * @param array $out - Array with response
     * @param array $form - Current form 
     * 
      @return array - Updated response
     */
    public function filter_caldera_forms_ajax_return($out, $form) {

        if (isset($out['html'])) {

            if (false === strpos($out['html'], '[')) {
                return $out;
            }

            $shortcode_tags = array(
                'e2pdf-view'
            );

            preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $form['success'], $matches);

            $tagnames = array_intersect($shortcode_tags, $matches[1]);

            if (!empty($tagnames)) {
                $pattern = get_shortcode_regex($tagnames);

                preg_match_all("/$pattern/", $out['html'], $shortcodes);
                foreach ($shortcodes[0] as $key => $shortcode_value) {

                    $shortcode = array();
                    $shortcode[1] = $shortcodes[1][$key];
                    $shortcode[2] = $shortcodes[2][$key];
                    $shortcode[3] = $shortcodes[3][$key];
                    $shortcode[4] = $shortcodes[4][$key];
                    $shortcode[5] = $shortcodes[5][$key];
                    $shortcode[6] = $shortcodes[6][$key];

                    $out['html'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $out['html']);
                }
            }
        }

        return $out;
    }

    public function action_caldera_forms_submit_complete($form, $referrer, $process_id) {
        global $form, $transdata;

        if (isset($form['success'])) {

            if (false === strpos($form['success'], '[')) {
                return;
            }

            $shortcode_tags = array(
                'e2pdf-download',
                'e2pdf-save',
                'e2pdf-view',
                'e2pdf-adobesign'
            );

            preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $form['success'], $matches);

            $tagnames = array_intersect($shortcode_tags, $matches[1]);

            if (!empty($tagnames)) {
                $pattern = get_shortcode_regex($tagnames);

                preg_match_all("/$pattern/", $form['success'], $shortcodes);
                foreach ($shortcodes[0] as $key => $shortcode_value) {

                    $shortcode = array();
                    $shortcode[1] = $shortcodes[1][$key];
                    $shortcode[2] = $shortcodes[2][$key];
                    $shortcode[3] = $shortcodes[3][$key];
                    $shortcode[4] = $shortcodes[4][$key];
                    $shortcode[5] = $shortcodes[5][$key];
                    $shortcode[6] = $shortcodes[6][$key];

                    $atts = shortcode_parse_atts($shortcode[3]);

                    if (!array_key_exists('dataset', $atts) && array_key_exists('id', $atts)) {
                        $template = new Model_E2pdf_Template();
                        $template->load($atts['id']);
                        if ($template->get('extension') === 'caldera') {
                            $dataset_id = isset($transdata['entry_id']) ? $transdata['entry_id'] : false;
                            if ($dataset_id) {
                                $atts['dataset'] = $dataset_id;
                                $shortcode[3] .= " dataset=\"{$dataset_id}\"";
                            }
                        }
                    }

                    if ($shortcode[2] === 'e2pdf-save' || $shortcode[2] === 'e2pdf-adobesign') {
                        $shortcode[3] .= " apply=\"true\"";
                    }

                    if ($shortcode[2] === 'e2pdf-view') {
                        $new_shortcode = $shortcode[2] . $shortcode[3];
                        $form['success'] = str_replace($shortcode_value, "[{$new_shortcode}]", $form['success']);
                    } else {
                        $form['success'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $form['success']);
                    }
                }
            }
        }
    }

    /**
     * Load filters for this extension
     */
    public function load_filters() {
        add_filter('caldera_forms_mailer', array($this, 'filter_caldera_forms_mailer'), 30, 3);
        add_filter('caldera_forms_ajax_return', array($this, 'filter_caldera_forms_ajax_return'), 30, 2);
    }

    public function filter_caldera_forms_mailer($mail, $data, $form) {

        if ($mail && isset($mail['message'])) {
            if (false !== strpos($mail['message'], '[')) {
                $shortcode_tags = array(
                    'e2pdf-download',
                    'e2pdf-save',
                    'e2pdf-attachment',
                    'e2pdf-adobesign'
                );

                preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $mail['message'], $matches);
                $tagnames = array_intersect($shortcode_tags, $matches[1]);

                if (!empty($tagnames)) {
                    $pattern = get_shortcode_regex($tagnames);

                    preg_match_all("/$pattern/", $mail['message'], $shortcodes);

                    foreach ($shortcodes[0] as $key => $shortcode_value) {
                        $shortcode = array();
                        $shortcode[1] = $shortcodes[1][$key];
                        $shortcode[2] = $shortcodes[2][$key];
                        $shortcode[3] = $shortcodes[3][$key];
                        $shortcode[4] = $shortcodes[4][$key];
                        $shortcode[5] = $shortcodes[5][$key];
                        $shortcode[6] = $shortcodes[6][$key];

                        $atts = shortcode_parse_atts($shortcode[3]);

                        if (!array_key_exists('dataset', $atts) && array_key_exists('id', $atts)) {
                            $template = new Model_E2pdf_Template();
                            $template->load($atts['id']);
                            if ($template->get('extension') === 'caldera') {
                                $dataset_id = isset($data['_entry_id']) ? $data['_entry_id'] : false;
                                if ($dataset_id) {
                                    $atts['dataset'] = $dataset_id;
                                    $shortcode[3] .= " dataset=\"{$dataset_id}\"";
                                }
                            }
                        }

                        if ($shortcode[2] === 'e2pdf-attachment' || $shortcode[2] === 'e2pdf-save' || $shortcode[2] === 'e2pdf-adobesign') {
                            $shortcode[3] .= " apply=\"true\"";
                        }

                        $shortcode[3] .= " filter=\"true\"";

                        if ($shortcode[2] === 'e2pdf-attachment') {
                            $file = do_shortcode_tag($shortcode);
                            if ($file) {
                                $this->helper->add('caldera_attachments', $file);
                                $mail['attachments'][] = $file;
                            }
                            $mail['message'] = str_replace($shortcode_value, '', $mail['message']);
                        } else {
                            $mail['message'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $mail['message']);
                        }
                    }
                }
            }
        }

        return $mail;
    }

    /**
     * Get styles for generating Map Field function
     * 
     * @return array - List of css files to load
     */
    public function styles() {

        $styles = array();
        if (class_exists('Caldera_Forms_Render_Assets')) {
            $url = Caldera_Forms_Render_Assets::make_url('caldera-forms-front', false);
            $styles[] = $url;
        }

        return $styles;
    }

}

```
