/**
  * Add a custom feature to a product
  * @param int $id_product
  * @param int $id_feature
  * @param int $id_lang
  * @param array $values
  */
 public static function addCustomFeatureToProductId($id_product, $id_feature, $id_lang, $values)
 {
     if (empty($id_product) || empty($id_feature) || empty($id_lang) || empty($values)) {
         return false;
     }
     // Create the new custom feature
     $custom_feature_value = new FeatureValue();
     $custom_feature_value->id_feature = (int) $id_feature;
     $custom_feature_value->custom = (bool) true;
     $custom_feature_value->value = $values;
     $custom_feature_value->add();
     // Associate the new feature to product
     self::addFeatureToProduct($id_product, $id_feature, $custom_feature_value->id);
 }
 public function renderForm()
 {
     if (!$this->object->id) {
         $this->object->price = -1;
     }
     $this->fields_form = array('legend' => array('title' => $this->l('Catalog price rules'), 'icon' => 'icon-dollar'), 'input' => array(array('type' => 'text', 'label' => $this->l('Name'), 'name' => 'name', 'maxlength' => 32, 'required' => true, 'hint' => $this->l('Forbidden characters') . ' <>;=#{}'), array('type' => 'select', 'label' => $this->l('Shop'), 'name' => 'shop_id', 'options' => array('query' => Shop::getShops(), 'id' => 'id_shop', 'name' => 'name'), 'condition' => Shop::isFeatureActive(), 'default_value' => Shop::getContextShopID()), array('type' => 'select', 'label' => $this->l('Currency'), 'name' => 'id_currency', 'options' => array('query' => array_merge(array(0 => array('id_currency' => 0, 'name' => $this->l('All currencies'))), Currency::getCurrencies()), 'id' => 'id_currency', 'name' => 'name')), array('type' => 'select', 'label' => $this->l('Country'), 'name' => 'id_country', 'options' => array('query' => array_merge(array(0 => array('id_country' => 0, 'name' => $this->l('All countries'))), Country::getCountries((int) $this->context->language->id)), 'id' => 'id_country', 'name' => 'name')), array('type' => 'select', 'label' => $this->l('Group'), 'name' => 'id_group', 'options' => array('query' => array_merge(array(0 => array('id_group' => 0, 'name' => $this->l('All groups'))), Group::getGroups((int) $this->context->language->id)), 'id' => 'id_group', 'name' => 'name')), array('type' => 'text', 'label' => $this->l('From quantity'), 'name' => 'from_quantity', 'maxlength' => 10, 'required' => true), array('type' => 'text', 'label' => $this->l('Price (tax excl.)'), 'name' => 'price', 'disabled' => $this->object->price == -1 ? 1 : 0, 'maxlength' => 10, 'suffix' => $this->context->currency->getSign('right')), array('type' => 'checkbox', 'name' => 'leave_bprice', 'values' => array('query' => array(array('id' => 'on', 'name' => $this->l('Leave base price'), 'val' => '1', 'checked' => '1')), 'id' => 'id', 'name' => 'name')), array('type' => 'datetime', 'label' => $this->l('From'), 'name' => 'from'), array('type' => 'datetime', 'label' => $this->l('To'), 'name' => 'to'), array('type' => 'select', 'label' => $this->l('Reduction type'), 'name' => 'reduction_type', 'options' => array('query' => array(array('reduction_type' => 'amount', 'name' => $this->l('Amount')), array('reduction_type' => 'percentage', 'name' => $this->l('Percentage'))), 'id' => 'reduction_type', 'name' => 'name')), array('type' => 'select', 'label' => $this->l('Reduction with or without taxes'), 'name' => 'reduction_tax', 'align' => 'center', 'options' => array('query' => array(array('lab' => $this->l('Tax included'), 'val' => 1), array('lab' => $this->l('Tax excluded'), 'val' => 0)), 'id' => 'val', 'name' => 'lab')), array('type' => 'text', 'label' => $this->l('Reduction'), 'name' => 'reduction', 'required' => true)), 'submit' => array('title' => $this->l('Save')));
     if (($value = $this->getFieldValue($this->object, 'price')) != -1) {
         $price = number_format($value, 6);
     } else {
         $price = '';
     }
     $this->fields_value = array('price' => $price, 'from_quantity' => ($value = $this->getFieldValue($this->object, 'from_quantity')) ? $value : 1, 'reduction' => number_format(($value = $this->getFieldValue($this->object, 'reduction')) ? $value : 0, 6), 'leave_bprice_on' => $price ? 0 : 1);
     $attribute_groups = array();
     $attributes = Attribute::getAttributes((int) $this->context->language->id);
     foreach ($attributes as $attribute) {
         if (!isset($attribute_groups[$attribute['id_attribute_group']])) {
             $attribute_groups[$attribute['id_attribute_group']] = array('id_attribute_group' => $attribute['id_attribute_group'], 'name' => $attribute['attribute_group']);
         }
         $attribute_groups[$attribute['id_attribute_group']]['attributes'][] = array('id_attribute' => $attribute['id_attribute'], 'name' => $attribute['name']);
     }
     $features = Feature::getFeatures((int) $this->context->language->id);
     foreach ($features as &$feature) {
         $feature['values'] = FeatureValue::getFeatureValuesWithLang((int) $this->context->language->id, $feature['id_feature'], true);
     }
     $this->tpl_form_vars = array('manufacturers' => Manufacturer::getManufacturers(), 'suppliers' => Supplier::getSuppliers(), 'attributes_group' => $attribute_groups, 'features' => $features, 'categories' => Category::getSimpleCategories((int) $this->context->language->id), 'conditions' => $this->object->getConditions(), 'is_multishop' => Shop::isFeatureActive());
     return parent::renderForm();
 }
 /**
  * @param bool $autodate
  * @param bool $nullValues
  * @return bool
  */
 public function add($autodate = true, $nullValues = false)
 {
     if ($this->position <= 0) {
         $this->position = FeatureValue::getHigherPosition($this->id_feature) + 1;
     }
     return parent::add($autodate, $nullValues);
 }
 public function add($autodate = true, $null_values = false)
 {
     if ($this->position <= 0) {
         $this->position = FeatureValue::getHigherPosition($this->id_feature) + 1;
     }
     $return = parent::add($autodate, $null_values);
     if ($return) {
         Hook::exec('actionFeatureValueSave', array('id_feature_value' => $this->id));
     }
     return $return;
 }
    public function initFormFeatures($obj)
    {
        if (!$this->default_form_language) {
            $this->getLanguages();
        }
        $tpl_path = _PS_MODULE_DIR_ . 'advancedfeaturesvalues/views/templates/admin/products/features.tpl';
        $data = $this->context->smarty->createTemplate($tpl_path, $this->context->smarty);
        $data->assign('default_form_language', $this->default_form_language);
        $data->assign('languages', $this->_languages);
        if (!Feature::isFeatureActive()) {
            $this->displayWarning($this->l('This feature has been disabled. ') . '
				<a href="index.php?tab=AdminPerformance&token=' . Tools::getAdminTokenLite('AdminPerformance') . '#featuresDetachables">' . $this->l('Performances') . '</a>');
        } else {
            if ($obj->id) {
                if ($this->product_exists_in_shop) {
                    $features = Feature::getFeatures($this->context->language->id, Shop::isFeatureActive() && Shop::getContext() == Shop::CONTEXT_SHOP);
                    foreach ($features as $k => $tab_features) {
                        $features[$k]['current_item'] = array();
                        $features[$k]['val'] = array();
                        $custom = true;
                        foreach ($obj->getFeatures() as $tab_products) {
                            if ($tab_products['id_feature'] == $tab_features['id_feature']) {
                                $features[$k]['current_item'][] = $tab_products['id_feature_value'];
                            }
                        }
                        $features[$k]['featureValues'] = FeatureValue::getFeatureValuesWithLang($this->context->language->id, (int) $tab_features['id_feature']);
                        if (count($features[$k]['featureValues'])) {
                            foreach ($features[$k]['featureValues'] as $value) {
                                if (in_array($value['id_feature_value'], $features[$k]['current_item'])) {
                                    $custom = false;
                                }
                            }
                        }
                        if ($custom && !empty($features[$k]['current_item'])) {
                            $features[$k]['val'] = FeatureValue::getFeatureValueLang($features[$k]['current_item'][0]);
                        }
                    }
                    $data->assign('available_features', $features);
                    $data->assign('product', $obj);
                    $data->assign('link', $this->context->link);
                    $data->assign('default_form_language', $this->default_form_language);
                } else {
                    $this->displayWarning($this->l('You must save the product in this shop before adding features.'));
                }
            } else {
                $this->displayWarning($this->l('You must save this product before adding features.'));
            }
        }
        $this->tpl_form_vars['custom_form'] = $data->fetch();
    }
 public function addFeature($id_product, $feature_name, $feature_value)
 {
     if (empty($feature_value)) {
         return;
     }
     $id_feature = Feature::addFeatureImport($feature_name);
     $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $feature_value);
     Product::addFeatureProductImport($id_product, $id_feature, $id_feature_value);
 }
Example #7
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 #8
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = $line['count'];
        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 70);
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        $available->id_shop = Context::getContext()->shop->id;
        $available->quantity = $line['count'];
        $available->save();

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }
    }
 private function initContentForFeatures()
 {
     $tlwvvxr = "features";
     ${"GLOBALS"}["pihske"] = "features";
     $jxbahojyvlt = "available_features_all";
     $fotyrrre = "available_features_all";
     $lueyeppw = "features";
     ${"GLOBALS"}["iavdbtipeie"] = "tab_features";
     ${$lueyeppw} = Feature::getFeatures($this->id_language);
     foreach (${$tlwvvxr} as ${${"GLOBALS"}["qtxqhylrbsm"]} => ${${"GLOBALS"}["iavdbtipeie"]}) {
         ${"GLOBALS"}["ringgeomwho"] = "tab_products";
         $oovownr = "k";
         $dibecrefieyf = "k";
         ${"GLOBALS"}["llnriurbfb"] = "features";
         ${"GLOBALS"}["krrouj"] = "k";
         ${"GLOBALS"}["ezrxbtdf"] = "features";
         ${${"GLOBALS"}["nrjxzlhiqjg"]}[${${"GLOBALS"}["krrouj"]}]["current_item"] = false;
         ${${"GLOBALS"}["nrjxzlhiqjg"]}[${$dibecrefieyf}]["val"] = array();
         ${${"GLOBALS"}["vwmhyvovziq"]} = true;
         foreach ($this->object->getFeatures() as ${${"GLOBALS"}["ringgeomwho"]}) {
             $hozllwqodl = "features";
             $koyfxiz = "k";
             ${"GLOBALS"}["hkqtkv"] = "tab_products";
             ${"GLOBALS"}["icrwrssx"] = "tab_products";
             $wbqcupctp = "tab_features";
             if (${${"GLOBALS"}["hkqtkv"]}["id_feature"] == ${$wbqcupctp}["id_feature"]) {
                 ${$hozllwqodl}[${$koyfxiz}]["current_item"] = ${${"GLOBALS"}["icrwrssx"]}["id_feature_value"];
             }
         }
         ${${"GLOBALS"}["nrjxzlhiqjg"]}[${${"GLOBALS"}["qtxqhylrbsm"]}]["featureValues"] = FeatureValue::getFeatureValuesWithLang($this->id_language, (int) ${${"GLOBALS"}["kowgsfpm"]}["id_feature"]);
         if (count(${${"GLOBALS"}["nrjxzlhiqjg"]}[${$oovownr}]["featureValues"])) {
             $gtmlwoq = "features";
             $ryjttmtpvt = "k";
             foreach (${$gtmlwoq}[${$ryjttmtpvt}]["featureValues"] as ${${"GLOBALS"}["kzwkbwmzgtl"]}) {
                 $rtsfkxsq = "features";
                 $tduybwwrxb = "value";
                 if (${$rtsfkxsq}[${${"GLOBALS"}["qtxqhylrbsm"]}]["current_item"] == ${$tduybwwrxb}["id_feature_value"]) {
                     ${${"GLOBALS"}["vwmhyvovziq"]} = false;
                 }
             }
         }
         if (${${"GLOBALS"}["vwmhyvovziq"]}) {
             ${${"GLOBALS"}["llnriurbfb"]}[${${"GLOBALS"}["qtxqhylrbsm"]}]["val"] = FeatureValue::getFeatureValueLang(${${"GLOBALS"}["ezrxbtdf"]}[${${"GLOBALS"}["qtxqhylrbsm"]}]["current_item"]);
         }
     }
     ${$jxbahojyvlt} = "";
     foreach (${${"GLOBALS"}["nrjxzlhiqjg"]} as ${${"GLOBALS"}["jtsfpdcbh"]}) {
         ${"GLOBALS"}["tpyuivnp"] = "available_features_all";
         ${${"GLOBALS"}["mogxjutudv"]} = ${${"GLOBALS"}["tpyuivnp"]} . "custom_" . ${${"GLOBALS"}["jtsfpdcbh"]}["id_feature"] . "&curren;";
     }
     self::$smarty->assign(array("available_features_all" => ${$fotyrrre}, "available_features" => ${${"GLOBALS"}["pihske"]}));
 }
