# e2pdf/1.01.01/classes/extension/e2pdf-divi.php

E2Pdf – Export Pdf Tool for WordPress, version 1.01.01. 1,447 lines.

- Page: https://pluginprobe.com/plugins/e2pdf/1.01.01/code/classes/extension/e2pdf-divi.php
- Raw: https://pluginprobe.com/plugins/e2pdf/1.01.01/raw/classes/extension/e2pdf-divi.php
- Modified: 2018-11-07T14:59:18+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.01.01/code/classes/extension/e2pdf-divi.php#L10-L20`.

```php
<?php

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

class Extension_E2pdf_Divi extends Model_E2pdf_Model {

    private $options;

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

    /**
     * Get info about extension
     * 
     * @return array() - Extension key and name
     */
    public function info() {
        return array(
            'divi' => __('Divi', 'e2pdf')
        );
    }

    /**
     * Check if needed plugin active
     * 
     * @return bool - Activated/Not Activated plugin
     */
    public function active() {
        if (file_exists(get_template_directory() . "/et-pagebuilder/et-pagebuilder.php")) {
            require_once(get_template_directory() . "/et-pagebuilder/et-pagebuilder.php");
            if (defined('ET_BUILDER_THEME')) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if export item function available
     * 
     * @return bool - Item export available/not available
     */
    public function export() {
        return false;
    }

    /**
     * Set option
     * 
     * @param string $attr - 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;
    }

    /**
     * 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 get_items() {
        global $wpdb;

        $helper_e2pdf_db = new Helper_E2pdf_Db();

        $condition = array(
            'post_content' => array(
                'condition' => 'LIKE',
                'value' => '%et_pb_contact_form%',
                'type' => '%s'
            ),
            'post_type' => array(
                'condition' => '<>',
                'value' => array(
                    'revision',
                    'et_pb_layout'
                ),
                'type' => '%s'
            ),
        );

        $order_condition = array(
            'orderby' => 'id',
            'order' => 'desc',
        );

        $where = $helper_e2pdf_db->prepare_where($condition);
        $orderby = $helper_e2pdf_db->prepare_orderby($order_condition);

        $posts = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . 'posts' . $where['sql'] . $orderby . "", $where['filter']));

        $forms = array();
        foreach ($posts as $key => $post) {
            if ($forms_labels = $this->get_forms($post->post_content)) {

                foreach ($forms_labels as $form_key => $form_value) {
                    $forms[] = array(
                        'key' => $form_key,
                        'value' => $form_value
                    );
                }
            }
        }
        return $forms;
    }

    /**
     * Parse available forms from pages
     * 
     * @param string $content - Page content
     * 
     * @return array() - Forms list
     */
    public function get_forms($content) {

        $forms = array();
        if (false !== strpos($content, 'et_pb_contact_form')) {
            $shortcode_tags = array(
                'et_pb_contact_form',
            );

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

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

                preg_match_all("/$pattern/", $content, $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];

                    preg_match_all('/admin_label="(.*?)"/', $shortcode[3], $labels);
                    if (isset($labels['1'])) {
                        foreach ($labels['1'] as $label) {
                            $forms[$label] = $label;
                        }
                    }
                }
            }
        }

        return $forms;
    }

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

        global $wpdb;

        $datasets = array();

        if ($item) {
            $helper_e2pdf_db = new Helper_E2pdf_Db();
            $condition = array(
                'extension' => array(
                    'condition' => '=',
                    'value' => 'divi',
                    'type' => '%s'
                ),
                'item' => array(
                    'condition' => '=',
                    'value' => $item,
                    'type' => '%s'
                ),
            );

            $order_condition = array(
                'orderby' => 'ID',
                'order' => 'desc',
            );

            $where = $helper_e2pdf_db->prepare_where($condition);
            $orderby = $helper_e2pdf_db->prepare_orderby($order_condition);

            $datasets_tmp = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . 'e2pdf_datasets' . $where['sql'] . $orderby . "", $where['filter']));

            if ($datasets_tmp) {
                foreach ($datasets_tmp as $key => $dataset) {
                    $this->set('item', $item);
                    $this->set('dataset', $dataset->ID);
                    $dataset_title = $this->render($name);
                    if (!$dataset_title) {
                        $dataset_title = $dataset->ID;
                    }
                    $datasets[] = array(
                        'key' => $dataset->ID,
                        'value' => $dataset_title
                    );
                }
            }
        }

        return $datasets;
    }

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

        $dataset = (int) $dataset;

        if (!$dataset) {
            return;
        }

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

        return $data;
    }

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

        $form = new stdClass();

        if ($item) {
            $form->name = $item;
            $post = $this->get_post($item);
            $form->url = isset($post->ID) ? $this->helper->get_url(array('post' => $post->ID, 'action' => 'edit'), 'post.php?') : 'javascript:void(0);';
        } else {
            $form->name = '';
            $form->url = 'javascript:void(0);';
        }
        return $form;
    }

    /**
     * Get post
     * 
     * @param string $item_id - Form label
     * 
     * @return object - Post
     */
    public function get_post($item_id = false) {
        global $wpdb;

        $item_post = false;
        $helper_e2pdf_db = new Helper_E2pdf_Db();

        $condition = array(
            'post_content' => array(
                'condition' => 'LIKE',
                'value' => '%admin_label="' . $item_id . '"%',
                'type' => '%s'
            ),
            'post_type' => array(
                'condition' => '<>',
                'value' => array(
                    'revision',
                    'et_pb_layout'
                ),
                'type' => '%s'
            ),
        );

        $order_condition = array(
            'orderby' => 'id',
            'order' => 'desc',
        );

        $where = $helper_e2pdf_db->prepare_where($condition);
        $orderby = $helper_e2pdf_db->prepare_orderby($order_condition);

        $posts = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . 'posts' . $where['sql'] . $orderby . "", $where['filter']));
        foreach ($posts as $key => $post) {
            if ($forms_labels = $this->get_forms($post->post_content)) {
                if (in_array($item_id, $forms_labels)) {
                    $item_post = $post;
                    break;
                }
            }
        }
        return $item_post;
    }

    /**
     * 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 "";
            }
        }

        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()) {
        global $wpdb;

        $dataset_id = $this->get('dataset');
        $item_id = $this->get('item');

        $condition = array(
            'ID' => array(
                'condition' => '=',
                'value' => $dataset_id,
                'type' => '%d'
            ),
            'item' => array(
                'condition' => '=',
                'value' => $item_id,
                'type' => '%s'
            ),
            'extension' => array(
                'condition' => '=',
                'value' => 'divi',
                'type' => '%s'
            ),
        );

        $helper_e2pdf_db = new Helper_E2pdf_Db();
        $where = $helper_e2pdf_db->prepare_where($condition);

        $dataset = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . 'e2pdf_datasets' . $where['sql'] . "", $where['filter']));

        $processed_fields_values = array();
        if ($dataset) {
            $post = unserialize($dataset->entry);
            if ($post && is_array($post)) {

                $et_pb_contact_form_num = 0;

                $current_form_fields = isset($post['et_pb_contact_email_fields_' . $et_pb_contact_form_num]) ? $post['et_pb_contact_email_fields_' . $et_pb_contact_form_num] : '';
                $hidden_form_fields = isset($post['et_pb_contact_email_hidden_fields_' . $et_pb_contact_form_num]) ? $post['et_pb_contact_email_hidden_fields_' . $et_pb_contact_form_num] : false;
                $processed_fields_values = array();

                if ('' !== $current_form_fields) {
                    $fields_data_json = str_replace('\\', '', $current_form_fields);
                    $fields_data_array = json_decode($fields_data_json, true);

                    if (!empty($fields_data_array)) {
                        foreach ($fields_data_array as $index => $field_value) {
                            $processed_fields_values[$field_value['original_id']]['value'] = isset($post[$field_value['field_id']]) ? $post[$field_value['field_id']] : '';
                            $processed_fields_values[$field_value['original_id']]['label'] = $field_value['field_label'];
                        }
                    }
                }
            }

            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'])) {
                            foreach ($processed_fields_values as $field_key => $field_value) {
                                $shortcode['5'] = str_ireplace("%%{$field_key}%%", wp_strip_all_tags($field_value['value']), $shortcode['5']);
                            }
                            $sub_value = $this->strip_shortcodes($shortcode['5']);
                            $value = str_replace($shortcode_value, "[" . $shortcode['2'] . $shortcode['3'] . "]" . $sub_value . "[/" . $shortcode['2'] . "]", $value);
                        }
                    }
                }
            }

            $value = do_shortcode($value);

            if ($dataset) {
                foreach ($processed_fields_values as $field_key => $field_value) {
                    $value = str_ireplace("%%{$field_key}%%", wp_strip_all_tags($field_value['value']), $value);
                }
            }

            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 {
                    $helper_e2pdf_image = new Helper_E2pdf_Image();
                    if (!$helper_e2pdf_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->hexColorAllocate($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 = "";
                        }
                    }
                }
            }
        }

        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('~(?:%%/?)[^/%%]+/?%%~', "", $value);
        return $value;
    }

    public function auto() {

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

        if ($this->get('item')) {
            $post = $this->get_post($this->get('item'));
            if ($post && isset($post->post_content)) {

                $content = $post->post_content;

                if (false !== strpos($content, '[')) {
                    $shortcode_tags = array(
                        'et_pb_contact_form',
                    );

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

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

                        preg_match_all("/$pattern/", $content, $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 (isset($atts['admin_label']) && $atts['admin_label'] == $this->get('item')) {

                                require_once(ET_BUILDER_DIR . 'class-et-builder-element.php');
                                require_once(ET_BUILDER_DIR . 'functions.php');
                                require_once(ET_BUILDER_DIR . 'ab-testing.php');
                                require_once(ET_BUILDER_DIR . 'class-et-global-settings.php');
                                require_once(ET_BUILDER_DIR . 'module/ContactForm.php');
                                require_once(ET_BUILDER_DIR . 'module/ContactFormItem.php');

                                new ET_Builder_Module_Contact_Form();
                                new ET_Builder_Module_Contact_Form_Item();


                                $source = do_shortcode($shortcode_value);

                                libxml_use_internal_errors(true);
                                $dom = new DOMDocument;
                                $html = $dom->loadHTML($source);
                                libxml_clear_errors();

                                if ($html) {
                                    $xpath = new DomXPath($dom);
                                    $blocks = $xpath->query("//*[contains(@class, 'et_pb_contact_field')]");
                                    foreach ($blocks as $element) {

                                        $data_type = $element->attributes->getNamedItem("data-type")->nodeValue;

                                        if ($data_type == 'radio') {

                                            $label = $xpath->query(".//label", $element)->item(0);
                                            $check_handler = $xpath->query(".//input[contains(@class, 'et_pb_checkbox_handle')]", $element)->item(0);

                                            $name = "";
                                            if ($check_handler) {
                                                $name = "%%" . $check_handler->attributes->getNamedItem("data-original_id")->nodeValue . "%%";
                                            }

                                            $elements[] = $this->auto_field($element, 'e2pdf-html', array(
                                                'top' => '20',
                                                'left' => '20',
                                                'right' => '20',
                                                'block' => true,
                                                'properties' => array(
                                                    'value' => $label->nodeValue,
                                                )
                                            ));

                                            $top = 0;
                                            $fields = $xpath->query("//*[contains(@class, 'et_pb_contact_field_radio')]", $element);

                                            foreach ($fields as $field) {
                                                $radio_label = $xpath->query(".//label", $field)->item(0);
                                                $radio = $xpath->query(".//input[@type='radio']", $field)->item(0);

                                                $elements[] = $this->auto_field($field, 'e2pdf-radio', array(
                                                    'top' => $top,
                                                    'properties' => array(
                                                        'width' => '15',
                                                        'height' => '15',
                                                        'value' => "%%" . $radio->attributes->getNamedItem("data-original_id")->nodeValue . "%%",
                                                        'option' => $radio->attributes->getNamedItem("value")->nodeValue,
                                                        'group' => $radio->attributes->getNamedItem("data-original_id")->nodeValue,
                                                    )
                                                ));
                                                $elements[] = $this->auto_field($radio, 'e2pdf-html', array(
                                                    'top' => $top,
                                                    'left' => '20',
                                                    'properties' => array(
                                                        'value' => $radio_label->nodeValue
                                                    )
                                                ));

                                                $top = $top + 20;
                                            }
                                        } elseif ($data_type == 'checkbox') {

                                            $label = $xpath->query(".//label", $element)->item(0);
                                            $check_handler = $xpath->query(".//input[contains(@class, 'et_pb_checkbox_handle')]", $element)->item(0);

                                            $name = "";
                                            if ($check_handler) {
                                                $name = "%%" . $check_handler->attributes->getNamedItem("data-original_id")->nodeValue . "%%";
                                            }


                                            $elements[] = $this->auto_field($element, 'e2pdf-html', array(
                                                'top' => '20',
                                                'left' => '20',
                                                'right' => '20',
                                                'block' => true,
                                                'properties' => array(
                                                    'value' => $label->nodeValue,
                                                )
                                            ));


                                            $top = 0;
                                            $fields = $xpath->query("//*[contains(@class, 'et_pb_contact_field_checkbox')]", $element);

                                            foreach ($fields as $field) {
                                                $checkbox_label = $xpath->query(".//label", $field)->item(0);
                                                $checkbox = $xpath->query(".//input[@type='checkbox']", $field)->item(0);


                                                $elements[] = $this->auto_field($field, 'e2pdf-checkbox', array(
                                                    'top' => $top,
                                                    'properties' => array(
                                                        'width' => '15',
                                                        'height' => '15',
                                                        'value' => $name,
                                                        'option' => $checkbox->attributes->getNamedItem("value")->nodeValue
                                                    )
                                                ));
                                                $elements[] = $this->auto_field($checkbox, 'e2pdf-html', array(
                                                    'top' => $top,
                                                    'left' => '20',
                                                    'properties' => array(
                                                        'value' => $checkbox_label->nodeValue
                                                    )
                                                ));

                                                $top = $top + 20;
                                            }
                                        } else {

                                            $label = $xpath->query(".//label", $element)->item(0);
                                            $input_text = $xpath->query(".//input[@type='text']", $element)->item(0);
                                            $select = $xpath->query(".//select", $element)->item(0);
                                            $textarea = $xpath->query(".//textarea", $element)->item(0);

                                            if ($label && ($input_text || $select || $textarea)) {
                                                $elements[] = $this->auto_field($element, 'e2pdf-html', array(
                                                    'top' => '20',
                                                    'left' => '20',
                                                    'right' => '20',
                                                    'block' => true,
                                                    'properties' => array(
                                                        'value' => $label->nodeValue,
                                                    )
                                                ));
                                            }


                                            if ($input_text) {
                                                $elements[] = $this->auto_field($input_text, 'e2pdf-input', array(
                                                    'properties' => array(
                                                        'value' => "%%{$input_text->attributes->getNamedItem("data-original_id")->nodeValue}%%",
                                                    )
                                                ));
                                            } elseif ($select) {
                                                $options_tmp = array();
                                                $options = $xpath->query(".//option", $select);
                                                foreach ($options as $option) {
                                                    $options_tmp[] = $option->attributes->getNamedItem("value")->nodeValue;
                                                }

                                                $elements[] = $this->auto_field($select, 'e2pdf-select', array(
                                                    'properties' => array(
                                                        'options' => implode("\n", $options_tmp),
                                                        'value' => "%%{$select->attributes->getNamedItem("data-original_id")->nodeValue}%%",
                                                    )
                                                ));
                                            } elseif ($textarea) {
                                                $elements[] = $this->auto_field($textarea, 'e2pdf-textarea', array(
                                                    'properties' => array(
                                                        'value' => "%%{$textarea->attributes->getNamedItem("data-original_id")->nodeValue}%%",
                                                    )
                                                ));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

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

        return $response;
    }

    /**
     * Convert Field name to Value
     * @since 0.01.34
     * 
     * @param string $name - Field name
     * 
     * @return bool|string - Converted value or false
     */
    public function auto_map($name = false) {
        $item = $this->get('item');
        if ($item) {
            $post = $this->get_post($item);
            if ($post && isset($post->post_content)) {
                $content = $post->post_content;

                if (false !== strpos($content, '[')) {
                    $shortcode_tags = array(
                        'et_pb_contact_form',
                    );

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

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

                        preg_match_all("/$pattern/", $content, $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 (isset($atts['admin_label']) && $atts['admin_label'] == $this->get('item')) {

                                $field_content = $shortcode_value;
                                $field_shortcode_tags = array(
                                    'et_pb_contact_field',
                                );

                                preg_match_all('@\[([^<>&/\[\]\x00-\x20=]++)@', $field_content, $field_matches);
                                $field_tagnames = array_intersect($field_shortcode_tags, $field_matches[1]);

                                if (!empty($field_tagnames)) {
                                    $field_pattern = get_shortcode_regex($field_tagnames);

                                    preg_match_all("/$field_pattern/", $field_content, $field_shortcodes);

                                    foreach ($field_shortcodes[0] as $field_key => $field_shortcode_value) {
                                        $field_shortcode = array();
                                        $field_shortcode[3] = $field_shortcodes[3][$field_key];
                                        $field_atts = shortcode_parse_atts($field_shortcode[3]);
                                        if (isset($field_atts['field_title']) && isset($field_atts['field_id'])) {
                                            if ($field_atts['field_title'] == $name || $field_atts['field_id'] == $name) {
                                                return "%%" . strtolower($field_atts['field_id']) . "%%";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return false;
    }

    /**
     * Generate field for Auto PDF
     * 
     * @param object $field - Formidable field object
     * @param string $type - Field type
     * @param array $options - Field additional options
     * 
     * @return array - Prepared auto field
     */
    public function auto_field($field = false, $type = false, $options = array()) {

        if (!$field || !$type) {
            return false;
        }

        $element = array(
            'type' => $type,
            'properties' => isset($options['properties']) ? $options['properties'] : array(),
        );

        $element['top'] = isset($options['top']) ? $options['top'] : '0';
        $element['left'] = isset($options['left']) ? $options['left'] : '0';
        $element['right'] = isset($options['right']) ? $options['right'] : '0';
        $element['block'] = isset($options['block']) ? $options['block'] : false;

        $classes = array();
        if (isset($field->attributes->getNamedItem("class")->nodeValue)) {
            $classes = explode(" ", $field->attributes->getNamedItem("class")->nodeValue);
        }

        $float_classes = array(
            'et_pb_contact_field_half',
        );
        $array_intersect = array_intersect($classes, $float_classes);

        if (!empty($array_intersect)) {
            $element['float'] = true;
        };

        $primary_class = false;
        if (!empty($array_intersect)) {
            $primary_class = end($array_intersect);
        }

        if ($element['block']) {
            switch ($primary_class) {
                case 'et_pb_contact_field_half':
                    $element['width'] = '50%';
                    break;
                default:
                    break;
            }
        }

        return $element;
    }

    /**
     * Verify if form and dataset exists
     * 
     * @return bool - Exists/Not exists
     */
    public function verify() {
        global $wpdb;
        $item_id = $this->get('item');
        $dataset_id = $this->get('dataset');

        if ($item_id && $dataset_id) {
            $condition = array(
                'ID' => array(
                    'condition' => '=',
                    'value' => $dataset_id,
                    'type' => '%d'
                ),
                'extension' => array(
                    'condition' => '=',
                    'value' => 'divi',
                    'type' => '%s'
                ),
                'item' => array(
                    'condition' => '=',
                    'value' => $item_id,
                    'type' => '%s'
                ),
            );

            $helper_e2pdf_db = new Helper_E2pdf_Db();
            $where = $helper_e2pdf_db->prepare_where($condition);
            $dataset = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . 'e2pdf_datasets' . $where['sql'] . "", $where['filter']));

            if ($dataset) {
                return true;
            }
        }
        return false;
    }

    /**
     * Visual Mapper for Mapping field
     * 
     * @return bool|string - Prepared form or false
     */
    public function visual_mapper() {
        if ($this->get('item')) {
            $post = $this->get_post($this->get('item'));
            if ($post && isset($post->post_content)) {

                $content = $post->post_content;

                if (false !== strpos($content, '[')) {
                    $shortcode_tags = array(
                        'et_pb_contact_form',
                    );

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



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

                        preg_match_all("/$pattern/", $content, $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 (isset($atts['admin_label']) && $atts['admin_label'] == $this->get('item')) {

                                require_once(ET_BUILDER_DIR . 'class-et-builder-element.php');
                                require_once(ET_BUILDER_DIR . 'functions.php');
                                require_once(ET_BUILDER_DIR . 'ab-testing.php');
                                require_once(ET_BUILDER_DIR . 'class-et-global-settings.php');
                                require_once(ET_BUILDER_DIR . 'module/ContactForm.php');
                                require_once(ET_BUILDER_DIR . 'module/ContactFormItem.php');

                                new ET_Builder_Module_Contact_Form();
                                new ET_Builder_Module_Contact_Form_Item();

                                $source = do_shortcode($shortcode_value);

                                libxml_use_internal_errors(true);
                                $dom = new DOMDocument;
                                $html = $dom->loadHTML($source);
                                libxml_clear_errors();

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

                                    $xpath = new DomXPath($dom);
                                    // Replace names
                                    $fields = $xpath->query("//*[contains(@name, 'et_pb_contact_')]");
                                    foreach ($fields as $element) {
                                        $element->attributes->getNamedItem("name")->nodeValue = "%%" . $element->attributes->getNamedItem("data-original_id")->nodeValue . "%%";
                                    }

                                    $checkboxes = $xpath->query("//*[contains(@class, 'et_pb_contact_field') and @data-type='checkbox']");
                                    foreach ($checkboxes as $element) {

                                        $check_handler = $xpath->query(".//input[contains(@class, 'et_pb_checkbox_handle')]", $element)->item(0);

                                        $name = "";
                                        if ($check_handler) {
                                            $name = "%%" . $check_handler->attributes->getNamedItem("data-original_id")->nodeValue . "%%";
                                        }

                                        $checks = $xpath->query(".//input[@type='checkbox']", $element);
                                        foreach ($checks as $check) {
                                            $attr = $dom->createAttribute('name');
                                            $attr->value = $name;
                                            $check->appendChild($attr);
                                        }
                                    }

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


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


                                    if ($xpath->query("//form")->item(0)) {
                                        $autocomplete = $dom->createAttribute('autocomplete');
                                        $autocomplete->value = 'off';
                                        $xpath->query("//form")->item(0)->appendChild($autocomplete);
                                    }
                                }

                                return $dom->saveHTML();
                            }
                        }
                    }
                }
            }
        }

        return false;
    }

    /**
     * Overwrite shortcodes
     */
    public function action_overwrite_shortcodes() {
        remove_shortcode('et_pb_contact_form');
        add_shortcode('et_pb_contact_form', array($this, 'shortcode_et_pb_contact_form'));
    }

    public function filter_wp_mail($args) {

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

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

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

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

                    foreach ($shortcodes[0] as $key => $shortcode_value) {
                        $extension = false;
                        $item = false;

                        $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('id', $atts)) {
                            $template = new Model_E2pdf_Template();
                            $template->load($atts['id']);
                            if ($template->get('extension') === 'divi') {
                                $extension = $template->get('extension');
                                $item = $template->get('item');
                                if (array_key_exists('dataset', $atts)) {
                                    $shortcode[3] .= " apply='true'";
                                    if ($shortcode[2] === 'e2pdf-download') {
                                        $args['headers'][] = 'Content-Type: text/html; charset=UTF-8';
                                        $args['message'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $args['message']);
                                        $args['message'] = str_replace("\r\n", "<br/>", $args['message']);
                                    } elseif ($shortcode[2] === 'e2pdf-attachment') {
                                        $file = do_shortcode_tag($shortcode);
                                        if ($file) {
                                            $this->helper->add('divi_attachments', $file);
                                            $args['attachments'][] = $file;
                                        }
                                        $args['message'] = str_replace($shortcode_value, '', $args['message']);
                                    } elseif ($shortcode[2] === 'e2pdf-save') {
                                        do_shortcode_tag($shortcode);
                                        $args['message'] = str_replace($shortcode_value, '', $args['message']);
                                    }
                                } else {
                                    $args['message'] = str_replace($shortcode_value, '', $args['message']);
                                }
                            }
                        }
                    }
                }
            }
        }

        $wp_mail = array(
            'to' => $args['to'],
            'subject' => $args['subject'],
            'message' => $args['message'],
            'headers' => $args['headers'],
            'attachments' => $args['attachments'],
        );

        return $wp_mail;
    }

    /**
     * Load actions for this extension
     */
    public function load_actions() {
        add_action('wp', array($this, 'action_overwrite_shortcodes'), 99);
    }

    public function shortcode_et_pb_contact_form($shortcode_atts, $content = null, $function_name, $parent_address = '', $global_parent = '', $global_parent_type = '') {
        global $wpdb;

        if (class_exists('ET_Builder_Module_Contact_Form')) {

            $et_pb_contact = new ET_Builder_Module_Contact_Form();

            if (isset($_POST['_wpnonce-et-pb-contact-form-submitted'])) {

                $et_pb_contact_form_num = 0;

                $nonce_result = isset($_POST['_wpnonce-et-pb-contact-form-submitted']) && wp_verify_nonce($_POST['_wpnonce-et-pb-contact-form-submitted'], 'et-pb-contact-form-submit') ? true : false;

                if ($nonce_result && isset($_POST['et_pb_contactform_submit_' . $et_pb_contact_form_num]) && empty($_POST['et_pb_contactform_validate_' . $et_pb_contact_form_num])) {
                    if ('' !== $current_form_fields) {
                        $fields_data_json = str_replace('\\', '', $current_form_fields);
                        $fields_data_array = json_decode($fields_data_json, true);

                        // check whether captcha field is not empty
                        if ('on' === $captcha && (!isset($_POST['et_pb_contact_captcha_' . $et_pb_contact_form_num]) || empty($_POST['et_pb_contact_captcha_' . $et_pb_contact_form_num]) )) {
                            $et_error_message .= sprintf('<p class="et_pb_contact_error_text">%1$s</p>', esc_html__('Make sure you entered the captcha.', 'et_builder'));
                            $et_contact_error = true;
                        }

                        // check all fields on current form and generate error message if needed
                        if (!empty($fields_data_array)) {
                            foreach ($fields_data_array as $index => $value) {
                                // check all the required fields, generate error message if required field is empty
                                if ('required' === $value['required_mark'] && empty($_POST[$value['field_id']])) {
                                    $et_error_message .= sprintf('<p class="et_pb_contact_error_text">%1$s</p>', esc_html__('Make sure you fill in all required fields.', 'et_builder'));
                                    $et_contact_error = true;
                                    continue;
                                }

                                // additional check for email field
                                if ('email' === $value['field_type'] && 'required' === $value['required_mark'] && !empty($_POST[$value['field_id']])) {
                                    $contact_email = sanitize_email($_POST[$value['field_id']]);
                                    if (!is_email($contact_email)) {
                                        $et_error_message .= sprintf('<p class="et_pb_contact_error_text">%1$s</p>', esc_html__('Invalid Email.', 'et_builder'));
                                        $et_contact_error = true;
                                    }
                                }

                                // prepare the array of processed field values in convenient format
                                if (false === $et_contact_error) {
                                    $processed_fields_values[$value['original_id']]['value'] = isset($_POST[$value['field_id']]) ? $_POST[$value['field_id']] : '';
                                    $processed_fields_values[$value['original_id']]['label'] = $value['field_label'];
                                }
                            }
                        }
                    } else {
                        $et_error_message .= sprintf('<p class="et_pb_contact_error_text">%1$s</p>', esc_html__('Make sure you fill in all required fields.', 'et_builder'));
                        $et_contact_error = true;
                    }
                } else {
                    if (false === $nonce_result && isset($_POST['et_pb_contactform_submit_' . $et_pb_contact_form_num]) && empty($_POST['et_pb_contactform_validate_' . $et_pb_contact_form_num])) {
                        $et_error_message .= sprintf('<p class="et_pb_contact_error_text">%1$s</p>', esc_html__('Please refresh the page and try again.', 'et_builder'));
                    }
                    $et_contact_error = true;
                }

                if (!$et_contact_error && $nonce_result) {
                    if (isset($shortcode_atts['success_message'])) {
                        $shortcode_atts['success_message'] = str_replace(array('%91', '%93', '%22'), array('[', ']', '"'), $shortcode_atts['success_message']);
                        if (false !== strpos($shortcode_atts['success_message'], '[')) {

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

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

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

                                preg_match_all("/$pattern/", $shortcode_atts['success_message'], $shortcodes);

                                foreach ($shortcodes[0] as $key => $shortcode_value) {

                                    $extension = false;
                                    $item = false;

                                    $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('id', $atts)) {
                                        $template = new Model_E2pdf_Template();
                                        $template->load($atts['id']);
                                        if ($template->get('extension') === 'divi') {
                                            $extension = $template->get('extension');
                                            $item = $template->get('item');
                                        }
                                    }

                                    if ($item && isset($shortcode_atts['admin_label']) && $shortcode_atts['admin_label'] == $item && $extension) {
                                        if (!array_key_exists('dataset', $atts)) {
                                            $serialized = serialize($_POST);
                                            $dataset = array(
                                                'extension' => 'divi',
                                                'item' => $item,
                                                'entry' => $serialized
                                            );
                                            $wpdb->insert($wpdb->prefix . 'e2pdf_datasets', $dataset);

                                            $dataset_id = $wpdb->insert_id;

                                            $atts['dataset'] = $dataset_id;
                                            $shortcode[3] .= " dataset='{$dataset_id}' apply='true'";
                                            $shortcode_atts['success_message'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $shortcode_atts['success_message']);
                                        }
                                    } elseif ($shortcode[2] === 'e2pdf-view') {
                                        $shortcode_atts['success_message'] = str_replace($shortcode_value, do_shortcode_tag($shortcode), $shortcode_atts['success_message']);
                                    }
                                }
                            }
                        }
                    }


                    if (isset($shortcode_atts['custom_message'])) {

                        $shortcode_atts['custom_message'] = str_replace(array('%91', '%93', '%22'), array('[', ']', '"'), $shortcode_atts['custom_message']);

                        if (false !== strpos($shortcode_atts['custom_message'], '[')) {
                            $shortcode_tags = array(
                                'e2pdf-download',
                                'e2pdf-attachment',
                                'e2pdf-save'
                            );

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


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

                                preg_match_all("/$pattern/", $shortcode_atts['custom_message'], $shortcodes);

                                add_filter('wp_mail', array($this, 'filter_wp_mail'), 10, 2);

                                foreach ($shortcodes[0] as $key => $shortcode_value) {

                                    $extension = false;
                                    $item = false;

                                    $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('id', $atts)) {
                                        $template = new Model_E2pdf_Template();
                                        $template->load($atts['id']);
                                        if ($template->get('extension') === 'divi') {
                                            $extension = $template->get('extension');
                                            $item = $template->get('item');
                                        }
                                    }

                                    if ($item && isset($shortcode_atts['admin_label']) && $shortcode_atts['admin_label'] == $item && $extension) {
                                        if (!array_key_exists('dataset', $atts)) {
                                            if (!$dataset_id) {
                                                $serialized = serialize($_POST);
                                                $dataset = array(
                                                    'extension' => 'divi',
                                                    'item' => $item,
                                                    'entry' => $serialized
                                                );
                                                $wpdb->insert($wpdb->prefix . 'e2pdf_datasets', $dataset);
                                                $dataset_id = $wpdb->insert_id;
                                            }

                                            $atts['dataset'] = $dataset_id;
                                            $shortcode[3] .= " dataset='{$dataset_id}'";

                                            $new_shortcode = "[" . $shortcode[2] . $shortcode[3] . "]";
                                            $shortcode_atts['custom_message'] = str_replace($shortcode_value, $new_shortcode, $shortcode_atts['custom_message']);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            $output = $et_pb_contact->_shortcode_callback($shortcode_atts, $content, $function_name, $parent_address, $global_parent, $global_parent_type);

            remove_filter('wp_mail', array($this, 'filter_wp_mail'), 10, 2);

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

            return html_entity_decode($output, ENT_QUOTES);
        }
    }

    /**
     * Delete dataset for template
     * 
     * @param int $template_id - Template ID
     * @param int $dataset_id - Dataset ID
     * 
     * @return bool - Result of removing items
     */
    public function delete_item($template_id = false, $dataset_id = false) {
        global $wpdb;

        $template = new Model_E2pdf_Template();
        if ($template_id && $dataset_id && $template->load($template_id)) {
            $extension = new Model_E2pdf_Extension();
            if ($template->get('extension') === 'divi' && $extension->load($template->get('extension'))) {

                $item_id = $template->get('item');

                $where = array(
                    'ID' => $dataset_id,
                    'item' => $item_id,
                    'extension' => 'divi'
                );
                $wpdb->delete($wpdb->prefix . 'e2pdf_datasets', $where);
                return true;
            }
        }

        return false;
    }

    /**
     * Delete all datasets for Template
     * 
     * @param int $template_id - Template ID
     * 
     * @return bool - Result of removing items
     */
    public function delete_items($template_id = false) {
        global $wpdb;

        $template = new Model_E2pdf_Template();

        if ($template_id && $template->load($template_id)) {
            $extension = new Model_E2pdf_Extension();
            if ($template->get('extension') === 'divi' && $extension->load($template->get('extension'))) {

                $item_id = $template->get('item');

                $where = array(
                    'item' => $item_id,
                    'extension' => 'divi'
                );
                $wpdb->delete($wpdb->prefix . 'e2pdf_datasets', $where);
                return true;
            }
        }

        return false;
    }

    /**
     * Get styles for generating Map Field function
     * 
     * @return array - List of css files to load
     */
    public function get_styles() {
        $styles = array(
            plugins_url('css/extension/divi.css?v=' . time(), $this->helper->get('plugin_file_path'))
        );
        return $styles;
    }

}

```
