/** * Search a specific string in the products and categories * * @params string $query String to find in the catalog */ public function searchCatalog($query) { global $cookie; $this->_list['products'] = Product::searchByName((int) $cookie->id_lang, $query); if (!empty($this->_list['products'])) { for ($i = 0; $i < count($this->_list['products']); $i++) { $this->_list['products'][$i]['nameh'] = str_ireplace($query, '<span class="highlight">' . Tools::htmlentitiesUTF8($query) . '</span>', $this->_list['products'][$i]['name']); } } $this->_list['categories'] = Category::searchByName((int) $cookie->id_lang, $query); }
/** * Search a specific string in the products and categories * * @params string $query String to find in the catalog */ public function searchCatalog($query) { global $cookie; $products = false; if (Validate::isCatalogName($query)) { $this->_list['products'] = Product::searchByName(intval($cookie->id_lang), $query); if (!empty($this->_list['products'])) { for ($i = 0; $i < count($this->_list['products']); $i++) { $this->_list['products'][$i]['nameh'] = str_ireplace($query, '<span class="highlight">' . $query . '</span>', $this->_list['products'][$i]['name']); } } } if (Validate::isCatalogName($query)) { $this->_list['categories'] = Category::searchByName(intval($cookie->id_lang), $query); } }
/** * Search a specific string in the products and categories * * @params string $query String to find in the catalog */ public function searchCatalog() { $this->context = Context::getContext(); $this->_list['products'] = Product::searchByName($this->context->language->id, $this->query); $this->_list['categories'] = Category::searchByName($this->context->language->id, $this->query); }
/** * Search with Pathes for categories * * @param int $id_lang Language ID * @param string $path of category * @param bool $object_to_create a category * * @param bool $method_to_create a category * @return array Corresponding categories */ public static function searchByPath($id_lang, $path, $object_to_create = false, $method_to_create = false) { $categories = explode('/', trim($path)); $category = $id_parent_category = false; if (is_array($categories) && count($categories)) { foreach ($categories as $category_name) { if ($id_parent_category) { $category = Category::searchByNameAndParentCategoryId($id_lang, $category_name, $id_parent_category); } else { $category = Category::searchByName($id_lang, $category_name, true, true); } if (!$category && $object_to_create && $method_to_create) { call_user_func_array(array($object_to_create, $method_to_create), array($id_lang, $category_name, $id_parent_category)); $category = Category::searchByPath($id_lang, $category_name); } if (isset($category['id_category']) && $category['id_category']) { $id_parent_category = (int) $category['id_category']; } } } return $category; }
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); }
protected function categoryImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, &$cat_moved, $validateOnly = false) { $tab_categ = array(Configuration::get('PS_HOME_CATEGORY'), Configuration::get('PS_ROOT_CATEGORY')); if (isset($info['id']) && in_array((int) $info['id'], $tab_categ)) { $this->errors[] = Tools::displayError('The category ID must be unique. It can\'t be the same as the one for Root or Home category.'); return; } AdminImportController::setDefaultValues($info); if ($force_ids && isset($info['id']) && (int) $info['id']) { $category = new Category((int) $info['id']); } else { if (isset($info['id']) && (int) $info['id'] && Category::existsInDatabase((int) $info['id'], 'category')) { $category = new Category((int) $info['id']); } else { $category = new Category(); } } AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $category); // Parent category if (isset($category->parent) && is_numeric($category->parent)) { // Validation for parenting itself if ($validateOnly && $category->parent == $category->id || isset($info['id']) && $category->parent == (int) $info['id']) { $this->errors[] = sprintf(Tools::displayError('The category ID must be unique. It can\'t be the same as the one for the parent category (ID: %1$s).'), isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); return; } if (isset($cat_moved[$category->parent])) { $category->parent = $cat_moved[$category->parent]; } $category->id_parent = $category->parent; } elseif (isset($category->parent) && is_string($category->parent)) { // Validation for parenting itself if ($validateOnly && isset($category->name) && $category->parent == $category->name) { $this->errors[] = sprintf(Tools::displayError('A category can\'t be its own parent. You should rename it (current name: %1$s).'), $category->parent); return; } $category_parent = Category::searchByName($id_lang, $category->parent, true); if ($category_parent['id_category']) { $category->id_parent = (int) $category_parent['id_category']; $category->level_depth = (int) $category_parent['level_depth'] + 1; } else { $category_to_create = new Category(); $category_to_create->name = AdminImportController::createMultiLangField($category->parent); $category_to_create->active = 1; $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$id_lang]); $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite); $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create 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()) { $category->id_parent = $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[$id_lang], 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(); } } } } if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id])) { $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]); } else { $valid_link = false; } if (!$shop_is_feature_active) { $category->id_shop_default = 1; } else { $category->id_shop_default = (int) Context::getContext()->shop->id; } $bak = $category->link_rewrite[$default_language_id]; if (isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id]) || !$valid_link) { $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]); if ($category->link_rewrite == '') { $category->link_rewrite = 'friendly-url-autogeneration-failed'; $this->warnings[] = sprintf($this->trans('URL rewriting failed to auto-generate a friendly URL for: %s', array(), 'Admin.Parameters.Notification'), $category->name[$default_language_id]); } $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite); } 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'), $bak, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $category->link_rewrite[$default_language_id]); } $res = false; if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors)) { $category_already_created = Category::searchByNameAndParentCategoryId($id_lang, $category->name[$id_lang], $category->id_parent); // If category already in base, get id category back if ($category_already_created['id_category']) { $cat_moved[$category->id] = (int) $category_already_created['id_category']; $category->id = (int) $category_already_created['id_category']; if (Validate::isDate($category_already_created['date_add'])) { $category->date_add = $category_already_created['date_add']; } } if ($category->id && $category->id == $category->id_parent) { $this->errors[] = sprintf($this->trans('A category cannot be its own parent. The parent category ID is either missing or unknown (ID: %1$s).', array(), 'Admin.Parameters.Notification'), isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null'); return; } /* No automatic nTree regeneration for import */ $category->doNotRegenerateNTree = true; // If id category AND id category already in base, trying to update $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY')); if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root) && !$validateOnly) { $res = $category->update(); } if ($category->id == Configuration::get('PS_ROOT_CATEGORY')) { $this->errors[] = $this->trans('The root category cannot be modified.', array(), 'Admin.Parameters.Notification'); } // If no id_category or update failed $category->force_id = (bool) $force_ids; if (!$res && !$validateOnly) { $res = $category->add(); } } // ValidateOnly mode : stops here if ($validateOnly) { return; } //copying images of categories if (isset($category->image) && !empty($category->image)) { if (!AdminImportController::copyImg($category->id, null, $category->image, 'categories', !$regenerate)) { $this->warnings[] = $category->image . ' ' . $this->trans('cannot be copied.', array(), 'Admin.Parameters.Notification'); } } // If both failed, mysql error if (!$res) { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be ' . ($validateOnly ? 'validated' : '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'); $error_tmp = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); if ($error_tmp != '') { $this->errors[] = $error_tmp; } } else { // Associate category to shop if ($shop_is_feature_active) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'category_shop WHERE id_category = ' . (int) $category->id); 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']); foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $category->addShop(Shop::getIdByName($shop)); } elseif (!empty($shop)) { $category->addShop($shop); } } } } }
$prod = new Product((int) Tools::getValue('id'), false, $obj->getCurrentIdLang()); die($prod->name); } if (Tools::getValue('action') == 'categoryname') { $obj = new Segmentation(); $cat = new Category((int) Tools::getValue('id'), $obj->getCurrentIdLang()); die($cat->name); } if (Tools::getValue('action') == 'brandname') { $obj = new Segmentation(); $man = new Manufacturer((int) Tools::getValue('id'), $obj->getCurrentIdLang()); die($man->name); } if (Tools::getValue('action') == 'category') { if (Tools::getValue('name') != '') { $products = Category::searchByName(Configuration::get('PS_LANG_DEFAULT'), Tools::getValue('name')); if ($products) { $i = 0; $return = '<ul id="plugproduct' . Tools::safeOutput(Tools::getValue('id')) . '">'; foreach ($products as $product) { $name = str_replace("'", '’', $product['name']); $name = str_replace('"', '\\"', $name); if ($i % 2 == 0) { $return .= '<li id="' . Tools::safeOutput($product['id_category']) . '" class="pair">' . Tools::safeOutput($name) . '</li>'; } else { $return .= '<li id="' . Tools::safeOutput($product['id_category']) . '" class="impair">' . Tools::safeOutput($name) . '</li>'; } $i++; } $return .= '</ul>'; }
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); }
public function categoryImport() { $cat_moved = array(); $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(); 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); $tab_categ = array(Configuration::get('PS_HOME_CATEGORY'), Configuration::get('PS_ROOT_CATEGORY')); if (isset($info['id']) && in_array((int) $info['id'], $tab_categ)) { $this->errors[] = Tools::displayError('The category ID cannot be the same as the Root category ID or the Home category ID.'); continue; } AdminImportController::setDefaultValues($info); if (Tools::getValue('forceIDs') && isset($info['id']) && (int) $info['id']) { $category = new Category((int) $info['id']); } else { if (isset($info['id']) && (int) $info['id'] && Category::existsInDatabase((int) $info['id'], 'category')) { $category = new Category((int) $info['id']); } else { $category = new Category(); } } AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $category); if (isset($category->parent) && is_numeric($category->parent)) { if (isset($cat_moved[$category->parent])) { $category->parent = $cat_moved[$category->parent]; } $category->id_parent = $category->parent; } elseif (isset($category->parent) && is_string($category->parent)) { $category_parent = Category::searchByName($id_lang, $category->parent, true); if ($category_parent['id_category']) { $category->id_parent = (int) $category_parent['id_category']; $category->level_depth = (int) $category_parent['level_depth'] + 1; } else { $category_to_create = new Category(); $category_to_create->name = AdminImportController::createMultiLangField($category->parent); $category_to_create->active = 1; $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$id_lang]); $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite); $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create 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()) { $category->id_parent = $category_to_create->id; } else { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), $category_to_create->name[$id_lang], 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(); } } } if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id])) { $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]); } else { $valid_link = false; } if (!Shop::isFeatureActive()) { $category->id_shop_default = 1; } else { $category->id_shop_default = (int) Context::getContext()->shop->id; } $bak = $category->link_rewrite[$default_language_id]; if (isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id]) || !$valid_link) { $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]); if ($category->link_rewrite == '') { $category->link_rewrite = 'friendly-url-autogeneration-failed'; $this->warnings[] = sprintf(Tools::displayError('URL rewriting failed to auto-generate a friendly URL for: %s'), $category->name[$default_language_id]); } $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite); } if (!$valid_link) { $this->warnings[] = sprintf(Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), $bak, isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $category->link_rewrite[$default_language_id]); } $res = false; if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors)) { $category_already_created = Category::searchByNameAndParentCategoryId($id_lang, $category->name[$id_lang], $category->id_parent); // If category already in base, get id category back if ($category_already_created['id_category']) { $cat_moved[$category->id] = (int) $category_already_created['id_category']; $category->id = (int) $category_already_created['id_category']; if (Validate::isDate($category_already_created['date_add'])) { $category->date_add = $category_already_created['date_add']; } } if ($category->id && $category->id == $category->id_parent) { $this->errors[] = Tools::displayError('A category cannot be its own parent'); continue; } /* No automatic nTree regeneration for import */ $category->doNotRegenerateNTree = true; // If id category AND id category already in base, trying to update $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY')); if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root)) { $res = $category->update(); } if ($category->id == Configuration::get('PS_ROOT_CATEGORY')) { $this->errors[] = Tools::displayError('The root category cannot be modified.'); } // If no id_category or update failed $category->force_id = (bool) Tools::getValue('forceIDs'); if (!$res) { $res = $category->add(); } } //copying images of categories if (isset($category->image) && !empty($category->image)) { if (!AdminImportController::copyImg($category->id, null, $category->image, 'categories', !Tools::getValue('regenerate'))) { $this->warnings[] = $category->image . ' ' . Tools::displayError('cannot be copied.'); } } // If both failed, mysql error if (!$res) { $this->errors[] = sprintf(Tools::displayError('%1$s (ID: %2$s) cannot be saved'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID'); $error_tmp = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError(); if ($error_tmp != '') { $this->errors[] = $error_tmp; } } else { // Associate category to shop if (Shop::isFeatureActive()) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'category_shop WHERE id_category = ' . (int) $category->id); if (!Shop::isFeatureActive()) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $category->addShop(Shop::getIdByName($shop)); } elseif (!empty($shop)) { $category->addShop($shop); } } } } } /* Import has finished, we can regenerate the categories nested tree */ Category::regenerateEntireNtree(); $this->closeCsvFile($handle); }
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); }