Example #10
0
    public static function addFeatureValueImport($id_feature, $name)
    {
        $rq = Db::getInstance()->executeS('
			SELECT fv.`id_feature_value`
			FROM ' . _DB_PREFIX_ . 'feature_value fv
			LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl
				ON (fvl.`id_feature_value` = fv.`id_feature_value`)
			WHERE `value` = \'' . pSQL($name) . '\'
				AND fv.`id_feature` = ' . (int) $id_feature . '
				AND fv.`custom` = 1
			GROUP BY fv.`id_feature_value` LIMIT 1
		');
        if (!isset($rq[0]['id_feature_value']) || !($id_feature_value = (int) $rq[0]['id_feature_value'])) {
            // Feature doesn't exist, create it
            $feature_value = new FeatureValue();
            $languages = Language::getLanguages();
            foreach ($languages as $language) {
                $feature_value->value[$language['id_lang']] = strval($name);
            }
            $feature_value->id_feature = (int) $id_feature;
            $feature_value->custom = 1;
            $feature_value->add();
            return (int) $feature_value->id;
        }
        return (int) $id_feature_value;
    }
Example #11
0
 function getFeatures($prod_id)
 {
     $features = Product::getFeaturesStatic((int) $prod_id);
     $params = array();
     foreach ($features as $feature) {
         $feature_name = Feature::getFeature($this->id_lang, $feature['id_feature']);
         $feature_name = $feature_name['name'];
         $feature_values = FeatureValue::getFeatureValueLang($feature['id_feature_value']);
         $feature_value = null;
         foreach ($feature_values as $f_value) {
             $feature_value = $f_value['value'];
             if ($f_value['id_lang'] == $this->id_lang) {
                 break;
             }
         }
         if ($feature_value != null) {
             $params[$feature_name] = $feature_value;
         }
     }
     return $params;
 }
    function displayFormFeatures($obj)
    {
        global $cookie, $currentIndex;
        parent::displayForm();
        if ($obj->id) {
            $feature = Feature::getFeatures((int) $cookie->id_lang);
            $ctab = '';
            foreach ($feature as $tab) {
                $ctab .= 'ccustom_' . $tab['id_feature'] . '¤';
            }
            $ctab = rtrim($ctab, '¤');
            echo '
			<table cellpadding="5">
				<tr>
					<td colspan="2">
						<b>' . $this->l('Assign features to this product:') . '</b><br />
						<ul style="margin: 10px 0 0 20px;">
							<li>' . $this->l('You can specify a value for each relevant feature regarding this product, empty fields will not be displayed.') . '</li>
							<li>' . $this->l('You can either set a specific value, or select among existing pre-defined values you added previously.') . '</li>
						</ul>
					</td>
				</tr>
			</table>
			<hr style="width:100%;" /><br />';
            // Header
            $nb_feature = Feature::nbFeatures((int) $cookie->id_lang);
            echo '
			<table border="0" cellpadding="0" cellspacing="0" class="table" style="width:900px;">
				<tr>
					<th>' . $this->l('Feature') . '</td>
					<th style="width:30%">' . $this->l('Pre-defined value') . '</td>
					<th style="width:40%"><u>' . $this->l('or') . '</u> ' . $this->l('Customized value') . '</td>
				</tr>';
            if (!$nb_feature) {
                echo '<tr><td colspan="3" style="text-align:center;">' . $this->l('No features defined') . '</td></tr>';
            }
            echo '</table>';
            // Listing
            if ($nb_feature) {
                echo '
				<table cellpadding="5" style="width: 900px; margin-top: 10px">';
                foreach ($feature as $tab_features) {
                    $current_item = false;
                    $custom = true;
                    foreach ($obj->getFeatures() as $tab_products) {
                        if ($tab_products['id_feature'] == $tab_features['id_feature']) {
                            $current_item = $tab_products['id_feature_value'];
                        }
                    }
                    $featureValues = FeatureValue::getFeatureValuesWithLang((int) $cookie->id_lang, (int) $tab_features['id_feature']);
                    echo '
					<tr>
						<td>' . $tab_features['name'] . '</td>
						<td style="width: 30%">';
                    if (sizeof($featureValues)) {
                        echo '
							<select id="feature_' . $tab_features['id_feature'] . '_value" name="feature_' . $tab_features['id_feature'] . '_value"
								onchange="$(\'.custom_' . $tab_features['id_feature'] . '_\').val(\'\');">
								<option value="0">---&nbsp;</option>';
                        foreach ($featureValues as $value) {
                            if ($current_item == $value['id_feature_value']) {
                                $custom = false;
                            }
                            echo '<option value="' . $value['id_feature_value'] . '"' . ($current_item == $value['id_feature_value'] ? ' selected="selected"' : '') . '>' . substr($value['value'], 0, 40) . (Tools::strlen($value['value']) > 40 ? '...' : '') . '&nbsp;</option>';
                        }
                        echo '</select>';
                    } else {
                        echo '<input type="hidden" name="feature_' . $tab_features['id_feature'] . '_value" value="0" /><span style="font-size: 10px; color: #666;">' . $this->l('N/A') . ' - <a href="index.php?tab=AdminFeatures&addfeature_value&id_feature=' . (int) $tab_features['id_feature'] . '&token=' . Tools::getAdminToken('AdminFeatures' . (int) Tab::getIdFromClassName('AdminFeatures') . (int) $cookie->id_employee) . '" style="color: #666; text-decoration: underline;">' . $this->l('Add pre-defined values first') . '</a></span>';
                    }
                    echo '
						</td>
						<td style="width:40%" class="translatable">';
                    $tab_customs = $custom ? FeatureValue::getFeatureValueLang($current_item) : array();
                    foreach ($this->_languages as $language) {
                        echo '
							<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
								<textarea class="custom_' . $tab_features['id_feature'] . '_" name="custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'] . '" cols="40" rows="1"
									onkeyup="if (isArrowKey(event)) return ;$(\'#feature_' . $tab_features['id_feature'] . '_value\').val(0);" >' . htmlentities(Tools::getValue('custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'], FeatureValue::selectLang($tab_customs, $language['id_lang'])), ENT_COMPAT, 'UTF-8') . '</textarea>
							</div>';
                    }
                    echo '
						</td>
					</tr>';
                }
                echo '
				<tr>
					<td style="height: 50px; text-align: center;" colspan="3"><input type="submit" name="submitProductFeature" id="submitProductFeature" value="' . $this->l('Save modifications') . '" class="button" /></td>
				</tr>';
            }
            echo '</table>
			<hr style="width:100%;" />
			<div style="text-align:center;">
				<a href="index.php?tab=AdminFeatures&addfeature&token=' . Tools::getAdminToken('AdminFeatures' . (int) Tab::getIdFromClassName('AdminFeatures') . (int) $cookie->id_employee) . '" onclick="return confirm(\'' . $this->l('You will lose all modifications not saved, you may want to save modifications first?', __CLASS__, true, false) . '\');"><img src="../img/admin/add.gif" alt="new_features" title="' . $this->l('Add a new feature') . '" />&nbsp;' . $this->l('Add a new feature') . '</a>
			</div>';
        } else {
            echo '<b>' . $this->l('You must save this product before adding features') . '.</b>';
        }
    }
Example #13
0
    protected function productImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, $shop_ids, $match_ref, &$accessories, $validateOnly = false)
    {
        if ($force_ids && isset($info['id']) && (int) $info['id']) {
            $product = new Product((int) $info['id']);
        } elseif ($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']) . '"
				', false);
            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();
        }
        $update_advanced_stock_management_value = false;
        if (isset($product->id) && $product->id && Product::existsInDatabase((int) $product->id, 'product')) {
            $product->loadStockData();
            $update_advanced_stock_management_value = true;
            $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);
        if (!$shop_is_feature_active) {
            $product->shop = (int) Configuration::get('PS_SHOP_DEFAULT');
        } elseif (!isset($product->shop) || empty($product->shop)) {
            $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
        }
        if (!$shop_is_feature_active) {
            $product->id_shop_default = (int) Configuration::get('PS_SHOP_DEFAULT');
        } 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, $this->trans('Unknown tax rule group ID. You need to create a group with this ID first.', array(), 'Admin.Parameters.Notification'));
            }
        }
        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;
                $manufacturer->active = true;
                if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $manufacturer->add()) {
                    $product->id_manufacturer = (int) $manufacturer->id;
                    $manufacturer->associateTo($product->id_shop_list);
                } else {
                    if (!$validateOnly) {
                        $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null');
                    }
                    if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                        $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 && !$validateOnly && $supplier->add()) {
                    $product->id_supplier = (int) $supplier->id;
                    $supplier->associateTo($product->id_shop_list);
                } else {
                    if (!$validateOnly) {
                        $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null');
                    }
                    if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                        $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 && !$validateOnly && $category_to_create->add()) {
                            $product->id_category[] = (int) $category_to_create->id;
                        } else {
                            if (!$validateOnly) {
                                $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                            }
                            if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    }
                } elseif (!$validateOnly && 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($this->trans('%1$s cannot be saved', array(), 'Admin.Parameters.Notification'), trim($value));
                    }
                }
            }
            $product->id_category = array_values(array_unique($product->id_category));
            // Will update default category if category column is not ignored AND if there is categories that are set in the import file row.
            if (isset($product->id_category[0])) {
                $product->id_category_default = (int) $product->id_category[0];
            } else {
                $defaultProductShop = new Shop($product->id_shop_default);
                $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id;
            }
        }
        // Will update default category if there is none set here. Home if no category at all.
        if (!isset($product->id_category_default) || !$product->id_category_default) {
            // this if will avoid ereasing default category if category column is not present in the CSV file (or ignored)
            if (isset($product->id_category[0])) {
                $product->id_category_default = (int) $product->id_category[0];
            } else {
                $defaultProductShop = new Shop($product->id_shop_default);
                $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id;
            }
        }
        $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->informations[] = sprintf($this->trans('Rewrite link for %1$s (ID %2$s): re-written as %3$s.', array(), 'Admin.Parameters.Notification'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite);
        }
        if (!$valid_link || !($match_ref || $force_ids) || !(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;
        $productExistsInDatabase = false;
        if ($product->id && Product::existsInDatabase((int) $product->id, 'product')) {
            $productExistsInDatabase = true;
        }
        if ($match_ref && $product->reference && $product->existsRefInDatabase($product->reference) || $productExistsInDatabase) {
            $product->date_upd = date('Y-m-d H:i:s');
        }
        $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 ($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) . '"
				', false);
                $product->id = (int) $datas['id_product'];
                $product->date_add = pSQL($datas['date_add']);
                $res = $validateOnly || $product->update();
            } elseif ($productExistsInDatabase) {
                $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, false);
                $product->date_add = pSQL($datas['date_add']);
                $res = $validateOnly || $product->update();
            }
            // If no id_product or update failed
            $product->force_id = (bool) $force_ids;
            if (!$res) {
                if (isset($product->date_add) && $product->date_add != '') {
                    $res = $validateOnly || $product->add(false);
                } else {
                    $res = $validateOnly || $product->add();
                }
            }
            if (!$validateOnly) {
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    StockAvailable::setProductOutOfStock((int) $product->id, 1);
                } else {
                    StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock);
                }
                if ($product_download_id = ProductDownload::getIdFromIdProduct((int) $product->id)) {
                    $product_download = new ProductDownload($product_download_id);
                    $product_download->delete(true);
                }
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    $product_download = new ProductDownload();
                    $product_download->filename = ProductDownload::getNewFilename();
                    Tools::copy($info['file_url'], _PS_DOWNLOAD_DIR_ . $product_download->filename);
                    $product_download->id_product = (int) $product->id;
                    $product_download->nb_downloadable = (int) $info['nb_downloadable'];
                    $product_download->date_expiration = $info['date_expiration'];
                    $product_download->nb_days_accessible = (int) $info['nb_days_accessible'];
                    $product_download->display_filename = basename($info['file_url']);
                    $product_download->add();
                }
            }
        }
        $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($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), 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 (!$validateOnly && 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_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();
            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 (!$validateOnly && !$specific_price->save()) {
                        $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                    }
                }
            }
            if (!$validateOnly && 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 (!$validateOnly && isset($product->delete_existing_images)) {
                if ((bool) $product->delete_existing_images) {
                    $product->deleteImages();
                }
            }
            if (!$validateOnly && 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;
                        $alt = $product->image_alt[$key];
                        if (strlen($alt) > 0) {
                            $image->legend = self::createMultiLangField($alt);
                        }
                        // 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', !$regenerate)) {
                                $image->delete();
                                $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url);
                            }
                        } else {
                            $error = true;
                        }
                    } else {
                        $error = true;
                    }
                    if ($error) {
                        $this->warnings[] = sprintf($this->trans('Product #%1$d: the picture (%2$s) cannot be saved.', array(), 'Admin.Parameters.Notification'), $image->id_product, $url);
                    }
                }
            }
            if (!$validateOnly && isset($product->id_category) && is_array($product->id_category)) {
                $product->updateCategories(array_map('intval', $product->id_category));
            }
            $product->checkDefaultAttributes();
            if (!$validateOnly && !$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            // Features import
            $features = get_object_vars($product);
            if (!$validateOnly && 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 ($force_ids || $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 (!$validateOnly && isset($product->advanced_stock_management)) {
                if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif ($update_advanced_stock_management_value) {
                    $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($this->trans('Advanced stock management is not enabled, warehouse not set on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif (!$validateOnly) {
                    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($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $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($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->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_id]);
                } elseif (!$validateOnly) {
                    StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                }
                // This code allows us to set qty and disable depends on stock
                if (!$validateOnly && 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_is_feature_active) {
                            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);
                        }
                    }
                }
            } elseif (!$validateOnly) {
                // if not depends_on_stock set, use normal qty
                if ($shop_is_feature_active) {
                    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);
                }
            }
            // Accessories linkage
            if (isset($product->accessories) && !$validateOnly && is_array($product->accessories) && count($product->accessories)) {
                $accessories[$product->id] = $product->accessories;
            }
        }
    }
    /**
     * Call the right method for creating or updating object
     *
     * @return mixed
     */
    public function processSave()
    {
        if ($this->table == 'feature') {
            $id_feature = (int) Tools::getValue('id_feature');
            // Adding last position to the feature if not exist
            if ($id_feature <= 0) {
                $sql = 'SELECT `position`+1
						FROM `' . _DB_PREFIX_ . 'feature`
						ORDER BY position DESC';
                // set the position of the new feature in $_POST for postProcess() method
                $_POST['position'] = DB::getInstance()->getValue($sql);
            }
            // clean \n\r characters
            foreach ($_POST as $key => $value) {
                if (preg_match('/^name_/Ui', $key)) {
                    $_POST[$key] = str_replace('\\n', '', str_replace('\\r', '', $value));
                }
            }
            //by webkul to save image of feature with feature name
            $obj_feature = parent::processSave();
            $feature_values = FeatureValue::getFeatureValuesWithLang(1, $obj_feature->id);
            if ($feature_values) {
                $obj_feature_value = new FeatureValue($feature_values[0]['id_feature_value']);
            } else {
                $obj_feature_value = new FeatureValue();
            }
            //validate feature image
            if (isset($_FILES['logo'])) {
                $this->validAddFeatureImage($_FILES['logo']);
            }
            $img_path = _PS_IMG_DIR_ . 'rf/' . $obj_feature->id . '.png';
            if (isset($_FILES['logo'])) {
                $current_file = _PS_TMP_IMG_DIR_ . 'feature_mini_' . $obj_feature->id . '_' . $this->context->shop->id . '.png';
                if (file_exists($current_file)) {
                    unlink($current_file);
                }
                $this->uploadFeatureImage($_FILES['logo'], $img_path);
            }
            $obj_feature_value->id_feature = $obj_feature->id;
            foreach (Language::getLanguages(true) as $lang) {
                $obj_feature_value->value[$lang['id_lang']] = $obj_feature->id . '.png';
            }
            $obj_feature_value->save();
        }
        return $obj_feature;
    }
