/**
  * Récupère le pilotage de prix, le nombre de produit avec un prix incohérent, le type de l'entité et la langue de la boutique. 
  * Parcours la tableau de donnée avec la nouvelle valeur des prix par produit incohérent puis met à jour tout les autres prix de 
  * ce produit. Ensuite renvoie le template avec le nombre de prix incohérent qui on été corrigé et le template de la méthode :
  * ajax_checking_products_values si des produits incohérents sont toujours présent. / Get the price piloting, the number of 
  * product with an inconsistent price, type of the entity and the language of the shop. Browse the given table with the new
  * new value pricing of the inconsistent product and updates any other price of this product. Then display the template 
  * of the number of corrected product and the template of the method : ajax_checking_products_values if inconsistent product
  * already present.
  * 
  * @param array $_POST['product_price'] List of the new price for the product like array( $id_product => $new_price )
  * @return JSON Response
  */
 public function ajax_save_product_price()
 {
     header('Content-Type: application/json');
     $response = array();
     $price_piloting_option = get_option('wpshop_shop_price_piloting');
     $inconsistent_product_number = !empty($_POST['product_price']) ? count($_POST['product_price']) : 0;
     $consistent_product_number = 0;
     $entity_type_id = wpshop_entities::get_entity_identifier_from_code(WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT);
     $language = WPSHOP_CURRENT_LOCALE;
     if (!empty($_REQUEST['icl_post_language'])) {
         $query = $wpdb->prepare("SELECT locale FROM " . $wpdb->prefix . "icl_locale_map WHERE code = %s", $_REQUEST['icl_post_language']);
         $language = $wpdb->get_var($query);
     }
     if (!empty($_POST['product_price'])) {
         foreach ($_POST['product_price'] as $product_id => $price) {
             try {
                 if ($price_piloting_option == 'TTC') {
                     wpshop_attributes::saveAttributeForEntity(array('decimal' => array('product_price' => $price)), $entity_type_id, $product_id, $language, 'wpshop_products');
                 } else {
                     wpshop_attributes::saveAttributeForEntity(array('decimal' => array('price_ht' => $price)), $entity_type_id, $product_id, $language, 'wpshop_product');
                 }
                 wpshop_products::calculate_price($product_id);
                 $consistent_product_number++;
             } catch (Exception $e) {
             }
         }
     }
     $response['template_number'] = __(sprintf('Number of processed product : %d/%d', $consistent_product_number, $inconsistent_product_number), 'wps-product');
     $list_product = wps_product_ctr::get_inconsistent_product();
     ob_start();
     require wpshop_tools::get_template_part(WPS_PRODUCT_DIR, WPS_PRODUCT_TEMPLATES_MAIN_DIR, "backend", "product_check_data");
     $response['template'] = ob_get_clean();
     wp_die(json_encode($response));
 }
예제 #2
0
/**
 * Add new entity element from anywhere
 */
