/**
 * Import/Export form data.
 *
 * @return type
 *
 * @deprecated in 2.0, to remove
 */
function wpcf_admin_import_export_form()
{
    $form = array();
    $form['wpnonce'] = array('#type' => 'hidden', '#name' => '_wpnonce', '#value' => wp_create_nonce('wpcf_import'));
    $form_base = $form;
    $show_first_screen = true;
    if (isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'wpcf_import')) {
        $show_first_screen = false;
        if (isset($_POST['import-final'])) {
            if ($_POST['mode'] == 'file' && !empty($_POST['file'])) {
                $file = get_transient(sanitize_text_field($_POST['file']));
                if (file_exists($file)) {
                    $info = pathinfo($file);
                    $is_zip = $info['extension'] == 'zip' ? true : false;
                    if ($is_zip) {
                        $zip = zip_open($file);
                        if (is_resource($zip)) {
                            while (($zip_entry = zip_read($zip)) !== false) {
                                if (zip_entry_name($zip_entry) == 'settings.xml') {
                                    $data = @zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                                }
                            }
                        } else {
                            echo '<div class="message error"><p>' . __('Unable to open zip file', 'wpcf') . '</p></div>';
                            return array();
                        }
                    } else {
                        $data = @file_get_contents($file);
                    }
                    @unlink($file);
                    if ($data) {
                        wpcf_admin_import_data($data);
                    } else {
                        echo '<div class="message error"><p>' . __('Unable to process file', 'wpcf') . '</p></div>';
                        return array();
                    }
                } else {
                    echo '<div class="message error"><p>' . __('Unable to process file', 'wpcf') . '</p></div>';
                    return array();
                }
            }
            if ($_POST['mode'] == 'text' && !empty($_POST['text'])) {
                $charset = !empty($_POST['text-encoding']) ? sanitize_text_field($_POST['text-encoding']) : get_option('blog_charset');
                wpcf_admin_import_data(stripslashes(html_entity_decode($_POST['text'], ENT_QUOTES, $charset)));
            }
        } elseif (isset($_POST['step'])) {
            $mode = 'none';
            $data = '';
            if (!empty($_POST['import-file']) && !empty($_FILES['file']['tmp_name'])) {
                if ($_FILES['file']['type'] == 'text/xml') {
                    $_FILES['file']['name'] .= '.txt';
                }
                /*
                 *
                 * We need to move uploaded file manually
                 */
                if (!empty($_FILES['file']['error'])) {
                    echo '<div class="message error"><p>' . __('Error uploading file', 'wpcf') . '</p></div>';
                    return array();
                }
                $wp_upload_dir = wp_upload_dir();
                $new_file = $wp_upload_dir['basedir'] . '/' . sanitize_file_name($_FILES['file']['name']);
                $move = move_uploaded_file($_FILES['file']['tmp_name'], $new_file);
                if (!$move) {
                    echo '<div class="message error"><p>' . __('Error moving uploaded file', 'wpcf') . '</p></div>';
                    return array();
                }
                $uploaded_file = array('file' => $new_file);
                $info = pathinfo($uploaded_file['file']);
                $is_zip = $info['extension'] == 'zip' ? true : false;
                if ($is_zip) {
                    $zip = zip_open($uploaded_file['file']);
                    if (is_resource($zip)) {
                        while (($zip_entry = zip_read($zip)) !== false) {
                            if (zip_entry_name($zip_entry) == 'settings.xml') {
                                $data = @zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                            }
                        }
                    } else {
                        echo '<div class="message error"><p>' . __('Unable to open zip file', 'wpcf') . '</p></div>';
                        return array();
                    }
                } else {
                    $data = @file_get_contents($uploaded_file['file']);
                }
                /**
                 * use Transients API to store file fullpath
                 */
                $current_user = wp_get_current_user();
                $cache_key = md5($current_user->user_email . $uploaded_file['file']);
                set_transient($cache_key, $uploaded_file['file'], 60 * 60);
                $form['file'] = array('#type' => 'hidden', '#name' => 'file', '#value' => $cache_key);
                $mode = 'file';
            } elseif (!empty($_POST['import-text']) && !empty($_POST['text'])) {
                $data = stripslashes($_POST['text']);
                if (preg_match('/encoding=("[^"]*"|\'[^\']*\')/s', $data, $match)) {
                    $charset = trim($match[1], '"');
                } else {
                    $charset = !empty($_POST['text-encoding']) ? sanitize_text_field($_POST['text-encoding']) : get_option('blog_charset');
                }
                $form['text'] = array('#type' => 'hidden', '#name' => 'text', '#value' => htmlentities(stripslashes($_POST['text']), ENT_QUOTES, $charset));
                $form['text-encoding'] = array('#type' => 'hidden', '#name' => 'text-encoding', '#value' => $charset);
                $mode = 'text';
            }
            if (empty($data)) {
                echo '<div class="message error"><p>' . __('Data not valid', 'wpcf') . '</p></div>';
                $show_first_screen = true;
            } else {
                $data = wpcf_admin_import_export_settings($data);
                if (empty($data)) {
                    echo '<div class="message error"><p>' . __('Data not valid', 'wpcf') . '</p></div>';
                    $show_first_screen = true;
                } else {
                    $form = array_merge($form, $data);
                    $form['mode'] = array('#type' => 'hidden', '#name' => 'mode', '#value' => $mode);
                    $form['import-final'] = array('#type' => 'hidden', '#name' => 'import-final', '#value' => 1);
                    $form['submit'] = array('#type' => 'submit', '#name' => 'import', '#value' => __('Import', 'wpcf'), '#attributes' => array('class' => 'button-primary'));
                }
            }
        }
    }
    if ($show_first_screen) {
        $form = $form_base;
        $form['submit'] = array('#type' => 'submit', '#name' => 'export', '#value' => __('Export', 'wpcf'), '#attributes' => array('class' => 'button-primary'), '#after' => '<br /><br />', '#before' => '<h3>' . __('Export Types data', 'wpcf') . '</h3>' . __('Download all custom fields, post types and taxonomies created by Types plugin.', 'wpcf') . '<br /><br />');
        /**
         * check is temp folder available?
         */
        $temp = wpcf_get_temporary_directory();
        if (empty($temp)) {
            unset($form['submit']);
        }
        if (extension_loaded('simplexml')) {
            $attributes = !wpcf_admin_import_dir() ? array('disabled' => 'disabled') : array();
            $form['file'] = array('#type' => 'file', '#name' => 'file', '#prefix' => __('Upload XML file', 'wpcf') . '<br />', '#before' => '<h3>' . __('Import Types data file', 'wpcf') . '</h3>', '#inline' => true, '#attributes' => $attributes);
            $form['submit-file'] = array('#type' => 'submit', '#name' => 'import-file', '#value' => __('Import file', 'wpcf'), '#attributes' => array_merge($attributes, array('class' => 'button-primary', 'disabled' => 'disabled')), '#prefix' => '<br />', '#suffix' => '<br /><br />');
            $form['text'] = array('#type' => 'textarea', '#title' => __('Paste code here', 'wpcf'), '#name' => 'text', '#attributes' => array('rows' => 20), '#before' => '<h3>' . __('Import Types data text input', 'wpcf') . '</h3>');
            $form['text-encoding'] = array('#type' => 'textfield', '#title' => __('Encoding', 'wpcf'), '#name' => 'text-encoding', '#value' => get_option('blog_charset'), '#description' => __('If encoding is set in text input, it will override this setting.', 'wpcf'));
            $form['submit-text'] = array('#type' => 'submit', '#name' => 'import-text', '#value' => __('Import text', 'wpcf'), '#attributes' => array('class' => 'button-primary'));
            $form['step'] = array('#type' => 'hidden', '#name' => 'step', '#value' => 1);
        } else {
            echo '<div class="message error"><p>' . __('PHP SimpleXML extension not loaded: Importing not available', 'wpcf') . '</p></div>';
        }
    }
    return $form;
}
/**
 * Custom Export function for Module Manager.
 *
 * Exports selected items (by ID) and of specified type (eg views, view-templates).
 * Returns xml string.
 *
 * @global type $iclTranslationManagement
 * @param array $items
 * @param type $_type
 * @param type $return mixed array|xml|download
 * @return string
 */