Example #15
0
    private function upsert($line) {
        $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
        $product = new Product($product);

        $product->reference = $line['reference'];
        $product->name = array(
            '1' => $line['name'],
            '2' => $line['name'],
            '3' => $line['name']
        );
        $product->description = array(
            '1' => $line['description'],
            '2' => $line['description'],
            '3' => $line['description']
        );
        $product->description_short = array(
            '1' => $line['description_short'],
            '2' => $line['description_short'],
            '3' => $line['description_short']
        );
        $product->link_rewrite = array(
            '1' => Tools::link_rewrite($line['name']),
            '2' => Tools::link_rewrite($line['name']),
            '3' => Tools::link_rewrite($line['name'])
        );
        $product->available_now = array(
            '1' => "Есть в наличии",
            '2' => "Есть в наличии",
            '3' => "Есть в наличии"
        );
        $product->id_category_default = $line['category'];
        $product->quantity = (int)$line['count'];

        $product->advanced_stock_management = 1; //использовать Advanced Stock management
        $product->depends_on_stock = 1; //1 - доступное количество на основе ASM. 0 - указывается вручную
        $product->out_of_stock = 1; //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)

        $product->price = $line['price'];
        $product->weight = $line['weight'] / 1000;
        $product->id_tax_rules_group = $line['id_tax'];

        $product->save();

        $product->updateCategories(array($line['category']));

        $product->deleteFeatures();
        if ($line['author']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 9, $id_feature_value);
        }

        if ($line['year']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
            Product::addFeatureProductImport($product->id, 10, $id_feature_value);
        }

        if ($line['paperback']) {
            Product::addFeatureProductImport($product->id, 11, 1); //1 - id значения "переплёт" у харакатеристики "Переплёт"
        }

        if ($line['pages']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 12, $id_feature_value);
        }

        /*
        if ($line['weight']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 4, $id_feature_value);
        }
        */

        if ($line['isbn']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 13, $id_feature_value);
        }

        if ($line['publishing']) {
            $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
            Product::addFeatureProductImport($product->id, 14, $id_feature_value);
        }

        $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
        $location = new WarehouseProductLocation($location);
        $location->id_product = $product->id;
        $location->id_product_attribute = 0;
        $location->id_warehouse = $line['warehouse'];
        $location->save();

        $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
        $stock = new Stock($stock);
        $stock->id_product = $product->id;
        $stock->id_product_attribute = 0;
        $stock->id_warehouse = $line['warehouse'];
        $stock->physical_quantity = $line['count'];
        $stock->usable_quantity = $line['count'];
        $stock->price_te = 0;
        $stock->save();

        $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
        $available = new StockAvailable($available);
        $available->id_product = $product->id;
        $available->id_product_attribute = 0;
        //$available->id_shop = Context::getContext()->shop->id;
        $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
        $available->save();

        StockAvailable::setProductDependsOnStock($product->id, true, null);
        StockAvailable::setProductOutOfStock($product->id, 1, null); //allow

        while(strlen($line['reference']) < 9) {
            $line['reference'] = '0' . $line['reference'];
        }

        if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
            $product->deleteImages();

            $image = new Image();
            $image->id_product = $product->id;
            $image->cover = 1;
            $image->position = 0;
            $image->save();

            $name = $image->getPathForCreation();

            copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name.'.'.$image->image_format);

            $types = ImageType::getImagesTypes('products');
            foreach ($types as $type) {
                ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
            }
        }

        /*
        Db::getInstance()->update('stock_available', array(
           'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
            'out_of_stock' => (int)1, //1-allow
        ), 'id_product='.$product->id.'');
         $affrows = Db::getInstance()->Affected_Rows();
         var_dump($affrows);
         */

        //var_dump($product->reference);
        //echo "<br/><br/><br/><br/>";
    }
Example #16
0
<?php

