Example #1
0
 public function loadImage($id_product, $images)
 {
     $images_array = $this->imagesToArray($images);
     $images_id = array();
     $product = new Product($id_product);
     $image_types = ImageType::getImagesTypes('product');
     if ($images_array) {
         foreach ($images_array as $img) {
             if (file_exists(_TM_ROOT_DIR_ . $img['url'])) {
                 //ajout de l'image au produit
                 $image = new Image();
                 $image->id_product = intval($product->id);
                 $image->position = Image::getHighestPosition($product->id) + 1;
                 if (!intval($product->id_image_default)) {
                     $image->cover = 1;
                 } else {
                     $image->cover = 0;
                 }
                 $image->legend = 0;
                 $image->add();
                 if ($image->cover) {
                     $product->id_image_default = (int) $image->id;
                 }
                 $id_image = $image->id;
                 $images_id[] = $id_image;
                 $path = $image->getPathForCreation();
                 //echo $imgDir.$img['url'];
                 @copy(_TM_ROOT_DIR_ . $img['url'], $path . '.jpg');
                 foreach ($image_types as $k => $image_type) {
                     ImageManager::resize(_TM_ROOT_DIR_ . $img['url'], $path . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height']);
                 }
                 //@unlink($tmpName);
             } else {
                 $this->_output .= '<div class="alert error">Image not exists!</div>';
             }
             $product->update();
         }
     }
     return $images_id;
 }
Example #2
0
    /**
     * Copy images from a product to another
     *
     * @param integer $id_product_old Source product ID
     * @param boolean $id_product_new Destination product ID
     */
    public static function duplicateProductImages($id_product_old, $id_product_new, $combinationImages)
    {
        $imagesTypes = ImageType::getImagesTypes('products');
        $result = Db::getInstance()->ExecuteS('
		SELECT `id_image`
		FROM `' . _DB_PREFIX_ . 'image`
		WHERE `id_product` = ' . intval($id_product_old));
        foreach ($result as $row) {
            $image = new Image($row['id_image']);
            $saved_id = $image->id_image;
            unset($image->id);
            unset($image->id_image);
            $image->id_product = intval($id_product_new);
            if ($image->add()) {
                foreach ($imagesTypes as $k => $imageType) {
                    if (file_exists(_PS_PROD_IMG_DIR_ . intval($id_product_old) . '-' . intval($row['id_image']) . '-' . $imageType['name'] . '.jpg')) {
                        copy(_PS_PROD_IMG_DIR_ . intval($id_product_old) . '-' . intval($row['id_image']) . '-' . $imageType['name'] . '.jpg', _PS_PROD_IMG_DIR_ . intval($id_product_new) . '-' . intval($image->id) . '-' . $imageType['name'] . '.jpg');
                    }
                }
                if (file_exists(_PS_PROD_IMG_DIR_ . intval($id_product_old) . '-' . intval($row['id_image']) . '.jpg')) {
                    copy(_PS_PROD_IMG_DIR_ . intval($id_product_old) . '-' . intval($row['id_image']) . '.jpg', _PS_PROD_IMG_DIR_ . intval($id_product_new) . '-' . intval($image->id) . '.jpg');
                }
                Db::getInstance()->Execute('
				UPDATE `' . _DB_PREFIX_ . 'product_attribute`
				SET id_image = ' . intval($image->id) . '
				WHERE id_image = ' . intval($saved_id) . '
				AND id_product = ' . intval($id_product_new));
                self::replaceAttributeImageAssociationId($combinationImages, intval($saved_id), intval($image->id));
            } else {
                return false;
            }
        }
        return self::duplicateAttributeImageAssociations($combinationImages);
    }
Example #3
0
 $multiple_value_separator = ($separator = Tools::substr(strval(trim(Tools::getValue('multiple_value_separator'))), 0, 1)) ? $separator : ',';
 if (isset($prd['images']) && $prd['images']) {
     $image_url = explode('/', $prd['images']);
     $url = _PS_IMG_MGT_DIR_ . end($image_url);
     $product_has_images = (bool) Image::getImages($id_lang, $product->id);
     $image = new Image();
     $image->id_product = (int) $product->id;
     $image->position = Image::getHighestPosition($product->id) + 1;
     $image->cover = !$product_has_images ? true : false;
     $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
     $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
     $id_shop_list = array();
     $errors = array();
     $warnings = array();
     $id_shop_list[] = $product->id_shop_default;
     if ($image->add()) {
         $image->associateTo($id_shop_list);
         $image->getPathForCreation();
         $image_final = $image->getPathForCreation() . '.jpg';
         if (Tools::copy($url, $image_final)) {
             $tgt_width = $tgt_height = 0;
             $src_width = $src_height = 0;
             $previous_path = null;
             $path_infos = array();
             $images_types = ImageType::getImagesTypes('products', true);
             foreach ($images_types as $image_type) {
                 if (ImageManager::resize($image_final, $image->getPathForCreation() . '-' . stripslashes($image_type['name']) . '.jpg', $image_type['width'], $image_type['height'], 'jpg', false, $error, $tgt_width, $tgt_height, 5, $src_width, $src_height)) {
                     if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '.jpg')) {
                         unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '.jpg');
                     }
                     if (is_file(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . (int) Context::getContext()->shop->id . '.jpg')) {
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and (int) $info['id'] and Product::existsInDatabase((int) $info['id'])) {
             $product = new Product((int) $info['id']);
             $categoryData = Product::getIndexedCategories((int) $product->id);
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp['id_category'];
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         $trg_id = (int) $product->id_tax_rules_group;
         if ($product->id_tax_rules_group == 0 || !Validate::isLoadedObject(new TaxRulesGroup($trg_id))) {
             $this->_addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID, you first need a group with this ID.'));
         } else {
             $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
         }
         if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists((int) $product->manufacturer)) {
             $product->id_manufacturer = (int) $product->manufacturer;
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = (int) $manufacturer;
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = (int) $manufacturer->id;
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists((int) $product->supplier)) {
             $product->id_supplier = (int) $product->supplier;
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = (int) $supplier;
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = (int) $supplier->id;
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !isset($product->price_tex)) {
             $product->price = $product->price_tin;
             // If a tax is already included in price, withdraw it from price
             if ($product->tax_rate) {
                 $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6);
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($product->category)) {
             $product->id_category = array();
             // Reset default values array
             foreach ($product->category as $value) {
                 if (is_numeric($value)) {
                     if (Category::categoryExists((int) $value)) {
                         $product->id_category[] = (int) $value;
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = (int) $value;
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = (int) $category['id_category'];
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = (int) $categoryToCreate->id;
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : '';
         $link_rewrite = is_array($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         $bak = $product->link_rewrite;
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
             if ($link_rewrite == '') {
                 $link_rewrite = 'friendly-url-autogeneration-failed';
             }
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrite link for') . ' ' . $bak . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If id product AND id product already in base, trying to update
             if ($product->id and Product::existsInDatabase((int) $product->id)) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product->id);
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             }
             // If no id_product or update failed
             if (!$res) {
                 $res = $product->add();
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             // SpecificPrice (only the basic reduction feature is supported by the import)
             if (isset($info['reduction_price']) or isset($info['reduction_percent'])) {
                 $specificPrice = new SpecificPrice();
                 $specificPrice->id_product = (int) $product->id;
                 $specificPrice->id_shop = (int) Shop::getCurrentShop();
                 $specificPrice->id_currency = 0;
                 $specificPrice->id_country = 0;
                 $specificPrice->id_group = 0;
                 $specificPrice->price = 0.0;
                 $specificPrice->from_quantity = 1;
                 $specificPrice->reduction = (isset($info['reduction_price']) and $info['reduction_price']) ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                 $specificPrice->reduction_type = (isset($info['reduction_price']) and $info['reduction_price']) ? 'amount' : 'percentage';
                 $specificPrice->from = (isset($info['reduction_from']) and Validate::isDate($info['reduction_from'])) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                 $specificPrice->to = (isset($info['reduction_to']) and Validate::isDate($info['reduction_to'])) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                 if (!$specificPrice->add()) {
                     $this->_addProductWarning($info['name'], $product->id, $this->l('Discount is invalid'));
                 }
             }
             if (isset($product->tags) and !empty($product->tags)) {
                 // Delete tags for this id product, for no duplicating error
                 Tag::deleteTagsForProduct($product->id);
                 $tag = new Tag();
                 if (!is_array($product->tags)) {
                     $product->tags = self::createMultiLangField($product->tags);
                     foreach ($product->tags as $key => $tags) {
                         $isTagAdded = $tag->addTags($key, $product->id, $tags);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, $this->l('Tags list') . ' ' . $this->l('is invalid'));
                             break;
                         }
                     }
                 } else {
                     foreach ($product->tags as $key => $tags) {
                         $str = '';
                         foreach ($tags as $one_tag) {
                             $str .= $one_tag . ',';
                         }
                         $str = rtrim($str, ',');
                         $isTagAdded = $tag->addTags($key, $product->id, $str);
                         if (!$isTagAdded) {
                             $this->_addProductWarning($info['name'], $product->id, 'Invalid tag(s) (' . $str . ')');
                             break;
                         }
                     }
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id);
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = (int) $product->id;
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             if (!self::copyImg($product->id, $image->id, $url)) {
                                 $this->_warnings[] = Tools::displayError('Error copying image: ') . $url;
                             }
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
 protected function importImages()
 {
     $this->truncateTables(array('image', 'image_lang', 'image_shop'));
     $handle = $this->openCsvFile('images.csv');
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) {
         $res = false;
         $fields = $this->filterFields('Image', $this->image_fields, $line);
         if (!isset($fields['id_image'])) {
             $img = new Image($line[0]);
         } else {
             $img = new Image($fields['id_image']);
         }
         $img->id = $line[0];
         foreach ($fields as $key => $field) {
             if ($key == 'legend') {
                 $img->{$key} = $this->multilFild($field);
             } else {
                 $img->{$key} = $field;
             }
         }
         $img->force_id = true;
         if (!$res) {
             $res = $img->add();
         }
     }
     $this->closeCsvFile($handle);
     return true;
 }
 /**
  * Write the posted image on disk
  *
  * @param string $sreceptionPath
  * @param int $destWidth
  * @param int $destHeight
  * @param array $imageTypes
  * @param string $parentPath
  * @return boolean
  */
 protected function writePostedImageOnDisk($receptionPath, $destWidth = null, $destHeight = null, $imageTypes = null, $parentPath = null)
 {
     if ($this->wsObject->method == 'PUT') {
         if (isset($_FILES['image']['tmp_name']) && $_FILES['image']['tmp_name']) {
             $file = $_FILES['image'];
             if ($file['size'] > $this->imgMaxUploadSize) {
                 throw new WebserviceException(sprintf('The image size is too large (maximum allowed is %d KB)', $this->imgMaxUploadSize / 1000), array(72, 400));
             }
             // Get mime content type
             $mime_type = false;
             if (Tools::isCallable('finfo_open')) {
                 $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
                 $finfo = finfo_open($const);
                 $mime_type = finfo_file($finfo, $file['tmp_name']);
                 finfo_close($finfo);
             } elseif (Tools::isCallable('mime_content_type')) {
                 $mime_type = mime_content_type($file['tmp_name']);
             } elseif (Tools::isCallable('exec')) {
                 $mime_type = trim(exec('file -b --mime-type ' . escapeshellarg($file['tmp_name'])));
             }
             if (empty($mime_type) || $mime_type == 'regular file') {
                 $mime_type = $file['type'];
             }
             if (($pos = strpos($mime_type, ';')) !== false) {
                 $mime_type = substr($mime_type, 0, $pos);
             }
             // Check mime content type
             if (!$mime_type || !in_array($mime_type, $this->acceptedImgMimeTypes)) {
                 throw new WebserviceException('This type of image format not recognized, allowed formats are: ' . implode('", "', $this->acceptedImgMimeTypes), array(73, 400));
             } elseif ($file['error']) {
                 throw new WebserviceException('Error while uploading image. Please change your server\'s settings', array(74, 400));
             }
             // Try to copy image file to a temporary file
             if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES['image']['tmp_name'], $tmpName)) {
                 throw new WebserviceException('Error while copying image to the temporary directory', array(75, 400));
             } else {
                 $result = $this->writeImageOnDisk($tmpName, $receptionPath, $destWidth, $destHeight, $imageTypes, $parentPath);
             }
             @unlink($tmpName);
             return $result;
         } else {
             throw new WebserviceException('Please set an "image" parameter with image data for value', array(76, 400));
         }
     } elseif ($this->wsObject->method == 'POST') {
         if (isset($_FILES['image']['tmp_name']) && $_FILES['image']['tmp_name']) {
             $file = $_FILES['image'];
             if ($file['size'] > $this->imgMaxUploadSize) {
                 throw new WebserviceException(sprintf('The image size is too large (maximum allowed is %d KB)', $this->imgMaxUploadSize / 1000), array(72, 400));
             }
             require_once _PS_ROOT_DIR_ . '/images.inc.php';
             if ($error = ImageManager::validateUpload($file)) {
                 throw new WebserviceException('Image upload error : ' . $error, array(76, 400));
             }
             if (isset($file['tmp_name']) && $file['tmp_name'] != null) {
                 if ($this->imageType == 'products') {
                     $product = new Product((int) $this->wsObject->urlSegment[2]);
                     if (!Validate::isLoadedObject($product)) {
                         throw new WebserviceException('Product ' . (int) $this->wsObject->urlSegment[2] . ' doesn\'t exists', array(76, 400));
                     }
                     $image = new Image();
                     $image->id_product = (int) $product->id;
                     $image->position = Image::getHighestPosition($product->id) + 1;
                     if (!Image::getCover((int) $product->id)) {
                         $image->cover = 1;
                     } else {
                         $image->cover = 0;
                     }
                     if (!$image->add()) {
                         throw new WebserviceException('Error while creating image', array(76, 400));
                     }
                     if (!Validate::isLoadedObject($product)) {
                         throw new WebserviceException('Product ' . (int) $this->wsObject->urlSegment[2] . ' doesn\'t exists', array(76, 400));
                     }
                 }
                 // copy image
                 if (!isset($file['tmp_name'])) {
                     return false;
                 }
                 if ($error = ImageManager::validateUpload($file, $this->imgMaxUploadSize)) {
                     throw new WebserviceException('Bad image : ' . $error, array(76, 400));
                 }
                 if ($this->imageType == 'products') {
                     $image = new Image($image->id);
                     if (!(Configuration::get('PS_OLD_FILESYSTEM') && file_exists(_PS_PROD_IMG_DIR_ . $product->id . '-' . $image->id . '.jpg'))) {
                         $image->createImgFolder();
                     }
                     if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($file['tmp_name'], $tmpName)) {
                         throw new WebserviceException('An error occurred during the image upload', array(76, 400));
                     } elseif (!ImageManager::resize($tmpName, _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '.' . $image->image_format)) {
                         throw new WebserviceException('An error occurred while copying image', array(76, 400));
                     } else {
                         $imagesTypes = ImageType::getImagesTypes('products');
                         foreach ($imagesTypes as $imageType) {
                             if (!ImageManager::resize($tmpName, _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                                 $this->_errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                             }
                         }
                     }
                     @unlink($tmpName);
                     $this->imgToDisplay = _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '.' . $image->image_format;
                     $this->objOutput->setFieldsToDisplay('full');
                     $this->output = $this->objOutput->renderEntity($image, 1);
                     $image_content = array('sqlId' => 'content', 'value' => base64_encode(file_get_contents($this->imgToDisplay)), 'encode' => 'base64');
                     $this->output .= $this->objOutput->objectRender->renderField($image_content);
                 } elseif (in_array($this->imageType, array('categories', 'manufacturers', 'suppliers', 'stores'))) {
                     if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($file['tmp_name'], $tmpName)) {
                         throw new WebserviceException('An error occurred during the image upload', array(76, 400));
                     } elseif (!ImageManager::resize($tmpName, $receptionPath)) {
                         throw new WebserviceException('An error occurred while copying image', array(76, 400));
                     }
                     $imagesTypes = ImageType::getImagesTypes($this->imageType);
                     foreach ($imagesTypes as $imageType) {
                         if (!ImageManager::resize($tmpName, $parentPath . $this->wsObject->urlSegment[2] . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height'])) {
                             $this->_errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                         }
                     }
                     @unlink(_PS_TMP_IMG_DIR_ . $tmpName);
                     $this->imgToDisplay = $receptionPath;
                 }
                 return true;
             }
         }
     } else {
         throw new WebserviceException('Method ' . $this->wsObject->method . ' is not allowed for an image resource', array(77, 405));
     }
 }
Example #7
0
 public function save()
 {
     $product = new Product($_GET['id_product']);
     if (!Validate::isLoadedObject($product)) {
         return array('error' => Tools::displayError('Cannot add image because product creation failed.'));
     } else {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         $legends = Tools::getValue('legend');
         if (is_array($legends)) {
             foreach ($legends as $key => $legend) {
                 if (Validate::isGenericName($legend)) {
                     $image->legend[(int) $key] = $legend;
                 } else {
                     return array('error' => sprintf(Tools::displayError('Error on image caption: "%1s" is not a valid caption.'), Tools::safeOutput($legend)));
                 }
             }
         }
         if (!Image::getCover($image->id_product)) {
             $image->cover = 1;
         } else {
             $image->cover = 0;
         }
         if (($validate = $image->validateFieldsLang(false, true)) !== true) {
             return array('error' => Tools::displayError($validate));
         }
         if (!$image->add()) {
             return array('error' => Tools::displayError('Error while creating additional image'));
         } else {
             return $this->copyImage($product->id, $image->id);
         }
     }
 }
Example #8
0
 private function AddImage($object, $url)
 {
     $shops = Shop::getShops(true, null, true);
     $url = str_replace(' ', '%20', $url);
     $image = new Image();
     $image->id_product = (int) $object->id;
     $image->position = Image::getHighestPosition($object->id) + 1;
     $image->cover = 1;
     // file_exists doesn't work with HTTP protocol
     if (@fopen($url, 'r') == false) {
         $error = true;
     } else {
         if (($field_error = $image->validateFields(false, true)) === true && ($lang_field_error = $image->validateFieldsLang(false, true)) === true && $image->add()) {
             // associate image to selected shops
             $image->associateTo($shops);
             if (!self::copyImg($object->id, $image->id, $url)) {
                 $image->delete();
                 $this->errors[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
             }
         } else {
             $error = true;
         }
     }
 }
 /**
  * handleImageUpload
  * @author Cornelius Hansjakob <*****@*****.**>
  * @version 1.0
  */
 private function handleImageUpload()
 {
     $this->core->logger->debug('media->controllers->UploadController->handleImageUpload()');
     $objImage = new Image();
     $objImage->setUpload($this->objUpload);
     $objImage->setParentId($this->intParentId);
     $objImage->setParentTypeId($this->core->sysConfig->parent_types->folder);
     $objImage->setUploadPath(GLOBAL_ROOT_PATH . $this->core->sysConfig->upload->images->path->local->private);
     $objImage->setPublicFilePath(GLOBAL_ROOT_PATH . $this->core->sysConfig->upload->images->path->local->public);
     $objImage->setDefaultImageSizes($this->core->sysConfig->upload->images->default_sizes->default_size->toArray());
     $objImage->add('Filedata');
     $this->writeViewData($objImage);
 }
    public function productImport()
    {
        // do standard stuff; need to copy/paste
        // because silly PS does not allow to hook inside of the import loop...
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
        if (!Validate::isUnsignedId($id_lang)) {
            $id_lang = $default_language_id;
        }
        AdminImportController::setLocale();
        $shop_ids = Shop::getCompleteListOfShopsID();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) {
                $product = new Product((int) $info['id']);
            } elseif (Tools::getValue('match_ref') && array_key_exists('reference', $info)) {
                $datas = Db::getInstance()->getRow('
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($info['reference']) . '"
				');
                if (isset($datas['id_product']) && $datas['id_product']) {
                    $product = new Product((int) $datas['id_product']);
                } else {
                    $product = new Product();
                }
            } elseif (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                $product = new Product((int) $info['id']);
            } else {
                $product = new Product();
            }
            if (isset($product->id) && $product->id && Product::existsInDatabase((int) $product->id, 'product')) {
                $product->loadStockData();
                $category_data = Product::getProductCategories((int) $product->id);
                if (is_array($category_data)) {
                    foreach ($category_data as $tmp) {
                        if (!isset($product->category) || !$product->category || is_array($product->category)) {
                            $product->category[] = $tmp;
                        }
                    }
                }
            }
            AdminImportController::setEntityDefaultValues($product);
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
            /*
             * 2015-03-26 - JLE SPECIFIC :
             * Import language specific infos
             */
            foreach ($this->csv_translated_fields as $field) {
                foreach ($this->csv_languages as $lang) {
                    if (isset($info[$field . "_" . $lang])) {
                        $lang_id = Language::getIdByIso($lang);
                        $product->{$field}[$lang_id] = $info[$field . "_" . $lang];
                    }
                }
            }
            /*
             * END SPECIFIC
             */
            if (!Shop::isFeatureActive()) {
                $product->shop = 1;
            } elseif (!isset($product->shop) || empty($product->shop)) {
                $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            if (!Shop::isFeatureActive()) {
                $product->id_shop_default = 1;
            } else {
                $product->id_shop_default = (int) Context::getContext()->shop->id;
            }
            // link product to shops
            $product->id_shop_list = array();
            foreach (explode($this->multiple_value_separator, $product->shop) as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $product->id_shop_list[] = Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $product->id_shop_list[] = $shop;
                }
            }
            if ((int) $product->id_tax_rules_group != 0) {
                if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                    $address = $this->context->shop->getAddress();
                    $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group);
                    $product_tax_calculator = $tax_manager->getTaxCalculator();
                    $product->tax_rate = $product_tax_calculator->getTotalRate();
                } else {
                    $this->addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID. You first need to create a group with this ID.'));
                }
            }
            if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) {
                $product->id_manufacturer = (int) $product->manufacturer;
            } elseif (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) {
                if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                    $product->id_manufacturer = (int) $manufacturer;
                } else {
                    $manufacturer = new Manufacturer();
                    $manufacturer->name = $product->manufacturer;
                    if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) {
                        $product->id_manufacturer = (int) $manufacturer->id;
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int) $product->supplier)) {
                $product->id_supplier = (int) $product->supplier;
            } elseif (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) {
                if ($supplier = Supplier::getIdByName($product->supplier)) {
                    $product->id_supplier = (int) $supplier;
                } else {
                    $supplier = new Supplier();
                    $supplier->name = $product->supplier;
                    $supplier->active = true;
                    if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) {
                        $product->id_supplier = (int) $supplier->id;
                        $supplier->associateTo($product->id_shop_list);
                    } else {
                        $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null');
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
            if (isset($product->price_tex) && !isset($product->price_tin)) {
                $product->price = $product->price_tex;
            } elseif (isset($product->price_tin) && !isset($product->price_tex)) {
                $product->price = $product->price_tin;
                // If a tax is already included in price, withdraw it from price
                if ($product->tax_rate) {
                    $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
                }
            } elseif (isset($product->price_tin) && isset($product->price_tex)) {
                $product->price = $product->price_tex;
            }
            if (!Configuration::get('PS_USE_ECOTAX')) {
                $product->ecotax = 0;
            }
            if (isset($product->category) && is_array($product->category) && count($product->category)) {
                $product->id_category = array();
                // Reset default values array
                foreach ($product->category as $value) {
                    if (is_numeric($value)) {
                        if (Category::categoryExists((int) $value)) {
                            $product->id_category[] = (int) $value;
                        } else {
                            $category_to_create = new Category();
                            $category_to_create->id = (int) $value;
                            $category_to_create->name = AdminImportController::createMultiLangField($value);
                            $category_to_create->active = 1;
                            $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                            // Default parent is home for unknown category to create
                            $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]);
                            $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                            if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) {
                                $product->id_category[] = (int) $category_to_create->id;
                            } else {
                                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    } elseif (is_string($value) && !empty($value)) {
                        $category = Category::searchByPath($default_language_id, trim($value), $this, 'productImportCreateCat');
                        if ($category['id_category']) {
                            $product->id_category[] = (int) $category['id_category'];
                        } else {
                            $this->errors[] = sprintf(Tools::displayError('%1$s cannot be saved'), trim($value));
                        }
                    }
                }
                $product->id_category = array_values(array_unique($product->id_category));
            }
            if (!isset($product->id_category_default) || !$product->id_category_default) {
                $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : (int) Configuration::get('PS_HOME_CATEGORY');
            }
            $link_rewrite = is_array($product->link_rewrite) && isset($product->link_rewrite[$id_lang]) ? trim($product->link_rewrite[$id_lang]) : '';
            $valid_link = Validate::isLinkRewrite($link_rewrite);
            if (isset($product->link_rewrite[$id_lang]) && empty($product->link_rewrite[$id_lang]) || !$valid_link) {
                $link_rewrite = Tools::link_rewrite($product->name[$id_lang]);
                if ($link_rewrite == '') {
                    $link_rewrite = 'friendly-url-autogeneration-failed';
                }
            }
            if (!$valid_link) {
                $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite);
            }
            if (!(Tools::getValue('match_ref') || Tools::getValue('forceIDs')) || !(is_array($product->link_rewrite) && count($product->link_rewrite) && !empty($product->link_rewrite[$id_lang]))) {
                $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
            }
            // replace the value of separator by coma
            if ($this->multiple_value_separator != ',') {
                if (is_array($product->meta_keywords)) {
                    foreach ($product->meta_keywords as &$meta_keyword) {
                        if (!empty($meta_keyword)) {
                            $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword);
                        }
                    }
                }
            }
            // Convert comma into dot for all floating values
            foreach (Product::$definition['fields'] as $key => $array) {
                if ($array['type'] == Product::TYPE_FLOAT) {
                    $product->{$key} = str_replace(',', '.', $product->{$key});
                }
            }
            // Indexation is already 0 if it's a new product, but not if it's an update
            $product->indexed = 0;
            $res = false;
            $field_error = $product->validateFields(UNFRIENDLY_ERROR, true);
            $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
            if ($field_error === true && $lang_field_error === true) {
                // check quantity
                if ($product->quantity == null) {
                    $product->quantity = 0;
                }
                // If match ref is specified && ref product && ref product already in base, trying to update
                if (Tools::getValue('match_ref') && $product->reference && $product->existsRefInDatabase($product->reference)) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`, p.`id_product`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`reference` = "' . pSQL($product->reference) . '"
					');
                    $product->id = (int) $datas['id_product'];
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                } elseif ($product->id && Product::existsInDatabase((int) $product->id, 'product')) {
                    $datas = Db::getInstance()->getRow('
						SELECT product_shop.`date_add`
						FROM `' . _DB_PREFIX_ . 'product` p
						' . Shop::addSqlAssociation('product', 'p') . '
						WHERE p.`id_product` = ' . (int) $product->id);
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                }
                // If no id_product or update failed
                $product->force_id = (bool) Tools::getValue('forceIDs');
                if (!$res) {
                    if (isset($product->date_add) && $product->date_add != '') {
                        $res = $product->add(false);
                    } else {
                        $res = $product->add();
                    }
                }
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    StockAvailable::setProductOutOfStock((int) $product->id, 1);
                } else {
                    StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock);
                }
            }
            $shops = array();
            $product_shop = explode($this->multiple_value_separator, $product->shop);
            foreach ($product_shop as $shop) {
                if (empty($shop)) {
                    continue;
                }
                $shop = trim($shop);
                if (!empty($shop) && !is_numeric($shop)) {
                    $shop = Shop::getIdByName($shop);
                }
                if (in_array($shop, $shop_ids)) {
                    $shops[] = $shop;
                } else {
                    $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid'));
                }
            }
            if (empty($shops)) {
                $shops = Shop::getContextListShopID();
            }
            // If both failed, mysql error
            if (!$res) {
                $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
            } else {
                // Product supplier
                if (isset($product->id) && $product->id && isset($product->id_supplier) && property_exists($product, 'supplier_reference')) {
                    $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                    if ($id_product_supplier) {
                        $product_supplier = new ProductSupplier($id_product_supplier);
                    } else {
                        $product_supplier = new ProductSupplier();
                    }
                    $product_supplier->id_product = (int) $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = (int) $product->id_supplier;
                    $product_supplier->product_supplier_price_te = $product->wholesale_price;
                    $product_supplier->product_supplier_reference = $product->supplier_reference;
                    $product_supplier->save();
                }
                // SpecificPrice (only the basic reduction feature is supported by the import)
                if (!Shop::isFeatureActive()) {
                    $info['shop'] = 1;
                } elseif (!isset($info['shop']) || empty($info['shop'])) {
                    $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
                }
                // Get shops for each attributes
                $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
                $id_shop_list = array();
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = (int) Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
                if (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                    foreach ($id_shop_list as $id_shop) {
                        $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, 0, 1, 0, 0, 0, 0);
                        if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                            $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                        } else {
                            $specific_price = new SpecificPrice();
                        }
                        $specific_price->id_product = (int) $product->id;
                        $specific_price->id_specific_price_rule = 0;
                        $specific_price->id_shop = $id_shop;
                        $specific_price->id_currency = 0;
                        $specific_price->id_country = 0;
                        $specific_price->id_group = 0;
                        $specific_price->price = -1;
                        $specific_price->id_customer = 0;
                        $specific_price->from_quantity = 1;
                        $specific_price->reduction = isset($info['reduction_price']) && $info['reduction_price'] ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                        $specific_price->reduction_type = isset($info['reduction_price']) && $info['reduction_price'] ? 'amount' : 'percentage';
                        $specific_price->from = isset($info['reduction_from']) && Validate::isDate($info['reduction_from']) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                        $specific_price->to = isset($info['reduction_to']) && Validate::isDate($info['reduction_to']) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                        if (!$specific_price->save()) {
                            $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                        }
                    }
                }
                /*
                 * 2015-03-26 - JLE SPECIFIC :
                 * Import group specific prices
                 */
                foreach ($this->groups as $group) {
                    if (isset($info['group' . $group['id_group'] . "_price"])) {
                        //	$group_price = str_replace(',', '.', $info['group'.$group['id_group']."_price"]);
                        $group_price = (double) str_replace(',', '.', trim($info['group' . $group['id_group'] . "_price"]));
                        foreach ($id_shop_list as $id_shop) {
                            $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, $group['id_group'], 1, 0, 0, 0, 0);
                            if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                                $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                            } else {
                                $specific_price = new SpecificPrice();
                            }
                            $specific_price->id_product = (int) $product->id;
                            $specific_price->id_specific_price_rule = 0;
                            $specific_price->id_shop = $id_shop;
                            $specific_price->id_currency = 0;
                            $specific_price->id_country = 0;
                            $specific_price->id_group = $group['id_group'];
                            $specific_price->price = $group_price;
                            $specific_price->id_customer = 0;
                            $specific_price->from_quantity = 1;
                            $specific_price->reduction = 0;
                            $specific_price->reduction_type = 'amount';
                            $specific_price->from = '0000-00-00 00:00:00';
                            $specific_price->to = '0000-00-00 00:00:00';
                            if (!$specific_price->save()) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                            }
                        }
                    }
                }
                /*
                 * END SPECIFIC 2015-03-26
                 */
                if (isset($product->tags) && !empty($product->tags)) {
                    if (isset($product->id) && $product->id) {
                        $tags = Tag::getProductTags($product->id);
                        if (is_array($tags) && count($tags)) {
                            if (!empty($product->tags)) {
                                $product->tags = explode($this->multiple_value_separator, $product->tags);
                            }
                            if (is_array($product->tags) && count($product->tags)) {
                                foreach ($product->tags as $key => $tag) {
                                    if (!empty($tag)) {
                                        $product->tags[$key] = trim($tag);
                                    }
                                }
                                $tags[$id_lang] = $product->tags;
                                $product->tags = $tags;
                            }
                        }
                    }
                    // Delete tags for this id product, for no duplicating error
                    Tag::deleteTagsForProduct($product->id);
                    if (!is_array($product->tags) && !empty($product->tags)) {
                        $product->tags = AdminImportController::createMultiLangField($product->tags);
                        foreach ($product->tags as $key => $tags) {
                            $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid'));
                                break;
                            }
                        }
                    } else {
                        foreach ($product->tags as $key => $tags) {
                            $str = '';
                            foreach ($tags as $one_tag) {
                                $str .= $one_tag . $this->multiple_value_separator;
                            }
                            $str = rtrim($str, $this->multiple_value_separator);
                            $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator);
                            if (!$is_tag_added) {
                                $this->addProductWarning(Tools::safeOutput($info['name']), (int) $product->id, 'Invalid tag(s) (' . $str . ')');
                                break;
                            }
                        }
                    }
                }
                //delete existing images if "delete_existing_images" is set to 1
                if (isset($product->delete_existing_images)) {
                    if ((bool) $product->delete_existing_images) {
                        $product->deleteImages();
                    }
                }
                if (isset($product->image) && is_array($product->image) && count($product->image)) {
                    $product_has_images = (bool) Image::getImages($this->context->language->id, (int) $product->id);
                    foreach ($product->image as $key => $url) {
                        $url = trim($url);
                        $error = false;
                        if (!empty($url)) {
                            $url = str_replace(' ', '%20', $url);
                            $image = new Image();
                            $image->id_product = (int) $product->id;
                            $image->position = Image::getHighestPosition($product->id) + 1;
                            $image->cover = !$key && !$product_has_images ? true : false;
                            // file_exists doesn't work with HTTP protocol
                            if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) {
                                // associate image to selected shops
                                $image->associateTo($shops);
                                if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                                    $image->delete();
                                    $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                                }
                            } else {
                                $error = true;
                            }
                        } else {
                            $error = true;
                        }
                        if ($error) {
                            $this->warnings[] = sprintf(Tools::displayError('Product #%1$d: the picture (%2$s) cannot be saved.'), $image->id_product, $url);
                        }
                    }
                }
                if (isset($product->id_category) && is_array($product->id_category)) {
                    $product->updateCategories(array_map('intval', $product->id_category));
                }
                $product->checkDefaultAttributes();
                if (!$product->cache_default_attribute) {
                    Product::updateDefaultAttribute($product->id);
                }
                // Features import
                $features = get_object_vars($product);
                if (isset($features['features']) && !empty($features['features'])) {
                    foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) {
                        if (empty($single_feature)) {
                            continue;
                        }
                        $tab_feature = explode(':', $single_feature);
                        $feature_name = isset($tab_feature[0]) ? trim($tab_feature[0]) : '';
                        $feature_value = isset($tab_feature[1]) ? trim($tab_feature[1]) : '';
                        $position = isset($tab_feature[2]) ? (int) $tab_feature[2] - 1 : false;
                        $custom = isset($tab_feature[3]) ? (int) $tab_feature[3] : false;
                        if (!empty($feature_name) && !empty($feature_value)) {
                            $id_feature = (int) Feature::addFeatureImport($feature_name, $position);
                            $id_product = null;
                            if (Tools::getValue('forceIDs') || Tools::getValue('match_ref')) {
                                $id_product = (int) $product->id;
                            }
                            $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
                            Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                        }
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
                // set advanced stock managment
                if (isset($product->advanced_stock_management)) {
                    if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product %1$s '), $product->name[$default_language_id]);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        $product->setAdvancedStockManagement($product->advanced_stock_management);
                    }
                    // automaticly disable depends on stock, if a_s_m set to disabled
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0);
                    }
                }
                // Check if warehouse exists
                if (isset($product->warehouse) && $product->warehouse) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse not set on product %1$s '), $product->name[$default_language_id]);
                    } else {
                        if (Warehouse::exists($product->warehouse)) {
                            // Get already associated warehouses
                            $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                            // Delete any entry in warehouse for this product
                            foreach ($associated_warehouses_collection as $awc) {
                                $awc->delete();
                            }
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = 0;
                            $warehouse_location_entity->id_warehouse = $product->warehouse;
                            if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language_id]);
                        }
                    }
                }
                // stock available
                if (isset($product->depends_on_stock)) {
                    if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management not enabled, cannot set "depends on stock" for product %1$s '), $product->name[$default_language_id]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                    }
                    // This code allows us to set qty and disable depends on stock
                    if (isset($product->quantity) && (int) $product->quantity) {
                        // if depends on stock and quantity, add quantity to stock
                        if ($product->depends_on_stock == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $product->wholesale_price);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round(floatval($price), 6);
                            $warehouse = new Warehouse($product->warehouse);
                            if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, (int) $product->quantity, 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($shops as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
Example #11
0
 public function save($type)
 {
     $image = new Image();
     $image->copyFromPost();
     if (!$image->add()) {
         return array('error' => Tools::displayError('Error while creating additional image'));
     } else {
         return $this->copyImage($image->id, $type);
     }
 }
 /**
  * handleImageUpload
  * @author Cornelius Hansjakob <*****@*****.**>
  * @version 1.0
  */
 private function handleImageUpload()
 {
     $this->core->logger->debug('media->controllers->UploadController->handleImageUpload()');
     $objImage = new Image();
     $objImage->setUpload($this->objUpload);
     $objImage->setParentId($this->intParentId);
     $objImage->setParentTypeId($this->core->sysConfig->parent_types->folder);
     $objImage->setSegmenting($this->core->sysConfig->upload->images->segmenting->enabled == 'true' ? true : false);
     $objImage->setNumberOfSegments($this->core->sysConfig->upload->images->segmenting->number_of_segments);
     $objImage->setUploadPath(GLOBAL_ROOT_PATH . $this->core->sysConfig->upload->images->path->local->private);
     $objImage->setPublicFilePath(GLOBAL_ROOT_PATH . $this->core->sysConfig->upload->images->path->local->public);
     $objImage->setTmpFilePath(GLOBAL_ROOT_PATH . $this->core->sysConfig->upload->images->path->local->tmp);
     $objImage->setDefaultImageSizes($this->core->sysConfig->upload->images->default_sizes->default_size->toArray());
     $objImage->setLanguageId($this->intLanguageId);
     $objImage->add(self::UPLOAD_FIELD);
     $this->writeViewData($objImage);
 }
 public static function execImages($pdt, $product)
 {
     $images = array();
     if (isset($pdt->images)) {
         $images = (array) $pdt->images->url;
     } else {
         return;
     }
     foreach ($images as &$img) {
         if (preg_match('/:\\/\\//', $img)) {
             continue;
         }
         $img = _PS_ROOT_DIR_ . $img;
         if (!file_exists($img)) {
             Log::notice($pdt->supplier_reference, 'File $img not found.');
         }
     }
     $product->deleteImages();
     $productHasImages = (bool) Image::getImages(self::getInfoEco('ID_LANG'), (int) $product->id);
     foreach ($images as $key => $url) {
         $url = str_replace(' ', '%20', $url);
         $image = new Image();
         $image->id_product = $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         $image->cover = !$key && !$productHasImages ? true : false;
         if ($image->add()) {
             if (version_compare(_PS_VERSION_, '1.5', '>=')) {
                 $image->associateTo($pdt->id_shop_default);
             }
             if (!self::copyImg($product->id, $image->id, $url)) {
                 Log::notice($pdt->supplier_reference, 'Error copying image: $url');
             }
         } else {
             Log::notice($pdt->supplier_reference, 'Cannot save image $url');
         }
     }
 }
    public function attributeImport()
    {
        $default_language = Configuration::get('PS_LANG_DEFAULT');
        $groups = array();
        foreach (AttributeGroup::getAttributesGroups($default_language) as $group) {
            $groups[$group['name']] = (int) $group['id_attribute_group'];
        }
        $attributes = array();
        foreach (Attribute::getAttributes($default_language) as $attribute) {
            $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute'];
        }
        $this->receiveTab();
        $handle = $this->openCsvFile();
        AdminImportController::setLocale();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (count($line) == 1 && empty($line[0])) {
                continue;
            }
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            $info = array_map('trim', $info);
            if (self::ignoreRow($info)) {
                continue;
            }
            AdminImportController::setDefaultValues($info);
            if (!Shop::isFeatureActive()) {
                $info['shop'] = 1;
            } elseif (!isset($info['shop']) || empty($info['shop'])) {
                $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
            $id_shop_list = array();
            if (is_array($info['shop']) && count($info['shop'])) {
                foreach ($info['shop'] as $shop) {
                    if (!empty($shop) && !is_numeric($shop)) {
                        $id_shop_list[] = Shop::getIdByName($shop);
                    } elseif (!empty($shop)) {
                        $id_shop_list[] = $shop;
                    }
                }
            }
            if (isset($info['id_product']) && is_string($info['id_product'])) {
                $prod = self::findProductByName($default_language, $info['id_product']);
                if ($prod['id_product']) {
                    $info['id_product'] = $prod['id_product'];
                } else {
                    unset($info['id_product']);
                }
            }
            if (!isset($info['id_product']) && Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) {
                $datas = Db::getInstance()->getRow('
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($info['product_reference']) . '"
				');
                if (isset($datas['id_product']) && $datas['id_product']) {
                    $info['id_product'] = $datas['id_product'];
                }
            }
            if (isset($info['id_product'])) {
                $product = new Product((int) $info['id_product'], false, $default_language);
            } else {
                continue;
            }
            $id_image = array();
            if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) {
                $product->deleteImages();
                $this->cache_image_deleted[(int) $product->id] = true;
            }
            if (isset($info['image_url']) && $info['image_url']) {
                $info['image_url'] = explode(',', $info['image_url']);
                if (is_array($info['image_url']) && count($info['image_url'])) {
                    foreach ($info['image_url'] as $url) {
                        $url = trim($url);
                        $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                        $image = new Image();
                        $image->id_product = (int) $product->id;
                        $image->position = Image::getHighestPosition($product->id) + 1;
                        $image->cover = !$product_has_images ? true : false;
                        $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                        $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                        if ($field_error === true && $lang_field_error === true && $image->add()) {
                            $image->associateTo($id_shop_list);
                            if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !Tools::getValue('regenerate'))) {
                                $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                                $image->delete();
                            } else {
                                $id_image[] = (int) $image->id;
                            }
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                        }
                    }
                }
            } elseif (isset($info['image_position']) && $info['image_position']) {
                $info['image_position'] = explode(',', $info['image_position']);
                if (is_array($info['image_position']) && count($info['image_position'])) {
                    foreach ($info['image_position'] as $position) {
                        $images = $product->getImages($default_language);
                        if ($images) {
                            foreach ($images as $row) {
                                if ($row['position'] == (int) $position) {
                                    $id_image[] = (int) $row['id_image'];
                                    break;
                                }
                            }
                        }
                        if (empty($id_image)) {
                            $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $position);
                        }
                    }
                }
            }
            $id_attribute_group = 0;
            $groups_attributes = array();
            if (isset($info['group'])) {
                foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                    if (empty($group)) {
                        continue;
                    }
                    $tab_group = explode(':', $group);
                    $group = trim($tab_group[0]);
                    if (!isset($tab_group[1])) {
                        $type = 'select';
                    } else {
                        $type = trim($tab_group[1]);
                    }
                    $groups_attributes[$key]['group'] = $group;
                    if (isset($tab_group[2])) {
                        $position = trim($tab_group[2]);
                    } else {
                        $position = false;
                    }
                    if (!isset($groups[$group])) {
                        $obj = new AttributeGroup();
                        $obj->is_color_group = false;
                        $obj->group_type = pSQL($type);
                        $obj->name[$default_language] = $group;
                        $obj->public_name[$default_language] = $group;
                        $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            $obj->add();
                            $obj->associateTo($id_shop_list);
                            $groups[$group] = $obj->id;
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                        $id_attribute_group = $obj->id;
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    } else {
                        $id_attribute_group = $groups[$group];
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    }
                }
            }
            $id_product_attribute = 0;
            $id_product_attribute_update = false;
            $attributes_to_add = array();
            if (isset($info['attribute'])) {
                foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                    if (empty($attribute)) {
                        continue;
                    }
                    $tab_attribute = explode(':', $attribute);
                    $attribute = trim($tab_attribute[0]);
                    if (isset($tab_attribute[1])) {
                        $position = trim($tab_attribute[1]);
                    } else {
                        $position = false;
                    }
                    if (isset($groups_attributes[$key])) {
                        $group = $groups_attributes[$key]['group'];
                        if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                            $id_attribute_group = $groups_attributes[$key]['id'];
                            $obj = new Attribute();
                            $obj->id_attribute_group = $groups_attributes[$key]['id'];
                            $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                            $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                            if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            } else {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                            }
                        }
                        $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                        $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                        $info['price'] = str_replace(',', '.', $info['price']);
                        $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                        $info['weight'] = str_replace(',', '.', $info['weight']);
                        $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null;
                        if (!Validate::isEan13($info['ean13'])) {
                            $this->warnings[] = sprintf(Tools::displayError('EAN13 "%1s" has incorrect value for product with id %2d.'), $info['ean13'], $product->id);
                            $info['ean13'] = '';
                        }
                        if ($info['default_on']) {
                            $product->deleteDefaultAttributes();
                        }
                        if (isset($info['reference']) && !empty($info['reference'])) {
                            $id_product_attribute = Combination::getIdByReference($product->id, (string) $info['reference']);
                            if ($id_product_attribute) {
                                $attribute_combinations = $product->getAttributeCombinations($default_language);
                                foreach ($attribute_combinations as $attribute_combination) {
                                    if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                        $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, (string) $info['reference'], (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list);
                                        $id_product_attribute_update = true;
                                        if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                            $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                                        }
                                    }
                                }
                            }
                        }
                        if (!$id_product_attribute) {
                            $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, (string) $info['reference'], 0, (string) $info['ean13'], (int) $info['default_on'], 0, (string) $info['upc'], (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']);
                            if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                            }
                        }
                        if (isset($attributes[$group . '_' . $attribute])) {
                            $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                        }
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
            $product->checkDefaultAttributes();
            if (!$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            if ($id_product_attribute) {
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')');
                }
                if (isset($info['advanced_stock_management'])) {
                    if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management has incorrect value. Not set for product with id %d.'), $product->id);
                    } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot enable on product with id %d.'), $product->id);
                    } else {
                        $product->setAdvancedStockManagement($info['advanced_stock_management']);
                    }
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                    }
                }
                if (isset($info['warehouse']) && $info['warehouse']) {
                    if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, warehouse is not set on product with id %d.'), $product->id);
                    } else {
                        if (Warehouse::exists($info['warehouse'])) {
                            $warehouse_location_entity = new WarehouseProductLocation();
                            $warehouse_location_entity->id_product = $product->id;
                            $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                            $warehouse_location_entity->id_warehouse = $info['warehouse'];
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        } else {
                            $this->warnings[] = sprintf(Tools::displayError('Warehouse did not exist, cannot set on product %1$s.'), $product->name[$default_language]);
                        }
                    }
                }
                if (isset($info['depends_on_stock'])) {
                    if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Incorrect value for depends on stock for product %1$s '), $product->name[$default_language]);
                    } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                        $this->warnings[] = sprintf(Tools::displayError('Advanced stock management is not enabled, cannot set depends on stock %1$s '), $product->name[$default_language]);
                    } else {
                        StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                    }
                    if (isset($info['quantity']) && $info['quantity']) {
                        if ($info['depends_on_stock'] == 1) {
                            $stock_manager = StockManagerFactory::getManager();
                            $price = str_replace(',', '.', $info['wholesale_price']);
                            if ($price == 0) {
                                $price = 1.0E-6;
                            }
                            $price = round((double) $price, 6);
                            $warehouse = new Warehouse($info['warehouse']);
                            if ($stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, $info['quantity'], 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($id_shop_list as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, $info['quantity'], $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($id_shop_list as $shop) {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
Example #15
0
     echo "Invalid Product Id {$id_product}";
     exit;
 }
 $product->deleteImages();
 $first_image = true;
 $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
 foreach ($images as $image_name) {
     $image_name = trim($image_name);
     $image_path = IMAGE_UPLOAD_PATH . $image_name;
     if (!empty($image_name)) {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         $image->cover = $first_image;
         $image->legend[$defaultLanguageId] = $product->name[$defaultLanguageId];
         if (($fieldError = $image->validateFields(false, true)) === true and ($langFieldError = $image->validateFieldsLang(false, true)) === true and $image->add()) {
             if (!Tools::copyImg($product->id, $image->id, $image_path)) {
                 echo "Error copying image:" . $image_path;
                 exit;
             } else {
                 //delete the original image
                 @unlink($image_path);
             }
         } else {
             print_r($fieldError);
             print_r($langFieldError);
             exit;
         }
     }
     $first_image = false;
 }
Example #16
0
 public function save()
 {
     $product = new Product($_GET['id_product']);
     if (!Validate::isLoadedObject($product)) {
         return array('error' => Tools::displayError('Cannot add image because product creation failed.'));
     } else {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         if (!Image::getCover($image->id_product)) {
             $image->cover = 1;
         } else {
             $image->cover = 0;
         }
         if (!$image->add()) {
             return array('error' => Tools::displayError('Error while creating additional image'));
         } else {
             return $this->copyImage($product->id, $image->id);
         }
     }
 }
Example #17
0
    protected function attributeImportOne($info, $default_language, &$groups, &$attributes, $regenerate, $shop_is_feature_active, $validateOnly = false)
    {
        AdminImportController::setDefaultValues($info);
        if (!$shop_is_feature_active) {
            $info['shop'] = 1;
        } elseif (!isset($info['shop']) || empty($info['shop'])) {
            $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
        }
        // Get shops for each attributes
        $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
        $id_shop_list = array();
        if (is_array($info['shop']) && count($info['shop'])) {
            foreach ($info['shop'] as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $id_shop_list[] = Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $id_shop_list[] = $shop;
                }
            }
        }
        if (isset($info['id_product']) && $info['id_product']) {
            $product = new Product((int) $info['id_product'], false, $default_language);
        } elseif (Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) {
            $datas = Db::getInstance()->getRow('
				SELECT p.`id_product`
				FROM `' . _DB_PREFIX_ . 'product` p
				' . Shop::addSqlAssociation('product', 'p') . '
				WHERE p.`reference` = "' . pSQL($info['product_reference']) . '"
			', false);
            if (isset($datas['id_product']) && $datas['id_product']) {
                $product = new Product((int) $datas['id_product'], false, $default_language);
            }
        } else {
            return;
        }
        $id_image = array();
        if (isset($info['image_url']) && $info['image_url']) {
            $info['image_url'] = explode($this->multiple_value_separator, $info['image_url']);
            if (is_array($info['image_url']) && count($info['image_url'])) {
                foreach ($info['image_url'] as $key => $url) {
                    $url = trim($url);
                    $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                    $image = new Image();
                    $image->id_product = (int) $product->id;
                    $image->position = Image::getHighestPosition($product->id) + 1;
                    $image->cover = !$product_has_images ? true : false;
                    if (isset($info['image_alt'])) {
                        $alt = self::split($info['image_alt']);
                        if (isset($alt[$key]) && strlen($alt[$key]) > 0) {
                            $alt = self::createMultiLangField($alt[$key]);
                            $image->legend = $alt;
                        }
                    }
                    $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                    $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                    if ($field_error === true && $lang_field_error === true && !$validateOnly && $image->add()) {
                        $image->associateTo($id_shop_list);
                        // FIXME: 2s/image !
                        if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !$regenerate)) {
                            $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url);
                            $image->delete();
                        } else {
                            $id_image[] = (int) $image->id;
                        }
                        // until here
                    } else {
                        if (!$validateOnly) {
                            $this->warnings[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                        }
                        if ($field_error !== true || $lang_field_error !== true) {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                        }
                    }
                }
            }
        } elseif (isset($info['image_position']) && $info['image_position']) {
            $info['image_position'] = explode($this->multiple_value_separator, $info['image_position']);
            if (is_array($info['image_position']) && count($info['image_position'])) {
                foreach ($info['image_position'] as $position) {
                    // choose images from product by position
                    $images = $product->getImages($default_language);
                    if ($images) {
                        foreach ($images as $row) {
                            if ($row['position'] == (int) $position) {
                                $id_image[] = (int) $row['id_image'];
                                break;
                            }
                        }
                    }
                    if (empty($id_image)) {
                        $this->warnings[] = sprintf($this->trans('No image was found for combination with id_product = %s and image position = %s.', array(), 'Admin.Parameters.Notification'), $product->id, (int) $position);
                    }
                }
            }
        }
        $id_attribute_group = 0;
        // groups
        $groups_attributes = array();
        if (isset($info['group'])) {
            foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                if (empty($group)) {
                    continue;
                }
                $tab_group = explode(':', $group);
                $group = trim($tab_group[0]);
                if (!isset($tab_group[1])) {
                    $type = 'select';
                } else {
                    $type = trim($tab_group[1]);
                }
                // sets group
                $groups_attributes[$key]['group'] = $group;
                // if position is filled
                if (isset($tab_group[2])) {
                    $position = trim($tab_group[2]);
                } else {
                    $position = false;
                }
                if (!isset($groups[$group])) {
                    $obj = new AttributeGroup();
                    $obj->is_color_group = false;
                    $obj->group_type = pSQL($type);
                    $obj->name[$default_language] = $group;
                    $obj->public_name[$default_language] = $group;
                    $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                    if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                        // here, cannot avoid attributeGroup insertion to avoid an error during validation step.
                        //if (!$validateOnly) {
                        $obj->add();
                        $obj->associateTo($id_shop_list);
                        $groups[$group] = $obj->id;
                        //}
                    } else {
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                    }
                    // fills groups attributes
                    $id_attribute_group = $obj->id;
                    $groups_attributes[$key]['id'] = $id_attribute_group;
                } else {
                    // already exists
                    $id_attribute_group = $groups[$group];
                    $groups_attributes[$key]['id'] = $id_attribute_group;
                }
            }
        }
        // inits attribute
        $id_product_attribute = 0;
        $id_product_attribute_update = false;
        $attributes_to_add = array();
        // for each attribute
        if (isset($info['attribute'])) {
            foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                if (empty($attribute)) {
                    continue;
                }
                $tab_attribute = explode(':', $attribute);
                $attribute = trim($tab_attribute[0]);
                // if position is filled
                if (isset($tab_attribute[1])) {
                    $position = trim($tab_attribute[1]);
                } else {
                    $position = false;
                }
                if (isset($groups_attributes[$key])) {
                    $group = $groups_attributes[$key]['group'];
                    if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                        $id_attribute_group = $groups_attributes[$key]['id'];
                        $obj = new Attribute();
                        // sets the proper id (corresponding to the right key)
                        $obj->id_attribute_group = $groups_attributes[$key]['id'];
                        $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                        $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            if (!$validateOnly) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            }
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                    }
                    $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                    $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                    $info['price'] = str_replace(',', '.', $info['price']);
                    $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                    $info['weight'] = str_replace(',', '.', $info['weight']);
                    $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null;
                    if (!Validate::isEan13($info['ean13'])) {
                        $this->warnings[] = sprintf($this->trans('EAN13 "%1s" has incorrect value for product with id %2d.', array(), 'Admin.Parameters.Notification'), $info['ean13'], $product->id);
                        $info['ean13'] = '';
                    }
                    if ($info['default_on'] && !$validateOnly) {
                        $product->deleteDefaultAttributes();
                    }
                    // if a reference is specified for this product, get the associate id_product_attribute to UPDATE
                    if (isset($info['reference']) && !empty($info['reference'])) {
                        $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference']));
                        // updates the attribute
                        if ($id_product_attribute && !$validateOnly) {
                            // gets all the combinations of this product
                            $attribute_combinations = $product->getAttributeCombinations($default_language);
                            foreach ($attribute_combinations as $attribute_combination) {
                                if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                    // FIXME: ~3s/declinaison
                                    $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list);
                                    $id_product_attribute_update = true;
                                    if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                                        $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                                    }
                                    // until here
                                }
                            }
                        }
                    }
                    // if no attribute reference is specified, creates a new one
                    if (!$id_product_attribute && !$validateOnly) {
                        $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']);
                        if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) {
                            $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']);
                        }
                    }
                    // fills our attributes array, in order to add the attributes to the product_attribute afterwards
                    if (isset($attributes[$group . '_' . $attribute])) {
                        $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                    }
                    // after insertion, we clean attribute position and group attribute position
                    if (!$validateOnly) {
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
        }
        $product->checkDefaultAttributes();
        if (!$product->cache_default_attribute && !$validateOnly) {
            Product::updateDefaultAttribute($product->id);
        }
        if ($id_product_attribute) {
            if (!$validateOnly) {
                // now adds the attributes in the attribute_combination table
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')', false);
                }
            }
            // set advanced stock managment
            if (isset($info['advanced_stock_management'])) {
                if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } elseif (!$validateOnly) {
                    $product->setAdvancedStockManagement($info['advanced_stock_management']);
                }
                // automaticly disable depends on stock, if a_s_m set to disabled
                if (!$validateOnly && StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) {
                    StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute);
                }
            }
            // Check if warehouse exists
            if (isset($info['warehouse']) && $info['warehouse']) {
                if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse is not set on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id);
                } else {
                    if (Warehouse::exists($info['warehouse'])) {
                        $warehouse_location_entity = new WarehouseProductLocation();
                        $warehouse_location_entity->id_product = $product->id;
                        $warehouse_location_entity->id_product_attribute = $id_product_attribute;
                        $warehouse_location_entity->id_warehouse = $info['warehouse'];
                        if (!$validateOnly) {
                            if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) {
                                $warehouse_location_entity->update();
                            } else {
                                $warehouse_location_entity->save();
                            }
                            StockAvailable::synchronize($product->id);
                        }
                    } else {
                        $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                    }
                }
            }
            // stock available
            if (isset($info['depends_on_stock'])) {
                if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) {
                    $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Notifications.Error'), $product->name[$default_language]);
                } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]);
                } elseif (!$validateOnly) {
                    StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute);
                }
                // This code allows us to set qty and disable depends on stock
                if (isset($info['quantity']) && (int) $info['quantity']) {
                    // if depends on stock and quantity, add quantity to stock
                    if ($info['depends_on_stock'] == 1) {
                        $stock_manager = StockManagerFactory::getManager();
                        $price = str_replace(',', '.', $info['wholesale_price']);
                        if ($price == 0) {
                            $price = 1.0E-6;
                        }
                        $price = round(floatval($price), 6);
                        $warehouse = new Warehouse($info['warehouse']);
                        if (!$validateOnly && $stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) {
                            StockAvailable::synchronize((int) $product->id);
                        }
                    } elseif (!$validateOnly) {
                        if ($shop_is_feature_active) {
                            foreach ($id_shop_list as $shop) {
                                StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                            }
                        } else {
                            StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                        }
                    }
                }
            } elseif (!$validateOnly) {
                // if not depends_on_stock set, use normal qty
                if ($shop_is_feature_active) {
                    foreach ($id_shop_list as $shop) {
                        StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop);
                    }
                } else {
                    StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id);
                }
            }
        }
    }
    public function attributeImport()
    {
        $default_language = Configuration::get('PS_LANG_DEFAULT');
        $groups = array();
        foreach (AttributeGroup::getAttributesGroups($default_language) as $group) {
            $groups[$group['name']] = (int) $group['id_attribute_group'];
        }
        $attributes = array();
        foreach (Attribute::getAttributes($default_language) as $attribute) {
            $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute'];
        }
        $this->receiveTab();
        $handle = $this->openCsvFile();
        AdminImportController::setLocale();
        for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) {
            if (count($line) == 1 && empty($line[0])) {
                continue;
            }
            if (Tools::getValue('convert')) {
                $line = $this->utf8EncodeArray($line);
            }
            $info = AdminImportController::getMaskedRow($line);
            $info = array_map('trim', $info);
            AdminImportController::setDefaultValues($info);
            if (!Shop::isFeatureActive()) {
                $info['shop'] = 1;
            } elseif (!isset($info['shop']) || empty($info['shop'])) {
                $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            // Get shops for each attributes
            $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
            $id_shop_list = array();
            foreach ($info['shop'] as $shop) {
                if (!is_numeric($shop)) {
                    $id_shop_list[] = Shop::getIdByName($shop);
                } else {
                    $id_shop_list[] = $shop;
                }
            }
            if (isset($info['id_product'])) {
                $product = new Product((int) $info['id_product'], false, $default_language);
            } else {
                continue;
            }
            $id_image = null;
            //delete existing images if "delete_existing_images" is set to 1
            if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) {
                $product->deleteImages();
                $this->cache_image_deleted[(int) $product->id] = true;
            }
            if (isset($info['image_url']) && $info['image_url']) {
                $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id);
                $url = $info['image_url'];
                $image = new Image();
                $image->id_product = (int) $product->id;
                $image->position = Image::getHighestPosition($product->id) + 1;
                $image->cover = !$product_has_images ? true : false;
                $field_error = $image->validateFields(UNFRIENDLY_ERROR, true);
                $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true);
                if ($field_error === true && $lang_field_error === true && $image->add()) {
                    $image->associateTo($id_shop_list);
                    if (!AdminImportController::copyImg($product->id, $image->id, $url)) {
                        $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url);
                        $image->delete();
                    } else {
                        $id_image = array($image->id);
                    }
                } else {
                    $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : '');
                    $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error();
                }
            } elseif (isset($info['image_position']) && $info['image_position']) {
                $images = $product->getImages($default_language);
                if ($images) {
                    foreach ($images as $row) {
                        if ($row['position'] == (int) $info['image_position']) {
                            $id_image = array($row['id_image']);
                            break;
                        }
                    }
                }
                if (!$id_image) {
                    $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']);
                }
            }
            $id_attribute_group = 0;
            // groups
            $groups_attributes = array();
            if (isset($info['group'])) {
                foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) {
                    $tab_group = explode(':', $group);
                    $group = trim($tab_group[0]);
                    if (!isset($tab_group[1])) {
                        $type = 'select';
                    } else {
                        $type = trim($tab_group[1]);
                    }
                    // sets group
                    $groups_attributes[$key]['group'] = $group;
                    // if position is filled
                    if (isset($tab_group[2])) {
                        $position = trim($tab_group[2]);
                    } else {
                        $position = false;
                    }
                    if (!isset($groups[$group])) {
                        $obj = new AttributeGroup();
                        $obj->is_color_group = false;
                        $obj->group_type = pSQL($type);
                        $obj->name[$default_language] = $group;
                        $obj->public_name[$default_language] = $group;
                        $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position;
                        if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                            $obj->add();
                            $obj->associateTo($id_shop_list);
                            $groups[$group] = $obj->id;
                        } else {
                            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                        }
                        // fils groups attributes
                        $id_attribute_group = $obj->id;
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    } else {
                        $id_attribute_group = $groups[$group];
                        $groups_attributes[$key]['id'] = $id_attribute_group;
                    }
                }
            }
            // inits attribute
            $id_product_attribute = 0;
            $id_product_attribute_update = false;
            $attributes_to_add = array();
            // for each attribute
            if (isset($info['attribute'])) {
                foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) {
                    $tab_attribute = explode(':', $attribute);
                    $attribute = trim($tab_attribute[0]);
                    // if position is filled
                    if (isset($tab_attribute[1])) {
                        $position = trim($tab_attribute[1]);
                    } else {
                        $position = false;
                    }
                    if (isset($groups_attributes[$key])) {
                        $group = $groups_attributes[$key]['group'];
                        if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) {
                            $id_attribute_group = $groups_attributes[$key]['id'];
                            $obj = new Attribute();
                            // sets the proper id (corresponding to the right key)
                            $obj->id_attribute_group = $groups_attributes[$key]['id'];
                            $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                            $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position;
                            if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                                $obj->add();
                                $obj->associateTo($id_shop_list);
                                $attributes[$group . '_' . $attribute] = $obj->id;
                            } else {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '');
                            }
                        }
                        $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1;
                        $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']);
                        $info['price'] = str_replace(',', '.', $info['price']);
                        $info['ecotax'] = str_replace(',', '.', $info['ecotax']);
                        $info['weight'] = str_replace(',', '.', $info['weight']);
                        // if a reference is specified for this product, get the associate id_product_attribute to UPDATE
                        if (isset($info['reference']) && !empty($info['reference'])) {
                            $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference']));
                            // updates the attribute
                            if ($id_product_attribute) {
                                // gets all the combinations of this product
                                $attribute_combinations = $product->getAttributeCombinations($default_language);
                                foreach ($attribute_combinations as $attribute_combination) {
                                    if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) {
                                        $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], 0, null, $id_shop_list);
                                        $id_product_attribute_update = true;
                                    }
                                }
                            }
                        }
                        // if no attribute reference is specified, creates a new one
                        if (!$id_product_attribute) {
                            $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list);
                        }
                        // fills our attributes array, in order to add the attributes to the product_attribute afterwards
                        if (isset($attributes[$group . '_' . $attribute])) {
                            $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute];
                        }
                        // after insertion, we clean attribute position and group attribute position
                        $obj = new Attribute();
                        $obj->cleanPositions((int) $id_attribute_group, false);
                        AttributeGroup::cleanPositions();
                    }
                }
            }
            $product->checkDefaultAttributes();
            if (!$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            if ($id_product_attribute) {
                // now adds the attributes in the attribute_combination table
                if ($id_product_attribute_update) {
                    Db::getInstance()->execute('
						DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination
						WHERE id_product_attribute = ' . (int) $id_product_attribute);
                }
                foreach ($attributes_to_add as $attribute_to_add) {
                    Db::getInstance()->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute)
						VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')');
                }
                StockAvailable::setQuantity($product->id, $id_product_attribute, (int) $info['quantity']);
            }
        }
        $this->closeCsvFile($handle);
    }
Example #19
0
 public function ajaxProcessaddProductImage()
 {
     self::$currentIndex = 'index.php?tab=AdminProducts';
     $product = new Product((int) Tools::getValue('id_product'));
     $legends = Tools::getValue('legend');
     if (!is_array($legends)) {
         $legends = (array) $legends;
     }
     if (!Validate::isLoadedObject($product)) {
         $files = array();
         $files[0]['error'] = Tools::displayError('Cannot add image because product creation failed.');
     }
     $image_uploader = new HelperImageUploader('file');
     $image_uploader->setAcceptTypes(array('jpeg', 'gif', 'png', 'jpg'))->setMaxSize($this->max_image_size);
     $files = $image_uploader->process();
     foreach ($files as &$file) {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         foreach ($legends as $key => $legend) {
             if (!empty($legend)) {
                 $image->legend[(int) $key] = $legend;
             }
         }
         if (!Image::getCover($image->id_product)) {
             $image->cover = 1;
         } else {
             $image->cover = 0;
         }
         if (($validate = $image->validateFieldsLang(false, true)) !== true) {
             $file['error'] = Tools::displayError($validate);
         }
         if (isset($file['error']) && (!is_numeric($file['error']) || $file['error'] != 0)) {
             continue;
         }
         if (!$image->add()) {
             $file['error'] = Tools::displayError('Error while creating additional image');
         } else {
             if (!($new_path = $image->getPathForCreation())) {
                 $file['error'] = Tools::displayError('An error occurred during new folder creation');
                 continue;
             }
             $error = 0;
             if (!ImageManager::resize($file['save_path'], $new_path . '.' . $image->image_format, null, null, 'jpg', false, $error)) {
                 switch ($error) {
                     case ImageManager::ERROR_FILE_NOT_EXIST:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file does not exist anymore.');
                         break;
                     case ImageManager::ERROR_FILE_WIDTH:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file width is 0px.');
                         break;
                     case ImageManager::ERROR_MEMORY_LIMIT:
                         $file['error'] = Tools::displayError('An error occurred while copying image, check your memory limit.');
                         break;
                     default:
                         $file['error'] = Tools::displayError('An error occurred while copying image.');
                         break;
                 }
                 continue;
             } else {
                 $imagesTypes = ImageType::getImagesTypes('products');
                 foreach ($imagesTypes as $imageType) {
                     if (!ImageManager::resize($file['save_path'], $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                         $file['error'] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                         continue;
                     }
                 }
             }
             unlink($file['save_path']);
             //Necesary to prevent hacking
             unset($file['save_path']);
             Hook::exec('actionWatermark', array('id_image' => $image->id, 'id_product' => $product->id));
             if (!$image->update()) {
                 $file['error'] = Tools::displayError('Error while updating status');
                 continue;
             }
             // Associate image to shop from context
             $shops = Shop::getContextListShopID();
             $image->associateTo($shops);
             $json_shops = array();
             foreach ($shops as $id_shop) {
                 $json_shops[$id_shop] = true;
             }
             $file['status'] = 'ok';
             $file['id'] = $image->id;
             $file['position'] = $image->position;
             $file['cover'] = $image->cover;
             $file['legend'] = $image->legend;
             $file['path'] = $image->getExistingImgPath();
             $file['shops'] = $json_shops;
             @unlink(_PS_TMP_IMG_DIR_ . 'product_' . (int) $product->id . '.jpg');
             @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . $this->context->shop->id . '.jpg');
         }
     }
     die(Tools::jsonEncode(array($image_uploader->getName() => $files)));
 }
 public function handleConfirm($update = false)
 {
     global $currentIndex, $cookie, $smarty;
     $products_to_import = array();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     $file_path = Tools::getValue('current_file');
     $overwrite_imgs = Tools::getValue("overwrite_imgs");
     //$file_path = '/Users/rohit/webroot/indusdiva/admin12/product-uploads/upload_sheet_1.csv';
     $f = fopen($file_path, 'r');
     $file_error = false;
     if ($f) {
         //discard header
         $line = fgetcsv($f);
         while ($line = fgetcsv($f)) {
             //ignore empty lines
             if (empty($line)) {
                 continue;
             }
             //trim data
             foreach ($line as $key => $value) {
                 $line[$key] = trim($value);
             }
             $id_product = $line[0];
             $images = $line[1];
             $product_name = $line[2];
             $fabric = $line[3];
             $color = $line[4];
             $mrp = $line[5];
             $supplier_code = $line[6];
             $reference = $line[7];
             $location = $line[8];
             $length = $line[9];
             $width = $line[10];
             $blouse_length = $line[11];
             $garment_type = $line[12];
             $work_type = $line[13];
             $weight = $line[14];
             $description = $line[15];
             $other_info = $line[16];
             $wash_care = $line[17];
             $shipping_estimate = $line[18];
             $supplier_price = $line[19];
             $manufacturer = $line[20];
             $categories = explode(",", $line[21]);
             $tax_rule = $line[22];
             $quantity = $line[23];
             $active = $line[24];
             $discount = $line[25];
             $tags = $line[26];
             $kameez_style = $line[27];
             $salwar_style = $line[28];
             $sleeves = $line[29];
             $customizable = $line[30];
             $generic_color = $line[31];
             $skirt_length = $line[32];
             $dupatta_length = $line[33];
             $stone = $line[34];
             $plating = $line[35];
             $material = $line[36];
             $dimensions = $line[37];
             $look = $line[38];
             $as_shown = isset($line[39]) && !empty($line[39]) ? intval($line[39]) : 0;
             $id_sizechart = isset($line[40]) && !empty($line[40]) ? intval($line[40]) : 0;
             $is_exclusive = isset($line[41]) && !empty($line[41]) ? intval($line[41]) : 0;
             $handbag_occasion = isset($line[42]) && !empty($line[42]) ? $line[42] : null;
             $handbag_style = isset($line[43]) && !empty($line[43]) ? $line[43] : null;
             $handbag_material = isset($line[44]) && !empty($line[44]) ? $line[44] : null;
             $images = explode(",", $images);
             $error = false;
             //validate fields
             if (!Validate::isFloat($mrp)) {
                 $error = 'MRP should be a number: ' . trim($reference);
             } elseif (!Validate::isFloat($supplier_price)) {
                 $error = 'Supplier Price should be a number: ' . trim($reference);
             }
             $importCategories = array();
             if (is_array($categories)) {
                 $categories = array_unique($categories);
                 foreach ($categories as $category) {
                     $category = intval(trim($category));
                     if (empty($category)) {
                         continue;
                     }
                     if (!is_numeric($category) || !Category::categoryExists($category)) {
                         $error = 'Category does not exist: ' . $category;
                     }
                     $importCategories[] = $category;
                 }
             } else {
                 $error = 'Atleast one category required: ' . trim($reference);
             }
             if (!Validate::isFloat($weight)) {
                 $error = 'Weight has to be a number: ' . trim($reference);
             }
             if (!empty($manufacturer) && (!is_numeric($manufacturer) || !Manufacturer::manufacturerExists((int) $manufacturer))) {
                 $error = 'Manufacturer does not exist';
             }
             if ($quantity && !is_numeric($quantity) || $discount && !is_numeric($discount)) {
                 $error = 'Quantity and discount should be numbers: ' . trim($reference);
             }
             if (!Validate::isLoadedObject(new TaxRulesGroup($tax_rule))) {
                 $error = 'Tax rate invalid: ' . trim($reference);
             }
             if (!$update) {
                 $sql = "SELECT `reference`\n\t\t\t\t\t\t\tFROM " . _DB_PREFIX_ . "product p\n\t\t\t\t\t\t\tWHERE p.`reference` = '" . $reference . "'";
                 $row = Db::getInstance()->getRow($sql);
                 if (isset($row['reference'])) {
                     $error = "Duplicate indusdiva code : " . trim($reference);
                 }
             }
             //check for souring price
             if ($supplier_price > $mrp / 1.2) {
                 $error = "MRP too low : " . trim($reference);
             }
             //check for images
             if (!$update || $overwrite_imgs == "on") {
                 foreach ($images as $image_name) {
                     $image_name = trim($image_name);
                     $image_path = IMAGE_UPLOAD_PATH . $image_name;
                     if (!empty($image_name) && !file_exists($image_path)) {
                         $error = "Image not found for: " . trim($reference) . ", Image Name: " . $image_name;
                         break;
                     }
                 }
             }
             $vendor_code = substr($reference, 0, 6);
             $sql = "select id_supplier from ps_supplier where code = '{$vendor_code}'";
             $row = Db::getInstance()->getRow($sql);
             if (!isset($row['id_supplier'])) {
                 $error = "Vendor Details not found for : " . trim($reference);
             } else {
                 $id_supplier = $row['id_supplier'];
             }
             //For sudarshan, supplier_code (vendor product code) is mandatory
             if (false) {
                 //(int) $id_supplier === 2 ) {
                 if (empty($supplier_code)) {
                     $error = "Reference: {$reference} -- Supplier Code is Mandatory for Vendor {$vendor_code}";
                 } else {
                     if (strpos("::", ${$supplier_code}) === false) {
                         $error = "Reference: {$reference} -- Supplier Code:{$supplier_code} is not in DESIGN_NO::ITEM_CODE format for Vendor {$vendor_code}";
                     }
                 }
             }
             if (!$error) {
                 if ($update && !empty($id_product)) {
                     $product = new Product((int) $id_product);
                     if (!Validate::isLoadedObject($product)) {
                         $error = "Error loading the product: " . $id_product;
                         return;
                     }
                 } elseif (!$update) {
                     $product = new Product();
                 }
                 $product->id_tax_rules_group = $tax_rule;
                 $product->reference = $reference;
                 $product->id_supplier = $id_supplier;
                 $product->location = $location;
                 $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
                 if (isset($manufacturer) and is_numeric($manufacturer) and Manufacturer::manufacturerExists((int) $manufacturer)) {
                     $product->id_manufacturer = $manufacturer;
                 }
                 $product->price = (double) $mrp;
                 $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
                 $product->id_category = $importCategories;
                 $product->id_category_default = 1;
                 $product->name = array();
                 $product->name[$defaultLanguageId] = $product_name;
                 $product->description_short = array();
                 $product->description_short[$defaultLanguageId] = $style_tips;
                 $product->description = array();
                 $product->description[$defaultLanguageId] = $description;
                 $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
                 $product->link_rewrite = array();
                 $product->link_rewrite[$defaultLanguageId] = $link_rewrite;
                 $product->quantity = $quantity ? intval($quantity) : 0;
                 if ($discount && is_numeric($discount)) {
                     $product->discount = $discount;
                 }
                 if (!empty($tags)) {
                     $product->tags = $tags;
                 }
                 $product->weight = is_numeric($weight) ? $weight : 0;
                 $product->width = is_numeric($width) ? $width : 0;
                 $product->height = is_numeric($length) ? $length : 0;
                 $product->supplier_reference = $supplier_code;
                 $product->wholesale_price = $supplier_price ? (double) $supplier_price : 0;
                 $product->active = $active == 1 ? 1 : 0;
                 $product->images = $images;
                 $product->fabric = $fabric;
                 $product->color = $color;
                 $product->generic_color = $generic_color;
                 $product->garment_type = $garment_type;
                 $product->work_type = $work_type;
                 $product->blouse_length = $blouse_length ? $blouse_length : ' ';
                 $product->wash_care = $wash_care ? $wash_care : ' ';
                 $product->other_info = $other_info ? $other_info : ' ';
                 $product->shipping_estimate = $shipping_estimate ? $shipping_estimate : ' ';
                 $product->is_customizable = $customizable == 1 ? 1 : 0;
                 $product->kameez_style = $kameez_style;
                 $product->salwar_style = $salwar_style;
                 $product->sleeves = $sleeves;
                 $product->skirt_length = $skirt_length;
                 $product->dupatta_length = $dupatta_length;
                 $product->stone = $stone;
                 $product->plating = $plating;
                 $product->material = $material;
                 $product->dimensions = $dimensions;
                 $product->look = $look;
                 $product->as_shown = $as_shown;
                 $product->id_sizechart = $id_sizechart;
                 $product->is_exclusive = $is_exclusive;
                 $product->handbag_occasion = $handbag_occasion;
                 $product->handbag_style = $handbag_style;
                 $product->handbag_material = $handbag_material;
                 $product->indexed = 0;
                 $products_to_import[] = $product;
             } else {
                 $smarty->assign('error', $error);
                 return;
                 $file_error = true;
             }
         }
         if (!$file_error) {
             $added_product_ids = array();
             foreach ($products_to_import as $product) {
                 $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
                 $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
                 if ($fieldError === true and $langFieldError === true) {
                     // check quantity
                     if ($product->quantity == NULL) {
                         $product->quantity = 0;
                     }
                     // If no id_product or update failed
                     if ($update && $product->id) {
                         $res = $product->update();
                     } else {
                         $res = $product->add();
                     }
                     $added_product_ids[] = $product->id;
                 }
                 if (isset($product->discount) && $product->discount > 0) {
                     SpecificPrice::deleteByProductId((int) $product->id);
                     $specificPrice = new SpecificPrice();
                     $specificPrice->id_product = (int) $product->id;
                     $specificPrice->id_shop = (int) Shop::getCurrentShop();
                     $specificPrice->id_currency = 0;
                     $specificPrice->id_country = 0;
                     $specificPrice->id_group = 0;
                     $specificPrice->from_quantity = 1;
                     $specificPrice->reduction = $product->discount / 100;
                     $specificPrice->reduction_type = 'percentage';
                     $specificPrice->from = '2012-01-01 00:00:00';
                     $specificPrice->to = '2016-01-01 00:00:00';
                     $specificPrice->price = $product->price;
                     $specificPrice->add();
                 }
                 if (isset($product->tags) and !empty($product->tags)) {
                     // Delete tags for this id product, for no duplicating error
                     Tag::deleteTagsForProduct($product->id);
                     $tag = new Tag();
                     $tag->addTags($defaultLanguageId, $product->id, $tags);
                 }
                 if (isset($product->images) and is_array($product->images) and sizeof($product->images) and !$update || $overwrite_imgs == "on") {
                     $product->deleteImages();
                     $first_image = true;
                     foreach ($product->images as $image_name) {
                         $image_name = trim($image_name);
                         $image_path = IMAGE_UPLOAD_PATH . $image_name;
                         if (!empty($image_name)) {
                             $image = new Image();
                             $image->id_product = (int) $product->id;
                             $image->position = Image::getHighestPosition($product->id) + 1;
                             $image->cover = $first_image;
                             $image->legend[$defaultLanguageId] = $product->name[$defaultLanguageId];
                             if (($fieldError = $image->validateFields(false, true)) === true and ($langFieldError = $image->validateFieldsLang(false, true)) === true and $image->add()) {
                                 if (!self::copyImg($product->id, $image->id, $image_path)) {
                                     $_warnings[] = Tools::displayError('Error copying image: ') . $image_path;
                                 } else {
                                     //delete the original image
                                     @unlink($image_path);
                                 }
                             } else {
                                 $_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                                 $_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                             }
                         }
                         $first_image = false;
                     }
                 }
                 if (isset($product->id_category)) {
                     $product->updateCategories(array_map('intval', $product->id_category));
                 }
                 $this->addFeature($product->id, 'fabric', $product->fabric);
                 $this->addFeature($product->id, 'color', $product->color);
                 $this->addFeature($product->id, 'garment_type', $product->garment_type);
                 $this->addFeature($product->id, 'work_type', $product->work_type);
                 $this->addFeature($product->id, 'blouse_length', $product->blouse_length);
                 $this->addFeature($product->id, 'wash_care', $product->wash_care);
                 $this->addFeature($product->id, 'other_info', $product->other_info);
                 // to avoid type errors in the catalog sheet - construct the string here again
                 $shipping_sla = (int) preg_replace('/\\D/', '', $product->shipping_estimate);
                 $shipping_estimate_str = "";
                 if ($shipping_sla > 0) {
                     $shipping_estimate_str = $shipping_sla === 1 ? "Ready to be shipped in 1 day" : "Ready to be shipped in {$shipping_sla} days";
                 }
                 $this->addFeature($product->id, 'shipping_estimate', $shipping_estimate_str);
                 $this->addFeature($product->id, 'kameez_style', $product->kameez_style);
                 $this->addFeature($product->id, 'salwar_style', $product->salwar_style);
                 $this->addFeature($product->id, 'sleeves', $product->sleeves);
                 $this->addFeature($product->id, 'generic_color', $product->generic_color);
                 $this->addFeature($product->id, 'skirt_length', $product->skirt_length);
                 $this->addFeature($product->id, 'dupatta_length', $product->dupatta_length);
                 $this->addFeature($product->id, 'stone', $product->stone);
                 $this->addFeature($product->id, 'plating', $product->plating);
                 $this->addFeature($product->id, 'material', $product->material);
                 $this->addFeature($product->id, 'dimensions', $product->dimensions);
                 $this->addFeature($product->id, 'look', $product->look);
                 $this->addFeature($product->id, 'handbag_occasion', $product->handbag_occasion);
                 $this->addFeature($product->id, 'handbag_style', $product->handbag_style);
                 $this->addFeature($product->id, 'handbag_material', $product->handbag_material);
             }
             $smarty->assign("products_affected", $products_to_import);
             //reindex the products
             SolrSearch::updateProducts($added_product_ids);
             $smarty->assign("is_update", $update);
         } else {
             $smarty->assign('file_error', 1);
         }
     } else {
         $smarty->assign('error_reading', 1);
     }
 }
Example #21
0
 public function attributeImport()
 {
     global $cookie;
     $defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
     $groups = array();
     foreach (AttributeGroup::getAttributesGroups($defaultLanguage) as $group) {
         $groups[$group['name']] = (int) $group['id_attribute_group'];
     }
     $attributes = array();
     foreach (Attribute::getAttributes($defaultLanguage) as $attribute) {
         $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute'];
     }
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $fsep = (is_null(Tools::getValue('multiple_value_separator')) or trim(Tools::getValue('multiple_value_separator')) == '') ? ',' : Tools::getValue('multiple_value_separator');
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $line = $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         $info = array_map('trim', $info);
         self::setDefaultValues($info);
         $product = new Product((int) $info['id_product'], false, $defaultLanguage);
         $id_image = null;
         if (isset($info['image_url']) && $info['image_url']) {
             $productHasImages = (bool) Image::getImages((int) $cookie->id_lang, (int) $product->id);
             $url = $info['image_url'];
             $image = new Image();
             $image->id_product = (int) $product->id;
             $image->position = Image::getHighestPosition($product->id) + 1;
             $image->cover = !$productHasImages ? true : false;
             $image->legend = self::createMultiLangField($product->name);
             if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                 if (!self::copyImg($product->id, $image->id, $url)) {
                     $this->_warnings[] = Tools::displayError('Error copying image: ') . $url;
                 } else {
                     $id_image = array($image->id);
                 }
             } else {
                 $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                 $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
             }
         } elseif (isset($info['image_position']) && $info['image_position']) {
             $images = $product->getImages($defaultLanguage);
             if ($images) {
                 foreach ($images as $row) {
                     if ($row['position'] == (int) $info['image_position']) {
                         $id_image = array($row['id_image']);
                         break;
                     }
                 }
             }
             if (!$id_image) {
                 $this->_warnings[] = sprintf(Tools::displayError('No image found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']);
             }
         }
         $id_product_attribute = $product->addProductAttribute((double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), strval($info['supplier_reference']), strval($info['ean13']), (int) $info['default_on'], strval($info['upc']));
         foreach (explode($fsep, $info['options']) as $option) {
             list($group, $attribute) = array_map('trim', explode(':', $option));
             if (!isset($groups[$group])) {
                 $obj = new AttributeGroup();
                 $obj->is_color_group = false;
                 $obj->name[$defaultLanguage] = $group;
                 $obj->public_name[$defaultLanguage] = $group;
                 if (($fieldError = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                     $obj->add();
                     $groups[$group] = $obj->id;
                 } else {
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '');
                 }
             }
             if (!isset($attributes[$group . '_' . $attribute])) {
                 $obj = new Attribute();
                 $obj->id_attribute_group = $groups[$group];
                 $obj->name[$defaultLanguage] = str_replace('\\n', '', str_replace('\\r', '', $attribute));
                 if (($fieldError = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
                     $obj->add();
                     $attributes[$group . '_' . $attribute] = $obj->id;
                 } else {
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '');
                 }
             }
             Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attributes[$group . '_' . $attribute] . ',' . (int) $id_product_attribute . ')');
         }
     }
     $this->closeCsvFile($handle);
 }
Example #22
0
 public function productImport()
 {
     global $cookie;
     $this->receiveTab();
     $handle = $this->openCsvFile();
     $defaultLanguageId = intval(Configuration::get('PS_LANG_DEFAULT'));
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         if (array_key_exists('id', $info) and intval($info['id']) and Product::existsInDatabase(intval($info['id']))) {
             $product = new Product(intval($info['id']));
             if ($product->reduction_from == '0000-00-00') {
                 $product->reduction_from = date('Y-m-d');
             }
             if ($product->reduction_to == '0000-00-00') {
                 $product->reduction_to = date('Y-m-d');
             }
             $categoryData = Product::getIndexedCategories(intval($product->id));
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp['id_category'];
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         // Find id_tax corresponding to given values for product taxe
         if (isset($product->tax_rate)) {
             $product->id_tax = intval(Tax::getTaxIdByRate(floatval($product->tax_rate)));
         }
         if (isset($product->tax_rate) and !$product->id_tax) {
             $tax = new Tax();
             $tax->rate = floatval($product->tax_rate);
             $tax->name = self::createMultiLangField(strval($product->tax_rate));
             if (($fieldError = $tax->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $tax->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $tax->add()) {
                 $product->id_tax = intval($tax->id);
             } else {
                 $this->_errors[] = 'TAX ' . $tax->name[$defaultLanguageId] . ' ' . Tools::displayError('cannot be saved');
                 $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
             }
         }
         if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists(intval($product->manufacturer))) {
             $product->id_manufacturer = intval($product->manufacturer);
         } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) {
             if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                 $product->id_manufacturer = intval($manufacturer);
             } else {
                 $manufacturer = new Manufacturer();
                 $manufacturer->name = $product->manufacturer;
                 if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                     $product->id_manufacturer = intval($manufacturer->id);
                 } else {
                     $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists(intval($product->supplier))) {
             $product->id_supplier = intval($product->supplier);
         } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) {
             if ($supplier = Supplier::getIdByName($product->supplier)) {
                 $product->id_supplier = intval($supplier);
             } else {
                 $supplier = new Supplier();
                 $supplier->name = $product->supplier;
                 if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                     $product->id_supplier = intval($supplier->id);
                 } else {
                     $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($product->price_tex) and !isset($product->price_tin)) {
             $product->price = $product->price_tex;
         } elseif (isset($product->price_tin) and !isset($product->price_tex)) {
             $product->price = $product->price_tin;
             // If a tax is already included in price, withdraw it from price
             if ($product->tax_rate) {
                 $product->price = floatval(number_format($product->price / (1 + $product->tax_rate / 100), 6));
             }
         } elseif (isset($product->price_tin) and isset($product->price_tex)) {
             $product->price = $product->price_tex;
         }
         if (isset($product->category) and is_array($product->category) and sizeof($product->category)) {
             $product->id_category = array();
             // Reset default values array
             foreach ($product->category as $value) {
                 if (is_numeric($value)) {
                     if (Category::categoryExists(intval($value))) {
                         $product->id_category[] = intval($value);
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->id = intval($value);
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = intval($categoryToCreate->id);
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 } elseif (is_string($value) and !empty($value)) {
                     $category = Category::searchByName($defaultLanguageId, $value, true);
                     if ($category['id_category']) {
                         $product->id_category[] = intval($category['id_category']);
                     } else {
                         $categoryToCreate = new Category();
                         $categoryToCreate->name = self::createMultiLangField($value);
                         $categoryToCreate->active = 1;
                         $categoryToCreate->id_parent = 1;
                         // Default parent is home for unknown category to create
                         if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) {
                             $product->id_category[] = intval($categoryToCreate->id);
                         } else {
                             $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
         }
         $product->id_category_default = isset($product->id_category[0]) ? intval($product->id_category[0]) : '';
         $link_rewrite = is_array($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($link_rewrite);
         $bak = $product->link_rewrite;
         if (isset($product->link_rewrite[$defaultLanguageId]) and empty($product->link_rewrite[$defaultLanguageId]) or !$valid_link) {
             $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]);
         }
         if (!$valid_link) {
             $this->_warnings[] = Tools::displayError('Rewrited link for') . ' ' . $bak . (isset($info['id']) ? ' (ID ' . $info['id'] . ') ' : '') . ' ' . Tools::displayError('was re-written as') . ' ' . $link_rewrite;
         }
         $product->link_rewrite = self::createMultiLangField($link_rewrite);
         $res = false;
         $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true);
         $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
         if ($fieldError === true and $langFieldError === true) {
             // check quantity
             if ($product->quantity == NULL) {
                 $product->quantity = 0;
             }
             // If id product AND id product already in base, trying to update
             if ($product->id and Product::existsInDatabase(intval($product->id))) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . intval($product->id));
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             }
             // If no id_product or update failed
             if (!$res) {
                 $res = $product->add();
             }
         }
         // If both failed, mysql error
         if (!$res) {
             $this->_errors[] = $info['name'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         } else {
             if (isset($product->tags) and !empty($product->tags)) {
                 $tag = new Tag();
                 $array = self::createMultiLangField($product->tags);
                 foreach ($array as $key => $tags) {
                     $a = $tag->addTags($key, $product->id, $tags);
                 }
             }
             if (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                 $productHasImages = (bool) Image::getImages(intval($cookie->id_lang), intval($product->id));
                 foreach ($product->image as $key => $url) {
                     if (!empty($url)) {
                         $image = new Image();
                         $image->id_product = intval($product->id);
                         $image->position = Image::getHighestPosition($product->id) + 1;
                         $image->cover = (!$key and !$productHasImages) ? true : false;
                         $image->legend = self::createMultiLangField($product->name[$defaultLanguageId]);
                         if (($fieldError = $image->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $image->add()) {
                             self::copyImg($product->id, $image->id, $url);
                         } else {
                             $this->_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('cannot be saved');
                             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                         }
                     }
                 }
             }
             if (isset($product->id_category)) {
                 $product->updateCategories(array_map('intval', $product->id_category));
             }
             $features = get_object_vars($product);
             foreach ($features as $feature => $value) {
                 if (!strncmp($feature, '#F_', 3) and Tools::strlen($product->{$feature})) {
                     $feature_name = str_replace('#F_', '', $feature);
                     $id_feature = Feature::addFeatureImport($feature_name);
                     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $product->{$feature});
                     Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                 }
             }
         }
     }
     $this->closeCsvFile($handle);
 }
Example #23
0
 private function copyImg($item, $className)
 {
     require_once '../../images.inc.php';
     $identifier = $this->supportedImports[strtolower($className)]['identifier'];
     $matchId = $this->getMatchId(strtolower($className));
     $matchIdLang = $this->getMatchIdLang();
     switch ($className) {
         default:
         case 'Product':
             $path = _PS_PROD_IMG_DIR_;
             $type = 'products';
             break;
         case 'Category':
             $path = _PS_CAT_IMG_DIR_;
             $type = 'categories';
             break;
         case 'Manufacturer':
             $path = _PS_MANU_IMG_DIR_;
             $type = 'manufacturers';
             break;
         case 'Supplier':
             $path = _PS_SUPP_IMG_DIR_;
             $type = 'suppliers';
             break;
     }
     $cover = 1;
     if (array_key_exists($item[$identifier], $matchId)) {
         if (array_key_exists('images', $item) && !is_null($item['images'])) {
             foreach ($item['images'] as $key => $image) {
                 $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import');
                 if (@copy(str_replace(' ', '%20', $image), $tmpfile)) {
                     $imagesTypes = ImageType::getImagesTypes($type);
                     ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '.jpg');
                     if ($className == 'Product') {
                         $image = new Image();
                         $image->id_product = (int) $matchId[$item[$identifier]];
                         $image->cover = $cover;
                         $image->position = Image::getHighestPosition((int) $matchId[$item[$identifier]]) + 1;
                         $legend = array();
                         foreach ($item['name'] as $key => $val) {
                             if (array_key_exists($key, $matchIdLang)) {
                                 $legend[$matchIdLang[$key]] = Tools::link_rewrite($val);
                             } else {
                                 $legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val);
                             }
                         }
                         $image->legend = $legend;
                         $image->add();
                         ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . (int) $image->id . '.jpg');
                         foreach ($imagesTypes as $k => $imageType) {
                             ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . (int) $image->id . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height']);
                         }
                     } else {
                         foreach ($imagesTypes as $imageType) {
                             ImageManager::resize($tmpfile, $path . (int) $matchId[$item[$identifier]] . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height']);
                         }
                     }
                 } else {
                     @unlink($tmpfile);
                 }
                 @unlink($tmpfile);
                 $cover = 0;
             }
         }
     }
 }
 public function createDummyDataForProject()
 {
     //delete privious products of prestashop
     $all_products = Product::getSimpleProducts(Configuration::get('PS_LANG_DEFAULT'));
     foreach ($all_products as $key_pro => $value_pro) {
         $obj_product = new Product($value_pro['id_product']);
         $obj_product->delete();
     }
     // first add a hotel.................
     $def_cont_id = Country::getDefaultCountryId();
     $obj_hotel_info = new HotelBranchInformation();
     $obj_hotel_info->active = 1;
     $obj_hotel_info->hotel_name = "The Hotel Prime";
     $obj_hotel_info->phone = 01234567;
     $obj_hotel_info->email = "*****@*****.**";
     $obj_hotel_info->check_in = '12:00';
     $obj_hotel_info->check_out = '12:00';
     $obj_hotel_info->short_description = $this->l('Nice place to stay');
     $obj_hotel_info->description = $this->l('Nice place to stay');
     $obj_hotel_info->rating = 3;
     $obj_hotel_info->city = 'Nainital';
     $states = State::getStatesByIdCountry($def_cont_id);
     $state_id = $states[0]['id_state'];
     $obj_hotel_info->state_id = $state_id;
     $obj_hotel_info->country_id = $def_cont_id;
     $obj_hotel_info->zipcode = 263001;
     $obj_hotel_info->policies = $this->l('1. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 2. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 3. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred. 4. intelligentsia tattooed pop-up salvia asymmetrical mixtape meggings tousled ramps VHS cred.');
     $obj_hotel_info->address = 'Near post office, Mallital, Nainital';
     $obj_hotel_info->save();
     $htl_id = $obj_hotel_info->id;
     $grp_ids = array();
     $obj_grp = new Group();
     $data_grp_ids = $obj_grp->getGroups(1, $id_shop = false);
     foreach ($data_grp_ids as $key => $value) {
         $grp_ids[] = $value['id_group'];
     }
     $country_name = (new Country())->getNameById(Configuration::get('PS_LANG_DEFAULT'), $def_cont_id);
     $cat_country = $this->addCategory($country_name, false, $grp_ids);
     if ($cat_country) {
         $states = State::getStatesByIdCountry($def_cont_id);
         $state_name = $states[0]['name'];
         $cat_state = $this->addCategory($state_name, $cat_country, $grp_ids);
     }
     if ($cat_state) {
         $cat_city = $this->addCategory('DefCity', $cat_state, $grp_ids);
     }
     if ($cat_city) {
         $cat_hotel = $this->addCategory('The Hotel Prime', $cat_city, $grp_ids, 1, $htl_id);
     }
     if ($cat_hotel) {
         $obj_hotel_info = new HotelBranchInformation($htl_id);
         $obj_hotel_info->id_category = $cat_hotel;
         $obj_hotel_info->save();
     }
     $branch_ftr_ids = array(1, 2, 4, 7, 8, 9, 11, 12, 14, 16, 17, 18, 21);
     foreach ($branch_ftr_ids as $key_ftr => $value_ftr) {
         $htl_ftr_obj = new HotelBranchFeatures();
         $htl_ftr_obj->id_hotel = $htl_id;
         $htl_ftr_obj->feature_id = $value_ftr;
         $htl_ftr_obj->save();
     }
     $prod_arr = array('Delux Rooms', 'Executive Rooms', 'luxury Rooms');
     $img_num = 1;
     foreach ($prod_arr as $key_prod => $value_prod) {
         // Add Product
         $product = new Product();
         $product->name = array();
         $product->description = array();
         $product->description_short = array();
         $product->link_rewrite = array();
         foreach (Language::getLanguages(true) as $lang) {
             $product->name[$lang['id_lang']] = $value_prod;
             $product->description[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->description_short[$lang['id_lang']] = $this->l('Fashion axe kogi yuccie, ramps shabby chic direct trade before they sold out distillery bicycle rights. Slow-carb +1 quinoa VHS. +1 brunch trust fund, meggings chartreuse sustainable everyday carry tumblr hoodie tacos tilde ramps post-ironic fixie.');
             $product->link_rewrite[$lang['id_lang']] = Tools::link_rewrite('Super Delux Rooms');
         }
         $product->id_shop_default = Context::getContext()->shop->id;
         $product->id_category_default = 2;
         $product->price = 1000;
         $product->active = 1;
         $product->quantity = 99999999;
         $product->is_virtual = 1;
         $product->indexed = 1;
         $product->save();
         $product_id = $product->id;
         Search::indexation(Tools::link_rewrite($value_prod), $product_id);
         $product->addToCategories(2);
         StockAvailable::updateQuantity($product_id, null, 99999999);
         //image upload for products
         $count = 0;
         $have_cover = false;
         $old_path = _PS_MODULE_DIR_ . $this->name . '/views/img/prod_imgs/' . $img_num . '.png';
         $image_obj = new Image();
         $image_obj->id_product = $product_id;
         $image_obj->position = Image::getHighestPosition($product_id) + 1;
         if ($count == 0) {
             if (!$have_cover) {
                 $image_obj->cover = 1;
             }
         } else {
             $image_obj->cover = 0;
         }
         $image_obj->add();
         $new_path = $image_obj->getPathForCreation();
         $imagesTypes = ImageType::getImagesTypes('products');
         foreach ($imagesTypes as $image_type) {
             ImageManager::resize($old_path, $new_path . '-' . $image_type['name'] . '.jpg', $image_type['width'], $image_type['height']);
         }
         ImageManager::resize($old_path, $new_path . '.jpg');
         for ($k = 1; $k <= 5; $k++) {
             $htl_room_info_obj = new HotelRoomInformation();
             $htl_room_info_obj->id_product = $product_id;
             $htl_room_info_obj->id_hotel = $htl_id;
             $htl_room_info_obj->room_num = 'A' . $i . '-10' . $k;
             $htl_room_info_obj->id_status = 1;
             $htl_room_info_obj->floor = 'first';
             $htl_room_info_obj->save();
         }
         $htl_rm_type = new HotelRoomType();
         $htl_rm_type->id_product = $product_id;
         $htl_rm_type->id_hotel = $htl_id;
         $htl_rm_type->adult = 2;
         $htl_rm_type->children = 2;
         $htl_rm_type->save();
         $img_num++;
         // Add features to the product
         $ftr_arr = array(0 => 8, 1 => 9, 2 => 10, 3 => 11);
         $ftr_val_arr = array(0 => 34, 1 => 35, 2 => 36, 3 => 37);
         foreach ($ftr_arr as $key_htl_ftr => $val_htl_ftr) {
             $product->addFeaturesToDB($val_htl_ftr, $ftr_val_arr[$key_htl_ftr]);
         }
     }
     return true;
 }