function wpcf_admin_export_selected_data(array $items, $_type = 'all', $return = 'download', $use_cache = false)
{
    global $wpcf;
    require_once WPCF_EMBEDDED_ABSPATH . '/common/array2xml.php';
    $xml = new ICL_Array2XML();
    $data = array();
    $data['settings'] = wpcf_get_settings();
    if ('user_groups' == $_type || 'all' == $_type) {
        // Get groups
        if (empty($items)) {
            $groups = get_posts('post_type=wp-types-user-group&post_status=null&numberposts=-1');
        } else {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            foreach ($items as $k => $item) {
                if (isset($item['id'])) {
                    $items[$k] = intval(wpcf_modman_get_submitted_id('groups', $item['id']));
                }
            }
            $args = array('post__in' => $items, 'post_type' => 'wp-types-user-group', 'post_status' => 'all', 'posts_per_page' => -1);
            $groups = get_posts($args);
        }
        if (!empty($groups)) {
            $data['user_groups'] = array('__key' => 'group');
            foreach ($groups as $key => $post) {
                $post = (array) $post;
                $post_data = array();
                $copy_data = array('ID', 'post_content', 'post_title', 'post_excerpt', 'post_type', 'post_status');
                foreach ($copy_data as $copy) {
                    if (isset($post[$copy])) {
                        $post_data[$copy] = $post[$copy];
                    }
                }
                $_data = $post_data;
                $meta = get_post_custom($post['ID']);
                if (!empty($meta)) {
                    $_meta = array();
                    foreach ($meta as $meta_key => $meta_value) {
                        if (in_array($meta_key, array('_wp_types_group_showfor', '_wp_types_group_fields', '_wp_types_group_admin_styles'))) {
                            $_meta[$meta_key] = $meta_value[0];
                        }
                    }
                    if (!empty($_meta)) {
                        $_data['meta'] = $_meta;
                    }
                }
                $_data['checksum'] = $_data['hash'] = $wpcf->export->generate_checksum('group', $post['ID']);
                $_data['__types_id'] = $post['post_name'];
                $_data['__types_title'] = $post['post_title'];
                $data['user_groups']['group-' . $post['ID']] = $_data;
            }
        }
        if (!empty($items)) {
            // Get fields by group
            // TODO Document why we use by_group
            $fields = array();
            foreach ($groups as $key => $post) {
                $fields = array_merge($fields, wpcf_admin_fields_get_fields_by_group($post->ID, 'slug', false, false, false, 'wp-types-user-group', 'wpcf-usermeta', $use_cache));
            }
        } else {
            // Get fields
            $fields = wpcf_admin_fields_get_fields(false, false, false, 'wpcf-usermeta');
        }
        if (!empty($fields)) {
            // Add checksums before WPML
            foreach ($fields as $field_id => $field) {
                // TODO WPML and others should use hook
                $fields[$field_id] = apply_filters('wpcf_export_field', $fields[$field_id]);
                $fields[$field_id]['__types_id'] = $field_id;
                $fields[$field_id]['__types_title'] = $field['name'];
                $fields[$field_id]['checksum'] = $fields[$field_id]['hash'] = $wpcf->export->generate_checksum('field', $field_id);
            }
            // WPML
            global $iclTranslationManagement;
            if (!empty($iclTranslationManagement)) {
                foreach ($fields as $field_id => $field) {
                    // TODO Check this for all fields
                    if (isset($iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id])) {
                        $fields[$field_id]['wpml_action'] = $iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id];
                    }
                }
            }
            $data['user_fields'] = $fields;
            $data['user_fields']['__key'] = 'field';
        }
    }
    if ('groups' == $_type || 'all' == $_type) {
        // Get groups
        if (empty($items)) {
            $groups = get_posts('post_type=wp-types-group&post_status=null&numberposts=-1');
        } else {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            foreach ($items as $k => $item) {
                if (isset($item['id'])) {
                    $items[$k] = intval(wpcf_modman_get_submitted_id('groups', $item['id']));
                }
            }
            $args = array('post__in' => $items, 'post_type' => 'wp-types-group', 'post_status' => 'all', 'posts_per_page' => -1);
            $groups = get_posts($args);
        }
        if (!empty($groups)) {
            $data['groups'] = array('__key' => 'group');
            foreach ($groups as $key => $post) {
                $post = (array) $post;
                $post_data = array();
                $copy_data = array('ID', 'post_content', 'post_title', 'post_excerpt', 'post_type', 'post_status');
                foreach ($copy_data as $copy) {
                    if (isset($post[$copy])) {
                        $post_data[$copy] = $post[$copy];
                    }
                }
                $_data = $post_data;
                $meta = get_post_custom($post['ID']);
                if (!empty($meta)) {
                    $_meta = array();
                    foreach ($meta as $meta_key => $meta_value) {
                        if (in_array($meta_key, array('_wp_types_group_terms', '_wp_types_group_post_types', '_wp_types_group_fields', '_wp_types_group_templates', '_wpcf_conditional_display', '_wp_types_group_filters_association', '_wp_types_group_admin_styles'))) {
                            $_meta[$meta_key] = $meta_value[0];
                            $_meta[$meta_key] = maybe_unserialize($_meta[$meta_key]);
                        }
                    }
                    if (!empty($_meta)) {
                        $_data['meta'] = $_meta;
                    }
                }
                $_data['checksum'] = $_data['hash'] = $wpcf->export->generate_checksum('group', $post['ID']);
                $_data['__types_id'] = $post['post_name'];
                $_data['__types_title'] = $post['post_title'];
                $data['groups']['group-' . $post['ID']] = $_data;
            }
        }
        if (!empty($items)) {
            // Get fields by group
            // TODO Document why we use by_group
            $fields = array();
            foreach ($groups as $key => $post) {
                $fields = array_merge($fields, wpcf_admin_fields_get_fields_by_group($post->ID, 'slug', false, false, false, 'wp-types-group', 'wpcf-fields', $use_cache));
            }
        } else {
            // Get fields
            $fields = wpcf_admin_fields_get_fields();
        }
        if (!empty($fields)) {
            // Add checksums before WPML
            foreach ($fields as $field_id => $field) {
                // TODO WPML and others should use hook
                $fields[$field_id] = apply_filters('wpcf_export_field', $fields[$field_id]);
                $fields[$field_id]['__types_id'] = $field_id;
                $fields[$field_id]['__types_title'] = $field['name'];
                $fields[$field_id]['checksum'] = $fields[$field_id]['hash'] = $wpcf->export->generate_checksum('field', $field_id);
            }
            // WPML
            global $iclTranslationManagement;
            if (!empty($iclTranslationManagement)) {
                foreach ($fields as $field_id => $field) {
                    // TODO Check this for all fields
                    if (isset($iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id])) {
                        $fields[$field_id]['wpml_action'] = $iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id];
                    }
                }
            }
            $data['fields'] = $fields;
            $data['fields']['__key'] = 'field';
        }
    }
    // Get custom types
    if ('types' == $_type || 'all' == $_type) {
        // Get custom types
        // TODO Document $items
        if (!empty($items)) {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            //            $custom_types = array_intersect_key( get_option( 'wpcf-custom-types',
            //                            array() ), array_flip( $items ) );
            $_items = array();
            foreach ($items as $k => $item) {
                if (is_array($item) && isset($item['id'])) {
                    $_items[$item['id']] = true;
                } else {
                    $_items[$item] = true;
                }
            }
            $custom_types = array_intersect_key(get_option('wpcf-custom-types', array()), $_items);
        } else {
            $custom_types = get_option('wpcf-custom-types', array());
        }
        // Get custom types
        if (!empty($custom_types)) {
            foreach ($custom_types as $key => $type) {
                $custom_types[$key]['id'] = $key;
                $custom_types[$key] = apply_filters('wpcf_export_custom_post_type', $custom_types[$key]);
                $custom_types[$key]['__types_id'] = $key;
                $custom_types[$key]['__types_title'] = $type['labels']['name'];
                $custom_types[$key]['checksum'] = $custom_types[$key]['hash'] = $wpcf->export->generate_checksum('custom_post_type', $key, $type);
            }
            $data['types'] = $custom_types;
            $data['types']['__key'] = 'type';
        }
        if (!empty($items)) {
            // Get post relationships only for items
            $relationships_all = get_option('wpcf_post_relationship', array());
            $relationships = array();
            foreach ($relationships_all as $parent => $children) {
                if (in_array($parent, $items)) {
                    foreach ($children as $child => $childdata) {
                        if (in_array($child, $items)) {
                            if (!isset($relationships[$parent])) {
                                $relationships[$parent] = array();
                            }
                            $relationships[$parent][$child] = $childdata;
                        }
                    }
                }
            }
        } else {
            // Get post relationships
            $relationships = get_option('wpcf_post_relationship', array());
        }
        if (!empty($relationships)) {
            $data['post_relationships']['data'] = json_encode($relationships);
        }
    }
    // Get custom tax
    if ('taxonomies' == $_type || 'all' == $_type) {
        if (!empty($items)) {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            //            $custom_taxonomies = array_intersect_key( get_option( 'wpcf-custom-taxonomies',
            //                            array() ), array_flip( $items ) );
            $_items = array();
            foreach ($items as $k => $item) {
                if (is_array($item) && isset($item['id'])) {
                    $_items[$item['id']] = true;
                } else {
                    $_items[$item] = true;
                }
            }
            $custom_taxonomies = array_intersect_key(get_option('wpcf-custom-taxonomies', array()), $_items);
        } else {
            // Get custom tax
            $custom_taxonomies = get_option('wpcf-custom-taxonomies', array());
        }
        if (!empty($custom_taxonomies)) {
            foreach ($custom_taxonomies as $key => $tax) {
                $custom_taxonomies[$key]['id'] = $key;
                $custom_taxonomies[$key] = apply_filters('wpcf_export_custom_post_type', $custom_taxonomies[$key]);
                $custom_taxonomies[$key]['__types_id'] = $key;
                $custom_taxonomies[$key]['__types_title'] = $tax['labels']['name'];
                $custom_taxonomies[$key]['checksum'] = $wpcf->export->generate_checksum('custom_taxonomy', $key, $tax);
            }
            $data['taxonomies'] = $custom_taxonomies;
            $data['taxonomies']['__key'] = 'taxonomy';
        }
    }
    /*
     *
     * Since Types 1.2
     */
    if ($return == 'array') {
        return $data;
    } else {
        if ($return == 'xml') {
            return $xml->array2xml($data, 'types');
        } else {
            if ($return == 'module_manager') {
                $items = array();
                // Re-arrange fields
                if (!empty($data['fields'])) {
                    foreach ($data['fields'] as $_data) {
                        if (is_array($_data) && isset($_data['__types_id']) && isset($_data['checksum'])) {
                            $_item = array();
                            $_item['hash'] = $_item['checksum'] = $_data['checksum'];
                            $_item['id'] = $_data['__types_id'];
                            $_item['title'] = $_data['__types_title'];
                            $items['__fields'][$_data['__types_id']] = $_item;
                        }
                    }
                }
                // Add checksums to items
                foreach ($data as $_t => $type) {
                    foreach ($type as $_data) {
                        // Skip fields
                        if ($_t == 'fields') {
                            continue;
                        }
                        if (is_array($_data) && isset($_data['__types_id']) && isset($_data['checksum'])) {
                            $_item = array();
                            $_item['hash'] = $_item['checksum'] = $_data['checksum'];
                            $_item['id'] = $_data['__types_id'];
                            $_item['title'] = $_data['__types_title'];
                            $items[$_data['__types_id']] = $_item;
                        }
                    }
                }
                return array('xml' => $xml->array2xml($data, 'types'), 'items' => $items);
            }
        }
    }
    // Offer for download
    $data = $xml->array2xml($data, 'types');
    $sitename = sanitize_title(get_bloginfo('name'));
    if (empty($sitename)) {
        $sitename = 'wp';
    }
    $sitename .= '.';
    $filename = $sitename . 'types.' . date('Y-m-d') . '.xml';
    $code = "<?php\r\n";
    $code .= '$timestamp = ' . time() . ';' . "\r\n";
    $code .= '$auto_import = ';
    $code .= isset($_POST['embedded-settings']) && $_POST['embedded-settings'] == 'ask' ? 0 : 1;
    $code .= ';' . "\r\n";
    $code .= "\r\n?" . ">";
    if (class_exists('ZipArchive')) {
        $zipname = $sitename . 'types.' . date('Y-m-d') . '.zip';
        $temp_dir = wpcf_get_temporary_directory();
        if (empty($temp_dir)) {
            die(__('There is a problem with temporary directory.'));
        }
        $file = tempnam($temp_dir, "zip");
        $zip = new ZipArchive();
        $zip->open($file, ZipArchive::OVERWRITE);
        /**
         * if sys_get_temp_dir fail in case of open_basedir restriction,
         * try use wp_upload_dir instead. if this fail too, send pure
         * xml file to user
         */
        if (empty($zip->filename)) {
            $temp_dir = wp_upload_dir();
            $temp_dir = $temp_dir['basedir'];
            $file = tempnam($temp_dir, "zip");
            $zip = new ZipArchive();
            $zip->open($file, ZipArchive::OVERWRITE);
        }
        /**
         * send a zip file
         */
        if (!empty($zip->filename)) {
            $zip->addFromString('settings.xml', $data);
            $zip->addFromString('settings.php', $code);
            $zip->close();
            $data = file_get_contents($file);
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=" . $zipname);
            header("Content-Type: application/zip");
            header("Content-length: " . strlen($data) . "\n\n");
            header("Content-Transfer-Encoding: binary");
            echo $data;
            unlink($file);
            die;
        }
    }
    /**
     * download the xml if fail downloading zip
     */
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . $filename);
    header("Content-Type: application/xml");
    header("Content-length: " . strlen($data) . "\n\n");
    echo $data;
    die;
}
/**
 * Custom Export function for Module Manager.
 *
 * Exports selected items (by ID) and of specified type (eg views, view-templates).
 * Returns xml string.
 *
 * @global type $iclTranslationManagement
 * @param array $items
 * @param type $_type
 * @param type $return mixed array|xml|download
 * @return string
 */