if (Tools::G('id_feature') > 0) {
    $id_feature = Tools::G('id_feature');
}
if (Tools::P('saveFeatureValue') == 'add' && Tools::P('id_feature') > 0) {
    $featureV = new FeatureValue();
    $featureV->copyFromPost();
    $featureV->add();
    if (is_array($featureV->_errors) and count($featureV->_errors) > 0) {
        $errors = $featureV->_errors;
    } else {
        $_GET['id'] = $featureV->id;
        UIAdminAlerts::conf('商品特征值已添加');
    }
    $id_feature = Tools::P('id_feature');
}
if (isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $obj = new FeatureValue($id);
    $id_feature = $obj->id_feature;
}
if (Tools::P('saveFeatureValue') == 'edit') {
    if (Validate::isLoadedObject($obj)) {
        $obj->copyFromPost();
        $obj->update();
    }
    if (is_array($obj->_errors) and count($obj->_errors) > 0) {
        $errors = $obj->_errors;
    } else {
        UIAdminAlerts::conf('商品特征值已更新');
 public function initFormFeatures($obj)
 {
     $data = $this->createTemplate($this->tpl_form);
     if (!Feature::isFeatureActive()) {
         $this->displayWarning($this->l('This feature has been disabled, you can active this feature at this page:') . ' <a href="index.php?tab=AdminPerformance&token=' . Tools::getAdminTokenLite('AdminPerformance') . '#featuresDetachables">' . $this->l('Performances') . '</a>');
     } else {
         if ($obj->id) {
             if ($this->product_exists_in_shop) {
                 $features = Feature::getFeatures($this->context->language->id);
                 foreach ($features as $k => $tab_features) {
                     $features[$k]['current_item'] = false;
                     $features[$k]['val'] = array();
                     $custom = true;
                     foreach ($obj->getFeatures() as $tab_products) {
                         if ($tab_products['id_feature'] == $tab_features['id_feature']) {
                             $features[$k]['current_item'] = $tab_products['id_feature_value'];
                         }
                     }
                     $features[$k]['featureValues'] = FeatureValue::getFeatureValuesWithLang($this->context->language->id, (int) $tab_features['id_feature']);
                     if (count($features[$k]['featureValues'])) {
                         foreach ($features[$k]['featureValues'] as $value) {
                             if ($features[$k]['current_item'] == $value['id_feature_value']) {
                                 $custom = false;
                             }
                         }
                     }
                     if ($custom) {
                         $features[$k]['val'] = FeatureValue::getFeatureValueLang($features[$k]['current_item']);
                     }
                 }
                 $data->assign('available_features', $features);
                 $data->assign('product', $obj);
                 $data->assign('link', $this->context->link);
                 $data->assign('languages', $this->_languages);
                 $data->assign('default_form_language', $this->default_form_language);
             } else {
                 $this->displayWarning($this->l('You must save this product in this shop before adding features.'));
             }
         } else {
             $this->displayWarning($this->l('You must save this product before adding features.'));
         }
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
Example #18
0
<?php

if (Tools::G('delete') > 0) {
    $feature = new FeatureValue(Tools::G('delete'));
    if (Validate::isLoadedObject($feature)) {
        $feature->delete();
    }
    if (is_array($feature->_errors) and count($feature->_errors) > 0) {
        $errors = $feature->_errors;
    } else {
        UIAdminAlerts::conf('商品特征值已删除');
    }
} elseif (Tools::isSubmit('delSelected')) {
    $select_cat = Tools::P('itemsBox');
    $feature = new FeatureValue();
    if ($feature->deleteMulti($select_cat)) {
        UIAdminAlerts::conf('商品特征值已删除');
    }
}
/** 输出错误信息 */
if (isset($errors)) {
    UIAdminAlerts::MError($errors);
}
/** 导航 */
$breadcrumb = new UIAdminBreadcrumb();
$breadcrumb->home();
$breadcrumb->add(array('title' => '商品特征', 'href' => 'index.php?rule=feature'));
$breadcrumb->add(array('title' => '商品特征值', 'active' => true));
$bread = $breadcrumb->draw();
$btn_group = array(array('type' => 'a', 'title' => '返回', 'href' => 'index.php?rule=feature', 'class' => 'btn-primary', 'icon' => 'level-up'), array('type' => 'a', 'title' => '新商品属性值', 'href' => 'index.php?rule=feature_value_edit&id_feature=' . Tools::G('id'), 'class' => 'btn-success', 'icon' => 'plus'));
echo UIViewBlock::area(array('bread' => $bread, 'btn_groups' => $btn_group), 'breadcrumb');
Example #19
0
 private function upsert($line)
 {
     $product = DB::getInstance()->getValue("SELECT `id_product` FROM `" . _DB_PREFIX_ . "product` WHERE `reference` LIKE '{$line['reference']}'");
     $product = new Product($product);
     $product->reference = $line['reference'];
     $product->name = array('1' => $line['name'], '2' => $line['name'], '3' => $line['name']);
     $product->description = array('1' => $line['description'], '2' => $line['description'], '3' => $line['description']);
     $product->description_short = array('1' => $line['description_short'], '2' => $line['description_short'], '3' => $line['description_short']);
     $product->link_rewrite = array('1' => Tools::link_rewrite($line['name']), '2' => Tools::link_rewrite($line['name']), '3' => Tools::link_rewrite($line['name']));
     $product->available_now = array('1' => "Есть в наличии", '2' => "Есть в наличии", '3' => "Есть в наличии");
     $product->id_category_default = $line['category'];
     $product->quantity = (int) $line['count'];
     $product->advanced_stock_management = 1;
     //использовать Advanced Stock management
     $product->depends_on_stock = 1;
     //1 - доступное количество на основе ASM. 0 - указывается вручную
     $product->out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (Как в Preferences - не дает заказать товар на сайте)
     $product->price = $line['price'];
     $product->weight = $line['weight'] / 1000;
     $product->id_tax_rules_group = $line['id_tax'];
     $product->save();
     $product->updateCategories(array($line['category']));
     $product->deleteFeatures();
     if ($line['author']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(9, $line['author'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 9, $id_feature_value);
     }
     if ($line['year']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(10, $line['year'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 10, $id_feature_value);
     }
     if ($line['paperback']) {
         if ($line['paperback'] == 1) {
             $id_feature_value = 1;
         } else {
             $id_feature_value = 2;
         }
         //$id_feature_value = FeatureValue::addFeatureValueImport(11, $line['paperback'], null, Configuration::get('PS_LANG_DEFAULT'));
         Product::addFeatureProductImport($product->id, 11, $id_feature_value);
         //1 - id значения "твёрдый переплёт" у харакатеристики "Переплёт", 149226 - мягкая обложка
     }
     if ($line['pages']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(12, $line['pages'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 12, $id_feature_value);
     }
     /*
     if ($line['weight']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(4, $line['weight'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 4, $id_feature_value);
     }
     */
     if ($line['isbn']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(13, $line['isbn'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 13, $id_feature_value);
     }
     if ($line['publishing']) {
         $id_feature_value = FeatureValue::addFeatureValueImport(14, $line['publishing'], null, Configuration::get('PS_LANG_DEFAULT'), true);
         Product::addFeatureProductImport($product->id, 14, $id_feature_value);
     }
     $location = WarehouseProductLocation::getIdByProductAndWarehouse($product->id, 0, $line['warehouse']);
     $location = new WarehouseProductLocation($location);
     $location->id_product = $product->id;
     $location->id_product_attribute = 0;
     $location->id_warehouse = $line['warehouse'];
     $location->save();
     /*
     $stock = DB::getInstance()->getValue("SELECT `id_stock` FROM `" . _DB_PREFIX_ . "stock` WHERE `id_product` = {$product->id} AND `id_warehouse` = {$line['warehouse']}");
     $stock = new Stock($stock);
     $stock->id_product = $product->id;
     $stock->id_product_attribute = 0;
     $stock->id_warehouse = $line['warehouse'];
     $stock->physical_quantity = $line['count'];
     $stock->usable_quantity = $line['count'];
     $stock->price_te = 0;
     $stock->save();
     */
     //установить зависимость количества товара от остатка на складе для каждого магазинеа
     //исходим из того, что в настройках Мультимагазина остаток НЕ единый на все магазины
     $id_product = $product->id;
     $depends_on_stock = true;
     $out_of_stock = 1;
     //2 - как в Preferences product. 1 - allow (ставь 1, т.к. 2 (как в Preferences) не дает заказать товар на сайте)
     for ($id_shop = 1; $id_shop <= 4; $id_shop++) {
         StockAvailable::setProductDependsOnStock($id_product, $depends_on_stock, $id_shop);
     }
     //разрешить или запретить продажу товара без остатка
     /*  для магазина 2,3 запретить продажу, если нет в наличии. out_of_stock = 0
             2   Second shop Gelikon 
             3   First shop Gelikon
         */
     $out_of_stock = 0;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 2);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 3);
     /*
         Для online и заказов по телефону разрешить заказ товара, которого нет в наличии
         1 Gelikon DE online
         4 Заказы по телефону
     */
     $out_of_stock = 1;
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 1);
     StockAvailable::setProductOutOfStock($id_product, $out_of_stock, 4);
     //Добавить партию товара на склад с записью в журнал движения товаров
     $id_product = $product->id;
     $id_product_attribute = 0;
     $id_stock_mvt_reason = 1;
     $price = 1;
     $id_currency = 1;
     $id_warehouse = $line['warehouse'];
     $warehouse = new Warehouse($id_warehouse);
     $stock_manager = StockManagerFactory::getManager();
     if ($line['count'] != 0) {
         //echo "добавляем товар ";
         $is_usable = true;
         $quantity = $line['count'];
         // add stock
         if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $is_usable)) {
             StockAvailable::synchronize($id_product);
         } else {
             $errors[] = Tools::displayError('An error occurred. No stock was added.');
         }
     }
     /*
             $available = DB::getInstance()->getValue("SELECT `id_stock_available` FROM `". _DB_PREFIX_ . "stock_available` WHERE `id_product` = {$product->id} AND `id_shop` = " . Context::getContext()->shop->id);
             $available = new StockAvailable($available);
             $available->id_product = $product->id;
             $available->id_product_attribute = 0;
             //$available->id_shop = Context::getContext()->shop->id;
             $available->quantity = StockManagerFactory::getManager()->getProductPhysicalQuantities($product->id, 0);
             $available->save();
     
             StockAvailable::setProductDependsOnStock($product->id, true, null);
             StockAvailable::setProductOutOfStock($product->id, 1, null); //allow
     */
     while (strlen($line['reference']) < 9) {
         $line['reference'] = '0' . $line['reference'];
     }
     if (file_exists(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg')) {
         $product->deleteImages();
         $image = new Image();
         $image->id_product = $product->id;
         $image->cover = 1;
         $image->position = 0;
         $image->save();
         $name = $image->getPathForCreation();
         copy(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '.' . $image->image_format);
         $types = ImageType::getImagesTypes('products');
         foreach ($types as $type) {
             ImageManager::resize(_PS_ROOT_DIR_ . '/upload/import/' . $line['reference'] . '.jpg', $name . '-' . $type['name'] . '.' . $image->image_format, $type['width'], $type['height'], $image->image_format);
         }
     }
     /*
             Db::getInstance()->update('stock_available', array(
       'depends_on_stock' => (int)1, //1 - доступное количество на основе ASM. 0 - указывается вручную
        'out_of_stock' => (int)1, //1-allow
             ), 'id_product='.$product->id.'');
     $affrows = Db::getInstance()->Affected_Rows();
     var_dump($affrows);
     */
     //var_dump($product->reference);
     //echo "<br/><br/><br/><br/>";
 }
    public function productImport()
    {
        $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 (self::ignoreRow($info)) {
                continue;
            }
            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();
                }
            } else {
                if (array_key_exists('id', $info) && is_string($info['id'])) {
                    $prod = self::findProductByName($default_language_id, $info['id'], $info['name']);
                    if ($prod['id_product']) {
                        $info['id'] = (int) $prod['id_product'];
                    }
                }
                if (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                    $product = new Product((int) $info['id']);
                    $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;
                            }
                        }
                    }
                } else {
                    $product = new Product();
                }
            }
            AdminImportController::setEntityDefaultValues($product);
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
            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;
            }
            $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 ($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;
            }
            $properties = $product->productProperties();
            if ((double) $properties['pp_unit_price_ratio'] > 0) {
                $product->unit_price = (double) $product->price / (double) $properties['pp_unit_price_ratio'];
            }
            if (isset($product->category) && is_array($product->category) && count($product->category)) {
                $product->id_category = 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');
                            $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);
            }
            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);
                        }
                    }
                }
            }
            foreach (Product::$definition['fields'] as $key => $array) {
                if ($array['type'] == Product::TYPE_FLOAT) {
                    $product->{$key} = str_replace(',', '.', $product->{$key});
                }
            }
            $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) {
                if ($product->quantity == null) {
                    $product->quantity = 0;
                }
                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();
                }
                $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 (!$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 {
                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();
                }
                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();
                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'));
                        }
                    }
                }
                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;
                            }
                        }
                    }
                    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;
                            }
                        }
                    }
                }
                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;
                            if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) {
                                $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 = 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);
                        }
                    }
                }
                Feature::cleanPositions();
                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);
                    }
                    if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                        StockAvailable::setProductDependsOnStock($product->id, 0);
                    }
                }
                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)) {
                            $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                            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]);
                        }
                    }
                }
                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);
                    }
                    if (isset($product->quantity) && $product->quantity) {
                        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((double) $price, 6);
                            $warehouse = new Warehouse($product->warehouse);
                            if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, $product->quantity, 1, $price, true)) {
                                StockAvailable::synchronize((int) $product->id);
                            }
                        } else {
                            if (Shop::isFeatureActive()) {
                                foreach ($shops as $shop) {
                                    StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop);
                                }
                            } else {
                                StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id);
                            }
                        }
                    }
                } else {
                    if (Shop::isFeatureActive()) {
                        foreach ($shops as $shop) {
                            StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop);
                        }
                    } else {
                        StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $this->context->shop->id);
                    }
                }
            }
        }
        $this->closeCsvFile($handle);
    }
    public function displayList()
    {
        global $currentIndex;
        echo '<br />
			<a href="' . $currentIndex . '&add' . $this->table . '&token=' . $this->token . '"><img src="../img/admin/add.gif" border="0" /> <b>' . $this->l('Add a new feature') . '</b></a><br />
			<a href="' . $currentIndex . '&addfeature_value&token=' . $this->token . '"><img src="../img/admin/add.gif" border="0" /> ' . $this->l('Add a new feature value') . '</a><br /><br />
		' . $this->l('Click on a feature name to view its values and then click again if you want to hide them.') . '<br /><br />';
        $this->displayListHeader();
        echo '<input type="hidden" name="groupid" value="0">';
        if (!sizeof($this->_list)) {
            echo '<tr><td class="center" colspan="' . sizeof($this->_list) . '">' . $this->l('No features found.') . '</td></tr>';
        }
        $irow = 0;
        foreach ($this->_list as $tr) {
            $id = (int) $tr['id_' . $this->table];
            echo '
			<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . '>
				<td style="vertical-align: top; padding: 4px 0 4px 0" class="center"><input type="checkbox" name="' . $this->table . 'Box[]" value="' . $id . '" class="noborder" /></td>
				<td style="width: 140px; vertical-align: top; padding: 4px 0 4px 0; cursor: pointer" onclick="$(\'#features_values_' . $id . '\').slideToggle();">' . $tr['name'] . '</td>
				<td style="vertical-align: top; padding: 4px 0 4px 0; width: 340px">
					<div id="features_values_' . $id . '" style="display: none">
					<table class="table" cellpadding="0" cellspacing="0">
						<tr>
							<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'feature_value' . $id . 'Box[]\', this.checked)" /></th>
							<th width="100%">' . $this->l('Value') . '</th>
							<th>' . $this->l('Actions') . '</th>
						</tr>';
            $features = FeatureValue::getFeatureValuesWithLang((int) Configuration::get('PS_LANG_DEFAULT'), $id);
            foreach ($features as $feature) {
                echo '
				<tr>
					<td class="center"><input type="checkbox" name="feature_value' . $id . 'Box[]" value="' . $feature['id_feature_value'] . '" class="noborder" /></td>
					<td>' . $feature['value'] . '</td>
					<td class="center">
						<a href="' . $currentIndex . '&id_feature_value=' . $feature['id_feature_value'] . '&updatefeature_value&token=' . $this->token . '">
						<img src="../img/admin/edit.gif" border="0" alt="' . $this->l('Edit') . '" title="' . $this->l('Edit') . '" /></a>&nbsp;
						<a href="' . $currentIndex . '&id_feature_value=' . $feature['id_feature_value'] . '&deletefeature_value&token=' . $this->token . '"
						onclick="return confirm(\'' . $this->l('Delete value', __CLASS__, true, false) . ' #' . $feature['id_feature_value'] . '?\');">
						<img src="../img/admin/delete.gif" border="0" alt="' . $this->l('Delete') . '" title="' . $this->l('Delete') . '" /></a>
					</td>
				</tr>';
            }
            if (!sizeof($features)) {
                echo '
						<tr><td colspan="3" style="text-align:center">' . $this->l('No values defined') . '</td></tr>';
            }
            echo '
					</table>
					<p><input type="Submit" class="button" name="submitDelfeature_value" value="' . $this->l('Delete selection') . '"
					onclick="changeFormParam(this.form, \'?tab=AdminFeatures\', ' . $id . '); return confirm(\'' . $this->l('Delete selected items?', __CLASS__, true, false) . '\');" /></p>
					</div>
					</td>';
            echo '
				<td style="vertical-align: top; padding: 4px 0 4px 0" class="center">
					<a href="' . $currentIndex . '&id_' . $this->table . '=' . $id . '&update' . $this->table . '&token=' . $this->token . '">
					<img src="../img/admin/edit.gif" border="0" alt="' . $this->l('Edit') . '" title="' . $this->l('Edit') . '" /></a>&nbsp;
					<a href="' . $currentIndex . '&id_' . $this->table . '=' . $id . '&delete' . $this->table . '&token=' . $this->token . '" onclick="return confirm(\'' . $this->l('Delete item', __CLASS__, true, false) . ' #' . $id . '?\');">
					<img src="../img/admin/delete.gif" border="0" alt="' . $this->l('Delete') . '" title="' . $this->l('Delete') . '" /></a>
				</td>
			</tr>';
        }
        $this->displayListFooter();
    }
 public function ajaxProcessUpdatePositions()
 {
     if ($this->tabAccess['edit'] === '1') {
         $way = (int) Tools::getValue('way');
         $id_feature_value = (int) Tools::getValue('id');
         $positions = Tools::getValue('feature_value');
         $new_positions = array();
         foreach ($positions as $k => $v) {
             if (!empty($v)) {
                 $new_positions[] = $v;
             }
         }
         foreach ($new_positions as $position => $value) {
             $pos = explode('_', $value);
             if (isset($pos[2]) && (int) $pos[2] === $id_feature_value) {
                 if ($feature = new FeatureValue((int) $pos[2])) {
                     if (isset($position) && $feature->updatePosition($way, $position, $id_feature_value)) {
                         echo 'ok position ' . (int) $position . ' for feature value ' . (int) $pos[1] . '\\r\\n';
                     } else {
                         echo '{"hasError" : true, "errors" : "Can not update feature value ' . (int) $id_feature_value . ' to position ' . (int) $position . ' "}';
                     }
                 } else {
                     echo '{"hasError" : true, "errors" : "This feature value (' . (int) $id_feature_value . ') can t be loaded"}';
                 }
                 break;
             }
         }
     }
 }
