public function postProcess() { global $currentIndex, $cookie, $smarty; $product_ids = Tools::getValue('product_ids'); $group_id = 0; if ($product_ids) { $group_id = Tools::getValue('group_id'); $ids = explode(",", $product_ids); //update previous curated products $sql = "SELECT group_concat(id_product) FROM vb_product_groups WHERE id_group_type = 1 AND id_group = 1"; $res = Db::getInstance()->ExecuteS($sql); $productIds = array(); foreach ($res as $row) { $productIds[] = $row['id_product']; } SolrSearch::updateProducts($productIds); Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute("\r\n\t\t delete from vb_product_groups where id_group_type = 1 and id_group = " . $group_id); Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute("\r\n\t\t \t\tdelete from ps_category_product where id_category = " . CAT_CURATED); foreach ($ids as $product_id) { if (!$product_id) { continue; } Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute("\n\t\t insert into vb_product_groups (id_group_type, id_group, id_product)\n\t\t values (1, " . $group_id . ", " . $product_id . ")\n\t\t "); Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute("\r\n\t\t \t\tinsert into ps_category_product (id_category, id_product, position)\r\n\t\t \t\tvalues (" . CAT_CURATED . ", " . $product_id . ", 1)\r\n\t\t \t\t"); SolrSearch::updateProduct($product_id); } } //home products $product_ids = $this->assign_products('curated_products', 'curated_product_ids', 1); $smarty->assign('productToken', Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee)); }
exit; } else { //delete the original image @unlink($image_path); } } else { print_r($fieldError); print_r($langFieldError); exit; } } $first_image = false; } array_push($products, $id_product); } SolrSearch::updateProducts($products); } else { echo "There was an error in reading the file, please try again or report this incident"; } } else { echo "There was an error in reading the file, please try again or report this incident"; } } if (Tools::getValue('combqty')) { ini_set('max_execution_time', 0); ini_set('memory_limit', '-1'); header("Cache-Control: no-store, no-cache"); header('Content-Encoding: UTF-8'); header('Content-type: text/csv; charset=UTF-8'); header('Content-Disposition: attachment; filename="products-qty.csv"'); $outstream = fopen("php://output", 'w');
public static function indexation($full = false) { $db = Db::getInstance(); $dropIndex = false; if ($full) { $db->Execute('TRUNCATE ' . _DB_PREFIX_ . 'search_index'); $db->Execute('TRUNCATE ' . _DB_PREFIX_ . 'search_word'); $db->Execute('UPDATE ' . _DB_PREFIX_ . 'product SET indexed = 0'); $dropIndex = true; } else { $products = $db->ExecuteS('SELECT id_product FROM ' . _DB_PREFIX_ . 'product WHERE indexed = 0'); $ids = array(); if ($products) { foreach ($products as $product) { $ids[] = (int) $product['id_product']; } } if (sizeof($ids)) { //$db->Execute('DELETE FROM '._DB_PREFIX_.'search_index WHERE id_product IN ('.implode(',', $ids).')'); //reindex the products in solr index SolrSearch::updateProducts($ids); $products = $db->ExecuteS('UPDATE ' . _DB_PREFIX_ . 'product set indexed = 1 WHERE indexed = 0'); } if (count($ids)) { Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'product SET indexed = 1 WHERE id_product IN (' . implode(',', $ids) . ') LIMIT ' . (int) count($ids)); } if (count($products) > 2000) { $dropIndex = true; } } //do not do anything to the db index return; if ($dropIndex) { $dropIndex = false; $result = $db->ExecuteS('SHOW INDEX FROM `' . _DB_PREFIX_ . 'search_index`'); foreach ($result as $row) { if (strtolower($row['Key_name']) == 'primary') { $dropIndex = true; } } if ($dropIndex) { $db->Execute('ALTER TABLE ' . _DB_PREFIX_ . 'search_index DROP PRIMARY KEY'); } $dropIndex = true; } // Every fields are weighted according to the configuration in the backend $weightArray = array('pname' => Configuration::get('PS_SEARCH_WEIGHT_PNAME'), 'reference' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'ean13' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'upc' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'description_short' => Configuration::get('PS_SEARCH_WEIGHT_SHORTDESC'), 'description' => Configuration::get('PS_SEARCH_WEIGHT_DESC'), 'cname' => Configuration::get('PS_SEARCH_WEIGHT_CNAME'), 'mname' => Configuration::get('PS_SEARCH_WEIGHT_MNAME'), 'tags' => Configuration::get('PS_SEARCH_WEIGHT_TAG'), 'attributes' => Configuration::get('PS_SEARCH_WEIGHT_ATTRIBUTE'), 'features' => Configuration::get('PS_SEARCH_WEIGHT_FEATURE')); // All the product not yet indexed are retrieved $products = $db->ExecuteS(' SELECT p.id_product, pl.id_lang, pl.name pname, p.reference, p.ean13, p.upc, pl.description_short, pl.description, cl.name cname, m.name mname FROM ' . _DB_PREFIX_ . 'product p LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = p.id_category_default AND pl.id_lang = cl.id_lang) LEFT JOIN ' . _DB_PREFIX_ . 'manufacturer m ON m.id_manufacturer = p.id_manufacturer WHERE p.indexed = 0', false); // Those are kind of global variables required to save the processed data in the database every X occurences, in order to avoid overloading MySQL $countWords = 0; $countProducts = 0; $queryArray3 = array(); $productsArray = array(); // Every indexed words are cached into a PHP array $wordIdsByWord = array(); $wordIds = Db::getInstance()->ExecuteS(' SELECT sw.id_word, sw.word, id_lang FROM ' . _DB_PREFIX_ . 'search_word sw', false); $wordIdsByWord = array(); while ($wordId = $db->nextRow($wordIds)) { if (!isset($wordIdsByWord[$wordId['id_lang']])) { $wordIdsByWord[$wordId['id_lang']] = array(); } $wordIdsByWord[$wordId['id_lang']]['_' . $wordId['word']] = (int) $wordId['id_word']; } // Now each non-indexed product is processed one by one, langage by langage while ($product = $db->nextRow($products)) { $product['tags'] = Search::getTags($db, (int) $product['id_product'], (int) $product['id_lang']); $product['attributes'] = Search::getAttributes($db, (int) $product['id_product'], (int) $product['id_lang']); $product['features'] = Search::getFeatures($db, (int) $product['id_product'], (int) $product['id_lang']); // Data must be cleaned of html, bad characters, spaces and anything, then if the resulting words are long enough, they're added to the array $pArray = array(); foreach ($product as $key => $value) { if (strncmp($key, 'id_', 3)) { $words = explode(' ', Search::sanitize($value, (int) $product['id_lang'], true)); foreach ($words as $word) { if (!empty($word)) { $word = Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH); if (!isset($pArray[$word])) { $pArray[$word] = 0; } $pArray[$word] += $weightArray[$key]; } } } } // If we find words that need to be indexed, they're added to the word table in the database if (sizeof($pArray)) { $list = ''; foreach ($pArray as $word => $weight) { $list .= '\'' . $word . '\','; } $list = rtrim($list, ','); $queryArray = array(); $queryArray2 = array(); foreach ($pArray as $word => $weight) { if ($weight and !isset($wordIdsByWord['_' . $word])) { $queryArray[] = '(' . (int) $product['id_lang'] . ',\'' . pSQL($word) . '\')'; $queryArray2[] = '\'' . pSQL($word) . '\''; $wordIdsByWord[$product['id_lang']]['_' . $word] = 0; } } if (count($queryArray)) { // The words are inserted... $db->Execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'search_word (id_lang, word) VALUES ' . implode(',', $queryArray)); // ...then their IDs are retrieved and added to the cache $addedWords = $db->ExecuteS(' SELECT sw.id_word, sw.word FROM ' . _DB_PREFIX_ . 'search_word sw WHERE sw.word IN (' . implode(',', $queryArray2) . ') AND sw.id_lang = ' . (int) $product['id_lang'] . ' LIMIT ' . count($queryArray2)); foreach ($addedWords as $wordId) { $wordIdsByWord[$product['id_lang']]['_' . $wordId['word']] = (int) $wordId['id_word']; } } } foreach ($pArray as $word => $weight) { if (!$weight) { continue; } if (!isset($wordIdsByWord[$product['id_lang']]['_' . $word])) { continue; } if (!$wordIdsByWord[$product['id_lang']]['_' . $word]) { continue; } $queryArray3[] = '(' . (int) $product['id_product'] . ',' . (int) $wordIdsByWord[$product['id_lang']]['_' . $word] . ',' . (int) $weight . ')'; // Force save every 200 words in order to avoid overloading MySQL if (++$countWords % 200 == 0) { Search::saveIndex($queryArray3); } } if (!in_array($product['id_product'], $productsArray)) { $productsArray[] = (int) $product['id_product']; } // Force save every 50 products in order to avoid overloading MySQL if (++$countProducts % 50 == 0) { Search::setProductsAsIndexed($productsArray); } } // One last save is done at the end in order to save what's left Search::saveIndex($queryArray3); Search::setProductsAsIndexed($productsArray); // If it has been deleted, the index is created again once the indexation is done if (!$dropIndex) { $dropIndex = true; $result = $db->ExecuteS('SHOW INDEX FROM `' . _DB_PREFIX_ . 'search_index`'); foreach ($result as $row) { if (strtolower($row['Key_name']) == 'primary') { $dropIndex = false; } } } if ($dropIndex) { $db->Execute('ALTER TABLE `' . _DB_PREFIX_ . 'search_index` ADD PRIMARY KEY (`id_word`, `id_product`)'); } Configuration::updateValue('PS_NEED_REBUILD_INDEX', 0); return true; }
public function handleConfirm($update = false) { global $currentIndex, $cookie, $smarty; $products_to_import = array(); $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT'); $file_path = Tools::getValue('current_file'); $overwrite_imgs = Tools::getValue("overwrite_imgs"); //$file_path = '/Users/rohit/webroot/indusdiva/admin12/product-uploads/upload_sheet_1.csv'; $f = fopen($file_path, 'r'); $file_error = false; if ($f) { //discard header $line = fgetcsv($f); while ($line = fgetcsv($f)) { //ignore empty lines if (empty($line)) { continue; } //trim data foreach ($line as $key => $value) { $line[$key] = trim($value); } $id_product = $line[0]; $images = $line[1]; $product_name = $line[2]; $fabric = $line[3]; $color = $line[4]; $mrp = $line[5]; $supplier_code = $line[6]; $reference = $line[7]; $location = $line[8]; $length = $line[9]; $width = $line[10]; $blouse_length = $line[11]; $garment_type = $line[12]; $work_type = $line[13]; $weight = $line[14]; $description = $line[15]; $other_info = $line[16]; $wash_care = $line[17]; $shipping_estimate = $line[18]; $supplier_price = $line[19]; $manufacturer = $line[20]; $categories = explode(",", $line[21]); $tax_rule = $line[22]; $quantity = $line[23]; $active = $line[24]; $discount = $line[25]; $tags = $line[26]; $kameez_style = $line[27]; $salwar_style = $line[28]; $sleeves = $line[29]; $customizable = $line[30]; $generic_color = $line[31]; $skirt_length = $line[32]; $dupatta_length = $line[33]; $stone = $line[34]; $plating = $line[35]; $material = $line[36]; $dimensions = $line[37]; $look = $line[38]; $as_shown = isset($line[39]) && !empty($line[39]) ? intval($line[39]) : 0; $id_sizechart = isset($line[40]) && !empty($line[40]) ? intval($line[40]) : 0; $is_exclusive = isset($line[41]) && !empty($line[41]) ? intval($line[41]) : 0; $handbag_occasion = isset($line[42]) && !empty($line[42]) ? $line[42] : null; $handbag_style = isset($line[43]) && !empty($line[43]) ? $line[43] : null; $handbag_material = isset($line[44]) && !empty($line[44]) ? $line[44] : null; $images = explode(",", $images); $error = false; //validate fields if (!Validate::isFloat($mrp)) { $error = 'MRP should be a number: ' . trim($reference); } elseif (!Validate::isFloat($supplier_price)) { $error = 'Supplier Price should be a number: ' . trim($reference); } $importCategories = array(); if (is_array($categories)) { $categories = array_unique($categories); foreach ($categories as $category) { $category = intval(trim($category)); if (empty($category)) { continue; } if (!is_numeric($category) || !Category::categoryExists($category)) { $error = 'Category does not exist: ' . $category; } $importCategories[] = $category; } } else { $error = 'Atleast one category required: ' . trim($reference); } if (!Validate::isFloat($weight)) { $error = 'Weight has to be a number: ' . trim($reference); } if (!empty($manufacturer) && (!is_numeric($manufacturer) || !Manufacturer::manufacturerExists((int) $manufacturer))) { $error = 'Manufacturer does not exist'; } if ($quantity && !is_numeric($quantity) || $discount && !is_numeric($discount)) { $error = 'Quantity and discount should be numbers: ' . trim($reference); } if (!Validate::isLoadedObject(new TaxRulesGroup($tax_rule))) { $error = 'Tax rate invalid: ' . trim($reference); } if (!$update) { $sql = "SELECT `reference`\n\t\t\t\t\t\t\tFROM " . _DB_PREFIX_ . "product p\n\t\t\t\t\t\t\tWHERE p.`reference` = '" . $reference . "'"; $row = Db::getInstance()->getRow($sql); if (isset($row['reference'])) { $error = "Duplicate indusdiva code : " . trim($reference); } } //check for souring price if ($supplier_price > $mrp / 1.2) { $error = "MRP too low : " . trim($reference); } //check for images if (!$update || $overwrite_imgs == "on") { foreach ($images as $image_name) { $image_name = trim($image_name); $image_path = IMAGE_UPLOAD_PATH . $image_name; if (!empty($image_name) && !file_exists($image_path)) { $error = "Image not found for: " . trim($reference) . ", Image Name: " . $image_name; break; } } } $vendor_code = substr($reference, 0, 6); $sql = "select id_supplier from ps_supplier where code = '{$vendor_code}'"; $row = Db::getInstance()->getRow($sql); if (!isset($row['id_supplier'])) { $error = "Vendor Details not found for : " . trim($reference); } else { $id_supplier = $row['id_supplier']; } //For sudarshan, supplier_code (vendor product code) is mandatory if (false) { //(int) $id_supplier === 2 ) { if (empty($supplier_code)) { $error = "Reference: {$reference} -- Supplier Code is Mandatory for Vendor {$vendor_code}"; } else { if (strpos("::", ${$supplier_code}) === false) { $error = "Reference: {$reference} -- Supplier Code:{$supplier_code} is not in DESIGN_NO::ITEM_CODE format for Vendor {$vendor_code}"; } } } if (!$error) { if ($update && !empty($id_product)) { $product = new Product((int) $id_product); if (!Validate::isLoadedObject($product)) { $error = "Error loading the product: " . $id_product; return; } } elseif (!$update) { $product = new Product(); } $product->id_tax_rules_group = $tax_rule; $product->reference = $reference; $product->id_supplier = $id_supplier; $product->location = $location; $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0); if (isset($manufacturer) and is_numeric($manufacturer) and Manufacturer::manufacturerExists((int) $manufacturer)) { $product->id_manufacturer = $manufacturer; } $product->price = (double) $mrp; $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', ''); $product->id_category = $importCategories; $product->id_category_default = 1; $product->name = array(); $product->name[$defaultLanguageId] = $product_name; $product->description_short = array(); $product->description_short[$defaultLanguageId] = $style_tips; $product->description = array(); $product->description[$defaultLanguageId] = $description; $link_rewrite = Tools::link_rewrite($product->name[$defaultLanguageId]); $product->link_rewrite = array(); $product->link_rewrite[$defaultLanguageId] = $link_rewrite; $product->quantity = $quantity ? intval($quantity) : 0; if ($discount && is_numeric($discount)) { $product->discount = $discount; } if (!empty($tags)) { $product->tags = $tags; } $product->weight = is_numeric($weight) ? $weight : 0; $product->width = is_numeric($width) ? $width : 0; $product->height = is_numeric($length) ? $length : 0; $product->supplier_reference = $supplier_code; $product->wholesale_price = $supplier_price ? (double) $supplier_price : 0; $product->active = $active == 1 ? 1 : 0; $product->images = $images; $product->fabric = $fabric; $product->color = $color; $product->generic_color = $generic_color; $product->garment_type = $garment_type; $product->work_type = $work_type; $product->blouse_length = $blouse_length ? $blouse_length : ' '; $product->wash_care = $wash_care ? $wash_care : ' '; $product->other_info = $other_info ? $other_info : ' '; $product->shipping_estimate = $shipping_estimate ? $shipping_estimate : ' '; $product->is_customizable = $customizable == 1 ? 1 : 0; $product->kameez_style = $kameez_style; $product->salwar_style = $salwar_style; $product->sleeves = $sleeves; $product->skirt_length = $skirt_length; $product->dupatta_length = $dupatta_length; $product->stone = $stone; $product->plating = $plating; $product->material = $material; $product->dimensions = $dimensions; $product->look = $look; $product->as_shown = $as_shown; $product->id_sizechart = $id_sizechart; $product->is_exclusive = $is_exclusive; $product->handbag_occasion = $handbag_occasion; $product->handbag_style = $handbag_style; $product->handbag_material = $handbag_material; $product->indexed = 0; $products_to_import[] = $product; } else { $smarty->assign('error', $error); return; $file_error = true; } } if (!$file_error) { $added_product_ids = array(); foreach ($products_to_import as $product) { $fieldError = $product->validateFields(UNFRIENDLY_ERROR, true); $langFieldError = $product->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($fieldError === true and $langFieldError === true) { // check quantity if ($product->quantity == NULL) { $product->quantity = 0; } // If no id_product or update failed if ($update && $product->id) { $res = $product->update(); } else { $res = $product->add(); } $added_product_ids[] = $product->id; } if (isset($product->discount) && $product->discount > 0) { SpecificPrice::deleteByProductId((int) $product->id); $specificPrice = new SpecificPrice(); $specificPrice->id_product = (int) $product->id; $specificPrice->id_shop = (int) Shop::getCurrentShop(); $specificPrice->id_currency = 0; $specificPrice->id_country = 0; $specificPrice->id_group = 0; $specificPrice->from_quantity = 1; $specificPrice->reduction = $product->discount / 100; $specificPrice->reduction_type = 'percentage'; $specificPrice->from = '2012-01-01 00:00:00'; $specificPrice->to = '2016-01-01 00:00:00'; $specificPrice->price = $product->price; $specificPrice->add(); } if (isset($product->tags) and !empty($product->tags)) { // Delete tags for this id product, for no duplicating error Tag::deleteTagsForProduct($product->id); $tag = new Tag(); $tag->addTags($defaultLanguageId, $product->id, $tags); } if (isset($product->images) and is_array($product->images) and sizeof($product->images) and !$update || $overwrite_imgs == "on") { $product->deleteImages(); $first_image = true; foreach ($product->images as $image_name) { $image_name = trim($image_name); $image_path = IMAGE_UPLOAD_PATH . $image_name; if (!empty($image_name)) { $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = $first_image; $image->legend[$defaultLanguageId] = $product->name[$defaultLanguageId]; if (($fieldError = $image->validateFields(false, true)) === true and ($langFieldError = $image->validateFieldsLang(false, true)) === true and $image->add()) { if (!self::copyImg($product->id, $image->id, $image_path)) { $_warnings[] = Tools::displayError('Error copying image: ') . $image_path; } else { //delete the original image @unlink($image_path); } } else { $_warnings[] = $image->legend[$defaultLanguageId] . (isset($image->id_product) ? ' (' . $image->id_product . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } $first_image = false; } } if (isset($product->id_category)) { $product->updateCategories(array_map('intval', $product->id_category)); } $this->addFeature($product->id, 'fabric', $product->fabric); $this->addFeature($product->id, 'color', $product->color); $this->addFeature($product->id, 'garment_type', $product->garment_type); $this->addFeature($product->id, 'work_type', $product->work_type); $this->addFeature($product->id, 'blouse_length', $product->blouse_length); $this->addFeature($product->id, 'wash_care', $product->wash_care); $this->addFeature($product->id, 'other_info', $product->other_info); // to avoid type errors in the catalog sheet - construct the string here again $shipping_sla = (int) preg_replace('/\\D/', '', $product->shipping_estimate); $shipping_estimate_str = ""; if ($shipping_sla > 0) { $shipping_estimate_str = $shipping_sla === 1 ? "Ready to be shipped in 1 day" : "Ready to be shipped in {$shipping_sla} days"; } $this->addFeature($product->id, 'shipping_estimate', $shipping_estimate_str); $this->addFeature($product->id, 'kameez_style', $product->kameez_style); $this->addFeature($product->id, 'salwar_style', $product->salwar_style); $this->addFeature($product->id, 'sleeves', $product->sleeves); $this->addFeature($product->id, 'generic_color', $product->generic_color); $this->addFeature($product->id, 'skirt_length', $product->skirt_length); $this->addFeature($product->id, 'dupatta_length', $product->dupatta_length); $this->addFeature($product->id, 'stone', $product->stone); $this->addFeature($product->id, 'plating', $product->plating); $this->addFeature($product->id, 'material', $product->material); $this->addFeature($product->id, 'dimensions', $product->dimensions); $this->addFeature($product->id, 'look', $product->look); $this->addFeature($product->id, 'handbag_occasion', $product->handbag_occasion); $this->addFeature($product->id, 'handbag_style', $product->handbag_style); $this->addFeature($product->id, 'handbag_material', $product->handbag_material); } $smarty->assign("products_affected", $products_to_import); //reindex the products SolrSearch::updateProducts($added_product_ids); $smarty->assign("is_update", $update); } else { $smarty->assign('file_error', 1); } } else { $smarty->assign('error_reading', 1); } }
public function productImport() { global $cookie; $this->receiveTab(); $handle = $this->openCsvFile(); $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT'); self::setLocale(); $productIds = array(); 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 = 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); $trg_id = (int) $product->id_tax_rules_group; if ($product->id_tax_rules_group == 0 || !Validate::isLoadedObject(new TaxRulesGroup($trg_id))) { $this->_addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, Tools::displayError('Invalid tax rule group ID, you first need a group with this ID.')); } else { $product->tax_rate = TaxRulesGroup::getTaxesRate((int) $product->id_tax_rules_group, Configuration::get('PS_COUNTRY_DEFAULT'), 0, 0); } if (isset($product->manufacturer) and is_numeric($product->manufacturer) and Manufacturer::manufacturerExists((int) $product->manufacturer)) { $product->id_manufacturer = (int) $product->manufacturer; } elseif (isset($product->manufacturer) and is_string($product->manufacturer) and !empty($product->manufacturer)) { if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) { $product->id_manufacturer = (int) $manufacturer; } else { $manufacturer = new Manufacturer(); $manufacturer->name = $product->manufacturer; if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) { $product->id_manufacturer = (int) $manufacturer->id; } else { $this->_errors[] = $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } if (isset($product->supplier) and is_numeric($product->supplier) and Supplier::supplierExists((int) $product->supplier)) { $product->id_supplier = (int) $product->supplier; } elseif (isset($product->supplier) and is_string($product->supplier) and !empty($product->supplier)) { if ($supplier = Supplier::getIdByName($product->supplier)) { $product->id_supplier = (int) $supplier; } else { $supplier = new Supplier(); $supplier->name = $product->supplier; if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) { $product->id_supplier = (int) $supplier->id; } else { $this->_errors[] = $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } if (isset($product->price_tex) and !isset($product->price_tin)) { $product->price = $product->price_tex; } elseif (isset($product->price_tin) and !isset($product->price_tex)) { $product->price = $product->price_tin; // If a tax is already included in price, withdraw it from price if ($product->tax_rate) { $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', ''); } } elseif (isset($product->price_tin) and isset($product->price_tex)) { $product->price = $product->price_tex; } if (isset($product->category) and is_array($product->category) and sizeof($product->category)) { $product->id_category = array(); // Reset default values array foreach ($product->category as $value) { if (is_numeric($value)) { if (Category::categoryExists((int) $value)) { $product->id_category[] = (int) $value; } else { $categoryToCreate = new Category(); $categoryToCreate->id = (int) $value; $categoryToCreate->name = self::createMultiLangField($value); $categoryToCreate->active = 1; $categoryToCreate->id_parent = 1; // Default parent is home for unknown category to create if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) { $product->id_category[] = (int) $categoryToCreate->id; } else { $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } elseif (is_string($value) and !empty($value)) { $category = Category::searchByName($defaultLanguageId, $value, true); if ($category['id_category']) { $product->id_category[] = (int) $category['id_category']; } else { $categoryToCreate = new Category(); $categoryToCreate->name = self::createMultiLangField($value); $categoryToCreate->active = 1; $categoryToCreate->id_parent = 1; // Default parent is home for unknown category to create if (($fieldError = $categoryToCreate->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $categoryToCreate->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $categoryToCreate->add()) { $product->id_category[] = (int) $categoryToCreate->id; } else { $this->_errors[] = $categoryToCreate->name[$defaultLanguageId] . (isset($categoryToCreate->id) ? ' (' . $categoryToCreate->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved'); $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error(); } } } } } $product->id_category_default = isset($product->id_category[0]) ? (int) $product->id_category[0] : ''; $link_rewrite = is_array($product->link_rewrite) && 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 id product AND id product already in base, trying to update if ($product->id and Product::existsInDatabase((int) $product->id)) { $datas = Db::getInstance()->getRow('SELECT `date_add` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product->id); $product->date_add = pSQL($datas['date_add']); $res = $product->update(); } // If no id_product or update failed if (!$res) { $res = $product->add(); } $productIds[] = $product->id; } // 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::deleteByProductId((int) $product->id); $specificPrice = new SpecificPrice(); $specificPrice->id_product = (int) $product->id; $specificPrice->id_shop = (int) Shop::getCurrentShop(); $specificPrice->id_currency = 0; $specificPrice->id_country = 0; $specificPrice->id_group = 0; $specificPrice->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); if (sizeof($productIds)) { SolrSearch::updateProducts($productIds); } }
/** * postProcess handle every checks before saving products information * * @param mixed $token * @return void */ public function postProcess($token = NULL) { global $cookie, $currentIndex; /* Add a new product */ if (Tools::isSubmit('submitAddproduct') or Tools::isSubmit('submitAddproductAndStay') or Tools::isSubmit('submitAddProductAndPreview')) { if (Tools::getValue('id_product') and $this->tabAccess['edit'] === '1' or $this->tabAccess['add'] === '1' and !Tools::isSubmit('id_product')) { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitAddAttachments')) { if ($this->tabAccess['add'] === '1') { $languages = Language::getLanguages(false); $is_attachment_name_valid = false; foreach ($languages as $language) { $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']); if (strlen($attachment_name_lang) > 0) { $is_attachment_name_valid = true; } if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid Name'); } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) { $this->_errors[] = Tools::displayError('Name is too long'); } if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid description'); } } if (!$is_attachment_name_valid) { $this->_errors[] = Tools::displayError('Attachment Name Required'); } if (empty($this->_errors)) { if (isset($_FILES['attachment_file']) and is_uploaded_file($_FILES['attachment_file']['tmp_name'])) { if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) { $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb'); } else { do { $uniqid = sha1(microtime()); } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid)); if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) { $this->_errors[] = $this->l('File copy failed'); } @unlink($_FILES['attachment_file']['tmp_name']); } } else { if ((int) $_FILES['attachment_file']['error'] === 1) { $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $upload_mb = min($max_upload, $max_post); $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>'; } } if (empty($this->_errors) && isset($uniqid)) { $attachment = new Attachment(); foreach ($languages as $language) { if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) { $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]); } if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) { $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]); } } $attachment->file = $uniqid; $attachment->mime = $_FILES['attachment_file']['type']; $attachment->file_name = pSQL($_FILES['attachment_file']['name']); if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 64) { $this->_errors[] = Tools::displayError('Invalid file extension'); } if (!Validate::isGenericName($attachment->file_name)) { $this->_errors[] = Tools::displayError('Invalid file name'); } if (Tools::strlen($attachment->file_name) > 128) { $this->_errors[] = Tools::displayError('File name too long'); } if (!sizeof($this->_errors)) { $attachment->add(); Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Invalid file'); } } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = (int) Tools::getValue($this->identifier)) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::addProduct($product); Search::indexation(false); Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('An error occurred while creating object.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { SolrSearch::updateProduct($object->id); if ($object->toggleStatus()) { Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token); } else { $this->_errors[] = Tools::displayError('An error occurred while updating status.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; if ($this->deleted) { $object->deleteImages(); $object->deleted = 1; if ($object->update()) { SolrSearch::updateProduct($object->id); Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } } elseif ($object->delete()) { SolrSearch::updateProduct($object->id); Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } $this->_errors[] = Tools::displayError('An error occurred during deletion.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::getValue('submitDel' . $this->table)) { if ($this->tabAccess['delete'] === '1') { if (isset($_POST[$this->table . 'Box'])) { $object = new $this->className(); if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $result = true; if ($this->deleted) { $idsToUpdate = array(); foreach (Tools::getValue($this->table . 'Box') as $id) { $toDelete = new $this->className($id); $toDelete->deleted = 1; $result = $result and $toDelete->update(); $idsToUpdate[] = $id; } SolrSearch::updateProducts($idsToUpdate); } else { $result = $object->deleteSelection(Tools::getValue($this->table . 'Box')); SolrSearch::updateProducts(Tools::getValue($this->table . 'Box')); } if ($result) { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url); } $this->_errors[] = Tools::displayError('An error occurred while deleting selection.'); } } else { $this->_errors[] = Tools::displayError('You must select at least one element to delete.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $image->id_product); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . (int) $first_img['id_image']); } @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(false); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm(); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Cannot change the product cover'); } else { $productId = (int) Tools::getValue('id_product'); @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection')); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('Attribute price required.'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('You must add at least one attribute.'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('minimal_quantity')); if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) { $reason = new StockMvtReason((int) $id_reason); $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign; if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) { $this->_errors[] = Tools::displayError('An error occurred while updating qty.'); } } Hook::updateProductAttribute((int) $id_product_attribute); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } } } elseif (Tools::isSubmit('deleteProductAttribute')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute')); $product->checkDefaultAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if (!$product->hasAttributes()) { $product->cache_default_attribute = 0; $product->update(); } else { Product::updateDefaultAttribute($id_product); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('deleteAllProductAttributes')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteProductAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if ($product->cache_default_attribute) { $product->cache_default_attribute = 0; $product->update(); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attributes'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('defaultProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $product->deleteDefaultAttributes(); $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute')); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot make default attribute'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(false); foreach ($_POST as $key => $val) { if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding features.'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (Tools::isSubmit('submitPricesModification')) { $_POST['tabs'] = 5; if ($this->tabAccess['edit'] === '1') { $id_specific_prices = Tools::getValue('spm_id_specific_price'); $id_shops = Tools::getValue('spm_id_shop'); $id_currencies = Tools::getValue('spm_id_currency'); $id_countries = Tools::getValue('spm_id_country'); $id_groups = Tools::getValue('spm_id_group'); $prices = Tools::getValue('spm_price'); $from_quantities = Tools::getValue('spm_from_quantity'); $reductions = Tools::getValue('spm_reduction'); $reduction_types = Tools::getValue('spm_reduction_type'); $froms = Tools::getValue('spm_from'); $tos = Tools::getValue('spm_to'); foreach ($id_specific_prices as $key => $id_specific_price) { if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) { $specificPrice = new SpecificPrice((int) $id_specific_price); $specificPrice->id_shop = (int) $id_shops[$key]; $specificPrice->id_currency = (int) $id_currencies[$key]; $specificPrice->id_country = (int) $id_countries[$key]; $specificPrice->id_group = (int) $id_groups[$key]; $specificPrice->price = (double) $prices[$key]; $specificPrice->from_quantity = (int) $from_quantities[$key]; $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]); $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key]; $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key]; $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key]; if (!$specificPrice->update()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitPriceAddition')) { if ($this->tabAccess['add'] === '1') { $id_product = (int) Tools::getValue('id_product'); $id_shop = Tools::getValue('sp_id_shop'); $id_currency = Tools::getValue('sp_id_currency'); $id_country = Tools::getValue('sp_id_country'); $id_group = Tools::getValue('sp_id_group'); $price = Tools::getValue('sp_price'); $from_quantity = Tools::getValue('sp_from_quantity'); $reduction = (double) Tools::getValue('sp_reduction'); $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type'); $from = Tools::getValue('sp_from'); $to = Tools::getValue('sp_to'); if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) { $specificPrice = new SpecificPrice(); $specificPrice->id_product = $id_product; $specificPrice->id_shop = (int) $id_shop; $specificPrice->id_currency = (int) $id_currency; $specificPrice->id_country = (int) $id_country; $specificPrice->id_group = (int) $id_group; $specificPrice->price = (double) $price; $specificPrice->from_quantity = (int) $from_quantity; $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction); $specificPrice->reduction_type = $reduction_type; $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from; $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to; if (!$specificPrice->add()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('deleteSpecificPrice')) { if ($this->tabAccess['delete'] === '1') { if (!($obj = $this->loadObject())) { return; } if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) { $this->_errors[] = Tools::displayError('Invalid specific price ID'); } else { $specificPrice = new SpecificPrice((int) $id_specific_price); if (!$specificPrice->delete()) { $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitSpecificPricePriorities')) { if (!($obj = $this->loadObject())) { return; } if (!($priorities = Tools::getValue('specificPricePriority'))) { $this->_errors[] = Tools::displayError('Please specify priorities'); } elseif (Tools::isSubmit('specificPricePriorityToAll')) { if (!SpecificPrice::setPriorities($priorities)) { $this->_errors[] = Tools::displayError('An error occurred while updating priorities.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) { $this->_errors[] = Tools::displayError('An error occurred while setting priorities.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) { $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } $product->uploadable_files = (int) $_POST['uploadable_files']; $product->text_fields = (int) $_POST['text_fields']; $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('Label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['position'])) { if ($this->tabAccess['edit'] !== '1') { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (!Validate::isLoadedObject($object = $this->loadObject())) { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) { $this->_errors[] = Tools::displayError('Failed to update the position.'); } else { Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog')); } } else { parent::postProcess(true); } }