/**
  * New/Edit post submit handler
  *
  * @return void
  */
 function submit_post()
 {
     check_ajax_referer('wpuf_form_add');
     @header('Content-Type: application/json; charset=' . get_option('blog_charset'));
     $form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
     $form_vars = $this->get_input_fields($form_id);
     $form_settings = wpuf_get_form_settings($form_id);
     list($post_vars, $taxonomy_vars, $meta_vars) = $form_vars;
     // don't check captcha on post edit
     if (!isset($_POST['post_id'])) {
         // search if rs captcha is there
         if ($this->search($post_vars, 'input_type', 'really_simple_captcha')) {
             $this->validate_rs_captcha();
         }
         // check recaptcha
         if ($this->search($post_vars, 'input_type', 'recaptcha')) {
             $this->validate_re_captcha();
         }
     }
     $is_update = false;
     $post_author = null;
     $default_post_author = wpuf_get_option('default_post_owner', 'wpuf_general', 1);
     // Guest Stuffs: check for guest post
     if (!is_user_logged_in()) {
         if ($form_settings['guest_post'] == 'true' && $form_settings['guest_details'] == 'true') {
             $guest_name = trim($_POST['guest_name']);
             $guest_email = trim($_POST['guest_email']);
             // is valid email?
             if (!is_email($guest_email)) {
                 $this->send_error(__('Invalid email address.', 'wpuf'));
             }
             // check if the user email already exists
             $user = get_user_by('email', $guest_email);
             if ($user) {
                 // $post_author = $user->ID;
                 echo json_encode(array('success' => false, 'error' => __("You already have an account in our site. Please login to continue.\n\nClicking 'OK' will redirect you to the login page and you will lost the form data.\nClick 'Cancel' to stay at this page.", 'wpuf'), 'type' => 'login', 'redirect_to' => wp_login_url(get_permalink($_POST['page_id']))));
                 exit;
             } else {
                 // user not found, lets register him
                 // username from email address
                 $username = $this->guess_username($guest_email);
                 $user_pass = wp_generate_password(12, false);
                 $errors = new WP_Error();
                 do_action('register_post', $username, $guest_email, $errors);
                 $user_id = wp_create_user($username, $user_pass, $guest_email);
                 // if its a success and no errors found
                 if ($user_id && !is_wp_error($user_id)) {
                     update_user_option($user_id, 'default_password_nag', true, true);
                     //Set up the Password change nag.
                     if (class_exists('Theme_My_Login_Custom_Email')) {
                         do_action('tml_new_user_registered', $user_id, $user_pass);
                     } else {
                         wp_new_user_notification($user_id, $user_pass);
                     }
                     // update display name to full name
                     wp_update_user(array('ID' => $user_id, 'display_name' => $guest_name));
                     $post_author = $user_id;
                 } else {
                     //something went wrong creating the user, set post author to the default author
                     $post_author = $default_post_author;
                 }
             }
             // guest post is enabled and details are off
         } elseif ($form_settings['guest_post'] == 'true' && $form_settings['guest_details'] == 'false') {
             $post_author = $default_post_author;
         }
         // the user must be logged in already
     } else {
         $post_author = get_current_user_id();
     }
     $postarr = array('post_type' => $form_settings['post_type'], 'post_status' => isset($form_settings['post_status']) ? $form_settings['post_status'] : 'publish', 'post_author' => $post_author, 'post_title' => isset($_POST['post_title']) ? trim($_POST['post_title']) : '', 'post_content' => isset($_POST['post_content']) ? trim($_POST['post_content']) : '', 'post_excerpt' => isset($_POST['post_excerpt']) ? trim($_POST['post_excerpt']) : '');
     if (isset($_POST['category'])) {
         $category = $_POST['category'];
         $postarr['post_category'] = is_array($category) ? $category : array($category);
     }
     if (isset($_POST['tags'])) {
         $postarr['tags_input'] = explode(',', $_POST['tags']);
     }
     // if post_id is passed, we update the post
     if (isset($_POST['post_id'])) {
         $is_update = true;
         $postarr['ID'] = $_POST['post_id'];
         $postarr['post_date'] = $_POST['post_date'];
         $postarr['comment_status'] = $_POST['comment_status'];
         $postarr['post_author'] = $_POST['post_author'];
         $postarr['post_parent'] = get_post_field('post_parent', $_POST['post_id']);
         if ($form_settings['edit_post_status'] == '_nochange') {
             $postarr['post_status'] = get_post_field('post_status', $_POST['post_id']);
         } else {
             $postarr['post_status'] = $form_settings['edit_post_status'];
         }
     } else {
         if (isset($form_settings['comment_status'])) {
             $postarr['comment_status'] = $form_settings['comment_status'];
         }
     }
     // check the form status, it might be already a draft
     // in that case, it already has the post_id field
     // so, WPUF's add post action/filters won't work for new posts
     if (isset($_POST['wpuf_form_status']) && $_POST['wpuf_form_status'] == 'new') {
         $is_update = false;
     }
     // set default post category if it's not been set yet and if post type supports
     if (!isset($postarr['post_category']) && isset($form_settings['default_cat']) && is_object_in_taxonomy($form_settings['post_type'], 'category')) {
         $postarr['post_category'] = array($form_settings['default_cat']);
     }
     // validation filter
     if ($is_update) {
         $error = apply_filters('wpuf_update_post_validate', '');
     } else {
         $error = apply_filters('wpuf_add_post_validate', '');
     }
     if (!empty($error)) {
         $this->send_error($error);
     }
     // ############ It's Time to Save the World ###############
     if ($is_update) {
         $postarr = apply_filters('wpuf_update_post_args', $postarr, $form_id, $form_settings, $form_vars);
     } else {
         $postarr = apply_filters('wpuf_add_post_args', $postarr, $form_id, $form_settings, $form_vars);
     }
     $post_id = wp_insert_post($postarr);
     if ($post_id) {
         self::update_post_meta($meta_vars, $post_id);
         // if user has a subscription pack
         $user_wpuf_subscription_pack = get_user_meta(get_current_user_id(), '_wpuf_subscription_pack', true);
         if (!empty($user_wpuf_subscription_pack) && isset($user_wpuf_subscription_pack['_enable_post_expiration']) && isset($user_wpuf_subscription_pack['expire']) && strtotime($user_wpuf_subscription_pack['expire']) >= time()) {
             $expire_date = date('Y-m-d', strtotime("+" . $user_wpuf_subscription_pack['_post_expiration_time']));
             update_post_meta($post_id, $this->post_expiration_date, $expire_date);
             // save post status after expiration
             $expired_post_status = $user_wpuf_subscription_pack['_expired_post_status'];
             update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
             // if mail active
             if (isset($user_wpuf_subscription_pack['_enable_mail_after_expired']) && $user_wpuf_subscription_pack['_enable_mail_after_expired'] == 'on') {
                 $post_expiration_message = $user_wpuf_subscription_pack['_post_expiration_message'];
                 update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
             }
         } elseif (!empty($user_wpuf_subscription_pack) && isset($user_wpuf_subscription_pack['expire']) && strtotime($user_wpuf_subscription_pack['expire']) <= time()) {
             if (isset($form_settings['expiration_settings']['enable_post_expiration'])) {
                 $expire_date = date('Y-m-d', strtotime("+" . $form_settings['expiration_settings']['expiration_time_value'] . ' ' . $form_settings['expiration_settings']['expiration_time_type'] . ""));
                 update_post_meta($post_id, $this->post_expiration_date, $expire_date);
                 // save post status after expiration
                 $expired_post_status = $form_settings['expiration_settings']['expired_post_status'];
                 update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
                 // if mail active
                 if (isset($form_settings['expiration_settings']['enable_mail_after_expired']) && $form_settings['expiration_settings']['enable_mail_after_expired'] == 'on') {
                     $post_expiration_message = $form_settings['expiration_settings']['post_expiration_message'];
                     update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
                 }
             }
         } elseif (empty($user_wpuf_subscription_pack)) {
             if (isset($form_settings['expiration_settings']['enable_post_expiration'])) {
                 $expire_date = date('Y-m-d', strtotime("+" . $form_settings['expiration_settings']['expiration_time_value'] . ' ' . $form_settings['expiration_settings']['expiration_time_type'] . ""));
                 update_post_meta($post_id, $this->post_expiration_date, $expire_date);
                 // save post status after expiration
                 $expired_post_status = $form_settings['expiration_settings']['expired_post_status'];
                 update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
                 // if mail active
                 if (isset($form_settings['expiration_settings']['enable_mail_after_expired']) && $form_settings['expiration_settings']['enable_mail_after_expired'] == 'on') {
                     $post_expiration_message = $form_settings['expiration_settings']['post_expiration_message'];
                     update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
                 }
             }
         }
         // set the post form_id for later usage
         update_post_meta($post_id, self::$config_id, $form_id);
         // save post formats if have any
         if (isset($form_settings['post_format']) && $form_settings['post_format'] != '0') {
             if (post_type_supports($form_settings['post_type'], 'post-formats')) {
                 set_post_format($post_id, $form_settings['post_format']);
             }
         }
         // find our if any images in post content and associate them
         if (!empty($postarr['post_content'])) {
             $dom = new DOMDocument();
             @$dom->loadHTML($postarr['post_content']);
             $images = $dom->getElementsByTagName('img');
             if ($images->length) {
                 foreach ($images as $img) {
                     $url = $img->getAttribute('src');
                     $url = str_replace(array('"', "'", "\\"), '', $url);
                     $attachment_id = wpuf_get_attachment_id_from_url($url);
                     if ($attachment_id) {
                         wpuf_associate_attachment($attachment_id, $post_id);
                     }
                 }
             }
         }
         // save any custom taxonomies
         $woo_attr = array();
         foreach ($taxonomy_vars as $taxonomy) {
             if (isset($_POST[$taxonomy['name']])) {
                 if (is_object_in_taxonomy($form_settings['post_type'], $taxonomy['name'])) {
                     $tax = $_POST[$taxonomy['name']];
                     // if it's not an array, make it one
                     if (!is_array($tax)) {
                         $tax = array($tax);
                     }
                     if ($taxonomy['type'] == 'text') {
                         $hierarchical = array_map('trim', array_map('strip_tags', explode(',', $_POST[$taxonomy['name']])));
                         wp_set_object_terms($post_id, $hierarchical, $taxonomy['name']);
                         // woocommerce check
                         if (isset($taxonomy['woo_attr']) && $taxonomy['woo_attr'] == 'yes') {
                             $woo_attr[sanitize_title($taxonomy['name'])] = $this->woo_attribute($taxonomy);
                         }
                     } else {
                         if (is_taxonomy_hierarchical($taxonomy['name'])) {
                             wp_set_post_terms($post_id, $_POST[$taxonomy['name']], $taxonomy['name']);
                             // woocommerce check
                             if (isset($taxonomy['woo_attr']) && $taxonomy['woo_attr'] == 'yes') {
                                 $woo_attr[sanitize_title($taxonomy['name'])] = $this->woo_attribute($taxonomy);
                             }
                         } else {
                             if ($tax) {
                                 $non_hierarchical = array();
                                 foreach ($tax as $value) {
                                     $term = get_term_by('id', $value, $taxonomy['name']);
                                     if ($term && !is_wp_error($term)) {
                                         $non_hierarchical[] = $term->name;
                                     }
                                 }
                                 wp_set_post_terms($post_id, $non_hierarchical, $taxonomy['name']);
                             }
                         }
                         // hierarchical
                     }
                     // is text
                 }
                 // is object tax
             }
             // isset tax
         }
         // if a woocommerce attribute
         if ($woo_attr) {
             update_post_meta($post_id, '_product_attributes', $woo_attr);
         }
         if ($is_update) {
             // plugin API to extend the functionality
             do_action('wpuf_edit_post_after_update', $post_id, $form_id, $form_settings, $form_vars);
             //send mail notification
             if (isset($form_settings['notification']) && $form_settings['notification']['edit'] == 'on') {
                 $mail_body = $this->prepare_mail_body($form_settings['notification']['edit_body'], $post_author, $post_id);
                 wp_mail($form_settings['notification']['edit_to'], $form_settings['notification']['edit_subject'], $mail_body);
             }
         } else {
             // plugin API to extend the functionality
             do_action('wpuf_add_post_after_insert', $post_id, $form_id, $form_settings, $form_vars);
             // send mail notification
             if (isset($form_settings['notification']) && $form_settings['notification']['new'] == 'on') {
                 $mail_body = $this->prepare_mail_body($form_settings['notification']['new_body'], $post_author, $post_id);
                 wp_mail($form_settings['notification']['new_to'], $form_settings['notification']['new_subject'], $mail_body);
             }
         }
         //redirect URL
         $show_message = false;
         $redirect_to = false;
         if ($is_update) {
             if ($form_settings['edit_redirect_to'] == 'page') {
                 $redirect_to = get_permalink($form_settings['edit_page_id']);
             } elseif ($form_settings['edit_redirect_to'] == 'url') {
                 $redirect_to = $form_settings['edit_url'];
             } elseif ($form_settings['edit_redirect_to'] == 'same') {
                 $redirect_to = add_query_arg(array('pid' => $post_id, '_wpnonce' => wp_create_nonce('wpuf_edit'), 'msg' => 'post_updated'), get_permalink($_POST['page_id']));
             } else {
                 $redirect_to = get_permalink($post_id);
             }
         } else {
             if ($form_settings['redirect_to'] == 'page') {
                 $redirect_to = get_permalink($form_settings['page_id']);
             } elseif ($form_settings['redirect_to'] == 'url') {
                 $redirect_to = $form_settings['url'];
             } elseif ($form_settings['redirect_to'] == 'same') {
                 $show_message = true;
             } else {
                 $redirect_to = get_permalink($post_id);
             }
         }
         // send the response
         $response = array('success' => true, 'redirect_to' => $redirect_to, 'show_message' => $show_message, 'message' => $form_settings['message']);
         if ($is_update) {
             $response = apply_filters('wpuf_edit_post_redirect', $response, $post_id, $form_id, $form_settings);
         } else {
             $response = apply_filters('wpuf_add_post_redirect', $response, $post_id, $form_id, $form_settings);
         }
         wpuf_clear_buffer();
         echo json_encode($response);
         exit;
     }
     $this->send_error(__('Something went wrong', 'wpuf'));
 }
    /**
     * New/Edit post submit handler
     *
     * @return void
     */
    function submit_post()
    {
        check_ajax_referer('wpuf_form_add');
        @header('Content-Type: application/json; charset=' . get_option('blog_charset'));
        $form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
        $form_vars = $this->get_input_fields($form_id);
        $form_settings = wpuf_get_form_settings($form_id);
        list($post_vars, $taxonomy_vars, $meta_vars) = $form_vars;
        // don't check captcha on post edit
        if (!isset($_POST['post_id'])) {
            // search if rs captcha is there
            if ($this->search($post_vars, 'input_type', 'really_simple_captcha')) {
                $this->validate_rs_captcha();
            }
            // check recaptcha
            if ($this->search($post_vars, 'input_type', 'recaptcha')) {
                $this->validate_re_captcha();
            }
        }
        $is_update = false;
        $post_author = null;
        $default_post_author = wpuf_get_option('default_post_owner', 'wpuf_general', 1);
        // Guest Stuffs: check for guest post
        if (!is_user_logged_in()) {
            if ($form_settings['guest_post'] == 'true' && $form_settings['guest_details'] == 'true') {
                $guest_name = trim($_POST['guest_name']);
                $guest_email = trim($_POST['guest_email']);
                // is valid email?
                if (!is_email($guest_email)) {
                    $this->send_error(__('Invalid email address.', 'wpuf'));
                }
                // check if the user email already exists
                $user = get_user_by('email', $guest_email);
                if ($user) {
                    // $post_author = $user->ID;
                    echo json_encode(array('success' => false, 'error' => __("You already have an account in our site. Please login to continue.\n\nClicking 'OK' will redirect you to the login page and you will lost the form data.\nClick 'Cancel' to stay at this page.", 'wpuf'), 'type' => 'login', 'redirect_to' => wp_login_url(get_permalink($_POST['page_id']))));
                    exit;
                } else {
                    // user not found, lets register him
                    // username from email address
                    $username = $this->guess_username($guest_email);
                    $user_pass = wp_generate_password(12, false);
                    $errors = new WP_Error();
                    do_action('register_post', $username, $guest_email, $errors);
                    $user_id = wp_create_user($username, $user_pass, $guest_email);
                    // if its a success and no errors found
                    if ($user_id && !is_wp_error($user_id)) {
                        update_user_option($user_id, 'default_password_nag', true, true);
                        //Set up the Password change nag.
                        if (class_exists('Theme_My_Login_Custom_Email')) {
                            do_action('tml_new_user_registered', $user_id, $user_pass);
                        } else {
                            wp_new_user_notification($user_id, $user_pass);
                        }
                        // update display name to full name
                        wp_update_user(array('ID' => $user_id, 'display_name' => $guest_name));
                        $post_author = $user_id;
                    } else {
                        //something went wrong creating the user, set post author to the default author
                        $post_author = $default_post_author;
                    }
                }
                // guest post is enabled and details are off
            } elseif ($form_settings['guest_post'] == 'true' && $form_settings['guest_details'] == 'false') {
                //$post_author = $default_post_author;
                $post_author = 0;
            }
            // the user must be logged in already
        } else {
            $post_author = get_current_user_id();
        }
        $postarr = array('post_type' => $form_settings['post_type'], 'post_status' => isset($form_settings['post_status']) ? $form_settings['post_status'] : 'publish', 'post_author' => $post_author, 'post_title' => isset($_POST['post_title']) ? trim($_POST['post_title']) : '', 'post_content' => isset($_POST['post_content']) ? trim($_POST['post_content']) : '', 'post_excerpt' => isset($_POST['post_excerpt']) ? trim($_POST['post_excerpt']) : '');
        if (isset($_POST['category'])) {
            $category = $_POST['category'];
            $postarr['post_category'] = is_array($category) ? $category : array($category);
            if (!is_array($category) && is_string($category)) {
                $category_strings = explode(',', $category);
                $cat_ids = array();
                foreach ($category_strings as $key => $each_cat_string) {
                    $cat_ids[] = get_cat_ID(trim($each_cat_string));
                    $postarr['post_category'] = $cat_ids;
                }
            }
        }
        if (isset($_POST['tags'])) {
            $postarr['tags_input'] = explode(',', $_POST['tags']);
        }
        // if post_id is passed, we update the post
        if (isset($_POST['post_id'])) {
            $is_update = true;
            $postarr['ID'] = $_POST['post_id'];
            $postarr['post_date'] = $_POST['post_date'];
            $postarr['comment_status'] = $_POST['comment_status'];
            $postarr['post_author'] = $_POST['post_author'];
            $postarr['post_parent'] = get_post_field('post_parent', $_POST['post_id']);
            if ($form_settings['edit_post_status'] == '_nochange') {
                $postarr['post_status'] = get_post_field('post_status', $_POST['post_id']);
            } else {
                $postarr['post_status'] = $form_settings['edit_post_status'];
            }
        } else {
            if (isset($form_settings['comment_status'])) {
                $postarr['comment_status'] = $form_settings['comment_status'];
            }
        }
        // check the form status, it might be already a draft
        // in that case, it already has the post_id field
        // so, WPUF's add post action/filters won't work for new posts
        if (isset($_POST['wpuf_form_status']) && $_POST['wpuf_form_status'] == 'new') {
            $is_update = false;
        }
        // set default post category if it's not been set yet and if post type supports
        if (!isset($postarr['post_category']) && isset($form_settings['default_cat']) && is_object_in_taxonomy($form_settings['post_type'], 'category')) {
            $postarr['post_category'] = array($form_settings['default_cat']);
        }
        // validation filter
        if ($is_update) {
            $error = apply_filters('wpuf_update_post_validate', '');
        } else {
            $error = apply_filters('wpuf_add_post_validate', '');
        }
        if (!empty($error)) {
            $this->send_error($error);
        }
        // ############ It's Time to Save the World ###############
        if ($is_update) {
            $postarr = apply_filters('wpuf_update_post_args', $postarr, $form_id, $form_settings, $form_vars);
        } else {
            $postarr = apply_filters('wpuf_add_post_args', $postarr, $form_id, $form_settings, $form_vars);
        }
        $post_id = wp_insert_post($postarr);
        if ($post_id) {
            self::update_post_meta($meta_vars, $post_id);
            // if user has a subscription pack
            $user_wpuf_subscription_pack = get_user_meta(get_current_user_id(), '_wpuf_subscription_pack', true);
            if (!empty($user_wpuf_subscription_pack) && isset($user_wpuf_subscription_pack['_enable_post_expiration']) && isset($user_wpuf_subscription_pack['expire']) && strtotime($user_wpuf_subscription_pack['expire']) >= time()) {
                $expire_date = date('Y-m-d', strtotime("+" . $user_wpuf_subscription_pack['_post_expiration_time']));
                update_post_meta($post_id, $this->post_expiration_date, $expire_date);
                // save post status after expiration
                $expired_post_status = $user_wpuf_subscription_pack['_expired_post_status'];
                update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
                // if mail active
                if (isset($user_wpuf_subscription_pack['_enable_mail_after_expired']) && $user_wpuf_subscription_pack['_enable_mail_after_expired'] == 'on') {
                    $post_expiration_message = $user_wpuf_subscription_pack['_post_expiration_message'];
                    update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
                }
            } elseif (!empty($user_wpuf_subscription_pack) && isset($user_wpuf_subscription_pack['expire']) && strtotime($user_wpuf_subscription_pack['expire']) <= time()) {
                if (isset($form_settings['expiration_settings']['enable_post_expiration'])) {
                    $expire_date = date('Y-m-d', strtotime("+" . $form_settings['expiration_settings']['expiration_time_value'] . ' ' . $form_settings['expiration_settings']['expiration_time_type'] . ""));
                    update_post_meta($post_id, $this->post_expiration_date, $expire_date);
                    // save post status after expiration
                    $expired_post_status = $form_settings['expiration_settings']['expired_post_status'];
                    update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
                    // if mail active
                    if (isset($form_settings['expiration_settings']['enable_mail_after_expired']) && $form_settings['expiration_settings']['enable_mail_after_expired'] == 'on') {
                        $post_expiration_message = $form_settings['expiration_settings']['post_expiration_message'];
                        update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
                    }
                }
            } elseif (empty($user_wpuf_subscription_pack)) {
                if (isset($form_settings['expiration_settings']['enable_post_expiration'])) {
                    $expire_date = date('Y-m-d', strtotime("+" . $form_settings['expiration_settings']['expiration_time_value'] . ' ' . $form_settings['expiration_settings']['expiration_time_type'] . ""));
                    update_post_meta($post_id, $this->post_expiration_date, $expire_date);
                    // save post status after expiration
                    $expired_post_status = $form_settings['expiration_settings']['expired_post_status'];
                    update_post_meta($post_id, $this->expired_post_status, $expired_post_status);
                    // if mail active
                    if (isset($form_settings['expiration_settings']['enable_mail_after_expired']) && $form_settings['expiration_settings']['enable_mail_after_expired'] == 'on') {
                        $post_expiration_message = $form_settings['expiration_settings']['post_expiration_message'];
                        update_post_meta($post_id, $this->post_expiration_message, $post_expiration_message);
                    }
                }
            }
            // set the post form_id for later usage
            update_post_meta($post_id, self::$config_id, $form_id);
            // save post formats if have any
            if (isset($form_settings['post_format']) && $form_settings['post_format'] != '0') {
                if (post_type_supports($form_settings['post_type'], 'post-formats')) {
                    set_post_format($post_id, $form_settings['post_format']);
                }
            }
            // find our if any images in post content and associate them
            if (!empty($postarr['post_content'])) {
                $dom = new DOMDocument();
                @$dom->loadHTML($postarr['post_content']);
                $images = $dom->getElementsByTagName('img');
                if ($images->length) {
                    foreach ($images as $img) {
                        $url = $img->getAttribute('src');
                        $url = str_replace(array('"', "'", "\\"), '', $url);
                        $attachment_id = wpuf_get_attachment_id_from_url($url);
                        if ($attachment_id) {
                            wpuf_associate_attachment($attachment_id, $post_id);
                        }
                    }
                }
            }
            //If no_logged_in user, change into Variable Products
            if ($post_author != 1) {
                wp_set_object_terms($post_id, 'variable', 'product_type');
                //my array for setting the attributes
                $avail_attributes = array('xxlarge', 'extra-large', 'large', 'medium', 'small', 'extra-small', '12yrs', '10yrs', '8yrs', '6yrs', '4yrs', '2yrs');
                $avail_attributes2 = array('light-blue', 'pink', 'red', 'white-2');
                //Sets the attributes up to be used as variations but doesnt actually set them up as variations
                wp_set_object_terms($post_id, $avail_attributes, 'pa_size');
                wp_set_object_terms($post_id, $avail_attributes2, 'pa_color');
                $thedata = array('pa_color' => array('name' => 'pa_color', 'value' => '', 'position' => '0', 'is_visible' => '1', 'is_variation' => '1', 'is_taxonomy' => '1'), 'pa_size' => array('name' => 'pa_size', 'value' => '', 'position' => '0', 'is_visible' => '1', 'is_variation' => '1', 'is_taxonomy' => '1'));
                update_post_meta($post_id, '_product_attributes', $thedata);
                //Sets the Default Attributes
                $default_thedata = array('pa_color' => 'white-2', 'pa_size' => '8yrs');
                update_post_meta($post_id, '_default_attributes', $default_thedata);
                $this_post = get_post($post_id);
                $this_post_title = $this_post->post_title;
                //SKU追加
                update_post_meta($post_id, '_sku', $this_post_title);
                update_post_meta($post_id, '_price', 27.0);
                update_post_meta($post_id, '_regular_price', '27.0');
                update_post_meta($post_id, 'sf_page_title_one', 'Your Original T-shirt');
                update_post_meta($post_id, '_visibility', 'hidden');
                update_post_meta($post_id, '_stock_status', 'instock');
                wp_set_post_terms($post_id, '267', 'product_cat');
                //create Variations (Any size * Any Color) into DB _post//
                //insert Custmized Image into media library//
                $attach_id = get_post_thumbnail_id($post_id);
                $attachPath = get_attached_file($attach_id);
                $mediaDir = dirname($attachPath) . '/media';
                $originalDir = dirname($attachPath) . '/original';
                $reg = "/(.*)(?:\\.([^.]+\$))/";
                $originalName = basename($attachPath);
                $oriImagPath = $originalDir . '/' . $originalName;
                preg_match($reg, $originalName, $retArr);
                $upload_dir = wp_upload_dir();
                $media_upload_url = $upload_dir['url'] . '/media';
                //MIMEタイプの取得
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $org_mime_type = $finfo->file($oriImagPath);
                //Insert Original Image
                $org_attachment_post = array('post_mime_type' => $org_mime_type, 'post_title' => $originalName, 'post_content' => '', 'post_status' => 'inherit');
                $oriAttach_id = wp_insert_attachment($org_attachment_post, $oriImagPath, $post_id);
                // Set original image meta
                update_post_meta($post_id, 'l_original_thumbnail_id', $oriAttach_id);
                update_post_meta($post_id, 'm_original_thumbnail_id', $oriAttach_id);
                update_post_meta($post_id, 's_original_thumbnail_id', $oriAttach_id);
                //Amount of Variations
                $variationNum = 4;
                $thumbnail_size = 500;
                $thumbnail_string = $thumbnail_size . 'x' . $thumbnail_size;
                for ($i = 0; $i < $variationNum; $i++) {
                    //get T-shirts image path
                    if ($i == 0) {
                        $colImgName = $retArr[1] . '-lightblue';
                        $colImgName_half = $retArr[1] . '-lightblue-' . $thumbnail_string;
                    } elseif ($i == 1) {
                        $colImgName = $retArr[1] . '-pink';
                        $colImgName_half = $retArr[1] . '-pink-' . $thumbnail_string;
                    } elseif ($i == 2) {
                        $colImgName = $retArr[1] . '-red';
                        $colImgName_half = $retArr[1] . '-red-' . $thumbnail_string;
                    } elseif ($i == 3) {
                        $colImgName = $retArr[1] . '-white';
                        $colImgName_half = $retArr[1] . '-white-' . $thumbnail_string;
                    } elseif ($i == 4) {
                        $colImgName = $retArr[1] . '-sunshine';
                        $colImgName_half = $retArr[1] . '-sunshine-' . $thumbnail_string;
                    }
                    $colImgPath = $mediaDir . '/' . $colImgName . '.png';
                    /*
                                        $path_from_media = ltrim($upload_dir['subdir'],'/').'/media/'.$colImgName.'.png';
                                        $half_path_from_media = ltrim($upload_dir['subdir'],'/').'/media/'.$colImgName_half.'.png';
                    */
                    $attachment_post = array('post_mime_type' => 'image/png', 'post_title' => $colImgName, 'post_content' => '', 'post_status' => 'inherit');
                    // Insert the attachment.
                    $colAttach_id = wp_insert_attachment($attachment_post, $colImgPath, $post_id);
                    // Set wp_attachment_metadata
                    $the_attach_data = array('width' => 1000, 'height' => 1000, 'file' => $colImgName . '.png', 'sizes' => array('shop_single' => array('file' => $colImgName_half . '.png', 'width' => $thumbnail_size, 'height' => $thumbnail_size, 'mime-type' => 'image/png')));
                    // Insert wp_attachment_metadata
                    update_post_meta($colAttach_id, '_wp_attachment_metadata', $the_attach_data);
                    // Update main featured image to White T-shirt
                    if ($i == 3) {
                        //                        update_post_meta( $post_id, '_thumbnail_id' , $colAttach_id);
                        $featured_ColAttach_id = $colAttach_id;
                    }
                    //insert Variations Product//
                    $var_post = array('post_title' => 'Variation #' . $i . ' of ' . $this_post_title, 'post_author' => $post_author, 'post_name' => 'product-' . $post_id . '-variation-' . $i, 'post_status' => 'publish', 'post_parent' => $post_id, 'post_type' => 'product_variation', 'guid' => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $i);
                    // Insert the post into the database
                    $variable_id = wp_insert_post($var_post);
                    // Set ID
                    //$variable_id = $colAttach_id + 1;
                    // Set Original Image
                    //update_post_meta( $variable_id, '_ori_thumbnail_id', $oriAttach_id );
                    // Set thumbnail Image
                    update_post_meta($variable_id, '_thumbnail_id', $colAttach_id);
                    // Set price
                    update_post_meta($variable_id, '_price', 27.0);
                    update_post_meta($variable_id, '_regular_price', '27.0');
                    update_post_meta($variable_id, 'attribute_pa_size', '');
                    if ($i == 0) {
                        update_post_meta($variable_id, 'attribute_pa_color', 'light-blue');
                    } elseif ($i == 1) {
                        update_post_meta($variable_id, 'attribute_pa_color', 'pink');
                    } elseif ($i == 2) {
                        update_post_meta($variable_id, 'attribute_pa_color', 'red');
                    } elseif ($i == 3) {
                        update_post_meta($variable_id, 'attribute_pa_color', 'white-2');
                    } elseif ($i == 4) {
                        update_post_meta($variable_id, 'attribute_pa_color', 'sunshine');
                    }
                }
                //Set Featured Image 指定
                update_post_meta($post_id, '_thumbnail_id', $featured_ColAttach_id);
                //Delete original featured image
                wp_delete_post($attach_id, true);
                //商品タイトル変更
                $my_update_post = array();
                $my_update_post['ID'] = $post_id;
                $my_update_post['post_title'] = 'Customzed T-shirt';
                $my_update_post['post_content'] = '[spb_tabs width="1/1" el_position="first last"] [spb_tab title="Products"] [spb_text_block pb_margin_bottom="no" pb_border_bottom="no" el_class="product_tab" width="1/1" el_position="first last"]

&nbsp;

<strong>- American Apparel ® Fine jersey</strong>
<strong>- Slim fit</strong>
<strong>- Double stitched</strong>
<strong>- Direct-to-garment printing</strong>
<strong>- Brother GraffiTee, photo quality</strong>

<span style="color: #424242">The American Apparel® t-shirt is the smoothest and softest t-shirt you will ever wear. Made of fine jersey, it has a durable, vintage feel. These classic-cut shirts are known for their premium quality, as well as ability to stand up to a washing machine (will keep size and color after many washings). The shirts are 100% fine jersey cotton, except for the heather grey color (90% cotton, 10% polyester).</span>

&nbsp;

[/spb_text_block] [/spb_tab] [spb_tab title="Shipping"] [spb_text_block pb_margin_bottom="no" pb_border_bottom="no" width="1/1" el_position="first last"]

&nbsp;

We try to make sure that your product is sent out within 2 - 5 days of ordering it. But sometimes we are out of stock, and it might take a bit longer. But do not worry, we will always let you know in advance.

<strong>Estimated shipping times:</strong>
USA: 3-5 business days
Canada: 5-10 business days
World: 10-20 business days

All of our products are made and sent out by airmail from California, to anywhere in the world.

<small><span style="color: #ff0000"><strong>Important!</strong></span> Shipments outside of the USA may incur customs fees, depending on your country of residence. The fee may vary depending on your order value, country limits, and other factors. dumdiddy does not take responsibility for possible fees.</small>

&nbsp;

[/spb_text_block] [/spb_tab] [spb_tab title="Size"] [spb_text_block pb_margin_bottom="no" pb_border_bottom="no" width="1/1" el_position="first last"]

&nbsp;

ADULTS

U.S Size
<a href="http://dumdiddy.com/wp-content/uploads/2014/09/adult-us.png"><img class="alignnone wp-image-10640 size-full" src="http://dumdiddy.com/wp-content/uploads/2014/09/adult-us.png" alt="adult-us" width="467" height="70" /></a>

Metrics
<a href="http://dumdiddy.com/wp-content/uploads/2014/09/adult-metric.png"><img class="alignnone wp-image-10641 size-full" src="http://dumdiddy.com/wp-content/uploads/2014/09/adult-metric.png" alt="adult-metric" width="470" height="71" /></a>

&nbsp;

KIDS

U.S Size
<a href="http://dumdiddy.com/wp-content/uploads/2014/09/kids-us.png"><img class="alignnone wp-image-10638 size-full" src="http://dumdiddy.com/wp-content/uploads/2014/09/kids-us.png" alt="kids-us" width="524" height="92" /></a>

Metrics
<a href="http://dumdiddy.com/wp-content/uploads/2014/09/kids-metric.png"><img class="alignnone size-full wp-image-10639" src="http://dumdiddy.com/wp-content/uploads/2014/09/kids-metric.png" alt="kids-metric" width="525" height="92" /></a>

&nbsp;

[/spb_text_block] [/spb_tab] [spb_tab title="Color"] [spb_text_block pb_margin_bottom="no" pb_border_bottom="no" width="1/1" el_position="first last"]

&nbsp;

Actual colors based on American Apparel® color charts
<a href="http://dumdiddy.com/wp-content/uploads/2014/09/color-variation.png"><img class="alignnone size-full wp-image-10672" src="http://dumdiddy.com/wp-content/uploads/2014/09/color-variation.png" alt="color-variation" width="535" height="58" /></a>

&nbsp;

<address>This is only for reference based on the product. Actual product may differ.</address>&nbsp;

[/spb_text_block] [/spb_tab] [spb_tab title=""] [/spb_tab] [/spb_tabs]';
                wp_update_post($my_update_post);
                // Delete WPUF Pro form id
                delete_post_meta($post_id, '_wpuf_form_id');
            }
            // save any custom taxonomies
            $woo_attr = array();
            foreach ($taxonomy_vars as $taxonomy) {
                if (isset($_POST[$taxonomy['name']])) {
                    if (is_object_in_taxonomy($form_settings['post_type'], $taxonomy['name'])) {
                        $tax = $_POST[$taxonomy['name']];
                        // if it's not an array, make it one
                        if (!is_array($tax)) {
                            $tax = array($tax);
                        }
                        if ($taxonomy['type'] == 'text') {
                            $hierarchical = array_map('trim', array_map('strip_tags', explode(',', $_POST[$taxonomy['name']])));
                            wp_set_object_terms($post_id, $hierarchical, $taxonomy['name']);
                            // woocommerce check
                            if (isset($taxonomy['woo_attr']) && $taxonomy['woo_attr'] == 'yes') {
                                $woo_attr[sanitize_title($taxonomy['name'])] = $this->woo_attribute($taxonomy);
                            }
                        } else {
                            if (is_taxonomy_hierarchical($taxonomy['name'])) {
                                wp_set_post_terms($post_id, $_POST[$taxonomy['name']], $taxonomy['name']);
                                // woocommerce check
                                if (isset($taxonomy['woo_attr']) && $taxonomy['woo_attr'] == 'yes') {
                                    $woo_attr[sanitize_title($taxonomy['name'])] = $this->woo_attribute($taxonomy);
                                }
                            } else {
                                if ($tax) {
                                    $non_hierarchical = array();
                                    foreach ($tax as $value) {
                                        $term = get_term_by('id', $value, $taxonomy['name']);
                                        if ($term && !is_wp_error($term)) {
                                            $non_hierarchical[] = $term->name;
                                        }
                                    }
                                    wp_set_post_terms($post_id, $non_hierarchical, $taxonomy['name']);
                                }
                            }
                            // hierarchical
                        }
                        // is text
                    }
                    // is object tax
                }
                // isset tax
            }
            // if a woocommerce attribute
            if ($woo_attr) {
                update_post_meta($post_id, '_product_attributes', $woo_attr);
            }
            if ($is_update) {
                // plugin API to extend the functionality
                do_action('wpuf_edit_post_after_update', $post_id, $form_id, $form_settings, $form_vars);
                //send mail notification
                if (isset($form_settings['notification']) && $form_settings['notification']['edit'] == 'on') {
                    $mail_body = $this->prepare_mail_body($form_settings['notification']['edit_body'], $post_author, $post_id);
                    wp_mail($form_settings['notification']['edit_to'], $form_settings['notification']['edit_subject'], $mail_body);
                }
            } else {
                // plugin API to extend the functionality
                do_action('wpuf_add_post_after_insert', $post_id, $form_id, $form_settings, $form_vars);
                // send mail notification
                if (isset($form_settings['notification']) && $form_settings['notification']['new'] == 'on') {
                    $mail_body = $this->prepare_mail_body($form_settings['notification']['new_body'], $post_author, $post_id);
                    wp_mail($form_settings['notification']['new_to'], $form_settings['notification']['new_subject'], $mail_body);
                }
            }
            //redirect URL
            $show_message = false;
            $redirect_to = false;
            if ($is_update) {
                if ($form_settings['edit_redirect_to'] == 'page') {
                    $redirect_to = get_permalink($form_settings['edit_page_id']);
                } elseif ($form_settings['edit_redirect_to'] == 'url') {
                    $redirect_to = $form_settings['edit_url'];
                } elseif ($form_settings['edit_redirect_to'] == 'same') {
                    $redirect_to = add_query_arg(array('pid' => $post_id, '_wpnonce' => wp_create_nonce('wpuf_edit'), 'msg' => 'post_updated'), get_permalink($_POST['page_id']));
                } else {
                    $redirect_to = get_permalink($post_id);
                }
            } else {
                if ($form_settings['redirect_to'] == 'page') {
                    $redirect_to = get_permalink($form_settings['page_id']);
                } elseif ($form_settings['redirect_to'] == 'url') {
                    $redirect_to = $form_settings['url'];
                } elseif ($form_settings['redirect_to'] == 'same') {
                    $show_message = true;
                } else {
                    $redirect_to = get_permalink($post_id);
                }
            }
            // send the response
            $response = array('success' => true, 'redirect_to' => $redirect_to, 'show_message' => $show_message, 'message' => $form_settings['message']);
            if ($is_update) {
                $response = apply_filters('wpuf_edit_post_redirect', $response, $post_id, $form_id, $form_settings);
            } else {
                $response = apply_filters('wpuf_add_post_redirect', $response, $post_id, $form_id, $form_settings);
            }
            wpuf_clear_buffer();
            echo json_encode($response);
            exit;
        }
        $this->send_error(__('Something went wrong', 'wpuf'));
    }