Example #23
0
    public static function addFeatureValueImport($id_feature, $value, $id_product = null, $id_lang = null, $custom = false)
    {
        $id_feature_value = false;
        if (!is_null($id_product) && $id_product) {
            $id_feature_value = Db::getInstance()->getValue('
				SELECT fp.`id_feature_value`
				FROM ' . _DB_PREFIX_ . 'feature_product fp
				INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv USING (`id_feature_value`)
				WHERE fp.`id_feature` = ' . (int) $id_feature . '
				AND fv.`custom` = ' . (int) $custom . '
				AND fp.`id_product` = ' . (int) $id_product);
            if ($custom && $id_feature_value && !is_null($id_lang) && $id_lang) {
                Db::getInstance()->execute('
				UPDATE ' . _DB_PREFIX_ . 'feature_value_lang
				SET `value` = \'' . pSQL($value) . '\'
				WHERE `id_feature_value` = ' . (int) $id_feature_value . '
				AND `value` != \'' . pSQL($value) . '\'
				AND `id_lang` = ' . (int) $id_lang);
            }
        }
        if (!$custom) {
            $id_feature_value = Db::getInstance()->getValue('
				SELECT fv.`id_feature_value`
				FROM ' . _DB_PREFIX_ . 'feature_value fv
				LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.`id_feature_value` = fv.`id_feature_value` AND fvl.`id_lang` = ' . (int) $id_lang . ')
				WHERE `value` = \'' . pSQL($value) . '\'
				AND fv.`id_feature` = ' . (int) $id_feature . '
				AND fv.`custom` = 0
				GROUP BY fv.`id_feature_value`');
        }
        if ($id_feature_value) {
            return (int) $id_feature_value;
        }
        // Feature doesn't exist, create it
        $feature_value = new FeatureValue();
        $feature_value->id_feature = (int) $id_feature;
        $feature_value->custom = (bool) $custom;
        $feature_value->value = array_fill_keys(Language::getIDs(false), $value);
        $feature_value->add();
        return (int) $feature_value->id;
    }
Example #24
0
													options += $(this).val()+",";
												});
												$("#attribute-ids").val(options.substr(0, options.length - 1));
											}
										});
									</script>
								</div>
							</div>
						</div>

						<div id="product-tab-content-feature" class="product-tab-content" style=" display:none">
							<div class="row">
								<div class="col-md-10 form-horizontal">
									<?php 
$features = Feature::loadData();
$featureValues = FeatureValue::loadData();
if (isset($obj)) {
    $selectedFeature = $obj->getFeatures();
}
if ($features) {
    foreach ($features['items'] as $feature) {
        ?>
											<div class="form-group">
												<label for="categoryBox" class="col-sm-2 control-label"><?php 
        echo $feature['name'];
        ?>
</label>

												<div class="col-sm-10">
													<select name="id_feature_value[]" class="form-control">
														<option value="">--选择特征--</option>
Example #25
0
 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')) {
             $line = $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')) {
             $product = new Product((int) $info['id']);
             $categoryData = Product::getProductCategories((int) $product->id);
             foreach ($categoryData as $tmp) {
                 $product->category[] = $tmp;
             }
         } else {
             $product = new Product();
         }
         self::setEntityDefaultValues($product);
         self::array_walk($info, array('AdminImport', 'fillInfo'), $product);
         if ((int) $product->id_tax_rules_group != 0) {
             if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                 $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0);
             } else {
                 $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.'));
             }
         }
         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) && count($product->link_rewrite) ? $product->link_rewrite[$defaultLanguageId] : '';
         $valid_link = Validate::isLinkRewrite($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') . ' ' . $link_rewrite . (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 match ref is specified AND ref product AND ref product already in base, trying to update
             if (Tools::getValue('match_ref') == 1 and $product->reference and Product::existsRefInDatabase($product->reference)) {
                 $datas = Db::getInstance()->getRow('SELECT `date_add`, `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `reference` = "' . $product->reference . '"');
                 $product->id = pSQL($datas['id_product']);
                 $product->date_add = pSQL($datas['date_add']);
                 $res = $product->update();
             } else {
                 if ($product->id and Product::existsInDatabase((int) $product->id, 'product')) {
                     $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) {
                 if (isset($product->date_add) && $product->date_add != '') {
                     $res = $product->add(false);
                 } else {
                     $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']) and $info['reduction_price'] > 0 or isset($info['reduction_percent']) and $info['reduction_percent'] > 0) {
                 $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;
                         }
                     }
                 }
             }
             //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();
                 } elseif (isset($product->image) and is_array($product->image) and sizeof($product->image)) {
                     $product->deleteImages();
                 }
             }
             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);
 }
