/** * @covers QueueController::Add * @todo Implement testAdd(). */ public function testAdd() { $person = Person::factory('adult'); $person->name = 'Poehavshiy'; $person->add(); $store = Store::factory('Grocery'); $store->name = 'Prison'; $store->add(); $product = new Product(); $product->name = 'Sladkiy hleb'; $product->add(); $request = Application::getInstance()->request; $request->setParams(array('storeId' => $store->id, 'personId' => $person->id, 'product_' . $product->id => 'on')); $personId = $request->p('personId'); $storeId = $request->p('storeId'); $store = Store::get($storeId); $person = Person::get($personId); $store->queue->add($person); $person->basket->drop(); $name = 'product_' . $product->id; $value = $product; if (preg_match_all('/^product_(\\d+)$/', $name, $matches)) { $person->basket->add(Product::get($matches[1][0])); } }
public function Add() { $this->_response()->asJSON(); try { $name = $this->_request()->p('name'); $product = new Product(); $product->name = trim($name); $product->add(); return array('id' => $product->id, 'name' => $product->name); } catch (Exception $e) { return array('error' => $e->getMessage()); } }
/** * @covers Assortment::add * @todo Implement testAdd(). */ public function testAdd() { $db = Application::getInstance()->mysqli; $db->query('DELETE FROM Product'); $db->query('DELETE FROM Store'); $db->query('DELETE FROM Assortment'); for ($i = 1; $i < 3; $i++) { $store = Store::factory('grocery'); $store->name = 'store_' . $i; $store->add(); $stores[] = $store; } for ($i = 1; $i < 10; $i++) { $product = new Product(); $product->name = 'product_' . $i; $product->add(); $products[] = $product; $map[$product->id] = rand(0, 2); } $a = $stores[1]->assortment; $a->map($map); }
function product_handler() { $this->check_login(); $params = $this->input->post(); if (isset($params['save'])) { Product::add($params); } redirect('admin/products'); }
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 loadProduct($id_category, $fields) { $product = new Product(); $product->copyFromPost(); $product->id_category_default = (int) end($id_category); $product->id_brand = (int) $fields['id_brand']; $product->price = (double) $fields['price']; $product->special_price = (double) $fields['old_price']; $product->ean13 = pSQL($fields['ean13']); $product->weight = 1; $product->in_stock = 1; $product->quantity = (double) $fields['quantity']; $product->name = pSQL($fields['name']); $product->rewrite = pSQL(preg_replace("/[^-0-9a-zA-Z]+/", "", str_replace(' ', '-', trim($fields['name'])))); $product->description = pSQL($fields['description'], true); $product->active = 1; if ($product->add()) { $product->updateCategories($id_category); return (int) $product->id; } else { print_r($product->_errors); } }
public function processDuplicate() { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; if (empty($product->price) && Shop::getContext() == Shop::CONTEXT_GROUP) { $shops = ShopGroup::getShopsFromGroup(Shop::getContextShopGroupID()); foreach ($shops as $shop) { if ($product->isAssociatedToShop($shop['id_shop'])) { $product_price = new Product($id_product_old, false, null, $shop['id_shop']); $product->price = $product_price->price; } } } unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() && Category::duplicateProductCategories($id_product_old, $product->id) && ($combination_images = Product::duplicateAttributes($id_product_old, $product->id)) !== false && GroupReduction::duplicateReduction($id_product_old, $product->id) && Product::duplicateAccessories($id_product_old, $product->id) && Product::duplicateFeatures($id_product_old, $product->id) && Product::duplicateSpecificPrices($id_product_old, $product->id) && Pack::duplicate($id_product_old, $product->id) && Product::duplicateCustomizationFields($id_product_old, $product->id) && Product::duplicateTags($id_product_old, $product->id) && Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') && !Image::duplicateProductImages($id_product_old, $product->id, $combination_images)) { $this->errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::exec('actionProductAdd', array('product' => $product)); if (in_array($product->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) { Search::indexation(false, $product->id); } $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=19&token=' . $this->token; } } else { $this->errors[] = Tools::displayError('An error occurred while creating an object.'); } } }
/** * Save in special database each buyer protection product for a certificate, * Each Trusted Shops particular characteristics is saved. * Create a product in Prestashop database to allow added each of them in cart. * * @param array|stdClass $protection_items * @param string $ts_id */ private function _saveProtectionItems($protection_items, $ts_id) { $sql = ' DELETE ts, p, pl FROM `' . _DB_PREFIX_ . TSBuyerProtection::DB_ITEMS . '` AS ts LEFT JOIN `' . _DB_PREFIX_ . 'product` AS p ON ts.`id_product` = p.`id_product` LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` AS pl ON ts.`id_product` = pl.`id_product` WHERE ts.`ts_id`="' . $ts_id . '"'; Db::getInstance()->Execute($sql); foreach ($protection_items as $key => $item) { //add hidden product $product = new Product(); foreach ($this->available_languages as $iso => $lang) { $language = Language::getIdByIso(strtolower($iso)); if ((int) $language !== 0) { $product->name[$language] = 'TrustedShops guarantee'; $product->link_rewrite[$language] = 'trustedshops_guarantee'; } } // If the default lang is different than available languages : // (Bug occurred otherwise) if (!array_key_exists(Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT')), $this->available_languages)) { $product->name[(int) Configuration::get('PS_LANG_DEFAULT')] = 'Trustedshops'; $product->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')] = 'trustedshops'; } // Add specifics translations $id_lang = Language::getIdByIso('de'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops Käuferschutz'; } $id_lang = Language::getIdByIso('en'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops buyer protection'; } $id_lang = Language::getIdByIso('fr'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops protection acheteur'; } $product->quantity = 1000; $product->price = ToolsCore::convertPrice($item->grossFee, Currency::getIdByIsoCode($item->currency)); $product->id_category_default = TSBuyerProtection::$CAT_ID; $product->active = true; $product->id_tax = 0; $product->add(); if ($product->id) { $sql = ' INSERT INTO `' . _DB_PREFIX_ . TSBuyerProtection::DB_ITEMS . '` ( `creation_date`, `id_product`, `ts_id`, `id`, `currency`, `gross_fee`, `net_fee`, `protected_amount_decimal`, `protection_duration_int`, `ts_product_id` ) VALUES ( "' . pSQL($item->creationDate) . '", "' . pSQL($product->id) . '", "' . pSQL($ts_id) . '", "' . (int) $item->id . '", "' . pSQL($item->currency) . '", "' . pSQL($item->grossFee) . '", "' . pSQL($item->netFee) . '", "' . pSQL($item->protectedAmountDecimal) . '", "' . pSQL($item->protectionDurationInt) . '", "' . pSQL($item->tsProductID) . '" )'; Db::getInstance()->Execute($sql); } else { $this->errors['products'] = $this->l('Product wasn\'t saved.'); } } }
/** * Inserts a product in Prestashop. * * @param array $product_attributes * @param string $url * @param array $triple_cod_col_siz * @param array $array_combinations * @param integer $language * @return array * @see $this->setSupplierForProduct * @see $this->setArrayElementForLinkRewrite * @see $this->setManufacturerForProduct * @see $this->addFeaturesForProducts * @see $this->setCategoriesForProduct * @see $this->addCombinationsForPrestashop * @see PrestashopImageHandler insertImageInPrestashop() * */ public function insertProductForPrestashop($product_attributes = array(), $url_photo, $triple_cod_col_siz, $array_combinations, $language = 1) { $product = new Product(); //$language is 1 because 1 -> italian $string_name_product = trim($product_attributes["Nome"]); $product->name = $this->setArrayElementForLinkRewrite($string_name_product, true, $language); $product->meta_keywords = $string_name_product; $product->link_rewrite = $this->setArrayElementForLinkRewrite($string_name_product, false, $language); $product->id_category_default = 2; //Home $product->redirect_type = '404'; $product->price = (double) $product_attributes["Prezzo"]; $product->active = (int) $product_attributes["Attivo"]; $product->minimal_quantity = (int) $product_attributes["Qta_min"]; $product->show_price = 1; $product->reference = $product_attributes["Reference"]; $product->id_tax_rules_group = 0; //$product->id_supplier = $this->setSupplierForProduct(trim($product_attributes["Supplier"])); $product->id_supplier = 0; $product->id_manufacturer = $this->setManufacturerForProduct(trim($product_attributes["Manufacture"])); $array_features = $product_attributes["Feature"]; $product->width = (double) $array_features["Larghezza"]; $product->height = (double) $array_features["Altezza"]; $product->add(); $this->addFeaturesForProducts($product->id, $language, $array_features); $categories = trim($product_attributes["Categorie"]); $tmp = explode(",", $categories); $griffe = $tmp[1]; $modello = $tmp[0]; $id_parent = null; $id_child = null; $id_parent = $this->setCategoriesForProduct(trim($griffe), 2, $language); $id_child = $this->setCategoriesForProduct(trim($modello), $id_parent, $language); $cat_pos_tmp = array(); array_push($cat_pos_tmp, $id_child); array_push($cat_pos_tmp, $id_parent); $product->addToCategories($cat_pos_tmp); if ($product->active != 0) { $activeCategory = new Category($id_parent); $activeCategory->active = 1; $activeCategory->update(); $activeCategory = new Category($id_child); $activeCategory->active = 1; $activeCategory->update(); } $tmp = explode(".jpg,", trim($product_attributes["URL"])); $size_url = sizeof($tmp); $array_id_image = array(); for ($i = 0; $i < $size_url; $i++) { if (!empty($tmp[$i])) { $url = trim($url_photo); $image = new PrestashopImageHandler(); $id_image = $image->insertImageInPrestashop($product->id, $url, $tmp[$i]); array_push($array_id_image, $id_image); } } $this->addCombinationsForPrestashop($product->id, $url_photo, $triple_cod_col_siz, $array_combinations, $language); $return = array(); $array_images_combinations_of_the_product = $product->getImages($language); array_push($return, $product->id); $element = array(); foreach ($array_images_combinations_of_the_product as $array_combo_image) { $name_of_the_image = $array_combo_image['legend']; $id_image_of_the_product = $array_combo_image['id_image']; array_push($element, $id_image_of_the_product . ";" . $name_of_the_image); } array_push($return, $element); return $return; }
private function _addTaxesAndDutiesProduct() { $product = new Product(); $product->id_shop_default = (int) $this->context->shop->id; $product->id_manufacturer = 0; $product->id_supplier = 0; $product->reference = 'TAXDUTIES'; $product->supplier_reference = ''; $product->location = ''; $product->width = 0; $product->height = 0; $product->depth = 0; $product->weight = 0; $product->quantity_discount = false; $product->ean13 = ''; $product->upc = ''; $product->is_virtual = false; $product->id_category_default = 2; $product->id_tax_rules_group = 1; $product->on_sale = 0; $product->online_only = 0; $product->ecotax = 0; $product->minimal_quantity = 1; $product->price = 0; $product->wholesale_price = 0; $product->unity = ''; $product->unit_price_ratio = 1; $product->additional_shipping_cost = 0; $product->customizable = 0; $product->active = 1; $product->condition = 'new'; $product->show_price = false; $product->visibility = 'none'; $product->date_add = date('Y-m-d H:i:s'); $product->date_upd = date('Y-m-d H:i:s'); $product->name[(int) Configuration::get('PS_LANG_DEFAULT')] = $this->l('Taxes and Duties'); $product->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')] = 'taxes-and-duties'; $result = $product->add(); /* Allowed to be ordered even if stock = 0 */ if ($result) { StockAvailable::setProductOutOfStock((int) $product->id, 1); StockAvailable::setProductDependsOnStock((int) $product->id, false); StockAvailable::setQuantity((int) $product->id, 0, 1000000); } return $result ? (int) $product->id : 0; }
/** * @brief Validate Method * * @return update the module depending on klarna webservices */ private function _postValidation() { $klarna = new Klarna(); if ($_POST['klarna_mod'] == 'live') { Configuration::updateValue('KLARNA_MOD', Klarna::LIVE); } else { Configuration::updateValue('KLARNA_MOD', Klarna::BETA); } if (isset($_POST['klarna_active_invoice']) && $_POST['klarna_active_invoice']) { Configuration::updateValue('KLARNA_ACTIVE_INVOICE', true); } else { Configuration::deleteByName('KLARNA_ACTIVE_INVOICE'); } if (isset($_POST['klarna_active_partpayment']) && $_POST['klarna_active_partpayment']) { Configuration::updateValue('KLARNA_ACTIVE_PARTPAYMENT', true); } else { Configuration::deleteByName('KLARNA_ACTIVE_PARTPAYMENT'); } if (isset($_POST['klarna_email']) && $_POST['klarna_email']) { Configuration::updateValue('KLARNA_EMAIL', true); } else { Configuration::deleteByName('KLARNA_EMAIL'); } foreach ($this->countries as $country) { Db::getInstance()->delete(_DB_PREFIX_ . 'klarna_payment_pclasses', 'country = "' . (int) $country['code'] . '"'); Configuration::updateValue('KLARNA_STORE_ID_' . $country['name'], null); Configuration::updateValue('KLARNA_SECRET_' . $country['name'], null); } foreach ($this->countries as $key => $country) { if (isset($_POST['activate' . $country['name']])) { $storeId = (int) Tools::getValue('klarnaStoreId' . $country['name']); $secret = pSQL(Tools::getValue('klarnaSecret' . $country['name'])); if ($storeId > 0 && $secret == '' || $storeId <= 0 && $secret != '') { $this->_postErrors[] = $this->l('your credentials are incorrect and can\'t be used in ') . $country['name']; } elseif ($storeId >= 0 && $secret != '') { $error = false; try { $klarna->config($storeId, Tools::safeOutput($secret), $country['code'], $country['langue'], $country['currency'], Configuration::get('KLARNA_MOD'), 'mysql', $this->_getDb()); $PClasses = $klarna->fetchPClasses($country['code']); } catch (Exception $e) { $error = true; $this->_postErrors[] = (int) $e->getCode() . ': ' . Tools::safeOutput($e->getMessage()); } if (!$error) { Configuration::updateValue('KLARNA_STORE_ID_' . $country['name'], $storeId); Configuration::updateValue('KLARNA_SECRET_' . $country['name'], $secret); Configuration::updateValue('KLARNA_INVOICE_FEE_' . $country['name'], (double) Tools::getValue('klarnaInvoiceFee' . $country['name'])); Configuration::updateValue('KLARNA_MINIMUM_VALUE_' . $country['name'], (double) Tools::getValue('klarnaMinimumValue' . $country['name'])); Configuration::updateValue('KLARNA_MAXIMUM_VALUE_' . $country['name'], $_POST['klarnaMaximumValue' . $country['name']] != 0 ? (double) Tools::getValue('klarnaMaximumValue' . $country['name']) : 99999); $id_product = Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product_lang` WHERE `name` = \'invoiceFee' . $country['name'] . '\''); $taxeRules = TaxRulesGroup::getAssociatedTaxRatesByIdCountry(Country::getByIso($key)); $maxiPrice = 0; $idTaxe = 0; foreach ($taxeRules as $key => $val) { if ((int) $val > $maxiPrice) { $maxiPrice = (int) $val; $idTaxe = $key; } } if ($id_product != null) { $productInvoicefee = new Product((int) $id_product); $productInvoicefee->price = (double) Tools::getValue('klarnaInvoiceFee' . $country['name']); if (_PS_VERSION_ >= 1.5) { StockAvailable::setProductOutOfStock((int) $productInvoicefee->id, true, null, 0); } if ($idTaxe != 0) { $productInvoicefee->id_tax_rules_group = (int) $idTaxe; } $productInvoicefee->update(); } else { $productInvoicefee = new Product(); $productInvoicefee->out_of_stock = 1; $productInvoicefee->available_for_order = true; $productInvoicefee->id_category_default = 2; if ($idTaxe != 0) { $productInvoicefee->id_tax_rules_group = (int) $idTaxe; } $languages = Language::getLanguages(false); foreach ($languages as $language) { $productInvoicefee->name[$language['id_lang']] = 'invoiceFee' . $country['name']; $productInvoicefee->link_rewrite[$language['id_lang']] = 'invoiceFee' . $country['name']; } $productInvoicefee->price = (double) Tools::getValue('klarnaInvoiceFee' . $country['name']); if (_PS_VERSION_ >= 1.5) { $productInvoicefee->active = false; } $productInvoicefee->add(); if (_PS_VERSION_ >= 1.5) { StockAvailable::setProductOutOfStock((int) $productInvoicefee->id, true, null, 0); } } Configuration::updateValue('KLARNA_INV_FEE_ID_' . $country['name'], $productInvoicefee->id); $this->_postValidations[] = $this->l('Your account has been updated to be used in ') . $country['name']; } $error = false; } } } }
/** * Save in special database each buyer protection product for a certificate, * Each Trusted Shops particular characteristics is saved. * Create a product in Prestashop database to allow added each of them in cart. * * @param array|stdClass $protection_items * @param string $ts_id */ private function saveProtectionItems($protection_items, $ts_id) { $query = ' DELETE ts, p, pl FROM `' . _DB_PREFIX_ . TSCommon::DB_ITEMS . '` AS ts LEFT JOIN `' . _DB_PREFIX_ . 'product` AS p ON ts.`id_product` = p.`id_product` LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` AS pl ON ts.`id_product` = pl.`id_product` WHERE ts.`ts_id`="' . pSQL($ts_id) . '"'; Db::getInstance()->Execute($query); foreach ($protection_items as $item) { //add hidden product $product = new Product(); foreach (array_keys(self::$available_languages) as $iso) { $language = Language::getIdByIso(Tools::strtolower($iso)); if ((int) $language !== 0) { $product->name[$language] = 'TrustedShops guarantee'; $product->link_rewrite[$language] = 'trustedshops_guarantee'; } } // If the default lang is different than available languages : // (Bug occurred otherwise) if (!array_key_exists(Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT')), self::$available_languages)) { $product->name[(int) Configuration::get('PS_LANG_DEFAULT')] = 'Trustedshops'; $product->link_rewrite[(int) Configuration::get('PS_LANG_DEFAULT')] = 'trustedshops'; } // Add specifics translations $id_lang = Language::getIdByIso('de'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops Käuferschutz'; } $id_lang = Language::getIdByIso('en'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops buyer protection'; } $id_lang = Language::getIdByIso('fr'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops protection acheteur'; } $id_lang = Language::getIdByIso('it'); if ((int) $id_lang > 0) { $product->name[$id_lang] = 'Trusted Shops protezione acquirenti'; } $product->quantity = 1000; $product->price = Tools::convertPrice($item->grossFee, Currency::getIdByIsoCode($item->currency)); $product->id_category_default = TSCommon::$cat_id; $product->active = true; $product->visibility = 'none'; $product->id_tax_rules_group = 0; $product->add(); $product->addToCategories(TSCommon::$cat_id); if ($product->id) { $query = ' INSERT INTO `' . _DB_PREFIX_ . TSCommon::DB_ITEMS . '` (`creation_date`, `id_product`, `ts_id`, `id`, `currency`, `gross_fee`, `net_fee`, `protected_amount_decimal`, `protection_duration_int`, `ts_product_id`) VALUES ("' . pSQL($item->creationDate) . '", "' . pSQL($product->id) . '", "' . pSQL($ts_id) . '", "' . (int) $item->id . '", "' . pSQL($item->currency) . '", "' . pSQL($item->grossFee) . '", "' . pSQL($item->netFee) . '", "' . pSQL($item->protectedAmountDecimal) . '", "' . pSQL($item->protectionDurationInt) . '", "' . pSQL($item->tsProductID) . '")'; Db::getInstance()->Execute($query); if (class_exists('StockAvailable')) { $id_stock_available = Db::getInstance()->getValue(' SELECT s.`id_stock_available` FROM `' . _DB_PREFIX_ . 'stock_available` s WHERE s.`id_product` = ' . (int) $product->id); $stock = new StockAvailable($id_stock_available); $stock->id_product = $product->id; $stock->out_of_stock = 1; $stock->id_product_attribute = 0; $stock->quantity = 1000000; $stock->id_shop = Context::getContext()->shop->id; if ($stock->id) { $stock->update(); } else { $stock->add(); } } } else { $this->errors['products'] = $this->l('Product wasn\'t saved.'); } } }
/** * Added Dotpay virtual product for extracharge option * @return bool */ private function addDotpayVirtualProduct() { if (Validate::isInt($this->config->getDotpayExchVPid()) and Validate::isLoadedObject($product = new Product($this->config->getDotpayExchVPid())) and Validate::isInt($product->id)) { return true; } $product = new Product(); $product->name = array((int) Configuration::get('PS_LANG_DEFAULT') => 'Online payment'); $product->link_rewrite = array((int) Configuration::get('PS_LANG_DEFAULT') => 'online-payment'); $product->visibility = 'none'; $product->reference = 'DOTPAYFEE'; $product->price = 0.0; $product->is_virtual = 1; $product->online_only = 1; $product->redirect_type = '404'; $product->quantity = 9999999; $product->id_tax_rules_group = 0; $product->active = 1; $product->meta_keywords = 'payment'; $product->id_category = 1; $product->id_category_default = 1; if (!$product->add()) { return false; } $product->addToCategories(array(1)); StockAvailable::setQuantity($product->id, NULL, $product->quantity); $this->config->setDotpayExchVPid($product->id); return true; }
public function addPaymentMethodCostVirtualItemToCart($cart) { $config = $this->loadConfiguration(); $langId = Context::getContext()->language->id; $product = new Product(); $product->is_virtual = true; $product->indexed = false; $product->active = true; $product->price = $this->calculatePaymentCost($cart); $product->visibility = 'none'; $product->name = array($langId => $config['PAYMENT_METHOD_COST_TITLE']); $product->link_rewrite = array($langId => uniqid()); $product->id_tax_rules_group = 0; $product->add(); StockAvailable::setQuantity($product->id, null, 1); $cart->updateQty(1, $product->id, null, false); $cart->update(); $cart->getPackageList(true); return $product->id; }
/** * Launch upgrade process */ public function runUpgrades($install = false) { if (!Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER')) { //add carrier for seller cost $this->createSoColissimoCarrierSeller($this->_config); } if (!Configuration::get('SOCOLISSIMO_PRODUCT_ID_BELG')) { //add hidden product overcots belgium $product = new Product(); $languages = Language::getLanguages(true); foreach ($languages as $language) { if ($language['iso_code'] == 'fr') { $product->name[$language['id_lang']] = 'Surcoût belgique'; $product->link_rewrite[$language['id_lang']] = 'belgium'; } if ($language['iso_code'] == 'en') { $product->name[$language['id_lang']] = 'Overcost Belgium'; $product->link_rewrite[$language['id_lang']] = 'belgium'; } } $product->quantity = 10; $product->price = 0; $product->id_category_default = intval(Configuration::get('SOCOLISSIMO_CAT_ID')); $product->active = true; $product->id_tax = 0; $product->add(); Configuration::updateValue('SOCOLISSIMO_PRODUCT_ID_BELG', intval($product->id)); } if (Configuration::get('SOCOLISSIMO_VERSION') != $this->version) { foreach (array('1.7', '1.9') as $version) { $file = dirname(__FILE__) . '/upgrade/install-' . $version . '.php'; if (Configuration::get('SOCOLISSIMO_VERSION') < $version && file_exists($file)) { include_once $file; call_user_func('upgrade_module_' . str_replace('.', '_', $version), $this, $install); } } } }
/** * 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') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) { if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !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']) && 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']); } } elseif ((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) > 128) { $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 GroupReduction::duplicateReduction($id_product_old, $product->id) 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, $product->id); 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())) { 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()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } } elseif ($object->delete()) { 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) { foreach (Tools::getValue($this->table . 'Box') as $id) { $toDelete = new $this->className($id); $toDelete->deleted = 1; $result = $result and $toDelete->update(); } } else { $result = $object->deleteSelection(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))) { /* PrestaShop demo mode */ if (_PS_MODE_DEMO_) { $this->_errors[] = Tools::displayError('This functionnality has been disabled.'); return; } /* PrestaShop demo mode*/ 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('attribute_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'), Tools::getValue('attribute_minimal_quantity')); } } 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 . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&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 . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&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 . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&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); } }
/** * Add product */ private function eeweeProductAdd() { $p = new Product(); // LANG $langs = $this->getLang(); foreach ($langs as $lang) { // INFORMATIONS $p->name[$lang['id_lang']] = 'Nom du produit'; // REFERENCEMENT - SEO $p->link_rewrite[$lang['id_lang']] = 'nom-du-produit'; } // INFORMATIONS $p->reference = '5512'; // Reference $p->active = true; // Active $p->description_short = 'Resume du produit.'; // Resume $p->description = 'Description longue du produit.'; // Description // PRIX $p->price = 20; // Prix de vente HT // INSERT $p->add(); }
jquery/plugins/ajaxfileupload/jquery.ajaxfileupload.js"></script> <script type="text/javascript" src="<?php echo $_tmconfig['tm_js_dir']; ?> fileuploader.js"></script> <script type="text/javascript" src="<?php echo $_tmconfig['tm_js_dir']; ?> jquery/jquery.tablednd_0_5.js"></script> <!--//head--> <div class="col-md-12"> <?php if (isset($_POST['sveProduct']) && Tools::getRequest('sveProduct') == 'add') { $product = new Product(); $product->copyFromPost(); if ($product->add()) { if (!$product->updateCategories($_POST['categoryBox']) or !$product->addToTags($_POST['tags']) or !$product->updateAttribute($_POST['attribute_items'])) { $product->_errors = '添加产品内容时发生了一个错误'; } } if (is_array($product->_errors) and count($product->_errors) > 0) { $errors = $product->_errors; } else { $_GET['id'] = $product->id; echo '<div class="conf">添加产品成功</div>'; } } if (isset($_GET['id'])) { $id = (int) $_GET['id']; $obj = new Product($id); $images = $obj->getImages($id);
} else { echo 'An error occurred while duplicating some object properties.'; } } } } if ($Version >= 14510 && $Version < 15000) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; for ($i = 1; $i <= $quantity; $i++) { echo $i; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if (!$product->add()) { echo "Parent_F:" . $product->id . " "; } if (!Category::duplicateProductCategories($id_product_old, $product->id)) { echo "Cat_F:" . $product->id . " "; } if (($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) 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') && !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { echo 'An error occurred while copying images.'; } else { echo ' done. '; } } else {
<?php session_start(); require_once 'common/autoload.php'; if (!isset($_SESSION['user']['id'])) { die('User is missing'); } $data = $_POST; $data['user_id'] = $_SESSION['user']['id']; // users.id // user_id, name, price, quantity $product = new Product(); if ($product->add($data) > 0) { echo 'You have added one item <a href="add_product.php">Go back</a>'; } else { echo 'You have failed my son'; }
public function postProcess($token = NULL) { global $currentIndex; /* Add a new product */ if (Tools::isSubmit('submitAddproduct') or Tools::isSubmit('submitAddproductAndStay')) { if ($this->tabAccess['add'] === '1') { $this->submitAddproduct($token); } elseif (Tools::getValue('id_product') and $this->tabAccess['edit'] === '1') { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything 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 anything here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = intval(Tools::getValue($this->identifier))) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . $id . '&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(intval(Tools::getValue('id_product'))))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 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::duplicateQuantityDiscount($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)) { 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=' . intval(Tools::getValue('id_category')) . '&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 anything here.'); } } elseif ($id_image = intval(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(); deleteImage($image->id_product, $image->id); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . intval($image->id_product)); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . intval($first_img['id_image'])); } @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $image->id_product . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(); 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($token ? $token : $this->token); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Impossible to change the product cover'); } else { $productId = intval(Tools::getValue('id_product')); @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $productId . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage(intval(Tools::getValue('imgPosition')), intval(Tools::getValue('imgDirection'))); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!isset($_POST['attribute_quantity']) or $_POST['attribute_quantity'] == NULL) { $this->_errors[] = Tools::displayError('attribute quantity is required'); } if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('attribute price is 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 = intval(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_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')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything 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_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')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('edit something here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['deleteProductAttribute'])) { if ($this->tabAccess['delete'] === '1') { if ($id_product = intval(Tools::getValue('id_product')) and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison(intval(Tools::getValue('id_product_attribute'))); $product->checkDefaultAttributes(); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . intval(Tools::getValue('id_category')) . '&tabs=2&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('impossible to delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(); 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, $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=3&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 anything here.'); } elseif (Tools::isSubmit('submitQuantityDiscount')) { $_POST['tabs'] = 5; if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!($id_discount_type = intval(Tools::getValue('id_discount_type')))) { $this->_errors[] = Tools::displayError('discount type not selected'); } else { if (!($quantity_discount = intval(Tools::getValue('quantity_discount')))) { $this->_errors[] = Tools::displayError('quantity is required'); } else { if (!($value_discount = floatval(Tools::getValue('value_discount')))) { $this->_errors[] = Tools::displayError('value is required'); } else { $qD = new QuantityDiscount(); $qD->id_product = $product->id; $qD->id_discount_type = $id_discount_type; $qD->quantity = $quantity_discount; $qD->value = $value_discount; if ($qD->add() and !sizeof($this->_errors) and $qD->validateFields()) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=3&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred while creating object'); } } } } else { $this->_errors[] = Tools::displayError('product must be created before adding quantity discounts'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } elseif (isset($_GET['deleteQuantityDiscount'])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (Validate::isLoadedObject($qD = new QuantityDiscount(intval(Tools::getValue('id_quantity_discount'))))) { $qD->delete(); if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('not a valid quantity discount'); } } else { $this->_errors[] = Tools::displayError('product must be created before delete quantity discounts'); } $qD = new QuantityDiscount(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$product->createLabels(intval($_POST['uploadable_files']) - intval($product->uploadable_files), intval($_POST['text_fields']) - intval($product->text_fields))) { $this->_errors[] = Tools::displayError('an error occured while creating customization fields'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('an error occured while updating customization'); } $product->uploadable_files = intval($_POST['uploadable_files']); $product->text_fields = intval($_POST['text_fields']); $product->customizable = (intval($_POST['uploadable_files']) > 0 or intval($_POST['text_fields']) > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('an error occured while updating customization configuration'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&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 anything here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(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 occured while updating customization'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&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 anything here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$this->deleteImage($product->id)) { $this->_errors[] = Tools::displayError('an error occurred during product image deletion'); } if ($product->delete()) { Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=1&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred during product deletion'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } else { parent::postProcess(true); } }
header('location:../user/login.php'); } //Require các file cần thiết require '../../config/Config.php'; require '../../models/Category.php'; require '../../models/Product.php'; date_default_timezone_set('Asia/Ho_Chi_Minh'); $productModel = new Product(); //Xử lý POST dữ liệu lên if ($_POST) { //Upload hình ảnh $image = $_FILES['image']['name']; if ($image != NULL) { move_uploaded_file($_FILES['image']['tmp_name'], '../../../upload/product' . '/' . trim($_POST['category_id']) . '/' . $image); } else { $image = null; } //Nhận dữ liệu từ form gán vào mảng $data = array('category_id' => $_POST['category_id'], 'name' => $_POST['name'], 'detail' => $_POST['detail'], 'image' => $image, 'price' => $_POST['price'], 'status' => isset($_POST['status']) ? 1 : 0, 'created' => date('Y-m-d H:i:s'), 'modified' => date('Y-m-d H:i:s')); //Truy vấn thêm mới vào cơ sở dữ liệu if ($productModel->add($data)) { header('location:list.php'); } else { echo "Thêm mới không thành công"; } } //Lấy danh sách danh mục sản phẩm có trạng thái kích hoạt (Status = 1) $categoryModel = new Category(); $category_active_list = $categoryModel->getActiveList(); //Require file giao diện (View) require '../../views/product/v_add.php';