function wpcf_admin_export_selected_data(array $items, $_type = 'all', $return = 'download', $use_cache = false)
{
    global $wpcf;
    $xml = new ICL_Array2XML();
    $data = array();
    $data['settings'] = wpcf_get_settings();
    if ('user_groups' == $_type || 'all' == $_type) {
        // Get groups
        if (empty($items)) {
            $groups = get_posts(array('post_type' => TYPES_USER_META_FIELD_GROUP_CPT_NAME, 'post_status' => null, 'numberposts' => '-1'));
        } else {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            foreach ($items as $k => $item) {
                if (isset($item['id'])) {
                    $items[$k] = intval(wpcf_modman_get_submitted_id('groups', $item['id']));
                }
            }
            $args = array('post__in' => $items, 'post_type' => TYPES_USER_META_FIELD_GROUP_CPT_NAME, 'post_status' => 'all', 'posts_per_page' => -1);
            $groups = get_posts($args);
        }
        if (!empty($groups)) {
            $data['user_groups'] = array('__key' => 'group');
            foreach ($groups as $key => $post) {
                $post = (array) $post;
                $post_data = array();
                $copy_data = array('ID', 'post_content', 'post_title', 'post_excerpt', 'post_type', 'post_status');
                foreach ($copy_data as $copy) {
                    if (isset($post[$copy])) {
                        $post_data[$copy] = $post[$copy];
                    }
                }
                $_data = $post_data;
                $meta = get_post_custom($post['ID']);
                if (!empty($meta)) {
                    $_meta = array();
                    foreach ($meta as $meta_key => $meta_value) {
                        if (in_array($meta_key, array('_wp_types_group_showfor', '_wp_types_group_fields', '_wp_types_group_admin_styles'))) {
                            $_meta[$meta_key] = $meta_value[0];
                        }
                    }
                    if (!empty($_meta)) {
                        $_data['meta'] = $_meta;
                    }
                }
                $_data['checksum'] = $_data['hash'] = $wpcf->export->generate_checksum('group', $post['ID']);
                $_data['__types_id'] = $post['post_name'];
                $_data['__types_title'] = $post['post_title'];
                $data['user_groups']['group-' . $post['ID']] = $_data;
            }
        }
        if (!empty($items)) {
            // Get fields by group
            // TODO Document why we use by_group
            $fields = array();
            foreach ($groups as $key => $post) {
                $fields = array_merge($fields, wpcf_admin_fields_get_fields_by_group($post->ID, 'slug', false, false, false, TYPES_USER_META_FIELD_GROUP_CPT_NAME, 'wpcf-usermeta', $use_cache));
            }
        } else {
            // Get fields
            $fields = wpcf_admin_fields_get_fields(false, false, false, 'wpcf-usermeta');
        }
        if (!empty($fields)) {
            // Add checksums before WPML
            foreach ($fields as $field_id => $field) {
                // TODO WPML and others should use hook
                $fields[$field_id] = apply_filters('wpcf_export_field', $fields[$field_id]);
                $fields[$field_id]['__types_id'] = $field_id;
                $fields[$field_id]['__types_title'] = $field['name'];
                $fields[$field_id]['checksum'] = $fields[$field_id]['hash'] = $wpcf->export->generate_checksum('field', $field_id);
            }
            // WPML
            // todo remove WPML dependency, see https://onthegosystems.myjetbrains.com/youtrack/issue/types-749#comment=102-105900
            global $iclTranslationManagement;
            if (!empty($iclTranslationManagement)) {
                foreach ($fields as $field_id => $field) {
                    // TODO Check this for all fields
                    if (isset($iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id])) {
                        $fields[$field_id]['wpml_action'] = $iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id];
                    }
                }
            }
            $data['user_fields'] = $fields;
            $data['user_fields']['__key'] = 'field';
        }
    }
    // Export term field groups and term field definitions.
    if (in_array($_type, array('term_groups', 'all'))) {
        $ie_controller = Types_Import_Export::get_instance();
        $data['term_groups'] = $ie_controller->export_field_groups_for_domain(Types_Field_Utils::DOMAIN_TERMS);
        $data['term_fields'] = $ie_controller->export_field_definitions_for_domain(Types_Field_Utils::DOMAIN_TERMS);
    }
    if ('groups' == $_type || 'all' == $_type) {
        // Get groups
        if (empty($items)) {
            $groups = get_posts('post_type=wp-types-group&post_status=null&numberposts=-1');
        } else {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            foreach ($items as $k => $item) {
                if (isset($item['id'])) {
                    $items[$k] = intval(wpcf_modman_get_submitted_id('groups', $item['id']));
                }
            }
            $args = array('post__in' => $items, 'post_type' => TYPES_CUSTOM_FIELD_GROUP_CPT_NAME, 'post_status' => 'all', 'posts_per_page' => -1);
            $groups = get_posts($args);
        }
        if (!empty($groups)) {
            $data['groups'] = array('__key' => 'group');
            foreach ($groups as $key => $post) {
                $post = (array) $post;
                $post_data = array();
                $copy_data = array('ID', 'post_content', 'post_title', 'post_excerpt', 'post_type', 'post_status');
                foreach ($copy_data as $copy) {
                    if (isset($post[$copy])) {
                        $post_data[$copy] = $post[$copy];
                    }
                }
                $_data = $post_data;
                $meta = get_post_custom($post['ID']);
                if (!empty($meta)) {
                    $_meta = array();
                    foreach ($meta as $meta_key => $meta_value) {
                        if (in_array($meta_key, array('_wp_types_group_terms', '_wp_types_group_post_types', '_wp_types_group_fields', '_wp_types_group_templates', '_wpcf_conditional_display', '_wp_types_group_filters_association', '_wp_types_group_admin_styles'))) {
                            $_meta[$meta_key] = $meta_value[0];
                            $_meta[$meta_key] = maybe_unserialize($_meta[$meta_key]);
                        }
                    }
                    if (!empty($_meta)) {
                        $_data['meta'] = $_meta;
                    }
                }
                $_data['checksum'] = $_data['hash'] = $wpcf->export->generate_checksum('group', $post['ID']);
                $_data['__types_id'] = $post['post_name'];
                $_data['__types_title'] = $post['post_title'];
                $data['groups']['group-' . $post['ID']] = $_data;
            }
        }
        if (!empty($items)) {
            // Get fields by group
            // TODO Document why we use by_group
            $fields = array();
            foreach ($groups as $key => $post) {
                $fields = array_merge($fields, wpcf_admin_fields_get_fields_by_group($post->ID, 'slug', false, false, false, TYPES_CUSTOM_FIELD_GROUP_CPT_NAME, 'wpcf-fields', $use_cache));
            }
        } else {
            // Get fields
            $fields = wpcf_admin_fields_get_fields();
        }
        if (!empty($fields)) {
            // Add checksums before WPML
            foreach ($fields as $field_id => $field) {
                // TODO WPML and others should use hook
                $fields[$field_id] = apply_filters('wpcf_export_field', $fields[$field_id]);
                $fields[$field_id]['__types_id'] = $field_id;
                $fields[$field_id]['__types_title'] = $field['name'];
                $fields[$field_id]['checksum'] = $fields[$field_id]['hash'] = $wpcf->export->generate_checksum('field', $field_id);
            }
            // WPML
            // todo remove WPML dependency, see https://onthegosystems.myjetbrains.com/youtrack/issue/types-749#comment=102-105900
            global $iclTranslationManagement;
            if (!empty($iclTranslationManagement)) {
                foreach ($fields as $field_id => $field) {
                    // TODO Check this for all fields
                    if (isset($iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id])) {
                        $fields[$field_id]['wpml_action'] = $iclTranslationManagement->settings['custom_fields_translation'][wpcf_types_get_meta_prefix($field) . $field_id];
                    }
                }
            }
            $data['fields'] = $fields;
            $data['fields']['__key'] = 'field';
        }
    }
    // Get custom types
    if ('types' == $_type || 'all' == $_type) {
        $custom_types = get_option(WPCF_OPTION_NAME_CUSTOM_TYPES, array());
        // Get custom types
        // TODO Document $items
        if (!empty($items)) {
            /*
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            $_items = array();
            foreach ($items as $k => $item) {
                if (is_array($item) && isset($item['id'])) {
                    $_items[$item['id']] = true;
                } else {
                    $_items[$item] = true;
                }
            }
            $custom_types = array_intersect_key($custom_types, $_items);
        }
        // Get custom types
        if (!empty($custom_types)) {
            foreach ($custom_types as $key => $type) {
                if (isset($type['custom-field-group']) && is_array($type['custom-field-group']) && !empty($type['custom-field-group'])) {
                    foreach ($type['custom-field-group'] as $custom_field_group_id => $senseless_as_it_is_always_one) {
                        $custom_field_group = get_post($custom_field_group_id);
                        // unset custom field USING ID AS KEY AND "1" AS VALUE from custom post type
                        unset($custom_types[$key]['custom-field-group'][$custom_field_group_id]);
                        // continue with next if this custom field group no longer exists
                        if (!is_object($custom_field_group)) {
                            continue;
                        }
                        // set custom field, generating an unique key (but without a particular meaning) AND ID AS VALUE to custom post type
                        $custom_types[$key]['custom-field-group']['group_' . $custom_field_group_id] = $custom_field_group_id;
                    }
                }
                $custom_types[$key]['id'] = $key;
                $custom_types[$key] = apply_filters('wpcf_export_custom_post_type', $custom_types[$key]);
                $custom_types[$key]['__types_id'] = $key;
                $custom_types[$key]['__types_title'] = $type['labels']['name'];
                $custom_types[$key]['checksum'] = $custom_types[$key]['hash'] = $wpcf->export->generate_checksum('custom_post_type', $key, $type);
            }
            $data['types'] = $custom_types;
            $data['types']['__key'] = 'type';
        }
        if (!empty($items)) {
            // Get post relationships only for items
            $relationships_all = get_option('wpcf_post_relationship', array());
            $relationships = array();
            foreach ($relationships_all as $parent => $children) {
                if (in_array($parent, $items)) {
                    foreach ($children as $child => $childdata) {
                        if (in_array($child, $items)) {
                            if (!isset($relationships[$parent])) {
                                $relationships[$parent] = array();
                            }
                            $relationships[$parent][$child] = $childdata;
                        }
                    }
                }
            }
        } else {
            // Get post relationships
            $relationships = get_option('wpcf_post_relationship', array());
        }
        if (!empty($relationships)) {
            $data['post_relationships']['data'] = json_encode($relationships);
        }
    }
    // Get custom tax
    if ('taxonomies' == $_type || 'all' == $_type) {
        if (!empty($items)) {
            /*
             *
             * This fails
             * $items are in form of:
             * 0 => array('id' => 'pt', ...)
             */
            //            $custom_taxonomies = array_intersect_key( get_option( WPCF_OPTION_NAME_CUSTOM_TAXONOMIES,
            //                            array() ), array_flip( $items ) );
            $_items = array();
            foreach ($items as $k => $item) {
                if (is_array($item) && isset($item['id'])) {
                    $_items[$item['id']] = true;
                } else {
                    $_items[$item] = true;
                }
            }
            $custom_taxonomies = array_intersect_key(get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array()), $_items);
        } else {
            // Get custom tax
            $custom_taxonomies = get_option(WPCF_OPTION_NAME_CUSTOM_TAXONOMIES, array());
        }
        if (!empty($custom_taxonomies)) {
            foreach ($custom_taxonomies as $key => $tax) {
                $custom_taxonomies[$key]['id'] = $key;
                $custom_taxonomies[$key] = apply_filters('wpcf_filter_export_custom_taxonomy', $custom_taxonomies[$key]);
                $custom_taxonomies[$key]['__types_id'] = $key;
                $custom_taxonomies[$key]['__types_title'] = $tax['labels']['name'];
                $custom_taxonomies[$key]['checksum'] = $wpcf->export->generate_checksum('custom_taxonomy', $key, $tax);
            }
            $data['taxonomies'] = $custom_taxonomies;
            $data['taxonomies']['__key'] = 'taxonomy';
        }
    }
    /*
     *
     * Since Types 1.2
     */
    if ($return == 'array') {
        return $data;
    } else {
        if ($return == 'xml') {
            return $xml->array2xml($data, 'types');
        } else {
            if ($return == 'module_manager') {
                $items = array();
                // Re-arrange fields
                if (!empty($data['fields'])) {
                    foreach ($data['fields'] as $_data) {
                        if (is_array($_data) && isset($_data['__types_id']) && isset($_data['checksum'])) {
                            $_item = array();
                            $_item['hash'] = $_item['checksum'] = $_data['checksum'];
                            $_item['id'] = $_data['__types_id'];
                            $_item['title'] = $_data['__types_title'];
                            $items['__fields'][$_data['__types_id']] = $_item;
                        }
                    }
                }
                // Add checksums to items
                foreach ($data as $_t => $type) {
                    foreach ($type as $_data) {
                        // Skip fields
                        if ($_t == 'fields') {
                            continue;
                        }
                        if (is_array($_data) && isset($_data['__types_id']) && isset($_data['checksum'])) {
                            $_item = array();
                            $_item['hash'] = $_item['checksum'] = $_data['checksum'];
                            $_item['id'] = $_data['__types_id'];
                            $_item['title'] = $_data['__types_title'];
                            $items[$_data['__types_id']] = $_item;
                        }
                    }
                }
                return array('xml' => $xml->array2xml($data, 'types'), 'items' => $items);
            }
        }
    }
    // Offer for download
    $data = $xml->array2xml($data, 'types');
    $sitename = sanitize_title(get_bloginfo('name'));
    if (empty($sitename)) {
        $sitename = 'wp';
    }
    $sitename .= '.';
    $filename = $sitename . 'types.' . date('Y-m-d') . '.xml';
    $code = "<?php\r\n";
    $code .= '$timestamp = ' . time() . ';' . "\r\n";
    $code .= "\r\n?" . ">";
    if (class_exists('ZipArchive')) {
        $zipname = $sitename . 'types.' . date('Y-m-d') . '.zip';
        $temp_dir = wpcf_get_temporary_directory();
        if (empty($temp_dir)) {
            die(__('There is a problem with temporary directory.', 'wpcf'));
        }
        $file = tempnam($temp_dir, "zip");
        $zip = new ZipArchive();
        $zip->open($file, ZipArchive::OVERWRITE);
        /**
         * if sys_get_temp_dir fail in case of open_basedir restriction,
         * try use wp_upload_dir instead. if this fail too, send pure
         * xml file to user
         */
        if (empty($zip->filename)) {
            $temp_dir = wp_upload_dir();
            $temp_dir = $temp_dir['basedir'];
            $file = tempnam($temp_dir, "zip");
            $zip = new ZipArchive();
            $zip->open($file, ZipArchive::OVERWRITE);
        }
        /**
         * send a zip file
         */
        if (!empty($zip->filename)) {
            $zip->addFromString('settings.xml', $data);
            $zip->addFromString('settings.php', $code);
            $zip->close();
            $data = file_get_contents($file);
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=" . $zipname);
            header("Content-Type: application/zip");
            header("Content-length: " . strlen($data) . "\n\n");
            header("Content-Transfer-Encoding: binary");
            echo $data;
            unlink($file);
            die;
        }
    }
    /**
     * download the xml if fail downloading zip
     */
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . $filename);
    header("Content-Type: application/xml");
    header("Content-length: " . strlen($data) . "\n\n");
    echo $data;
    die;
}