Example #26
0
    public function getProductByFilters($selected_filters = array())
    {
        global $cookie;
        if (!empty($this->products)) {
            return $this->products;
        }
        $home_category = Configuration::get('PS_HOME_CATEGORY');
        /* If the current category isn't defined or if it's homepage, we have nothing to display */
        $id_parent = (int) Tools::getValue('id_category', Tools::getValue('id_category_layered', $home_category));
        if ($id_parent == $home_category) {
            return false;
        }
        $alias_where = 'p';
        if (version_compare(_PS_VERSION_, '1.5', '>')) {
            $alias_where = 'product_shop';
        }
        $query_filters_where = ' AND ' . $alias_where . '.`active` = 1 AND ' . $alias_where . '.`visibility` IN ("both", "catalog")';
        $query_filters_from = '';
        $parent = new Category((int) $id_parent);
        if (!count($selected_filters['category'])) {
            if (Configuration::get('PS_LAYERED_FULL_TREE')) {
                $query_filters_from .= ' INNER JOIN ' . _DB_PREFIX_ . 'category_product cp
				ON p.id_product = cp.id_product
				INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND
				c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright . '
				AND c.active = 1)
				RIGHT JOIN ' . _DB_PREFIX_ . 'layered_category lc ON (lc.id_category = ' . (int) $id_parent . ' AND
				lc.id_shop = ' . (int) Context::getContext()->shop->id . ')';
            } else {
                $query_filters_from .= ' INNER JOIN ' . _DB_PREFIX_ . 'category_product cp
				ON p.id_product = cp.id_product
				INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category
				AND c.id_category = ' . (int) $id_parent . '
				AND c.active = 1)';
            }
        }
        foreach ($selected_filters as $key => $filter_values) {
            if (!count($filter_values)) {
                continue;
            }
            $key_start = $key;
            preg_match('/^(.*[^_0-9])/', $key, $res);
            $key = $res[1];
            switch ($key) {
                case 'id_feature':
                    $key_start = explode('id_feature_', $key_start);
                    if (count($key_start) == 1) {
                        $sub_queries = array();
                        foreach ($filter_values as $filter_value) {
                            $filter_value_array = explode('_', $filter_value);
                            if (!isset($sub_queries[$filter_value_array[0]])) {
                                $sub_queries[$filter_value_array[0]] = array();
                            }
                            $sub_queries[$filter_value_array[0]][] = 'fp.`id_feature_value` = ' . (int) $filter_value_array[1];
                        }
                        foreach ($sub_queries as $sub_query) {
                            $query_filters_where .= ' AND p.id_product IN (SELECT `id_product` FROM `' . _DB_PREFIX_ . 'feature_product` fp WHERE ';
                            $query_filters_where .= implode(' OR ', $sub_query) . ') ';
                        }
                    } else {
                        if (count($key_start) == 2) {
                            $id_feature = $key_start[1];
                            $f_values = FeatureValue::getFeatureValuesWithLang(1, $id_feature);
                            $f_values_in = array();
                            foreach ($f_values as $feature_value) {
                                if ((double) $feature_value['value'] >= (double) $filter_values[0] && (double) $feature_value['value'] <= (double) $filter_values[1]) {
                                    $f_values_in[] = $feature_value['id_feature_value'];
                                }
                            }
                            $f_values_in = array_unique($f_values_in);
                            $sub_queries = array();
                            foreach ($f_values_in as $f_value) {
                                $sub_queries[$id_feature][] = 'fp.`id_feature_value` = ' . (int) $f_value;
                            }
                            foreach ($sub_queries as $sub_query) {
                                $query_filters_where .= ' AND p.id_product IN (SELECT `id_product` FROM `' . _DB_PREFIX_ . 'feature_product` fp WHERE ';
                                $query_filters_where .= implode(' OR ', $sub_query) . ') ';
                            }
                        }
                    }
                    break;
                case 'id_attribute_group':
                    $sub_queries = array();
                    foreach ($filter_values as $filter_value) {
                        $filter_value_array = explode('_', $filter_value);
                        if (!isset($sub_queries[$filter_value_array[0]])) {
                            $sub_queries[$filter_value_array[0]] = array();
                        }
                        $sub_queries[$filter_value_array[0]][] = 'pac.`id_attribute` = ' . (int) $filter_value_array[1];
                    }
                    foreach ($sub_queries as $sub_query) {
                        $query_filters_where .= ' AND p.id_product IN (SELECT pa.`id_product`
						FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac
						LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa
						ON (pa.`id_product_attribute` = pac.`id_product_attribute`)' . Shop::addSqlAssociation('product_attribute', 'pa') . '
						WHERE ' . implode(' OR ', $sub_query) . ') ';
                    }
                    break;
                case 'category':
                    $query_filters_where .= ' AND p.id_product IN (SELECT id_product FROM ' . _DB_PREFIX_ . 'category_product cp WHERE ';
                    foreach ($selected_filters['category'] as $id_category) {
                        $query_filters_where .= 'cp.`id_category` = ' . (int) $id_category . ' OR ';
                    }
                    $query_filters_where = rtrim($query_filters_where, 'OR ') . ')';
                    break;
                case 'quantity':
                    if (count($selected_filters['quantity']) == 2) {
                        break;
                    }
                    $query_filters_where .= ' AND sa.quantity ' . (!$selected_filters['quantity'][0] ? '<=' : '>') . ' 0 ';
                    $query_filters_from .= 'LEFT JOIN `' . _DB_PREFIX_ . 'stock_available` sa ON (sa.id_product = p.id_product AND sa.id_shop = ' . (int) Context::getContext()->shop->id . ') ';
                    break;
                case 'manufacturer':
                    $query_filters_where .= ' AND p.id_manufacturer IN (' . implode($selected_filters['manufacturer'], ',') . ')';
                    break;
                case 'condition':
                    if (count($selected_filters['condition']) == 3) {
                        break;
                    }
                    $query_filters_where .= ' AND ' . $alias_where . '.condition IN (';
                    foreach ($selected_filters['condition'] as $cond) {
                        $query_filters_where .= '\'' . $cond . '\',';
                    }
                    $query_filters_where = rtrim($query_filters_where, ',') . ')';
                    break;
                case 'weight':
                    if ($selected_filters['weight'][0] != 0 || $selected_filters['weight'][1] != 0) {
                        $query_filters_where .= ' AND p.`weight` BETWEEN ' . (double) ($selected_filters['weight'][0] - 0.001) . ' AND ' . (double) ($selected_filters['weight'][1] + 0.001);
                    }
                    break;
                case 'price':
                    if (isset($selected_filters['price'])) {
                        if ($selected_filters['price'][0] !== '' || $selected_filters['price'][1] !== '') {
                            $price_filter = array();
                            $price_filter['min'] = (double) $selected_filters['price'][0];
                            $price_filter['max'] = (double) $selected_filters['price'][1];
                        }
                    } else {
                        $price_filter = false;
                    }
                    break;
            }
        }
        $id_currency = (int) Context::getContext()->currency->id;
        $price_filter_query_in = '';
        // All products with price range between price filters limits
        $price_filter_query_out = '';
        // All products with a price filters limit on it price range
        if (isset($price_filter) && $price_filter) {
            $price_filter_query_in = 'INNER JOIN `' . _DB_PREFIX_ . 'layered_price_index` psi
			ON
			(
				psi.price_min >= ' . (int) $price_filter['min'] . '
				AND psi.price_max <= ' . (int) $price_filter['max'] . '
				AND psi.`id_product` = p.`id_product`
				AND psi.`id_currency` = ' . $id_currency . '
			)';
            $price_filter_query_out = 'INNER JOIN `' . _DB_PREFIX_ . 'layered_price_index` psi
			ON
				((psi.price_min < ' . (int) $price_filter['min'] . ' AND psi.price_max > ' . (int) $price_filter['min'] . ')
				OR
				(psi.price_max > ' . (int) $price_filter['max'] . ' AND psi.price_min < ' . (int) $price_filter['max'] . '))
				AND psi.`id_product` = p.`id_product`
				AND psi.`id_currency` = ' . $id_currency;
        }
        $query_filters_from .= Shop::addSqlAssociation('product', 'p');
        $all_products_out = self::query('
		SELECT p.`id_product` id_product
		FROM `' . _DB_PREFIX_ . 'product` p
		' . $price_filter_query_out . '
		' . $query_filters_from . '
		WHERE 1 ' . $query_filters_where . ' GROUP BY id_product');
        $all_products_in = self::query('
		SELECT p.`id_product` id_product
		FROM `' . _DB_PREFIX_ . 'product` p
		' . $price_filter_query_in . '
		' . $query_filters_from . '
		WHERE 1 ' . $query_filters_where . ' GROUP BY id_product');
        $product_id_list = array();
        while ($product = DB::getInstance()->nextRow($all_products_in)) {
            $product_id_list[] = (int) $product['id_product'];
        }
        while ($product = DB::getInstance()->nextRow($all_products_out)) {
            if (isset($price_filter) && $price_filter) {
                $price = (int) Product::getPriceStatic($product['id_product'], Configuration::get('PS_LAYERED_FILTER_PRICE_USETAX'));
                // Cast to int because we don't care about cents
                if ($price < $price_filter['min'] || $price > $price_filter['max']) {
                    continue;
                }
                $product_id_list[] = (int) $product['id_product'];
            }
        }
        $this->nbr_products = count($product_id_list);
        if ($this->nbr_products == 0) {
            $this->products = array();
        } else {
            $n = (int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE'));
            $nb_day_new_product = Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20;
            $this->products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
			SELECT
				p.*,
				' . ($alias_where == 'p' ? '' : 'product_shop.*,') . '
				' . $alias_where . '.id_category_default,
				pl.*,
				MAX(image_shop.`id_image`) id_image,
				il.legend,
				m.name manufacturer_name,
				MAX(product_attribute_shop.id_product_attribute) id_product_attribute,
				DATEDIFF(' . $alias_where . '.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (int) $nb_day_new_product . ' DAY)) > 0 AS new,
				stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
			FROM `' . _DB_PREFIX_ . 'category_product` cp
			LEFT JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category)
			LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
			' . Shop::addSqlAssociation('product', 'p') . '
			' . Product::sqlStock('p', null, false, Context::getContext()->shop) . '
			LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product' . Shop::addSqlRestrictionOnLang('pl') . ' AND pl.id_lang = ' . (int) $cookie->id_lang . ')
			LEFT JOIN `' . _DB_PREFIX_ . 'image` i  ON (i.`id_product` = p.`id_product`)' . Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1') . '
			LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $cookie->id_lang . ')
			LEFT JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer)
			LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON (p.id_product = pa.id_product)' . Shop::addSqlAssociation('product_attribute', 'pa', false, 'product_attribute_shop.`default_on` = 1') . '
			WHERE ' . $alias_where . '.`active` = 1 AND ' . $alias_where . '.`visibility` IN ("both", "catalog")
			AND ' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
			AND c.active = 1
			AND p.id_product IN (' . implode(',', $product_id_list) . ')
			GROUP BY product_shop.id_product
			ORDER BY `quantity` DESC, ' . Tools::getProductsOrder('by', Tools::getValue('orderby'), true) . ' ' . Tools::getProductsOrder('way', Tools::getValue('orderway')) . ' LIMIT ' . (((int) $this->page - 1) * $n . ',' . $n));
        }
        if (Tools::getProductsOrder('by', Tools::getValue('orderby'), true) == 'p.price') {
            Tools::orderbyPrice($this->products, Tools::getProductsOrder('way', Tools::getValue('orderway')));
        }
        return $this->products;
    }
    public function displayFormFeatures($obj, $languages, $defaultLanguage)
    {
        global $cookie, $currentIndex;
        //duplicate AdminTab::displayForm for display flag near traanslateable input fields
        $allowEmployeeFormLang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        echo '
			<script type="text/javascript">
				$(document).ready(function() {
					id_language = ' . $defaultLanguage . ';
					languages = new Array();';
        foreach ($languages as $k => $language) {
            echo '
					languages[' . $k . '] = {
						id_lang: ' . (int) $language['id_lang'] . ',
						iso_code: \'' . $language['iso_code'] . '\',
						name: \'' . htmlentities($language['name'], ENT_COMPAT, 'UTF-8') . '\'
					};';
        }
        echo '
					displayFlags(languages, id_language, ' . $allowEmployeeFormLang . ');
				});
			</script>';
        if ($obj->id) {
            //  		$feature = Feature::getFeatures(intval($cookie->id_lang));
            include_once 'ExFeature.php';
            $feature = ExFeature::getFeatures($defaultLanguage);
            $ctab = '';
            foreach ($feature as $group) {
                foreach ($group["features"] as $f) {
                    $ctab .= 'ccustom_' . $f['id'] . '¤';
                }
            }
            $ctab = rtrim($ctab, '¤');
            ?>
			<table cellpadding="5">
				<tr>
					<td colspan="2"><b><?php 
            echo $this->l('Assign features to this product');
            ?>
</b></td>
				</tr>
			</table>
			<hr style="width:730px;" />
            <a href="#" id="all_close" class="module_toggle_all"><?php 
            echo $this->l('Collapse all');
            ?>
</a> 
            <a id="all_open" class="module_toggle_all" href="#"><?php 
            echo $this->l('Expand all');
            ?>
</a><br /> 
			
            <?php 
            // Header
            $nb_feature = Feature::nbFeatures(intval($cookie->id_lang));
            ?>
			<table border="0" cellpadding="0" cellspacing="0" class="table" style="width:906px;">
				<tr>
					<th style="width:30%; padding-left:10px;"><?php 
            echo $this->l('Features');
            ?>
</td>
					<th style="width:25%"><?php 
            echo $this->l('Value');
            ?>
</td>
					<th style="width:45%"><?php 
            echo $this->l('Customized');
            ?>
</td>
				</tr>
            <?php 
            if (!$nb_feature) {
                ?>
					<tr><td colspan="3" style="text-align:center;">'.$this->l('No features defined').'</td></tr>
            <?php 
            }
            ?>
			</table>
            
            <?php 
            // Listing
            if ($nb_feature) {
                $pfeatures = Product::getFeaturesStatic($obj->id);
                $product_features = array();
                foreach ($pfeatures as $pf) {
                    if (!array_key_exists($pf["id_feature"], $product_features)) {
                        $product_features[$pf["id_feature"]] = array();
                    }
                    $product_features[$pf["id_feature"]][] = $pf["id_feature_value"];
                }
                unset($pfeatures);
                $odd = 0;
                ?>
				
                <?php 
                // <table cellpadding="5" style="width:743px; margin-top:10px">
                ?>
                
                <?php 
                //Main loop
                foreach ($feature as $gid => $group) {
                    ?>
                    <div id="cgroup<?php 
                    echo $gid;
                    ?>
" class="header_module">
				        <span class="nbr_module" style="width:100px;text-align:right; margin-right: 125px;"><?php 
                    echo count($group["features"]);
                    ?>
 <?php 
                    echo $this->l('features');
                    ?>
</span>
	                    <a class="header_module_toggle" id="group_<?php 
                    echo $gid;
                    ?>
" href="modgo_search_filter" style="margin-left: 5px;">
                            <span style="padding-right:0.5em">
       					        <img class="header_module_img" id="search_filter_img" src="../img/admin/more.png" alt="" />
                            </span><?php 
                    echo $group["name"];
                    ?>
                        </a> 
				    </div>
                    <div id="group_<?php 
                    echo $gid;
                    ?>
_content" class="tab_module_content" style="display:none;border:solid 1px #CCC">
                        <div id="modgo_blocksearch">
                            <table style="width:100%" cellpadding="0" cellspacing="0">
                <?php 
                    foreach ($group["features"] as $tab_features) {
                        $current_item = false;
                        $custom = true;
                        foreach ($obj->getFeatures() as $tab_products) {
                            if ($tab_products['id_feature'] == $tab_features['id_feature']) {
                                $current_item = $tab_products['id_feature_value'];
                            }
                        }
                        $featureValues = FeatureValue::getFeatureValuesWithLang((int) $cookie->id_lang, (int) $tab_features['id_feature']);
                        echo '
					<tr>
						<td style="padding-left: 10px; width: 30%">' . $tab_features['name'] . '</td>
						<td style="width: 25%">';
                        if (sizeof($featureValues)) {
                            echo '
							<select id="feature_' . $tab_features['id_feature'] . '_value" name="feature_' . $tab_features['id_feature'] . '_value"
								onchange="$(\'.custom_' . $tab_features['id_feature'] . '_\').val(\'\');">
								<option value="0">---&nbsp;</option>';
                            foreach ($featureValues as $value) {
                                if ($current_item == $value['id_feature_value']) {
                                    $custom = false;
                                }
                                echo '<option value="' . $value['id_feature_value'] . '"' . ($current_item == $value['id_feature_value'] ? ' selected="selected"' : '') . '>' . substr($value['value'], 0, 40) . (Tools::strlen($value['value']) > 40 ? '...' : '') . '&nbsp;</option>';
                            }
                            echo '</select>';
                        } else {
                            echo '<input type="hidden" name="feature_' . $tab_features['id_feature'] . '_value" value="0" /><span style="font-size: 10px; color: #666;">' . $this->l('N/A') . ' - <a href="index.php?tab=AdminFeatures&addfeature_value&id_feature=' . (int) $tab_features['id_feature'] . '&token=' . Tools::getAdminToken('AdminFeatures' . (int) Tab::getIdFromClassName('AdminFeatures') . (int) $cookie->id_employee) . '" style="color: #666; text-decoration: underline;">' . $this->l('Add pre-defined values first') . '</a></span>';
                        }
                        echo '
						</td>
						<td style="width:45%" class="translatable">';
                        $tab_customs = $custom ? FeatureValue::getFeatureValueLang($current_item) : array();
                        foreach ($languages as $language) {
                            echo '
							<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left; margin-top: 5px; margin-bottom: 5px;">
								<textarea class="custom_' . $tab_features['id_feature'] . '_" name="custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'] . '" cols="40" rows="1"
									onkeyup="$(\'#feature_' . $tab_features['id_feature'] . '_value\').val(0);" >' . htmlentities(Tools::getValue('custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'], FeatureValue::selectLang($tab_customs, $language['id_lang'])), ENT_COMPAT, 'UTF-8') . '</textarea>
							</div>';
                        }
                        /*                    echo '<div style="
                                                      float: left;
                                                      margin-top: 10px;
                                                      margin-left: 5px">'
                                              .$this->displayFlags($languages, $defaultLanguage, $ctab, 'ccustom_'.$tab_features['id_feature'], true).
                                              '</div>'; */
                        echo '
						</td>
					</tr>';
                    }
                    ?>
		                        

                            </table>
				        </div>
				    </div> 
                <?php 
                }
                ?>
                <div id="updateFeatureAdminContainer" style="text-align: center; margin-top: 10px;">    
                    <input type="submit" name="submitProductFeature" id="submitProductFeature" value="<?php 
                echo $this->l('Update features');
                ?>
" class="button" />
                </div>
			<?php 
            }
            ?>
            
            
			<hr style="width:730px;" />
			<div style="text-align:center;">
				<a href="index.php?tab=AdminExFeatures&addfeature&token=<?php 
            echo Tools::getAdminToken('AdminExFeatures' . intval(Tab::getIdFromClassName('AdminExFeatures')) . intval($cookie->id_employee));
            ?>
" onclick="return confirm('<?php 
            echo $this->l('Are you sure you want to delete entered product information?', __CLASS__, true, false);
            ?>
');">
                    <img src="../img/admin/add.gif" alt="new_features" title="<?php 
            echo $this->l('Create new features');
            ?>
" />&nbsp;<?php 
            echo $this->l('Create new features');
            ?>
                </a>
			</div>
		<?php 
        } else {
            echo '<b>' . $this->l('You must save this product before adding features') . '.</b>';
        }
    }
    public function displayList()
    {
        global $currentIndex, $cookie;
        ?>
<h2><?php 
        echo $this->adminFeaturesGroups->loadObject()->name[$cookie->id_lang];
        ?>
</h2>
<br />
<a href="<?php 
        echo $currentIndex;
        ?>
&add<?php 
        echo $this->table . ($this->id_group ? '&id_group=' . $this->id_group : '');
        ?>
&token=<?php 
        echo $this->token;
        ?>
">
    <img src="../img/admin/add.gif" border="0" /> <b><?php 
        echo $this->l('Add feature', __CLASS__);
        ?>
</b>
</a><br />
<a href="<?php 
        echo $currentIndex;
        ?>
&reorderpositions=1<?php 
        echo $this->id_group ? '&id_group=' . $this->id_group : '';
        ?>
&token=<?php 
        echo $this->token;
        ?>
">
    <img src="../img/admin/add.gif" border="0" /> <b><?php 
        echo $this->l('Reorder position', __CLASS__);
        ?>
</b>
</a><br />

<a href="<?php 
        echo $currentIndex;
        ?>
&addfeature_value&token=<?php 
        echo $this->token;
        ?>
">
    <img src="../img/admin/add.gif" border="0" /> <?php 
        echo $this->l('Add feature value', __CLASS__);
        ?>
</a><br /><br />
<?php 
        echo $this->l('Click on the feature name to view its values. Click again to hide them', __CLASS__);
        ?>
<br /><br />

<script type="text/javascript" src="../js/jquery/jquery.tablednd_0_5.js"></script>
<script type="text/javascript">
	var token = '<?php 
        echo $this->token;
        ?>
';
	var come_from = '<?php 
        echo $this->table;
        ?>
';
	var alternate = '<?php 
        echo $this->_orderWay == 'DESC' ? '1' : '0';
        ?>
';
</script>
<script type="text/javascript" src="../js/admin-dnd.js"></script>

<?php 
        echo $this->displayListHeader();
        ?>
<input type="hidden" name="id_group" value="<?php 
        echo intval(Tools::getValue("id_group"));
        ?>
" />
<input type="hidden" name="groupid" value="0" />

<?php 
        if (!sizeof($this->_list)) {
            ?>
 
	<tr><td class="center" colspan="<?php 
            echo sizeof($this->_list);
            ?>
"><?php 
            echo $this->l('No features found', __CLASS__);
            ?>
</td></tr>
<?php 
        }
        ?>

<?php 
        $irow = 0;
        foreach ($this->_list as $tr) {
            $id = intval($tr['id_' . $this->table]);
            ?>
 
	<tr<?php 
            echo $irow++ % 2 ? ' class="alt_row"' : '';
            ?>
>
		<td style="vertical-align: top; padding: 4px 0 4px 0" class="center">
            <input type="checkbox" name="<?php 
            echo $this->table;
            ?>
Box[]" value="<?php 
            echo $id;
            ?>
" class="noborder" />
        </td>
		<td style="width: 140px; vertical-align: top; padding: 4px 0 4px 0; cursor: pointer" onclick="$('#features_values_<?php 
            echo $id;
            ?>
').slideToggle();">
            <?php 
            echo $tr['name'];
            ?>
        </td>
		<td style="vertical-align: top; padding: 4px 0 4px 0; width: 340px">
			<div 
                id="features_values_<?php 
            echo $id;
            ?>
" 
                style="display: <?php 
            echo $this->id_feature == $id && !Tools::getValue('upposition') && !Tools::getValue('downposition') ? "block" : "none";
            ?>
">
			<table class="table" cellpadding="0" cellspacing="0">
				<tr>
					<th>
                        <input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, 'feature_value<?php 
            echo $id;
            ?>
Box[]', this.checked)" />
                    </th>
					<th width="100%"><?php 
            echo $this->l('Value');
            ?>
</th>
					<th><?php 
            echo $this->l('Actions');
            ?>
</th>
				</tr>
        <?php 
            $features = FeatureValue::getFeatureValuesWithLang(intval(Configuration::get('PS_LANG_DEFAULT')), $id);
            foreach ($features as $feature) {
                ?>
				<tr>
					<td class="center">
                        <input type="checkbox" name="feature_value<?php 
                echo $id;
                ?>
Box[]" value="<?php 
                echo $feature['id_feature_value'];
                ?>
" class="noborder" />
                    </td>
					<td><?php 
                echo $feature['value'];
                ?>
</td>
					<td class="center">
						<a href="<?php 
                echo $currentIndex;
                ?>
&id_feature_value=<?php 
                echo $feature['id_feature_value'];
                ?>
&updatefeature_value&token=<?php 
                echo $this->token;
                ?>
">
                            <img src="../img/admin/edit.gif" border="0" alt="<?php 
                echo $this->l('Edit');
                ?>
" title="<?php 
                echo $this->l('Edit');
                ?>
" />
                        </a>&nbsp;
						<a href="<?php 
                echo $currentIndex;
                ?>
&id_feature_value=<?php 
                echo $feature['id_feature_value'];
                ?>
&deletefeature_value&token=<?php 
                echo $this->token;
                ?>
"
						  onclick="return confirm(\'<?php 
                echo $this->l('Delete value', __CLASS__, true, false);
                ?>
 #<?php 
                echo $feature['id_feature_value'];
                ?>
?\');">
						      <img src="../img/admin/delete.gif" border="0" alt="<?php 
                echo $this->l('Delete');
                ?>
" title="<?php 
                echo $this->l('Delete');
                ?>
" />
                        </a>
					</td>
				</tr>
	<?php 
            }
            ?>
	<?php 
            if (!sizeof($features)) {
                ?>
        <tr><td colspan="3" style="text-align:center"><?php 
                echo $this->l('No values defined');
                ?>
</td></tr>
    <?php 
            }
            ?>
	          </table>
				<p>
					<a href="<?php 
            echo $currentIndex;
            ?>
&<?php 
            echo $this->identifier;
            ?>
=<?php 
            echo $id;
            ?>
&addfeature_value&token=<?php 
            echo $this->token;
            ?>
" class="button"><?php 
            echo $this->l('Add new value', __CLASS__);
            ?>
</a> 
					<input type="Submit" class="button" name="submitDelfeature_value" value="<?php 
            echo $this->l('Delete selection');
            ?>
"
					   onclick="changeFormParam(this.form, '?tab=AdminExFeatures', <?php 
            echo $id;
            ?>
); return confirm('<?php 
            echo $this->l('Delete selected items?', __CLASS__, true, false);
            ?>
');" />
				</p>
			</div>
			</td>
    		<td style="width: 40px; vertical-align: top; padding: 4px 0 4px 0; cursor: pointer" onclick="$('#features_values_<?php 
            echo $id;
            ?>
').slideToggle();">
    			<?php 
            $tr['group_name'];
            ?>
    		</td>
    	    <td class="pointer dragHandle center" id="td_<?php 
            echo $tr["id_feature"];
            ?>
">
    	<?php 
            if ($irow < count($this->_list)) {
                ?>
 
    		<a href="<?php 
                echo $currentIndex;
                ?>
&id_feature=<?php 
                echo $tr["id_feature"];
                ?>
&downposition=<?php 
                echo $tr["f_position"];
                ?>
&id_group=<?php 
                echo intval(Tools::getValue('id_group'));
                ?>
&token=<?php 
                echo $this->token;
                ?>
">
                <img title="Down" alt="Down" src="../img/admin/down.gif" />
    		</a>
        <?php 
            }
            ?>
      
    	<?php 
            if ($irow > 1) {
                ?>
    		<a href="<?php 
                echo $currentIndex;
                ?>
&id_feature=<?php 
                echo $tr["id_feature"];
                ?>
&upposition=<?php 
                echo $tr["f_position"];
                ?>
&id_group=<?php 
                echo intval(Tools::getValue('id_group'));
                ?>
&token=<?php 
                echo $this->token;
                ?>
" style="">
                <img title="Up" alt="Up" src="../img/admin/up.gif" />
    		</a>
        <?php 
            }
            ?>
    	   </td>
        	<td style="vertical-align: top; padding: 4px 0 4px 0" class="center">
        		<a href="<?php 
            echo $currentIndex;
            ?>
&id_<?php 
            echo $this->table;
            ?>
=<?php 
            echo $id;
            ?>
&update<?php 
            echo $this->table;
            ?>
&token=<?php 
            echo $this->token;
            ?>
">
        		<img src="../img/admin/edit.gif" border="0" alt="<?php 
            echo $this->l('Edit');
            ?>
" title="<?php 
            echo $this->l('Edit');
            ?>
" /></a>&nbsp;
        		<a href="<?php 
            echo $currentIndex;
            ?>
&id_<?php 
            echo $this->table;
            ?>
=<?php 
            echo $id;
            ?>
&delete<?php 
            echo $this->table . ($this->id_group ? '&id_group=' . $this->id_group : '');
            ?>
&token=<?php 
            echo $this->token;
            ?>
" 
                    onclick="return confirm('<?php 
            echo $this->l('Delete item', __CLASS__, true, false);
            ?>
 #<?php 
            echo $id;
            ?>
?\');">
        		     <img src="../img/admin/delete.gif" border="0" alt="<?php 
            echo $this->l('Delete');
            ?>
" title="<?php 
            echo $this->l('Delete');
            ?>
" />
                </a>&nbsp;
        	</td>
	</tr>
<?php 
        }
        ?>

<?php 
        $this->displayListFooter();
        ?>

<br /><br />
<a href="<?php 
        echo $currentIndex;
        ?>
&token=<?php 
        echo $this->token;
        ?>
">
    <img src="../img/admin/arrow2.gif" /> <?php 
        echo $this->l('Back to groups list', __CLASS__);
        ?>
</a>
<br />
<?php 
    }
    function displayFormFeatures($obj, $languages, $defaultLanguage)
    {
        global $cookie, $currentIndex;
        if ($obj->id) {
            $feature = Feature::getFeatures(intval($cookie->id_lang));
            $ctab = '';
            foreach ($feature as $tab) {
                $ctab .= 'ccustom_' . $tab['id_feature'] . '¤';
            }
            $ctab = rtrim($ctab, '¤');
            echo '
			<table cellpadding="5">
				<tr>
					<td colspan="2"><b>' . $this->l('Assign features to this product') . '</b></td>
				</tr>
			</table>
			<hr style="width:730px;"><br />';
            // Header
            $nb_feature = Feature::nbFeatures(intval($cookie->id_lang));
            echo '
			<table border="0" cellpadding="0" cellspacing="0" class="table" style="width:600px;">
				<tr>
					<th>' . $this->l('Features') . '</td>
					<th style="width:220px">' . $this->l('Value') . '</td>
					<th style="width:170px">' . $this->l('Customized') . '</td>
				</tr>';
            if (!$nb_feature) {
                echo '<tr><td colspan="3" style="text-align:center;">' . $this->l('No features defined') . '</td></tr>';
            }
            echo '</table>';
            // Listing
            if ($nb_feature) {
                echo '
				<table cellpadding="5" style="width:600px; margin-top:10px">';
                foreach ($feature as $tab_features) {
                    $current_item = false;
                    $custom = false;
                    $product_features = $obj->getFeatures();
                    foreach ($product_features as $tab_products) {
                        if ($tab_products['id_feature'] == $tab_features['id_feature']) {
                            $current_item = $tab_products['id_feature_value'];
                        }
                    }
                    echo '
					<tr>
						<td>' . $tab_features['name'] . '</td>
						<td style="width:220px">
							<select name="feature_' . $tab_features['id_feature'] . '_value">
							<option value="0">---&nbsp;</option>';
                    $feature_values = FeatureValue::getFeatureValues($tab_features['id_feature']);
                    foreach ($feature_values as $tab_values) {
                        if (!$tab_values['custom']) {
                            $value = FeatureValue::selectLang(FeatureValue::getFeatureValueLang($tab_values['id_feature_value']), intval($cookie->id_lang));
                            echo '<option value="' . $tab_values['id_feature_value'] . '"' . ($current_item == $tab_values['id_feature_value'] ? ' selected="selected"' : '') . '>' . substr($value, 0, 40) . (Tools::strlen($value) > 40 ? '...' : '') . '&nbsp;</option>';
                        } else {
                            $custom = true;
                        }
                    }
                    echo '
							</select>
						</td>
						<td style="width:170px">';
                    $tab_customs = array();
                    if ($custom) {
                        $tab_customs = FeatureValue::getFeatureValueLang($current_item);
                    }
                    foreach ($languages as $language) {
                        $custom_lang = FeatureValue::selectLang($tab_customs, $language['id_lang']);
                        echo '
								<div id="ccustom_' . $tab_features['id_feature'] . '_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left;">
									<input type="text" name="custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'] . '" size="20" value="' . htmlentities(Tools::getValue('custom_' . $tab_features['id_feature'] . '_' . $language['id_lang'], $custom_lang), ENT_COMPAT, 'UTF-8') . '" />
								</div>';
                    }
                    $this->displayFlags($languages, $defaultLanguage, $ctab, 'ccustom_' . $tab_features['id_feature']);
                    echo '
						</td>
					</tr>';
                }
                echo '
				<tr>
					<td>&nbsp;</td>
					<td style="height:50px; " valign="bottom"><input type="submit" name="submitProductFeature" id="submitProductFeature" value="' . $this->l('Update features') . '" class="button" /></td>
				</tr>';
            }
            echo '</table>
			<hr style="width:730px;">
			<div style="text-align:center;">
				<a href="index.php?tab=AdminFeatures&addfeature&token=' . Tools::getAdminToken('AdminFeatures' . intval(Tab::getIdFromClassName('AdminFeatures')) . intval($cookie->id_employee)) . '" onclick="return confirm(\'' . $this->l('Are you sure you want to delete entered product information?', __CLASS__, true, false) . '\');"><img src="../img/admin/add.gif" alt="new_features" title="' . $this->l('Create new features') . '" />&nbsp;' . $this->l('Create new features') . '</a>
			</div>';
        } else {
            echo '<b>' . $this->l('You must save this product before adding features') . '.</b>';
        }
    }
    public function productImport()
    {
        $this->receiveTab();
        $handle = $this->openCsvFile();
        $default_language_id = (int) Configuration::get('PS_LANG_DEFAULT');
        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']);
            } else {
                if (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 (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
                $product->loadStockData();
                $category_data = Product::getProductCategories((int) $product->id);
                foreach ($category_data as $tmp) {
                    $product->category[] = $tmp;
                }
            }
            AdminImportController::setEntityDefaultValues($product);
            AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
            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 (!is_numeric($shop)) {
                    $product->id_shop_list[] = Shop::getIdByName($shop);
                } else {
                    $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;
            } else {
                if (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) ? $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;
            } else {
                if (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) ? $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;
            } else {
                if (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, '.', '');
                    }
                } else {
                    if (isset($product->price_tin) && isset($product->price_tex)) {
                        $product->price = $product->price_tex;
                    }
                }
            }
            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) ? $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();
                            }
                        }
                    } else {
                        if (is_string($value) && !empty($value)) {
                            $category = Category::searchByName($default_language_id, trim($value), true);
                            if ($category['id_category']) {
                                $product->id_category[] = (int) $category['id_category'];
                            } else {
                                $category_to_create = new Category();
                                if (!Shop::isFeatureActive()) {
                                    $category_to_create->id_shop_default = 1;
                                } else {
                                    $category_to_create->id_shop_default = (int) Context::getContext()->shop->id;
                                }
                                $category_to_create->name = AdminImportController::createMultiLangField(trim($value));
                                $category_to_create->active = 1;
                                $category_to_create->id_parent = (int) 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) ? $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();
                                }
                            }
                        }
                    }
                }
            }
            $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : '';
            $link_rewrite = is_array($product->link_rewrite) && count($product->link_rewrite) ? trim($product->link_rewrite[$default_language_id]) : '';
            $valid_link = Validate::isLinkRewrite($link_rewrite);
            if (isset($product->link_rewrite[$default_language_id]) && empty($product->link_rewrite[$default_language_id]) || !$valid_link) {
                $link_rewrite = Tools::link_rewrite($product->name[$default_language_id]);
                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[$default_language_id], isset($info['id']) ? $info['id'] : 'null', $link_rewrite);
            }
            $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
            // replace the value of separator by coma
            if ($this->multiple_value_separator != ',') {
                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') == 1 && $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` = "' . $product->reference . '"
					');
                    $product->id = (int) $datas['id_product'];
                    $product->date_add = pSQL($datas['date_add']);
                    $res = $product->update();
                } else {
                    if ($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
                if (!$res) {
                    if (isset($product->date_add) && $product->date_add != '') {
                        $res = $product->add(false);
                    } else {
                        $res = $product->add();
                    }
                }
            }
            $shops = array();
            $product_shop = explode($this->multiple_value_separator, $product->shop);
            foreach ($product_shop as $shop) {
                $shop = trim($shop);
                if (!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']) ? Tools::safeOutput($info['name']) : 'No Name', isset($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_supplier) && isset($product->supplier_reference)) {
                    $id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                    if ($id_product_supplier) {
                        $product_supplier = new ProductSupplier((int) $id_product_supplier);
                    } else {
                        $product_supplier = new ProductSupplier();
                    }
                    $product_supplier->id_product = $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = $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 (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                    $specific_price = new SpecificPrice();
                    $specific_price->id_product = (int) $product->id;
                    // @todo multishop specific price import
                    $specific_price->id_shop = $this->context->shop->id;
                    $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->add()) {
                        $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                    }
                }
                if (isset($product->tags) && !empty($product->tags)) {
                    // Delete tags for this id product, for no duplicating error
                    Tag::deleteTagsForProduct($product->id);
                    if (!is_array($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();
                    } else {
                        if (isset($product->image) && is_array($product->image) && count($product->image)) {
                            $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 (@fopen($url, 'r') == false) {
                                $error = true;
                            } else {
                                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)) {
                                        $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 n°%1$d: the picture cannot be saved: %2$s'), $image->id_product, $url);
                        }
                    }
                }
                if (isset($product->id_category)) {
                    $product->updateCategories(array_map('intval', $product->id_category));
                }
                // 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) {
                        $tab_feature = explode(':', $single_feature);
                        $feature_name = trim($tab_feature[0]);
                        $feature_value = trim($tab_feature[1]);
                        $position = isset($tab_feature[2]) ? $tab_feature[2] : false;
                        if (!empty($feature_name) && !empty($feature_value)) {
                            $id_feature = Feature::addFeatureImport($feature_name, $position);
                            $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $feature_value);
                            Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                        }
                    }
                }
                // clean feature positions to avoid conflict
                Feature::cleanPositions();
            }
            // stock available
            if (Shop::isFeatureActive()) {
                foreach ($shops as $shop) {
                    StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, (int) $shop);
                }
            } else {
                StockAvailable::setQuantity((int) $product->id, 0, $product->quantity, $this->context->shop->id);
            }
        }
        $this->closeCsvFile($handle);
    }