function ajax_wpshop_add_entity()
{
    global $wpdb;
    check_ajax_referer('wpshop_add_new_entity_ajax_nonce', 'wpshop_ajax_nonce');
    $attributes = array();
    /** Get the attribute to create	*/
    $attribute_to_reload = null;
    if (!empty($_POST['attribute']['new_value_creation']) && is_array($_POST['attribute']['new_value_creation'])) {
        foreach ($_POST['attribute']['new_value_creation'] as $attribute_code => $value) {
            $query = $wpdb->prepare('SELECT * FROM ' . WPSHOP_DBT_ATTRIBUTE . ' WHERE code = %s', $attribute_code);
            $attribute_def = $wpdb->get_row($query);
            if ($value != "") {
                if ($attribute_def->data_type_to_use == 'internal') {
                    $attribute_default_value = unserialize($attribute_def->default_value);
                    if ($attribute_default_value['default_value'] == WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS) {
                        $user_id = wp_create_user(sanitize_user($value), wp_generate_password(12, false));
                        $query = $wpdb->prepare("SELECT ID FROM " . $wpdb->posts . " WHERE post_type = %s AND post_author = %d", WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS, $user_id);
                        $attribute_option_id = $wpdb->get_var($query);
                    } else {
                        $entity_args = array('post_type' => $attribute_default_value['default_value'], 'post_title' => $value, 'post_author' => function_exists('is_user_logged_in') && is_user_logged_in() ? get_current_user_id() : 'NaN', 'comment_status' => 'closed');
                        $attribute_option_id = wp_insert_post($entity_args);
                    }
                } else {
                    $wpdb->insert(WPSHOP_DBT_ATTRIBUTE_VALUES_OPTIONS, array('status' => 'valid', 'creation_date' => current_time('mysql', 0), 'position' => 1, 'attribute_id' => $attribute_def->id, 'value' => $value, 'label' => $value));
                    $attribute_option_id = $wpdb->insert_id;
                }
                foreach ($_POST['attribute'] as $attribute => $val) {
                    foreach ($val as $k => $v) {
                        if ($k == $attribute_code) {
                            $_POST['attribute'][$attribute][$k] = $attribute_option_id;
                        }
                    }
                }
            }
        }
    }
    /** Store send attribute into a new array for save purpose	*/
    if (is_array($_POST['attribute'])) {
        foreach ($_POST['attribute'] as $attribute_type => $attribute) {
            foreach ($attribute as $attribute_code => $attribute_value) {
                if (!isset($attributes[$attribute_code])) {
                    $attributes[$attribute_code] = $attribute_value;
                }
            }
        }
    }
    /** Save the new entity into database */
    $result = wpshop_entities::create_new_entity($_POST['entity_type'], $_POST['wp_fields']['post_title'], '', $attributes, array('attribute_set_id' => $_POST['attribute_set_id']));
    $new_entity_id = $result[1];
    if (!empty($new_entity_id)) {
        /**	Save address for current entity	*/
        if (!empty($_POST['type_of_form']) && !empty($_POST['attribute'][$_POST['type_of_form']])) {
            global $wpshop_account;
            $result = wps_address::wps_address($_POST['type_of_form']);
            update_post_meta($new_entity_id, '_wpshop_attached_address', $result['current_id']);
        }
        /** Make price calculation if entity is a product	*/
        if ($_POST['entity_type'] == WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT) {
            $wpshop_prices_attribute = unserialize(WPSHOP_ATTRIBUTE_PRICES);
            $calculate_price = false;
            foreach ($wpshop_prices_attribute as $attribute_price_code) {
                if (array_key_exists($attribute_price_code, $attributes)) {
                    $calculate_price = true;
                }
            }
            if ($calculate_price) {
                wpshop_products::calculate_price($new_entity_id);
            }
        }
        /** Add picture if a file has been send	*/
        if (!empty($_FILES)) {
            $wp_upload_dir = wp_upload_dir();
            $final_dir = $wp_upload_dir['path'] . '/';
            if (!is_dir($final_dir)) {
                mkdir($final_dir, 0755, true);
            }
            foreach ($_FILES as $file) {
                $tmp_name = $file['tmp_name']['post_thumbnail'];
                $name = $file['name']['post_thumbnail'];
                $filename = $final_dir . $name;
                @move_uploaded_file($tmp_name, $filename);
                $wp_filetype = wp_check_filetype(basename($filename), null);
                $attachment = array('guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path($filename), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
                $attach_id = wp_insert_attachment($attachment, $filename, $new_entity_id);
                require_once ABSPATH . 'wp-admin/includes/image.php';
                $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
                wp_update_attachment_metadata($attach_id, $attach_data);
                add_post_meta($new_entity_id, '_thumbnail_id', $attach_id, true);
            }
        }
        echo json_encode(array(true, __('Element has been saved', 'wpshop'), $attribute_to_reload, $new_entity_id));
    } else {
        echo json_encode(array(false, __('An error occured while adding your element', 'wpshop')));
    }
    die;
}
 /**
  * Create a new variation for product
  *
  * @param integer $head_product The product identifier to create the new variation for
  * @param array $variation_attributes Attribute list for the variation
  *
  * @return mixed <number, WP_Error> The variation identifier or an error in case the creation was not succesfull
  */
 public static function create_variation($head_product, $variation_attributes)
 {
     /** Create custom title */
     $title_variation = "";
     if (!empty($variation_attributes)) {
         foreach ($variation_attributes as $type => $array) {
             if (!empty($array)) {
                 foreach ($array as $code => $value) {
                     $title_variation .= " " . $code . " " . $value;
                 }
             }
         }
     }
     $variation = array('post_title' => sprintf(__('Product %s variation %s', 'wpshop'), $head_product, get_the_title($head_product)) . $title_variation, 'post_content' => '', 'post_status' => 'publish', 'post_author' => get_current_user_id(), 'post_parent' => $head_product, 'post_type' => WPSHOP_NEWTYPE_IDENTIFIER_PRODUCT_VARIATION);
     $variation_id = wp_insert_post($variation);
     wpshop_attributes::saveAttributeForEntity($variation_attributes, wpshop_entities::get_entity_identifier_from_code(wpshop_products::currentPageCode), $variation_id, WPSHOP_CURRENT_LOCALE, '');
     /*	Update product price looking for shop parameters	*/
     wpshop_products::calculate_price($variation_id);
     /*	Save the attributes values into wordpress post metadata database in order to have a backup and to make frontend search working	*/
     $productMetaDatas = array();
     foreach ($variation_attributes as $attributeType => $attributeValues) {
         foreach ($attributeValues as $attributeCode => $attributeValue) {
             if (!empty($attributeValue)) {
                 $productMetaDatas[$attributeCode] = $attributeValue;
             }
         }
     }
     update_post_meta($variation_id, '_wpshop_variations_attribute_def', $productMetaDatas);
     update_post_meta($variation_id, WPSHOP_PRODUCT_ATTRIBUTE_META_KEY, $productMetaDatas);
     update_post_meta($variation_id, WPSHOP_PRODUCT_ATTRIBUTE_SET_ID_META_KEY, get_post_meta($head_product, WPSHOP_PRODUCT_ATTRIBUTE_SET_ID_META_KEY, true));
     return $variation_id;
 }