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)); }
public function preProcess() { parent::preProcess(); $customer = new Customer((int) self::$cookie->id_customer); if ($idAdd = Tools::getValue('add')) { $res = Db::getInstance()->ExecuteS("insert into ps_wishlist(id_customer, id_product) values(" . self::$cookie->id_customer . ", " . $idAdd . ")"); Tools::captureActivity(PSTAT_ADD_WL, $idAdd); Tools::redirect('wishlist.php'); } if ($idDelete = Tools::getValue('delete')) { $res = Db::getInstance()->ExecuteS("delete from ps_wishlist where id_customer = " . self::$cookie->id_customer . " and id_product = " . $idDelete); Tools::captureActivity(PSTAT_DEL_WL, $idDelete); Tools::redirect('wishlist.php'); } $sql = "select id_product from ps_wishlist where id_customer = " . self::$cookie->id_customer; $res = Db::getInstance()->ExecuteS($sql); if ($res) { $productIds = array(); foreach ($res as $row) { $productIds[] = $row['id_product']; } $total_found = 0; try { $wishlist_products = SolrSearch::getProductsForIDs($productIds, $total_found, 1, 100); self::$smarty->assign('wishlist_products', $wishlist_products); } catch (Exception $e) { } } }
public function preProcess() { if ($id_category = (int) Tools::getValue('id_category')) { $this->productSort(); if ($this->category->id != 1) { $brand_id = Tools::getValue('brand'); $this->category = new Category($id_category, self::$cookie->id_lang); $nbProducts = 0; $this->n = (int) Configuration::get('PS_PRODUCTS_PER_PAGE'); $this->p = abs((int) Tools::getValue('p', 1)); try { global $cart, $cookie; $id_country = (int) Country::getDefaultCountryId(); if ($cart->id_address_delivery) { $address = new Address($cart->id_address_delivery); if ($address->id_country) { $id_country = $address->id_country; } elseif (isset($cookie->id_country)) { $id_country = (int) $cookie->id_country; } } self::$smarty->assign('price_tax_country', $id_country); $products = SolrSearch::getCategoryProducts($id_category, $brand_id, $nbProducts); } catch (Exception $e) { self::$smarty->assign('fetch_error', 1); } $this->pagination((int) $nbProducts); self::$smarty->assign('nb_products', (int) $nbProducts); $this->cat_page_products = $products; } } if (!Validate::isLoadedObject($this->category)) { header('HTTP/1.1 404 Not Found'); header('Status: 404 Not Found'); } else { // Automatically redirect to the canonical URL if the current in is the right one // $_SERVER['HTTP_HOST'] must be replaced by the real canonical domain $currentURL = self::$link->getCategoryLink($this->category); $currentURL = preg_replace('/[?&].*$/', '', $currentURL); if (!preg_match('/^' . Tools::pRegexp($currentURL, '/') . '([&?].*)?$/', Tools::getProtocol() . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])) { header('HTTP/1.0 301 Moved'); if (defined('_PS_MODE_DEV_') and _PS_MODE_DEV_) { die('[Debug] This page has moved<br />Please use the following URL instead: <a href="' . $currentURL . '">' . $currentURL . '</a>'); } Tools::redirectLink($currentURL); } } parent::preProcess(); if ((int) Configuration::get('PS_REWRITING_SETTINGS')) { if ($id_category = (int) Tools::getValue('id_category')) { $rewrite_infos = Category::getUrlRewriteInformations((int) $id_category); $default_rewrite = array(); foreach ($rewrite_infos as $infos) { $default_rewrite[$infos['id_lang']] = self::$link->getCategoryLink((int) $id_category, $infos['link_rewrite'], $infos['id_lang']); } self::$smarty->assign('lang_rewrite_urls', $default_rewrite); } } }
public function preProcess() { parent::preProcess(); try { $total_found = 0; $curated_products = SolrSearch::getCategoryProducts(CAT_CURATED, $brand_id = false, $total_found, $p = 1, $n = 500); $right_products = array_slice($curated_products, $total_found * 0.48); $left_products = array_slice($curated_products, 0, $total_found * 0.48); self::$smarty->assign('curated_products_right', $right_products); self::$smarty->assign('curated_products_left', $left_products); } catch (Exception $e) { } }
public function preProcess() { $this->productSort(); $nbProducts = 0; $this->n = (int) Configuration::get('PS_PRODUCTS_PER_PAGE'); $this->p = abs((int) Tools::getValue('p', 1)); try { $products = SolrSearch::getExpressShippingProducts($nbProducts, $this->p, $this->n); $this->pagination($nbProducts); self::$smarty->assign('nbProducts', (int) $nbProducts); } catch (Exception $e) { self::$smarty->assign('fetch_error', 1); } $this->pageProducts = $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); } }
function getProductInformation($pid, $utm_s, $utm_m, $utm_c, $size = 'list') { $info = array(); if (isset($pid) && !empty($pid)) { global $link; $temp = 0; $product = SolrSearch::getProductsForIDs(array($pid), $temp); $product = $product[0]; $info['name'] = strtoupper((string) $product["name"]); $info['description'] = (string) $product['description']; $info['price'] = round($product["mrp"]); $info['sprice'] = round($product["offer_price"]); $info['url'] = buildURL((string) $product["product_link"], $utm_s, $utm_m, $utm_c); $info['image'] = (string) $product["image_link_{$size}"]; //echo "<pre>"; print_r( $info ); exit; } return $info; }
/** * Manage page processing * * @global string $currentIndex Current URL in order to keep current Tab */ public function postProcess() { global $currentIndex, $cookie; if (!isset($this->table)) { return false; } // set token $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token; // Sub included tab postProcessing $this->includeSubTab('postProcess', array('status', 'submitAdd1', 'submitDel', 'delete', 'submitFilter', 'submitReset')); /* Delete object image */ if (isset($_GET['deleteImage'])) { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->deleteImage()) { Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&' . $this->identifier . '=' . Tools::getValue($this->identifier) . '&conf=7&token=' . $token); } } $this->_errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).'); } 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(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 { if ($this->deleted) { $object->deleteImage(); $object->deleted = 1; if ($object->update()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . $token); } } elseif ($object->delete()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . $token); } $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 ((isset($_GET['status' . $this->table]) or isset($_GET['status'])) and Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->toggleStatus()) { if ($this->table == 'product') { SolrSearch::updateProduct($object->id); } Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = (int) Tools::getValue('id_category') 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['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)'); } elseif (!$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 = (int) Tools::getValue($this->identifier)) ? '&' . $this->identifier . '=' . $id_category : '') . '&token=' . $token); } Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = (int) Tools::getValue('id_category') and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token); } 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) { Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token); } $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 (Tools::getValue('submitAdd' . $this->table)) { /* Checking fields validity */ $this->validateRules(); if (!sizeof($this->_errors)) { $id = (int) Tools::getValue($this->identifier); /* Object update */ if (isset($id) and !empty($id)) { if ($this->tabAccess['edit'] === '1' or $this->table == 'employee' and $cookie->id_employee == Tools::getValue('id_employee') and Tools::isSubmit('updateemployee')) { $object = new $this->className($id); if (Validate::isLoadedObject($object)) { /* Specific to objects which must not be deleted */ if ($this->deleted and $this->beforeDelete($object)) { // Create new one with old objet values $objectNew = new $this->className($object->id); $objectNew->id = NULL; $objectNew->date_add = ''; $objectNew->date_upd = ''; // Update old object to deleted $object->deleted = 1; $object->update(); // Update new object with post values $this->copyFromPost($objectNew, $this->table); $result = $objectNew->add(); if (Validate::isLoadedObject($objectNew)) { $this->afterDelete($objectNew, $object->id); } } else { $this->copyFromPost($object, $this->table); $result = $object->update(); $this->afterUpdate($object); } if (!$result) { $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')'; } elseif ($this->postImage($object->id) and !sizeof($this->_errors)) { $parent_id = (int) Tools::getValue('id_parent', 1); // Specific back redirect if ($back = Tools::getValue('back')) { Tools::redirectAdmin(urldecode($back) . '&conf=4'); } // Specific scene feature if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1') { Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=4&updatescene&token=' . $token); } // Save and stay on same form if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) { Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=4&update' . $this->table . '&token=' . $token); } // Save and back to parent if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) { Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=4&token=' . $token); } // Default behavior (save and back) Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=4&token=' . $token); } } else { $this->_errors[] = Tools::displayError('An error occurred while updating object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } else { if ($this->tabAccess['add'] === '1') { $object = new $this->className(); $this->copyFromPost($object, $this->table); if (!$object->add()) { $this->_errors[] = Tools::displayError('An error occurred while creating object.') . ' <b>' . $this->table . ' (' . mysql_error() . ')</b>'; } elseif ($_POST[$this->identifier] = $object->id and $this->postImage($object->id) and !sizeof($this->_errors) and $this->_redirect) { $parent_id = (int) Tools::getValue('id_parent', 1); $this->afterAdd($object); // Save and stay on same form if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) { Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=3&update' . $this->table . '&token=' . $token); } // Save and back to parent if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) { Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=3&token=' . $token); } // Default behavior (save and back) Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=3&token=' . $token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } } $this->_errors = array_unique($this->_errors); } elseif (isset($_POST['submitReset' . $this->table])) { $filters = $cookie->getFamily($this->table . 'Filter_'); foreach ($filters as $cookieKey => $filter) { if (strncmp($cookieKey, $this->table . 'Filter_', 7 + Tools::strlen($this->table)) == 0) { $key = substr($cookieKey, 7 + Tools::strlen($this->table)); /* Table alias could be specified using a ! eg. alias!field */ $tmpTab = explode('!', $key); $key = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0]; if (array_key_exists($key, $this->fieldsDisplay)) { unset($cookie->{$cookieKey}); } } } if (isset($cookie->{'submitFilter' . $this->table})) { unset($cookie->{'submitFilter' . $this->table}); } if (isset($cookie->{$this->table . 'Orderby'})) { unset($cookie->{$this->table . 'Orderby'}); } if (isset($cookie->{$this->table . 'Orderway'})) { unset($cookie->{$this->table . 'Orderway'}); } unset($_POST); } elseif (Tools::getValue('submitOptions' . $this->table)) { $this->updateOptions($token); } elseif (Tools::isSubmit('submitFilter' . $this->table) or $cookie->{'submitFilter' . $this->table} !== false) { $_POST = array_merge($cookie->getFamily($this->table . 'Filter_'), isset($_POST) ? $_POST : array()); foreach ($_POST as $key => $value) { /* Extracting filters from $_POST on key filter_ */ if ($value != NULL and !strncmp($key, $this->table . 'Filter_', 7 + Tools::strlen($this->table))) { $key = Tools::substr($key, 7 + Tools::strlen($this->table)); /* Table alias could be specified using a ! eg. alias!field */ $tmpTab = explode('!', $key); $filter = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0]; if ($field = $this->filterToField($key, $filter)) { $type = array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false); if (($type == 'date' or $type == 'datetime') and is_string($value)) { $value = unserialize($value); } $key = isset($tmpTab[1]) ? $tmpTab[0] . '.`' . $tmpTab[1] . '`' : '`' . $tmpTab[0] . '`'; if (array_key_exists('tmpTableFilter', $field)) { $sqlFilter =& $this->_tmpTableFilter; } elseif (array_key_exists('havingFilter', $field)) { $sqlFilter =& $this->_filterHaving; } else { $sqlFilter =& $this->_filter; } /* Only for date filtering (from, to) */ if (is_array($value)) { if (isset($value[0]) and !empty($value[0])) { if (!Validate::isDate($value[0])) { $this->_errors[] = Tools::displayError('\'from:\' date format is invalid (YYYY-MM-DD)'); } else { $sqlFilter .= ' AND ' . pSQL($key) . ' >= \'' . pSQL(Tools::dateFrom($value[0])) . '\''; } } if (isset($value[1]) and !empty($value[1])) { if (!Validate::isDate($value[1])) { $this->_errors[] = Tools::displayError('\'to:\' date format is invalid (YYYY-MM-DD)'); } else { $sqlFilter .= ' AND ' . pSQL($key) . ' <= \'' . pSQL(Tools::dateTo($value[1])) . '\''; } } } else { $sqlFilter .= ' AND '; if ($type == 'int' or $type == 'bool') { $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`' or $key == '`active`') ? 'a.' : '') . pSQL($key) . ' = ' . (int) $value . ' '; } elseif ($type == 'decimal') { $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' = ' . (double) $value . ' '; } elseif ($type == 'select') { $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' = \'' . pSQL($value) . '\' '; } else { $sqlFilter .= (($key == $this->identifier or $key == '`' . $this->identifier . '`') ? 'a.' : '') . pSQL($key) . ' LIKE \'%' . pSQL($value) . '%\' '; } } } } } } elseif (Tools::isSubmit('submitFields') and $this->requiredDatabase and $this->tabAccess['add'] === '1' and $this->tabAccess['delete'] === '1') { if (!is_array($fields = Tools::getValue('fieldsBox'))) { $fields = array(); } $object = new $this->className(); if (!$object->addFieldsRequiredDatabase($fields)) { $this->_errors[] = Tools::displayError('Error in updating required fields'); } else { Tools::redirectAdmin($currentIndex . '&conf=4&token=' . $token); } } }
public static function updateQuantityCron() { $link = new Link(); global $link; $db = Db::getInstance(_PS_USE_SQL_SLAVE_); // update data from sudarshan_details table to ps_product $sql = "update ps_product p inner join sudarshan_details s on (s.id_product = p.id_product and p.reference like 'BLR002%') set p.supplier_reference = CASE WHEN concat(s.design_no,'::',s.item_code) = '::' THEN '' WHEN concat(s.design_no,'::',s.item_code) != '' THEN concat(s.design_no,'::',s.item_code) END, p.active = s.enabled"; $db->ExecuteS($sql); $sql = "select id_supplier from ps_supplier where code = 'BLR002'"; $res = $db->getRow($sql); $id_supplier = $res['id_supplier']; self::echomsg(null, "Start Sudarshan Stock Sync - UpdateQuantity", true); // Sudarshan Vendor Code is in the format design_no::item_code $sql = "select id_product, reference, supplier_reference from ps_product where id_supplier = {$id_supplier} and supplier_reference like '%::%' and active = 1"; $res = $db->ExecuteS($sql); /*$res = array( array('id_product' => 111, 'supplier_reference' => '675::CRB', 'reference' => 'BLR0021001'), array('id_product' => 112, 'supplier_reference' => 'BLR020020::CRB', 'reference' => 'BLR0020020'), array('id_product' => 113, 'supplier_reference' => 'BLR020021::CRB', 'reference' => 'BLR0020021'), array('id_product' => 114, 'supplier_reference' => 'BLR020022::CRB', 'reference' => 'BLR0020022'), array('id_product' => 115, 'supplier_reference' => 'BLR020023::CRB', 'reference' => 'BLR0020023'), );*/ foreach ($res as $product) { self::echomsg(null, "--------------------------------------------------", true); $id_product = $product['id_product']; $supplier_reference = $product['supplier_reference']; $reference = $product['reference']; if (empty($supplier_reference)) { self::echomsg($product, "No Vendor Code", true); continue; } $sup_details = explode("::", $supplier_reference); if (count($sup_details) !== 2) { self::echomsg($product, "Invalid Vendor Code {$supplier_reference}", true); continue; } self::echomsg($product, "Waiting for response"); $design_no = $sup_details[0]; $item_code = $sup_details[1]; $qres = self::getQuantityByItemcode($id_product, $design_no, $item_code); if ($qres === false) { $sql = "update sudarshan_details set valid = 0 where id_product = {$id_product}"; $db->ExecuteS($sql); self::echomsg($product, "Failed to get quantity - Updating quantity to 5 and shipping sla to 15 days", true); $quantity = 5; $shipping_sla = 15; } else { $sql = "update sudarshan_details set valid = 1 where id_product = {$id_product}"; $db->ExecuteS($sql); $quantity = (int) $qres->GetQuantityResult; if ($quantity === 0) { $quantity = 5; $shipping_sla = 15; } else { $shipping_sla = 3; } self::echomsg($product, "Vendor Quantity {$quantity}"); } $dbproduct = new Product($id_product); $old_quantity = (int) $dbproduct->quantity; //$sql = "select quantity from ps_product where id_product = {$id_product}"; //$res = $db->ExecuteS($sql); //$old_quantity = (int)$res[0]["quantity"]; if ($quantity === $old_quantity && (int) $dbproduct->shipping_sla === $shipping_sla) { self::echomsg($product, "Quantity {$quantity} already upto date", true); continue; } //update DB and Solr $dbproduct->quantity = $quantity; $dbproduct->update(); //$sql = "update ps_product set quantity=$quantity where id_product = $id_product"; //$db->ExecuteS($sql); self::addFeature($id_product, 'shipping_estimate', "Ready to be shipped in {$shipping_sla} days"); SolrSearch::updateProduct($id_product); //Search::indexation(); //Log the update $sql = "insert into stock_sync_data(id_product,old_quantity,new_quantity,id_employee,status) values({$id_product},{$old_quantity},{$quantity},-9999,1)"; $db->ExecuteS($sql); self::echomsg($product, "Updated Product Quantity to {$quantity}", true); } self::echomsg(null, "--------------------------------------------------", true); self::echomsg(null, "End Sudarshan Stock Sync - UpdateQuantity", true); self::send_log_mail('Update Quantity'); }
/** * @param unknown_type $id_category * @param unknown_type $search_query * @param unknown_type $id_manufacturer * @param unknown_type $selectedFilters * @return Solarium_Result_Select */ public function getResults($id_category, $search_query, $id_manufacturer, $selectedFilters = array(), $andquery = TRUE) { global $cookie, $cart, $smarty; //set the price field fro country $price_field = 'offer_price'; $sla_field = 'shipping_sla'; //get the right address for this cart $id_country = (int) Country::getDefaultCountryId(); if ($cart->id_address_delivery) { $address = new Address($cart->id_address_delivery); if ($address->id_country) { $id_country = $address->id_country; } elseif (isset($cookie->id_country)) { $id_country = (int) $cookie->id_country; } } $curr_currency = CurrencyCore::getCurrency($cookie->id_currency); $conversion_rate = $curr_currency['conversion_rate']; $smarty->assign('price_tax_country', $id_country); if ($id_country == 110) { $price_field = 'offer_price_in'; } if ($cookie->id_currency == 4) { $price_field = $price_field . "_rs"; } $new_products = Tools::getValue('latest', false); $sale_products = Tools::getValue('sale', false); $express_shipping = Tools::getValue('express_shipping', false); $cat_id = Tools::getValue('cat_id', false); if ($this->resultSet) { return $this->resultSet; } $n = (int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')); $start = ((int) Tools::getValue('p', 1) - 1) * $n; $rows = $n; $orderby = Tools::getValue('orderby'); $orderway = Tools::getValue('orderway'); //get the facet info // create a client instance $client = SolrSearch::getClient(); // get a select query instance $query = $client->createSelect(); if ($new_products) { $query->setQuery('date_add:[NOW/DAY-1MONTH/DAY TO *]'); } else { if ($sale_products) { $query->setQuery('discount:[1 TO *]'); } else { if ($express_shipping) { $query->setQuery('shipping_sla:[1 TO 2]'); } } } if ($search_query) { $dismax = $query->getDisMax(); $dismax->setQueryFields('name^10 text^1.2 tags^3 reference^10 style_tips^15'); $query->setQuery($search_query); } // add filter queries if ($id_category) { $catFilter = $query->createFilterQuery('cat')->setQuery('+cat_id:' . $id_category); } if ($id_manufacturer) { $manFilter = $query->createFilterQuery('man')->setQuery('+brand_id:' . $id_manufacturer); $id_categories = Tools::getValue('cat_id'); if (!empty($id_categories)) { $id_categories = explode("-", $id_categories); if (is_array($id_categories)) { $id_categories = implode(" OR ", $id_categories); $query->createFilterQuery("des_cat")->setQuery("cat_id: ({$id_categories})"); } } } if (isset($selectedFilters['pr']) && count($selectedFilters['pr']) > 0) { $filterquery = '+' . $price_field . ':('; $pricefilter = $query->createFilterQuery('maxprice'); $pricefilter->addTag($price_field); $selectedPrices = array(); foreach ($selectedFilters['pr'] as $range) { if ($cookie->id_currency == 4) { switch ($range['id']) { case 1: $selectedPrices[] = '[1 TO 1000]'; break; case 2: $selectedPrices[] = '[1001 TO 2500]'; break; case 3: $selectedPrices[] = '[2501 TO 5000]'; break; case 4: $selectedPrices[] = '[5001 TO 10000]'; break; case 5: $selectedPrices[] = '[10001 TO *]'; break; } } else { switch ($range['id']) { case 1: $selectedPrices[] = '[' . Tools::ps_round(1 / $conversion_rate) . ' TO ' . Tools::ps_round(50 / $conversion_rate) . ']'; break; case 2: $selectedPrices[] = '[' . Tools::ps_round(51 / $conversion_rate) . ' TO ' . Tools::ps_round(100 / $conversion_rate) . ']'; break; case 3: $selectedPrices[] = '[' . Tools::ps_round(101 / $conversion_rate) . ' TO ' . Tools::ps_round(150 / $conversion_rate) . ']'; break; case 4: $selectedPrices[] = '[' . Tools::ps_round(151 / $conversion_rate) . ' TO ' . Tools::ps_round(200 / $conversion_rate) . ']'; break; case 5: $selectedPrices[] = '[' . Tools::ps_round(201 / $conversion_rate) . ' TO *]'; break; } } } $filterquery .= implode(" OR ", $selectedPrices); $pricefilter->setQuery($filterquery . ")"); } if (isset($selectedFilters['manufacturer']) && count($selectedFilters['manufacturer']) > 0) { $brandfilter = $query->createFilterQuery('brand'); $brandfilter->addTag('brands'); $brandQuery = '+brand_id:('; $brandsSelected = array(); foreach ($selectedFilters['manufacturer'] as $brand) { $brandsSelected[] = $brand['id']; } $brandQuery .= implode(" OR ", $brandsSelected); $brandfilter->setQuery($brandQuery . ")"); } if (isset($selectedFilters['fabric']) && count($selectedFilters['fabric']) > 0) { $fabricfilter = $query->createFilterQuery('fabric'); $fabricfilter->addTag('fabrics'); $fabricQuery = '+fabric:('; $fabricsSelected = array(); foreach ($selectedFilters['fabric'] as $fabric) { $fabricsSelected[] = $fabric['id']; } $fabricQuery .= implode(" OR ", $fabricsSelected); $fabricfilter->setQuery($fabricQuery . ")"); } if (isset($selectedFilters['stone']) && count($selectedFilters['stone']) > 0) { $stonefilter = $query->createFilterQuery('stone'); $stonefilter->addTag('stones'); $stoneQuery = '+stone:('; $stonesSelected = array(); foreach ($selectedFilters['stone'] as $stone) { $stonesSelected[] = $stone['id']; } $stoneQuery .= implode(" OR ", $stonesSelected); $stonefilter->setQuery($stoneQuery . ")"); } if (isset($selectedFilters['plating']) && count($selectedFilters['plating']) > 0) { $platingfilter = $query->createFilterQuery('plating'); $platingfilter->addTag('platings'); $platingQuery = '+plating:('; $platingsSelected = array(); foreach ($selectedFilters['plating'] as $plating) { $platingsSelected[] = $plating['id']; } $platingQuery .= implode(" OR ", $platingsSelected); $platingfilter->setQuery($platingQuery . ")"); } if (isset($selectedFilters['material']) && count($selectedFilters['material']) > 0) { $materialfilter = $query->createFilterQuery('material'); $materialfilter->addTag('materials'); $materialQuery = '+material:('; $materialsSelected = array(); foreach ($selectedFilters['material'] as $material) { $materialsSelected[] = $material['id']; } $materialQuery .= implode(" OR ", $materialsSelected); $materialfilter->setQuery($materialQuery . ")"); } if (isset($selectedFilters['look']) && count($selectedFilters['look']) > 0) { $lookfilter = $query->createFilterQuery('look'); $lookfilter->addTag('looks'); $lookQuery = '+look:('; $looksSelected = array(); foreach ($selectedFilters['look'] as $look) { $looksSelected[] = $look['id']; } $lookQuery .= implode(" OR ", $looksSelected); $lookfilter->setQuery($lookQuery . ")"); } if (isset($selectedFilters['size']) && count($selectedFilters['size']) > 0) { $sizefilter = $query->createFilterQuery('size'); $sizefilter->addTag('sizes'); $sizeQuery = '+size:('; $sizesSelected = array(); foreach ($selectedFilters['size'] as $size) { $sizesSelected[] = $size['id']; } $sizeQuery .= implode(" OR ", $sizesSelected); $sizefilter->setQuery($sizeQuery . ")"); } if (isset($selectedFilters['customization']) && count($selectedFilters['customization']) > 0) { $custfilter = $query->createFilterQuery('cust'); $custfilter->addTag('customizations'); $custQuery = '+is_customizable:('; $custsSelected = array(); foreach ($selectedFilters['customization'] as $cust) { $custsSelected[] = $cust['id']; } $custQuery .= implode(" OR ", $custsSelected); $custfilter->setQuery($custQuery . ")"); } if (isset($selectedFilters['color']) && count($selectedFilters['color']) > 0) { $colorfilter = $query->createFilterQuery('color'); $colorfilter->addTag('colors'); $colorQuery = '+color:('; $colorsSelected = array(); foreach ($selectedFilters['color'] as $color) { $colorsSelected[] = $color['id']; } $colorQuery .= implode(" OR ", $colorsSelected); $colorfilter->setQuery($colorQuery . ")"); } if (isset($selectedFilters['handbag_occasion']) && count($selectedFilters['handbag_occasion']) > 0) { $handbag_occasionfilter = $query->createFilterQuery('handbag_occasion'); $handbag_occasionfilter->addTag('handbag_occasions'); $handbag_occasionQuery = '+handbag_occasion:('; $handbag_occasionsSelected = array(); foreach ($selectedFilters['handbag_occasion'] as $handbag_occasion) { $handbag_occasionsSelected[] = $handbag_occasion['id']; } $handbag_occasionQuery .= implode(" OR ", $handbag_occasionsSelected); $handbag_occasionfilter->setQuery($handbag_occasionQuery . ")"); } if (isset($selectedFilters['handbag_style']) && count($selectedFilters['handbag_style']) > 0) { $handbag_stylefilter = $query->createFilterQuery('handbag_style'); $handbag_stylefilter->addTag('handbag_styles'); $handbag_styleQuery = '+handbag_style:('; $handbag_stylesSelected = array(); foreach ($selectedFilters['handbag_style'] as $handbag_style) { $handbag_stylesSelected[] = $handbag_style['id']; } $handbag_styleQuery .= implode(" OR ", $handbag_stylesSelected); $handbag_stylefilter->setQuery($handbag_styleQuery . ")"); } if (isset($selectedFilters['handbag_material']) && count($selectedFilters['handbag_material']) > 0) { $handbag_materialfilter = $query->createFilterQuery('handbag_material'); $handbag_materialfilter->addTag('handbag_materials'); $handbag_materialQuery = '+handbag_material:('; $handbag_materialsSelected = array(); foreach ($selectedFilters['handbag_material'] as $handbag_material) { $handbag_materialsSelected[] = $handbag_material['id']; } $handbag_materialQuery .= implode(" OR ", $handbag_materialsSelected); $handbag_materialfilter->setQuery($handbag_materialQuery . ")"); } if (isset($selectedFilters['sla']) && count($selectedFilters['sla']) > 0) { $filterquery = '+' . $sla_field . ':('; $slafilter = $query->createFilterQuery('shipping_sla'); $slafilter->addTag($sla_field); $selectedSlas = array(); foreach ($selectedFilters['sla'] as $range) { switch ($range['id']) { case 1: $selectedSlas[] = '[1 TO 5]'; break; case 2: $selectedSlas[] = '[6 TO 10]'; break; case 3: $selectedSlas[] = '[11 TO 15]'; break; case 4: $selectedSlas[] = '[16 TO 20]'; break; case 5: $selectedSlas[] = '[21 TO *]'; break; } } $filterquery .= implode(" OR ", $selectedSlas); $slafilter->setQuery($filterquery . ")"); } $facetSet = $query->getFacetSet(); $facetSet->setMinCount(1); $facetSet->createFacetField('cat_id')->setField('cat_id'); $facet = $facetSet->createFacetRange('priceranges'); $facet->setField($price_field); $facet->setStart(0); if ($cookie->id_currency == 4) { $facet->setGap(500); $facet->setEnd(10000); } else { $facet->setGap(Tools::ps_round(50 / $conversion_rate)); $facet->setEnd(Tools::ps_round(200 / $conversion_rate)); } $facet->setInclude(Solarium_Query_Select_Component_Facet_Range::INCLUDE_UPPER); $facet->setOther(Solarium_Query_Select_Component_Facet_Range::OTHER_AFTER); $facet->addExclude($price_field); $facet = $facetSet->createFacetRange('slaranges'); $facet->setField($sla_field); $facet->setStart(0); $facet->setGap(5); $facet->setEnd(20); $facet->setInclude(Solarium_Query_Select_Component_Facet_Range::INCLUDE_UPPER); $facet->setOther(Solarium_Query_Select_Component_Facet_Range::OTHER_AFTER); $facet->addExclude($sla_field); if (!$id_manufacturer) { $facet = $facetSet->createFacetField('brand_id'); $facet->setField('brand_id'); $facet->addExclude('brands'); } $facet = $facetSet->createFacetField('stone'); $facet->setField('stone'); $facet->addExclude('stones'); $facet = $facetSet->createFacetField('plating'); $facet->setField('plating'); $facet->addExclude('platings'); $facet = $facetSet->createFacetField('material'); $facet->setField('material'); $facet->addExclude('materials'); $facet = $facetSet->createFacetField('look'); $facet->setField('look'); $facet->addExclude('looks'); $facet = $facetSet->createFacetField('fabric'); $facet->setField('fabric'); $facet->addExclude('fabrics'); $facet = $facetSet->createFacetField('size'); $facet->setField('size'); $facet->addExclude('sizes'); $facet = $facetSet->createFacetField('is_customizable'); $facet->setField('is_customizable'); $facet->addExclude('customizations'); $facet = $facetSet->createFacetField('color'); $facet->setField('color'); $facet->addExclude('colors'); $facet = $facetSet->createFacetField('handbag_occasion'); $facet->setField('handbag_occasion'); $facet->addExclude('handbag_occasions'); $facet = $facetSet->createFacetField('handbag_style'); $facet->setField('handbag_style'); $facet->addExclude('handbag_styles'); $facet = $facetSet->createFacetField('handbag_material'); $facet->setField('handbag_material'); $facet->addExclude('handbag_materials'); $facet = $facetSet->createFacetField('shipping_sla'); $facet->setField('shipping_sla'); $facet->addExclude('shipping_slas'); $query->setStart($start)->setRows($rows); $query->addSort('inStock', Solarium_Query_Select::SORT_DESC); if ($orderby && $orderway) { $way = Solarium_Query_Select::SORT_DESC; if ($orderby == 'price') { $orderby = $price_field; if ($orderway == 'asc') { $way = Solarium_Query_Select::SORT_ASC; } else { $way = Solarium_Query_Select::SORT_DESC; } } elseif ($orderby == 'discount') { $orderby = 'discount'; } elseif ($orderby == 'hot') { if ($search_query) { $query->addSort('score', Solarium_Query_Select::SORT_DESC); } $orderby = 'sales'; } elseif ($orderby == 'new') { if ($search_query) { $query->addSort('score', Solarium_Query_Select::SORT_DESC); } $orderby = 'date_add'; } if ($express_shipping) { $query->addSort('shipping_sla', Solarium_Query_Select::SORT_ASC); } $query->addSort($orderby, $way); /*if ($orderby != 'hot') { $query->addSort('sales', Solarium_Query_Select::SORT_DESC); $query->addSort('date_add', Solarium_Query_Select::SORT_DESC); }*/ } elseif ($search_query) { $query->addSort('score', Solarium_Query_Select::SORT_DESC); //$query->addSort('sales', Solarium_Query_Select::SORT_DESC); $query->addSort('date_add', Solarium_Query_Select::SORT_DESC); } else { if ($express_shipping) { $query->addSort('shipping_sla', Solarium_Query_Select::SORT_ASC); } else { //$query->addSort('sales', Solarium_Query_Select::SORT_DESC); $query->addSort('date_add', Solarium_Query_Select::SORT_DESC); } } $this->resultSet = SolrSearch::getFromCache($query); if (!$this->resultSet) { $this->resultSet = $client->select($query); if ($this->resultSet->getNumFound() == 0) { if (isset($dismax)) { $dismax->setMinimumMatch(0); } $this->resultSet = $client->select($query); } } return $this->resultSet; }
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; }
<?php include dirname(__FILE__) . '/config/config.inc.php'; include dirname(__FILE__) . '/init.php'; include dirname(__FILE__) . '/header.php'; $top_categories = array(array(2, 'sarees', 'Sarees'), array(3, 'salwar-kameez', 'Salwar Kameez'), array(1202, 'tops', 'Tops'), array(5, 'lehenga', 'Lehenga Choli'), array(454, 'jewelry', 'Jewelery'), array(450, 'indusdiva-pick', 'Exclusive Designs')); $cat_products = array(); foreach ($top_categories as $category) { $category_name = $category[2]; $category_link = $category[1]; $id_category = $category[0]; if (!is_array($cat_products[$category_name])) { $cat_products[$category_name] = array(); $cat_products[$category_name]["more_link"] = "{$id_category}-{$category_link}#express_shipping=0&sale=0&latest=0&id_category_layered={$id_category}&orderby=new&orderway=desc"; } $client = SolrSearch::getClient(); $query = $client->createSelect(); $query->setQuery('cat_id:' . $id_category); $query->setRows(10); $query->setStart(0); $orderby = 'date_add'; $way = Solarium_Query_Select::SORT_DESC; $query->addSort('inStock', Solarium_Query_Select::SORT_DESC); $query->addSort($orderby, $way); $results = $client->select($query); $total_found = $results->getNumFound(); $products = $results->getData(); $cat_products[$category_name]['products'] = $products['response']['docs']; } //echo "<pre>"; print_r( $cat_products ); exit; $smarty->assign("whats_new_products", $cat_products);
/** * @param Solarium_Query_Select $query * @param Solarium_Result_Select $resultset */ public static function cacheResult($query, $resultset) { if (!self::$resultCache) { self::$resultCache = array(); } $cacheKey = self::getKey($query); self::$resultCache[$cacheKey] = $resultset; }
public function preProcess() { if ($id_manufacturer = Tools::getValue('id_manufacturer')) { $this->productSort(); $remarketing_code = false; switch ($id_manufacturer) { case 116: $remarketing_code = "kl92CIiC5QMQmKP4zQM"; break; case 95: $remarketing_code = "sNEZCJCB5QMQmKP4zQM"; break; case 81: $remarketing_code = "NGiBCJiA5QMQmKP4zQM"; break; case 122: $remarketing_code = "RCfKCKD_5AMQmKP4zQM"; break; case 92: $remarketing_code = "0IK5CKj-5AMQmKP4zQM"; break; case 80: $remarketing_code = "aJbDCLD95AMQmKP4zQM"; break; case 71: $remarketing_code = "OusXCLj85AMQmKP4zQM"; break; case 70: $remarketing_code = "QCzPCMD75AMQmKP4zQM"; break; case 82: $remarketing_code = "U56cCMj65AMQmKP4zQM"; break; case 74: $remarketing_code = "R5LhCND55AMQmKP4zQM"; break; case 76: $remarketing_code = "DEchCKjAuwMQmKP4zQM"; break; case 78: $remarketing_code = "Pgf6CKDBuwMQmKP4zQM"; break; case 91: $remarketing_code = "_SisCMCoxwMQmKP4zQM"; break; case 11: $remarketing_code = "2OGTCJCuxwMQmKP4zQM"; break; case 18: $remarketing_code = "96c8CICwxwMQmKP4zQM"; break; case 73: $remarketing_code = "IMWcCPiwxwMQmKP4zQM"; break; case 79: $remarketing_code = "ONBTCPCxxwMQmKP4zQM"; break; case 121: $remarketing_code = "l37kCND68QMQmKP4zQM"; break; case 162: $remarketing_code = "DPxqCNj58QMQmKP4zQM"; break; case 69: $remarketing_code = "Nj-6CPiD5QMQmKP4zQM"; break; case 119: $remarketing_code = "mQJ6CICD5QMQmKP4zQM"; break; case 132: $remarketing_code = "ptPzCMj78QMQmKP4zQM"; break; case 153: $remarketing_code = "wplxCLD-8QMQmKP4zQM"; break; case 135: $remarketing_code = "1FgSCMD88QMQmKP4zQM"; break; case 94: $remarketing_code = "RvR3CLj98QMQmKP4zQM"; break; } if ($remarketing_code) { self::$smarty->assign('remarketing_code', $remarketing_code); } $this->manufacturer = new Manufacturer((int) $id_manufacturer, self::$cookie->id_lang); if (Validate::isLoadedObject($this->manufacturer) and $this->manufacturer->active) { $nbProducts = 0; $this->n = (int) Configuration::get('PS_PRODUCTS_PER_PAGE'); $this->p = abs((int) Tools::getValue('p', 1)); try { global $cart, $cookie; $id_country = (int) Country::getDefaultCountryId(); if ($cart->id_address_delivery) { $address = new Address($cart->id_address_delivery); if ($address->id_country) { $id_country = $address->id_country; } elseif (isset($cookie->id_country)) { $id_country = (int) $cookie->id_country; } } self::$smarty->assign('price_tax_country', $id_country); $products = SolrSearch::getBrandProducts((int) $id_manufacturer, $nbProducts); } catch (Exception $e) { self::$smarty->assign('fetch_error', 1); } //$nbProducts = $this->manufacturer->getProducts((int)$id_manufacturer, NULL, NULL, NULL, $this->orderBy, $this->orderWay, true); $this->pagination((int) $nbProducts); $this->page_products = $products; self::$smarty->assign(array('nb_products' => $nbProducts, 'products' => $this->page_products, 'path' => $this->manufacturer->active ? Tools::safeOutput($this->manufacturer->name) : '', 'manufacturer' => $this->manufacturer)); if ($this->manufacturer->description) { self::$smarty->assign('show_details', 1); } self::$smarty->assign('lazy', 1); } else { header('HTTP/1.1 404 Not Found'); header('Status: 404 Not Found'); $this->errors[] = Tools::displayError('Manufacturer does not exist.'); } } else { if (Configuration::get('PS_DISPLAY_SUPPLIERS')) { //$data = call_user_func(array('Manufacturer', 'getManufacturers'), true, (int)(self::$cookie->id_lang), true); //$this->pagination($nbProducts); $data = call_user_func(array('Manufacturer', 'getManufacturers'), true, (int) self::$cookie->id_lang, true, $this->p, $this->n); $nbProducts = count($data); $imgDir = _PS_MANU_IMG_DIR_; /* $data = array('acute nightmare','agricultural clown', 'banana','barry scott','beanie','Beechams ','big eyes','board pin ', 'cable','calendar','catagorical','Cauliflower','chainlegs','cheese','chicken ','chicken flavoured sugar sip noodle puffs','chronological', 'dance like michael barrymore','deep down in the desert','Dentalux','dillon','dingleberries','Dreadonaught','dumplings', 'e*********n','elastic band wagon','elastic face','extra long wizard sword', 'facebook','fat goose blister','gammon','Garfunkle flan','gem nose','giggle','glistening old one','glory hole','glue','goldblend', 'harry and the food of the world','hash brown','inbox','jim','kak','kettle','key licence','lecturer','little kangaroo pouch','little mouse','loin cloth','lovejuice','Love walrus', 'makes you weird','mankini','nail stuff','nitro','no more','nostrillious','oblong','pad','pages','paper measure','pen on the new face of a legend', 'radiator','sadomasakistic monk jack','square circle','squid climbing frame','strangers','sugar beet rat','sugar momma','suger plum hole','syndrome','syngenta', 'tape','teddy','urinal','woolworths','you'); */ $chars = range('A', 'Z'); $brandsIndex = array(); foreach ($chars as $char) { $brandsIndex[$char] = array(); } foreach ($data as $brand) { $char = strtoupper(substr($brand['name'], 0, 1)); array_push($brandsIndex[$char], $brand); } $colNumbers = array(0, 1, 2, 3, 4); $cols = array(); foreach ($colNumbers as $colNumber) { $cols[$colNumber] = array(); } $totalGroupSize = 0; foreach ($brandsIndex as $brandChar => $brandGroup) { $totalGroupSize = $totalGroupSize + 60 + count($brandGroup) * 18; } $maxColSize = $totalGroupSize / 5 + 90; $curCol = 0; $curColSize = 0; foreach ($brandsIndex as $brandChar => $brandGroup) { $curGroupSize = 60 + count($brandGroup) * 18; if ($curColSize + $curGroupSize < $maxColSize) { $cols[$curCol][$brandChar] = $brandGroup; $curColSize = $curColSize + $curGroupSize; } else { $curCol++; $cols[$curCol][$brandChar] = $brandGroup; $curColSize = $curGroupSize; } } /* $chars = range('A', 'Z'); $brandsIndex = array(); foreach($chars as $char) $brandsIndex[$char] = array(); foreach($data as $brand) { $char = strtoupper(substr($brand['name'], 0, 1)); array_push($brandsIndex[$char], $brand); } foreach ($data AS &$item) { $item['image'] = (!file_exists($imgDir.'/'.$item['id_manufacturer'].'-medium.jpg')) ? Language::getIsoById((int)(self::$cookie->id_lang)).'-default' : $item['id_manufacturer']; } */ self::$smarty->assign(array('cols' => $cols, 'brandsIndex' => $brandsIndex, 'nbManufacturers' => $nbProducts, 'mediumSize' => Image::getSize('medium'), 'manufacturers' => $data, 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'))); } else { self::$smarty->assign('nbManufacturers', 0); } } }
$sql = "select id_employee from ps_employee where email = '{$t_email}'"; $res = $db->ExecuteS($sql); $id_employee = $res[0]["id_employee"]; $sql = "select quantity from ps_product where id_product = {$id_product}"; $res = $db->ExecuteS($sql); $old_quantity = (int) $res[0]["quantity"]; if ($old_quantity = $quantity) { $error = true; $msg = "Quantity is not updated (May be the quantity is already up to date)"; } else { $product = new Product($id_product); $product->quantity = (int) $quantity; $product->update(); $error = false; $msg = "Quantity is updated successfully"; SolrSearch::updateProduct($id_product); $sql = "insert into stock_sync_data(id_product,old_quantity,new_quantity,id_employee,status) values({$id_product},{$old_quantity},{$quantity},{$id_employee},1)"; $db->Execute($sql); } } $sql = getProductQuery(); $sql = $sql . " where p.id_product = {$id_product} limit 1"; $res = $db->ExecuteS($sql); $product = $res[0]; $product["sourcing_price"] = number_format(Tools::convertPrice($product["sourcing_price"], 4, 2)); $response = array(); $response['status'] = $error ? 'Error' : 'OK'; $response['message'] = $msg; $response['product'] = $product; $response = Tools::jsonEncode($response); $callback = Tools::getValue('callback', false);
/** * 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); } }
public function process() { $productsViewed = (isset(self::$cookie->viewed) and !empty(self::$cookie->viewed)) ? array_slice(explode(',', self::$cookie->viewed), 0, 12) : array(); //$productsViewed = array(3866, 4553, 2338); global $cart; if ($cart->id_address_delivery) { $address = new Address($cart->id_address_delivery); if ($address->id_country) { $id_country = $address->id_country; } elseif (isset($cookie->id_country)) { $id_country = (int) $cookie->id_country; } } else { $id_country = self::$cookie->id_country; } self::$smarty->assign('price_tax_country', $id_country); if (sizeof($productsViewed)) { $total_found = 0; try { $recentlyViewed = SolrSearch::getProductsForIDs($productsViewed, $total_found, 1, 12); self::$smarty->assign('recently_viewed', $recentlyViewed); } catch (Exception $e) { } } }
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); } }
public function addStockMvt($quantity, $id_reason, $id_product_attribute = NULL, $id_order = NULL, $id_employee = NULL) { $stockMvt = new StockMvt(); $stockMvt->id_product = (int) $this->id; $stockMvt->id_product_attribute = (int) $id_product_attribute; $stockMvt->id_order = (int) $id_order; $stockMvt->id_employee = (int) $id_employee; $stockMvt->quantity = (int) $quantity; $stockMvt->id_stock_mvt_reason = (int) $id_reason; $result = $stockMvt->add(); $last_quantity = $this->quantity; // Increase or decrease current product quantity value if ($id_reason == 1) { $this->quantity += abs($quantity); } else { if ($id_reason == 2) { $this->quantity -= abs($quantity); } } Hook::updateQuantity($this, null); //reindex the updated product if ($this->quantity < 1 || $last_quantity < 1 && $this->quantity > 0) { SolrSearch::updateProduct($this->id); } return $result; }
protected function getProductInformation($pid, $size = 'list') { $link = new Link(); $product = new Product($pid, true, 1); $temp = 0; $product = SolrSearch::getProductsForIDs(array($pid), $temp); $product = $product[0]; //echo "<pre>"; print_r( $product ); exit; $info = array(); $info['name'] = strtoupper((string) $product["name"]); $info['description'] = (string) $product['description']; $info['price'] = round($product["mrp"]); $info['sprice'] = round($product["offer_price"]); $info['url'] = $this->buildURL((string) $product["product_link"]); $info['image'] = (string) $product["image_link_{$size}"]; //echo "<pre>"; print_r( $info ); exit; return $info; }
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');
<html> <head> <title>Indusdiva-Sudarshan BLR0002 products list</title> </head> <body style="font-size:0.9em"> <table style="font-size:0.9em;border-collapse:collapse; border:1px solid #CCC;"> <tr> <th> Image</th> <th> Exclusive </th> <th></th> </tr> <?php foreach ($products as $product) { $id_product = $product['id_product']; $found = 0; $sproduct = SolrSearch::getProductsForIDs(array($product['id_product']), $found); if (empty($sproduct)) { $sproduct = new Product($id_product, true, 1); $idImage = $sproduct->getCoverWs(); if ($idImage) { $idImage = $sproduct->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $list_image = $link->getImageLink($sproduct->link_rewrite, $idImage, "medium"); } else { $list_image = $sproduct[0]['image_link_medium']; } if (!empty($product['is_exclusive'])) { echo "<tr style='background-color:#383; color:#FFF; height:205px' id='trow_{$id_product}'>"; } else {
//region $data[] = "Other"; $patterns = array("Animal Print", "Batik", "Checkered", "Floral", "Geometric", "Ikat", "Paisley", "Polka Dots", "Printed", "Solid", "Stripes", "Tattoo", "batik", "checkered", "floral", "ikat", "paisley", "polka dots", "printed", "solid", "stripes", "checkers", "stripe", "checker", "animal print", "print", "Striped", "Print", "Checker", "Checkers", "Check", "check"); $this_pattern = array(); foreach ($patterns as $pattern) { if (stripos($product->name, $pattern) !== false || stripos($product->description, $pattern) !== false || stripos($product->work_type, $pattern) !== false) { array_push($this_pattern, $pattern); } } if (count($this_pattern) > 0) { $data[] = implode("::", $this_pattern); } else { $data[] = "Other"; } $c = 0; $solrProduct = SolrSearch::getProductsForIDs(array($product->id), $c); $data[] = str_replace('large', 'thickbox', $solrProduct[0]['image_link_large']); $c = 2; foreach ($solrProduct[0]['image_links'] as $oImage) { if ($oImage !== $solrProduct[0]['image_link_large']) { $data[] = str_replace('large', 'thickbox', $oImage); $c++; if ($c == 6) { break; } } } $cdata .= tocsv($data) . "\n"; } echo $cdata = str_replace("\r", "", $cdata); exit;
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false) { global $cart, $link, $cookie; $id_payment_state = _PS_PS_NOT_PAID_; $cart = new Cart((int) $id_cart); // Does order already exists ? if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) { if ($secure_key !== false and $secure_key != $cart->secure_key) { die(Tools::displayError()); } // Copying data from cart $order = new Order(); $order->id_carrier = (int) $cart->id_carrier; $order->id_customer = (int) $cart->id_customer; $order->id_address_invoice = (int) $cart->id_address_invoice; $order->id_address_delivery = (int) $cart->id_address_delivery; $vat_address = new Address((int) $order->id_address_delivery); $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency; $order->id_lang = (int) $cart->id_lang; $order->id_cart = (int) $cart->id; $customer = new Customer((int) $order->id_customer); $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key); $order->payment = $paymentMethod; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = (int) $cart->gift; $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $order->total_customization = $cart->getCartCustomizationCost(); $order->total_donation = round($cookie->donation_amount); unset($cookie->donation_amount); if (strpos($order->payment, 'COD') === false) { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true)); } else { $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false)); $order->total_cod = COD_CHARGE; } $order->total_shipping = (double) $cart->getOrderShippingCost(); $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; $shippingdate = $cart->getExpectedShippingDate(); $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s')); // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) { $id_order_state = _PS_OS_ERROR_; $id_payment_state = _PS_PS_NOT_PAID_; } else { if (strpos($order->payment, 'COD') === false) { $id_payment_state = _PS_PS_PAID_; } } //update payment status // Creating order if ($cart->OrderExists() == false) { $cart_value = $cart->getOrderTotal(); if ($cart_value >= 1000) { //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL)) //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE); } $result = $order->add(); } else { $errorMessage = Tools::displayError('An order has already been placed using this cart.'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart)); die($errorMessage); } // Next ! if ($result and isset($order->id)) { if (!$secure_key) { $message .= $this->l('Warning : the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; foreach ($products as $key => $product) { $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL); $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity']; if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) { if (Product::updateQuantity($product, (int) $order->id)) { $product['stock_quantity'] -= $product['cart_quantity']; } if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) { $outOfStock = true; } if ($product['stock_quantity'] < 1) { SolrSearch::updateProduct((int) $product['id_product']); } Product::updateDefaultAttribute($product['id_product']); } $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = NULL; if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) { $productDownload = new ProductDownload((int) $id_product_download); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (Tax::excludeTaxeOption()) { $product['tax'] = 0; $product['rate'] = 0; $tax_rate = 0; } else { $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $ecotaxTaxRate = 0; if (!empty($product['ecotax'])) { $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']); $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $specificPrice = 0; $query .= '(' . (int) $order->id . ', ' . (int) $product['id_product'] . ', ' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . (int) $product['cart_quantity'] . ', ' . $quantityInStock . ', ' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ', ' . (double) Group::getReduction((int) $order->id_customer) . ', ' . $quantityDiscountValue . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\', ' . (double) $tax_rate . ', ' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ', ' . (double) $ecotaxTaxRate . ', ' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),'; $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { if ($text['index'] == 8) { $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 1) { $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />'; } else { if ($text['index'] == 2) { $customizationText .= 'Stitched to measure blouse.' . '<br />'; } else { if ($text['index'] == 3) { $customizationText .= 'Stitched to measure in-skirt.' . '<br />'; } else { if ($text['index'] == 4) { $customizationText .= 'Stitched to measure kurta.' . '<br />'; } else { if ($text['index'] == 5) { $customizationText .= 'Stitched to measure salwar.' . '<br />'; } } } } } } } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />'; } $customizationText .= '---<br />'; } $customizationText = rtrim($customizationText, '---<br />'); $customizationQuantity = (int) $product['customizationQuantityTotal']; $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> </tr>'; } if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td> </tr>'; } //if giftcard, create voucher and send the mails now. $categories = Product::getProductCategories($product['id_product']); if (in_array(CAT_GIFTCARD, $categories)) { $friendsName = ''; $friendsEmail = ''; $giftMessage = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { if ($text['index'] == 21) { $friendsName = $text['value']; } else { if ($text['index'] == 22) { $friendsEmail = $text['value']; } else { if ($text['index'] == 23) { $giftMessage = $text['value']; } else { if ($text['index'] == 25) { $couponCode = $text['value']; } } } } } } } //$couponCode = "GC" . Tools::rand_string(8); // create discount $languages = Language::getLanguages($order); $voucher = new Discount(); $voucher->id_discount_type = 2; foreach ($languages as $language) { $voucher->description[$language['id_lang']] = $product['name']; } $voucher->value = (double) $unitPrice; $voucher->name = $couponCode; $voucher->id_currency = 2; //USD $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = 0; $voucher->active = 1; $voucher->cart_display = 0; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365); /* 365 days */ $voucher->add(); $productObj = new Product($product['id_product'], true, 1); $idImage = $productObj->getCoverWs(); if ($idImage) { $idImage = $productObj->id . '-' . $idImage; } else { $idImage = Language::getIsoById(1) . '-default'; } $params = array(); $params['{voucher_code}'] = $voucher->name; $params['{freinds_name}'] = $friendsName; $params['{gift_message}'] = $giftMessage; $params['{product_name}'] = $product['name']; $params['{voucher_value}'] = $voucher->value; $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location; $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname; $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card'; @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true); } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; $total_discount_value = 0; $shrunk = false; foreach ($discounts as $discount) { $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang); $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) { $voucher = new Discount(); foreach ($objDiscount as $key => $discountValue) { $voucher->{$key} = $discountValue; } $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->value = (double) $value - $amount_to_add; $voucher->add(); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $amount_to_add = $value; } $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add); $total_discount_value += $amount_to_add; if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId((int) $cart->id); if ($oldMessage) { $message = new Message((int) $oldMessage['id_message']); $message->id_order = (int) $order->id; $message->update(); } // Hook new order $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } } if (isset($outOfStock) and $outOfStock) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id); $new_history->addWithemail(true, $extraVars); //Payment status $paymentHistory = new OrderPaymentHistory(); $paymentHistory->id_order = (int) $order->id; $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id); $paymentHistory->addState(); // Order is reloaded because the status just changed $order = new Order($order->id); //Update tracking code for quantium if ($order->id_carrier == QUANTIUM) { if (strpos($order->payment, 'COD') === false) { $order->shipping_number = 'VBN' . $order->id; } else { $order->shipping_number = 'VBC' . $order->id; } $order->update(); } else { if ($order->id_carrier == SABEXPRESS) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } else { if ($order->id_carrier == AFL) { $db = Db::getInstance(); $db->Execute('LOCK TABLES vb_awb_pool WRITE'); $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0"); $awb = $res['awb']; $id = $res['id']; $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id); $db->Execute('UNLOCK TABLES'); $order->shipping_number = $awb; $order->update(); } } } // Send an e-mail to customer if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) { //deduct reward points $points_redeemed = $cart->getPoints(); if ($points_redeemed) { VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add); } /* if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0) { VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add); } */ $invoice = new Address((int) $order->id_address_invoice); $delivery = new Address((int) $order->id_address_delivery); $carrier = new Carrier((int) $order->id_carrier, $order->id_lang); $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false; $shippingdate = new DateTime($order->expected_shipping_date); $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = NULL; } if (Validate::isEmail($customer->email)) { if ($id_order_state == _PS_OS_BANKWIRE_) { Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } else { $data['payment'] = 'Online Payment'; Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } //Send SMS //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com'; //Tools::sendSMS($delivery->phone_mobile, $smsText); } $this->currentOrder = (int) $order->id; return true; } else { $errorMessage = Tools::displayError('Order creation failed'); Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart)); die($errorMessage); } } else { $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }