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);
         }
     }
 }
Exemple #2
0
 public function __construct()
 {
     global $cookie;
     $this->bootstrap = true;
     $this->table = "product";
     $this->identifier = "id_product";
     $this->className = "Product";
     $this->list_no_link = false;
     parent::__construct();
     ${${"GLOBALS"}["ongvhybr"]} = (int) Configuration::get("PS_CURRENCY_DEFAULT");
     $this->addRowAction("");
     $this->confirmations[] = $this->l('Only products waiting approval will be displayed here, no matter what category the product is in. Products have been approved will not appear here.');
     $this->bulk_actions["bulkaproval"] = array("text" => $this->l('Approve'), "confirm" => $this->l('Approve all selected items?'));
     $this->_isSeller = intval($cookie->profile) == Configuration::get("AGILE_MS_PROFILE_ID");
     $this->_join = $this->_join . " LEFT JOIN `" . _DB_PREFIX_ . "product_lang` b ON (a.`id_product` = b.`id_product` AND b.id_lang=" . $cookie->id_lang . ")" . "\tLEFT JOIN `" . _DB_PREFIX_ . "product_owner` po ON (a.`id_product`=po.`id_product`)" . " LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo` s ON (po.`id_owner` = s.`id_seller`)" . " LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo_lang` sl ON (sl.`id_sellerinfo` = s.`id_sellerinfo`AND sl.id_lang=" . $cookie->id_lang . ")" . " LEFT JOIN `" . _DB_PREFIX_ . "image` i ON (i.`id_product` = a.`id_product` AND i.`cover` = 1) " . " LEFT JOIN `" . _DB_PREFIX_ . "category_product` cp ON (cp.`id_product` = a.`id_product` AND cp.id_category=a.id_category_default) " . " LEFT JOIN `" . _DB_PREFIX_ . "tax_rule` tr ON (a.`id_tax_rules_group` = tr.`id_tax_rules_group` AND tr.`id_country` = " . (_PS_VERSION_ >= "1.5" ? Context::getContext()->country->id : (int) Country::getDefaultCountryId()) . " AND tr.`id_state` = 0)" . " LEFT JOIN `" . _DB_PREFIX_ . "tax` t ON (t.`id_tax` = tr.`id_tax`)";
     $this->_select = $this->_select . "b.name, cp.`position`,sl.company AS owner, IFNULL(po.approved,0) AS approved, i.`id_image`, (a.`price` * ((100 + (IFNULL(t.rate,0)))/100)) AS price_final\n\t\t\t," . ${${"GLOBALS"}["ongvhybr"]} . " as id_currency\n\t\t\t,CASE WHEN IFNULL(po.approved,0)=1 THEN '" . $this->_approved_statuses[1] . "' ELSE '" . $this->_approved_statuses[0] . "' END AS approved_text\n            ";
     $this->_where = $this->_where . " AND IFNULL(po.approved,0)=0";
     $this->fields_list = array("id_product" => array("title" => $this->l('ID'), "align" => "center", "width" => 20), "image" => array("title" => $this->l('Photo'), "align" => "center", "image" => "p", "width" => 45, "orderby" => false, "filter" => false, "search" => false), "name" => array("title" => $this->l('Name'), "width" => 220, "filter_key" => "b!name"), "price" => array("title" => $this->l('Base price'), "width" => 70, "type" => "price", "currency" => true, "align" => "right", "filter_key" => "a!price"), "price_final" => array("title" => $this->l('Final price'), "width" => 70, "type" => "price", "currency" => true, "align" => "right", "havingFilter" => true, "orderby" => false), "approved_text" => array("title" => $this->l('Approved'), "width" => 60, "type" => "select", "list" => $this->_approved_statuses, "filter_type" => "int", "filter_key" => "po!approved"), "owner" => array("title" => $this->l('Owner'), "width" => 90, "filter_key" => "owner"));
 }
 /**
  * calculates the price for a specific customer group
  *
  * @param int $shopId
  * @param int $itemId
  * @param int $variantId
  * @param int $groupId
  * @param int $qty
  */
 protected function calculateCustomerGroupPrice($shopId, $itemId, $variantId, $groupId, $qty)
 {
     /*
      * class Product method: priceCalculation is available Since 1.4.0.17
      */
     $specific_price = '';
     // This needs to be passed by reference
     return Product::priceCalculation($shopId, $itemId, $variantId, (int) Country::getDefaultCountryId(), 0, 0, (int) (Validate::isLoadedObject($this->getPlugin()->getContext()->currency) ? $this->getPlugin()->getContext()->currency->id : Configuration::get('PS_CURRENCY_DEFAULT')), $groupId, (int) $qty, $this->getUseTax(), 6, false, true, true, $specific_price, true);
 }
Exemple #4
0
 /**
  * Get available Carriers for Order
  *
  * @param int       $id_zone Zone ID
  * @param array     $groups  Group of the Customer
  * @param Cart|null $cart    Optional Cart object
  * @param array     &$error  Contains an error message if an error occurs
  *
  * @return array Carriers for the order
  */
 public static function getCarriersForOrder($id_zone, $groups = null, $cart = null, &$error = array())
 {
     $context = Context::getContext();
     $id_lang = $context->language->id;
     if (is_null($cart)) {
         $cart = $context->cart;
     }
     if (isset($context->currency)) {
         $id_currency = $context->currency->id;
     }
     if (is_array($groups) && !empty($groups)) {
         $result = Carrier::getCarriers($id_lang, true, false, (int) $id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
     } else {
         $result = Carrier::getCarriers($id_lang, true, false, (int) $id_zone, array(Configuration::get('PS_UNIDENTIFIED_GROUP')), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
     }
     $results_array = array();
     foreach ($result as $k => $row) {
         $carrier = new Carrier((int) $row['id_carrier']);
         $shipping_method = $carrier->getShippingMethod();
         if ($shipping_method != Carrier::SHIPPING_METHOD_FREE) {
             // Get only carriers that are compliant with shipping method
             if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false) {
                 $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION;
                 unset($result[$k]);
                 continue;
             }
             if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false) {
                 $error[$carrier->id] = Carrier::SHIPPING_PRICE_EXCEPTION;
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set to "Deactivate carrier"
             if ($row['range_behavior']) {
                 // Get id zone
                 if (!$id_zone) {
                     $id_zone = (int) Country::getIdZone(Country::getDefaultCountryId());
                 }
                 // Get only carriers that have a range compatible with cart
                 if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone)) {
                     $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION;
                     unset($result[$k]);
                     continue;
                 }
                 if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency)) {
                     $error[$carrier->id] = Carrier::SHIPPING_PRICE_EXCEPTION;
                     unset($result[$k]);
                     continue;
                 }
             }
         }
         $row['name'] = strval($row['name']) != '0' ? $row['name'] : Carrier::getCarrierNameFromShopName();
         $row['price'] = $shipping_method == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getPackageShippingCost((int) $row['id_carrier'], true, null, null, $id_zone);
         $row['price_tax_exc'] = $shipping_method == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getPackageShippingCost((int) $row['id_carrier'], false, null, null, $id_zone);
         $row['img'] = file_exists(_PS_SHIP_IMG_DIR_ . (int) $row['id_carrier'] . '.jpg') ? _THEME_SHIP_DIR_ . (int) $row['id_carrier'] . '.jpg' : '';
         // If price is false, then the carrier is unavailable (carrier module)
         if ($row['price'] === false) {
             unset($result[$k]);
             continue;
         }
         $results_array[] = $row;
     }
     // if we have to sort carriers by price
     $prices = array();
     if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE) {
         foreach ($results_array as $r) {
             $prices[] = $r['price'];
         }
         if (Configuration::get('PS_CARRIER_DEFAULT_ORDER') == Carrier::SORT_BY_ASC) {
             array_multisort($prices, SORT_ASC, SORT_NUMERIC, $results_array);
         } else {
             array_multisort($prices, SORT_DESC, SORT_NUMERIC, $results_array);
         }
     }
     return $results_array;
 }
Exemple #5
0
    protected function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1)
    {
        global $cookie, $smarty;
        $id_seller = $this->seller->id;
        if ($p < 1) {
            $p = 1;
        }
        if ($n <= 0) {
            $n = 10;
        }
        if (empty($orderBy)) {
            $orderBy = 'price';
        } else {
            $orderBy = strtolower($orderBy);
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if ($orderBy == 'id_product' or $orderBy == 'date_add') {
            $orderByPrefix = 'p';
        } elseif ($orderBy == 'name') {
            $orderByPrefix = 'pl';
        } elseif ($orderBy == 'manufacturer') {
            $orderByPrefix = 'm';
            $orderBy = 'name';
        }
        if ($orderBy == 'price') {
            $orderBy = 'orderprice';
        }
        if (!Validate::isBool($active) or !Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $agile_sql_parts = AgileSellerManager::getAdditionalSqlForProducts("p", true);
        if (Module::isInstalled('agilesellerlistoptions') && empty($orderby)) {
            $orderby = 'position2';
        }
        if ($getTotal) {
            $sql = '
			SELECT COUNT(po.`id_product`) AS total
			FROM `' . _DB_PREFIX_ . 'product` p
			LEFT JOIN `' . _DB_PREFIX_ . 'product_owner` po ON p.`id_product` = po.`id_product`
			' . $agile_sql_parts['joins'] . '
			WHERE p.id_category_default>0 AND po.`id_owner` = ' . (int) $this->seller->id . '
			' . ($active ? ' AND p.`active` = 1' : '') . '
			' . $agile_sql_parts['wheres'] . '
			';
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
            return isset($result) ? $result['total'] : 0;
        }
        $sql = '
		        SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			        (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice
					' . $agile_sql_parts['selects'] . '
		        FROM `' . _DB_PREFIX_ . 'product_owner` po
		        LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = po.`id_product`
		        LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		        LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		        LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                                   AND tr.`id_country` = ' . (int) (_PS_VERSION_ > '1.5' ? Context::getContext()->country->id : Country::getDefaultCountryId()) . '
	                                           	           AND tr.`id_state` = 0)
	            LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		        LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
    			' . $agile_sql_parts['joins'] . '
		        WHERE p.id_category_default>0 AND po.`id_owner` = ' . $id_seller . '
        			' . ($active ? ' AND p.`active` = 1' : '') . '
        			' . $agile_sql_parts['wheres'] . '
		        ';
        if ($random === true) {
            $sql .= ' ORDER BY RAND()';
            $sql .= ' LIMIT 0, ' . (int) $randomNumberProducts;
        } else {
            $sql .= ' ORDER BY ' . (isset($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
			LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if ($orderBy == 'orderprice') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        $finalResults = Product::getProductsProperties($id_lang, $result);
        $finalResults = AgileSellerManager::prepareSellerRattingInfo($finalResults);
        return $finalResults;
    }
Exemple #6
0
    /**
     * Return cart products
     *
     * @result array Products
     */
    public function getProducts($refresh = false, $id_product = false)
    {
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== NULL and !$refresh) {
            return $this->_products;
        }
        $sql = '
		SELECT cp.`id_product_attribute`, cp.`id_product`, cu.`id_customization`, cp.`quantity` AS cart_quantity, cu.`quantity` AS customization_quantity, pl.`name`,
		pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`id_product`, p.`id_category_default`, p.`id_supplier`, p.`id_manufacturer`, p.`on_sale`, p.`ecotax`, p.`additional_shipping_cost`, p.`available_for_order`,
		p.`quantity`, p.`price`, p.`weight`, p.`width`, p.`height`, p.`depth`, p.`out_of_stock`, p.`active`, p.`date_add`, p.`date_upd`, IFNULL(pa.`minimal_quantity`, p.`minimal_quantity`) as minimal_quantity,
		t.`id_tax`, tl.`name` AS tax, t.`rate`, pa.`price` AS price_attribute, pa.`quantity` AS quantity_attribute,
		pa.`ecotax` AS ecotax_attr, pl.`link_rewrite`, cl.`link_rewrite` AS category, CONCAT(cp.`id_product`, cp.`id_product_attribute`) AS unique_id,
		IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
		IF (IFNULL(pa.`supplier_reference`, \'\') = \'\', p.`supplier_reference`, pa.`supplier_reference`) AS supplier_reference,
		(p.`weight`+ pa.`weight`) weight_attribute,
		IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13, IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
		pai.`id_image` pai_id_image, il.`legend` pai_legend
		FROM `' . _DB_PREFIX_ . 'cart_product` cp
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $this->id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (pa.`id_product_attribute` = cp.`id_product_attribute`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
			AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
			AND tr.`id_state` = 0)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $this->id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'customization` cu ON (cp.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = cp.`id_cart`)
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_image` pai ON (pai.`id_product_attribute` = pa.`id_product_attribute`)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $this->id_lang . ')
		WHERE cp.`id_cart` = ' . (int) $this->id . '
		' . ($id_product ? ' AND cp.`id_product` = ' . (int) $id_product : '') . '
		AND p.`id_product` IS NOT NULL
		GROUP BY unique_id
		ORDER BY cp.date_add ASC';
        $result = Db::getInstance()->ExecuteS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $productsIds = array();
        $paIds = array();
        foreach ($result as $row) {
            $productsIds[] = $row['id_product'];
            $paIds[] = $row['id_product_attribute'];
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($productsIds);
        self::cacheSomeAttributesLists($paIds, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        foreach ($result as $row) {
            if (isset($row['ecotax_attr']) and $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) and (int) $row['id_product_attribute']) {
                $row['weight'] = $row['weight_attribute'];
                $row['stock_quantity'] = $row['quantity_attribute'];
            }
            if ($this->_taxCalculationMethod == PS_TAX_EXC) {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : NULL, (int) $this->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} ? (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} : NULL, $specificPriceOutput);
                // Here taxes are computed only once the quantity has been applied to the product price
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : NULL, (int) $this->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} ? (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} : NULL);
                $tax_rate = Tax::getProductTaxRate((int) $row['id_product'], (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                $row['total_wt'] = Tools::ps_round($row['price'] * (double) $row['cart_quantity'] * (1 + (double) $tax_rate / 100), 2);
                $row['total'] = $row['price'] * (int) $row['cart_quantity'];
            } else {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, (int) $row['id_product_attribute'], 6, NULL, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : NULL, (int) $this->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} ? (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} : NULL, $specificPriceOutput);
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, (int) $row['id_product_attribute'], 2, NULL, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : NULL, (int) $this->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} ? (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')} : NULL);
                /* In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals */
                $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
                $row['total_wt'] = $row['price_wt'] * (int) $row['cart_quantity'];
                $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], 2);
            }
            if (!isset($row['pai_id_image']) or $row['pai_id_image'] == 0) {
                $row2 = Db::getInstance()->getRow('
				SELECT i.`id_image`, il.`legend`
				FROM `' . _DB_PREFIX_ . 'image` i
				LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
				WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND i.`cover` = 1');
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = ($specificPriceOutput and (double) $specificPriceOutput['reduction']);
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            $this->_products[] = $row;
        }
        return $this->_products;
    }
    /**
     * Get product accessories
     *
     * @param integer $id_lang Language id
     * @return array Product accessories
     */
    public function getAccessories($id_lang, $active = true)
    {
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`, p.`upc`,
		i.`id_image`, il.`legend`, t.`rate`, m.`name` as manufacturer_name, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(),
		INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new
		FROM `' . _DB_PREFIX_ . 'accessory`
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = `id_product_2`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (p.`id_manufacturer`= m.`id_manufacturer`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
													AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
													AND tr.`id_state` = 0)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		WHERE `id_product_1` = ' . (int) $this->id . '
		' . ($active ? 'AND p.`active` = 1' : ''));
        if (!$result) {
            return false;
        }
        return $this->getProductsProperties($id_lang, $result);
    }
Exemple #8
0
    /**
     * Return current category products
     *
     * @param integer $id_lang Language ID
     * @param integer $p Page number
     * @param integer $n Number of products per page
     * @param boolean $getTotal return the number of results instead of the results themself
     * @param boolean $active return only active products
     * @param boolean $random active a random filter for returned products
     * @param int $randomNumberProducts number of products to return if random is activated
     * @param boolean $checkAccess set to false to return all products (even if customer hasn't access)
     * @return mixed Products or number of products
     */
    public function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1, $checkAccess = true)
    {
        global $cookie;
        if (!$checkAccess or !$this->checkAccess($cookie->id_customer)) {
            return false;
        }
        if ($p < 1) {
            $p = 1;
        }
        if (empty($orderBy)) {
            $orderBy = 'position';
        } else {
            /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */
            $orderBy = strtolower($orderBy);
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if ($orderBy == 'id_product' or $orderBy == 'date_add') {
            $orderByPrefix = 'p';
        } elseif ($orderBy == 'name') {
            $orderByPrefix = 'pl';
        } elseif ($orderBy == 'manufacturer') {
            $orderByPrefix = 'm';
            $orderBy = 'name';
        } elseif ($orderBy == 'position') {
            $orderByPrefix = 'cp';
        }
        if ($orderBy == 'price') {
            $orderBy = 'orderprice';
        }
        if (!Validate::isBool($active) or !Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $id_supplier = (int) Tools::getValue('id_supplier');
        /* Return only the number of products */
        if ($getTotal) {
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT COUNT(cp.`id_product`) AS total
			FROM `' . _DB_PREFIX_ . 'product` p
			LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON p.`id_product` = cp.`id_product`
			WHERE cp.`id_category` = ' . (int) $this->id . ($active ? ' AND p.`active` = 1' : '') . '
			' . ($id_supplier ? 'AND p.id_supplier = ' . (int) $id_supplier : ''));
            return isset($result) ? $result['total'] : 0;
        }
        $sql = '
		SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice
		FROM `' . _DB_PREFIX_ . 'category_product` cp
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
		WHERE cp.`id_category` = ' . (int) $this->id . ($active ? ' AND p.`active` = 1' : '') . '
		' . ($id_supplier ? 'AND p.id_supplier = ' . (int) $id_supplier : '');
        if ($random === true) {
            $sql .= ' ORDER BY RAND()';
            $sql .= ' LIMIT 0, ' . (int) $randomNumberProducts;
        } else {
            $sql .= ' ORDER BY ' . (isset($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
			LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if ($orderBy == 'orderprice') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        /* Modify SQL result */
        return Product::getProductsProperties($id_lang, $result);
    }
    public static function getBestSales($id_lang, $pageNumber = 0, $nbProducts = 10, $orderBy = null, $orderWay = null)
    {
        if ($pageNumber < 0) {
            $pageNumber = 0;
        }
        if ($nbProducts < 1) {
            $nbProducts = 10;
        }
        if (empty($orderBy) || $orderBy == 'position') {
            $orderBy = 'sales';
        }
        if (empty($orderWay)) {
            $orderWay = 'DESC';
        }
        $groups = FrontController::getCurrentCustomerGroups();
        $sqlGroups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT p.*,
			pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, m.`name` manufacturer_name, p.`id_manufacturer` as id_manufacturer,
			i.`id_image`, il.`legend`,
			ps.`quantity` sales, t.`rate`, pl.`meta_keywords`, pl.`meta_title`, pl.`meta_description`,
			DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 new
		FROM `' . _DB_PREFIX_ . 'product_sale` ps
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON ps.`id_product` = p.`id_product`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		WHERE p.`active` = 1
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `' . _DB_PREFIX_ . 'category_group` cg
			LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` ' . $sqlGroups . '
		)
		ORDER BY ' . (isset($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
		LIMIT ' . (int) ($pageNumber * $nbProducts) . ', ' . (int) $nbProducts);
        if ($orderBy == 'price') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        return Product::getProductsProperties($id_lang, $result);
    }
Exemple #10
0
    public static function getNewProducts($id_lang, $pageNumber = 0, $nbProducts = 10, $count = false, $orderBy = NULL, $orderWay = NULL, Context $context = null)
    {
        global $cookie;
        if ($context == null) {
            $context = Context::getContext();
        }
        $agile_sql_parts = AgileSellerManager::getAdditionalSqlForProducts("p", true);
        if (Module::isInstalled('agilesellerlistoptions') && empty($orderby)) {
            $orderby = 'position2';
        }
        if (empty($agile_sql_parts['joins']) or empty($agile_sql_parts['wheres'])) {
            parent::getNewProducts($id_lang, $pageNumber, $nbProducts, $count, $orderBy, $orderWay);
        }
        $front = true;
        if (!in_array($context->controller->controller_type, array('front', 'modulefront'))) {
            $front = false;
        }
        if ($pageNumber < 0) {
            $pageNumber = 0;
        }
        if ($nbProducts < 1) {
            $nbProducts = 10;
        }
        if (empty($orderBy) || $orderBy == 'position') {
            $orderBy = 'date_add';
        }
        if (empty($orderWay)) {
            $orderWay = 'DESC';
        }
        if ($orderBy == 'id_product' or $orderBy == 'price' or $orderBy == 'date_add') {
            $orderByPrefix = 'p';
        } elseif ($orderBy == 'name') {
            $orderByPrefix = 'pl';
        }
        if (!Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $groups = FrontController::getCurrentCustomerGroups();
        $sqlGroups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
        if ($count) {
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT COUNT(p.`id_product`) AS nb
			FROM `' . _DB_PREFIX_ . 'product` p
				' . Shop::addSqlAssociation('product', 'p') . '
			    ' . $agile_sql_parts['joins'] . '
			WHERE product_shop.`active` = 1
			AND DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0
			' . $agile_sql_parts['wheres'] . '
			' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . '
			AND p.`id_product` IN (
				SELECT cp.`id_product`
				FROM `' . _DB_PREFIX_ . 'category_group` cg
				LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
				WHERE cg.`id_group` ' . $sqlGroups . '
			)');
            return (int) $result['nb'];
        }
        $sql = '
		SELECT p.*, pl.`description`,pl.`country`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`, p.`upc`,
			i.`id_image`, il.`legend`, t.`rate`, m.`name` AS manufacturer_name, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * ((100 + (t.`rate`))/100)) AS orderprice, pa.id_product_attribute
			' . $agile_sql_parts['selects'] . '
		FROM `' . _DB_PREFIX_ . 'product` p
				' . Shop::addSqlAssociation('product', 'p') . '
			    ' . $agile_sql_parts['joins'] . '
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT OUTER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND `default_on` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		   AND tr.`id_country` = ' . (_PS_VERSION_ > '1.5' ? (int) Context::getContext()->country->id : (int) Country::getDefaultCountryId()) . '
		   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
		WHERE product_shop.`active` = 1
			' . $agile_sql_parts['wheres'] . '
		AND DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0
		' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . '
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `' . _DB_PREFIX_ . 'category_group` cg
			LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` ' . $sqlGroups . '
		)
		ORDER BY ' . (isset($orderByPrefix) ? pSQL($orderByPrefix) . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
		LIMIT ' . (int) ($pageNumber * $nbProducts) . ', ' . (int) $nbProducts;
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if ($orderBy == 'price') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        $productsIds = array();
        foreach ($result as $row) {
            $productsIds[] = $row['id_product'];
        }
        $finalResults = Product::getProductsProperties((int) $id_lang, $result);
        $finalResults = AgileSellerManager::prepareSellerRattingInfo($finalResults);
        // die('<pre>' . print_r($finalResults, true));
        /*foreach($finalResults as $k => $v) {
        			$country = $v['country'];
        			$flagId = Country::getIdByName(1, $country);
        			$finalResults[$k]['img_exist']	= file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini'. DS . $flagId . '.jpg')? 1 : 0;
        			$finalResults[$k]['img_name']	= $flagId . '.jpg';
        		}*/
        foreach ($finalResults as $key => $value) {
            $seller_id = $value['id_seller'];
            $flagIds = self::getFlagsId($seller_id);
            foreach ($flagIds as $k => $flgId) {
                $finalResults[$key]['img_exist'][$k] = file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini' . DS . $flgId . '.jpg') ? 1 : 0;
                $finalResults[$key]['img_name'][$k] = $flgId . '.jpg';
            }
        }
        return $finalResults;
    }
Exemple #11
0
 public static function getCarrierTaxRate($id_carrier, $id_address = NULL)
 {
     $id_country = (int) Country::getDefaultCountryId();
     $id_state = 0;
     $id_county = 0;
     if (!empty($id_address)) {
         $address_infos = Address::getCountryAndState($id_address);
         if ($address_infos['id_country']) {
             $id_country = (int) $address_infos['id_country'];
             $id_state = (int) $address_infos['id_state'];
             $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']);
         }
         if (!empty($address_infos['vat_number']) and $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') and Configuration::get('VATNUMBER_MANAGEMENT')) {
             return 0;
         }
     }
     return TaxRulesGroup::getTaxesRate((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $id_carrier), (int) $id_country, (int) $id_state, (int) $id_county);
 }
Exemple #12
0
    public static function getProducts($id_category, $id_product, $id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1, $extended = false, $idCountry = NULL)
    {
        /* global $cookie; */
        if (!preg_match("/^1.(3|4).*/", _PS_VERSION_)) {
            $context = Context::getContext();
            if (!$idCountry) {
                /* Used for calculating the taxes */
                $idCountry = (int) $context->country->id;
            }
        }
        if ($p < 1) {
            $p = 1;
        }
        if ($n < 1) {
            $n = 1;
        }
        if (empty($orderBy)) {
            $orderBy = 'position';
        } else {
            /* Fix for all modules which are now using lowercase values for 'orderBy' parameter */
            $orderBy = strtolower($orderBy);
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if ($orderBy == 'id_product' or $orderBy == 'date_add') {
            $orderByPrefix = 'p';
        } elseif ($orderBy == 'name') {
            $orderByPrefix = 'pl';
        } elseif ($orderBy == 'manufacturer') {
            $orderByPrefix = 'm';
            $orderBy = 'name';
        } elseif ($orderBy == 'position') {
            $orderByPrefix = 'cp';
        }
        if ($orderBy == 'price') {
            $orderBy = 'orderprice';
        }
        if (!Validate::isBool($active) or !Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $id_supplier = (int) Tools::getValue('id_supplier');
        /* Return only the number of products */
        if ($getTotal) {
            $result = ProductExtended::getDbInstance()->getRow('
        SELECT COUNT(cp.`id_product`) AS total
        FROM `' . _DB_PREFIX_ . 'product` p
        LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON p.`id_product` = cp.`id_product`
        WHERE cp.`id_category` = ' . (int) $id_category . ($active ? ' AND p.`active` = 1' : '') . '
        ' . ($id_supplier ? 'AND p.id_supplier = ' . (int) $id_supplier : ''));
            return isset($result) ? $result['total'] : 0;
        }
        if (isset($id_category)) {
            $where = 'cp.`id_category` = ' . (int) $id_category;
        } elseif (isset($id_product)) {
            $where = 'p.`id_product` = ' . (int) $id_product;
        }
        if (preg_match("/^1.3.*/", _PS_VERSION_)) {
            $sql = '
      SELECT p.*, p.price as original_price, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
        (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1) - IF((DATEDIFF(`reduction_from`, CURDATE()) <= 0 AND DATEDIFF(`reduction_to`, CURDATE()) >=0) OR `reduction_from` = `reduction_to`, IF(`reduction_price` > 0, `reduction_price`, (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1) * `reduction_percent` / 100)),0)) AS price 
      FROM `' . _DB_PREFIX_ . 'category_product` cp
      LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
      LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
      LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . intval($id_lang) . ')
      LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . intval($id_lang) . ')
      LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
      LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . intval($id_lang) . ')
      LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON t.`id_tax` = p.`id_tax`
      LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . intval($id_lang) . ')
      LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
      WHERE ' . $where . ($active ? ' AND p.`active` = 1' : '') . '
      ' . ($id_supplier ? 'AND p.id_supplier = ' . $id_supplier : '');
        } else {
            if (preg_match("/^1.4.*/", _PS_VERSION_)) {
                $sql = '
        SELECT p.`price` as original_price, p.out_of_stock, p.id_product,p.id_tax_rules_group,p.quantity,p.id_category_default,p.id_manufacturer,p.active,p.id_supplier, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`name`, t.`rate`
        FROM `' . _DB_PREFIX_ . 'category_product` cp
        LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
        LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
        LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $id_lang . ')
        LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
        LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
        LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
      LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
        AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
        AND tr.`id_state` = 0)
        LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
        LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
        LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
        WHERE ' . $where . ($active ? ' AND p.`active` = 1' : '') . '
        ' . ($id_supplier ? 'AND p.id_supplier = ' . (int) $id_supplier : '');
            } else {
                $sql = '
    SELECT product_shop.`price` as original_price, stock.out_of_stock as out_of_stock_2, p.out_of_stock, p.id_product,p.id_tax_rules_group,IFNULL(stock.quantity, 0) as quantity,p.id_category_default,p.id_manufacturer,p.active,p.id_supplier, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`name`, t.`rate`,pl.available_now, (product_shop.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice
				FROM `' . _DB_PREFIX_ . 'category_product` cp
				LEFT JOIN `' . _DB_PREFIX_ . 'product` p
					ON p.`id_product` = cp.`id_product`
				' . Shop::addSqlAssociation('product', 'p') . '
				LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa
				ON (p.`id_product` = pa.`id_product`)
				' . Shop::addSqlAssociation('product_attribute', 'pa', false, 'product_attribute_shop.`default_on` = 1') . '
				' . Product::sqlStock('p', 'product_attribute_shop', false, $context->shop) . '
				LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl
					ON (product_shop.`id_category_default` = cl.`id_category`
					AND cl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('cl') . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
					ON (p.`id_product` = pl.`id_product`
					AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'image` i
					ON (i.`id_product` = p.`id_product`
					AND i.`cover` = 1)
				LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il
					ON (i.`id_image` = il.`id_image`
					AND il.`id_lang` = ' . (int) $id_lang . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr
					ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group`
					AND tr.`id_country` = ' . $idCountry . '
					AND tr.`id_state` = 0
					AND tr.`zipcode_from` = 0)
				LEFT JOIN `' . _DB_PREFIX_ . 'tax` t
					ON (t.`id_tax` = tr.`id_tax`)
				LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl
					ON (t.`id_tax` = tl.`id_tax`
					AND tl.`id_lang` = ' . (int) $id_lang . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m
					ON m.`id_manufacturer` = p.`id_manufacturer`
				WHERE ' . $where . ' AND product_shop.`id_shop` = ' . (int) $context->shop->id . '
				AND ((product_attribute_shop.id_product_attribute IS NOT NULL OR pa.id_product_attribute IS NULL) 
					OR (product_attribute_shop.id_product_attribute IS NULL AND pa.default_on=1))' . ($active ? ' AND product_shop.`active` = 1' : '') . ($id_supplier ? ' AND p.id_supplier = ' . (int) $id_supplier : '');
            }
        }
        if ($random === true) {
            $sql .= ' ORDER BY RAND()';
            $sql .= ' LIMIT 0, ' . (int) $randomNumberProducts;
        } else {
            $sql .= ' ORDER BY ' . (isset($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
        LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        }
        $result = ProductExtended::getDbInstance()->ExecuteS($sql);
        if ($orderBy == 'orderprice') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        return $extended ? ProductExtended::getProductsProperties($id_lang, $result) : $result;
    }
    public function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1, $checkAccess = true)
    {
        global $cookie;
        $sql = '
		SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice
		FROM `' . _DB_PREFIX_ . 'category_product` cp
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
		WHERE p.on_sale > 0 GROUP BY p.`id_product`';
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if (!$result) {
            return false;
        }
        /* Modify SQL result */
        return Product::getProductsProperties($id_lang, $result);
    }
Exemple #14
0
	/**
	 *
	 * @param int $id_zone
	 * @param Array $groups group of the customer
	 * @return Array
	 */
	public static function getCarriersForOrder($id_zone, $groups = null, $cart = null)
	{
		
		$context = Context::getContext();
		$id_lang = $context->language->id;
		if (is_null($cart))
			$cart = $context->cart;
		$id_currency = $context->currency->id;

		if (is_array($groups) && !empty($groups))
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		else
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, array(Configuration::get('PS_UNIDENTIFIED_GROUP')), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		$results_array = array();
                
               // var_dump($result);
		foreach ($result as $k => $row)
		{
			$carrier = new Carrier((int)$row['id_carrier']);
			$shipping_method = $carrier->getShippingMethod();
			if ($shipping_method != Carrier::SHIPPING_METHOD_FREE)
			{
				// Get only carriers that are compliant with shipping method
				if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false)
					|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false))
				{
					unset($result[$k]);
					continue;
				}

				// If out-of-range behavior carrier is set on "Desactivate carrier"
				if ($row['range_behavior'])
				{
					// Get id zone
					if (!$id_zone)
							$id_zone = Country::getIdZone(Country::getDefaultCountryId());

					// Get only carriers that have a range compatible with cart
					if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT
						&& (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone)))
						|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE
						&& (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency))))
					{
						unset($result[$k]);
						continue;
					}
				}
			}

			$row['name'] = (strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME'));
			$row['price'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], true, null, null, $id_zone));
			$row['price_tax_exc'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], false, null, null, $id_zone));
			$row['img'] = file_exists(_PS_SHIP_IMG_DIR_.(int)$row['id_carrier']).'.jpg' ? _THEME_SHIP_DIR_.(int)$row['id_carrier'].'.jpg' : '';

			// If price is false, then the carrier is unavailable (carrier module)
			if ($row['price'] === false)
			{
                            $row['price'] = 0;
//				unset($result[$k]);
//				continue;
			}

			//Проверка, если способ доставки - DP, то этот способ доставки доступен, если в корзине только книги
			$log = '';
			$DeutschePostCarrierName = "Deutsche Post"; //название службы доставки "Deutsche post"
			
			$books_cat_ru_name = "Книги";
			$parent_for_books_cat_id = 2;
			$books_KNIGI_lang = 1;

			if ($row['name'] == $DeutschePostCarrierName) {
				//echo "поиск категории Книги";
				$bookscat = Category::searchByNameAndParentCategoryId($books_KNIGI_lang,$books_cat_ru_name,$parent_for_books_cat_id);
				//var_dump($bookscat);
				$books_cat_id = $bookscat["id_category"];
				/*
				id_category"]=> string(1) "3" ["id_parent"]=> string(1) "2" ["id_shop_default"]=> string(1) "1" ["level_depth"]=> string(1) "2" ["nleft"]=> string(1) "3" ["nright"]=> string(3) "102" ["active"]=> string(1) "1" ["date_add"]=> string(19) "2015-02-19 21:05:41" ["date_upd"]=> string(19) "2015-02-19 21:05:41" ["position"]=> string(1) "0" ["is_root_category"]=> string(1) "0" ["id_shop"]=> string(1) "1" ["id_lang"]=> string(1) "1" ["name"]=> string(10) "Книги" ["description"]=> string(0) "" ["link_rewrite"]=> string(5) "knigi" ["meta_title"]=> string(0) "" ["meta_keywords"]=> string(0) "" ["meta_description"]=> string(0) "" }

				*/
				/*
				$books_cat_id = 12; //id категории книги
				$BooksCategory = new Category($books_cat_id);
				$interval = $BooksCategory->getInterval($books_cat_id);
				
				$books_nleft = $interval['nleft'];//21;
				$books_nright = $interval['nright'];//134;
				*/
				$books_nleft = $bookscat["nleft"];
				$books_nright = $bookscat["nright"];
				$cart_products = $cart->getProducts();
				if (!empty($cart_products))
				{ 
					$all_books = true;
					foreach ($cart_products as $key => $cart_product)
					{
						$product = new Product($cart_product['id_product']);
						$categories = $product->getCategories();
						//var_dump($categories);
						if (!empty($categories))
						{
							$product_is_book = false;
							foreach ($categories as $key => $category) 
							{
								//echo $category;
								if ($category == $books_cat_id)
								{
									$product_is_book = true;
									//echo "это в самих книгах";
									break;
								}

								/*искать родителей до рута. если id родителя любого уровня = $books_cat_id, значить это книги*/
								//echo "nleft ".$books_nleft;
								//echo "nright ".$books_nright;
								//echo "<br/><br/>";
								$current_cat_id = $category;
								while (1)
								{
									$current_cat = new Category($current_cat_id);
									//var_dump($current_cat->id_parent);
									if ($current_cat->is_root_category == 1){
										//echo "это корневая категория";
										break;
									}
									if ($current_cat->id_parent == $books_cat_id)
									{
										$product_is_book = true;
										//echo " это книга";
										break;
									}
									$current_cat_id = $current_cat->id_parent;
									
								}
								
								
								if ($category >= $books_nleft AND $category <= $books_nright)
								{
									$product_is_book = true;
									//echo " это книга";
									break;
								}
								//echo " не книга";
							}
						}
						if (!$product_is_book) {
							$all_books = false;
							break;
						}
					}
					if (!$all_books){
						unset($result[$k]);
						continue;
					}
				}
				
			}
			//Конец проверки

			$results_array[] = $row;
		}


		// if we have to sort carriers by price
		$prices = array();
		if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE)
		{
			foreach ($results_array as $r)
				$prices[] = $r['price'];
			if (Configuration::get('PS_CARRIER_DEFAULT_ORDER') == Carrier::SORT_BY_ASC)
				array_multisort($prices, SORT_ASC, SORT_NUMERIC, $results_array);
			else
				array_multisort($prices, SORT_DESC, SORT_NUMERIC, $results_array);
		}

		return $results_array;
	}
Exemple #15
0
    public static function getBestSales($id_lang, $page_number = 0, $nb_products = 10, $order_by = null, $order_way = null)
    {
        $agile_sql_parts = AgileSellerManager::getAdditionalSqlForProducts("p", true);
        if (empty($agile_sql_parts['joins']) or empty($agile_sql_parts['wheres'])) {
            parent::getBestSales($id_lang, $page_number, $nb_products, $order_by, $order_way);
        }
        if ($page_number < 0) {
            $page_number = 0;
        }
        if ($nb_products < 1) {
            $nb_products = 10;
        }
        $final_order_by = $order_by;
        if (empty($order_by) || $order_by == 'position' || ($order_by = 'price')) {
            $order_by = 'sales';
        }
        if (empty($order_way) || $order_by == 'sales') {
            $order_way = 'DESC';
        }
        $groups = FrontController::getCurrentCustomerGroups();
        $sql_groups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
        $interval = Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20;
        $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity,
                                        pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`,
                                        pl.`meta_keywords`, pl.`meta_title`, pl.`name`,
                                        m.`name` AS manufacturer_name, p.`id_manufacturer` as id_manufacturer,
                                        MAX(image_shop.`id_image`) id_image, il.`legend`,
                                        ps.`quantity` AS sales, t.`rate`, pl.`meta_keywords`, pl.`meta_title`, pl.`meta_description`,
                                        MAX(product_attribute_shop.id_product_attribute) id_product_attribute,
                                        IFNULL(pa.minimal_quantity, p.minimal_quantity) as minimal_quantity,
                                        DATEDIFF(p.`date_add`, DATE_SUB(NOW(),
                                        INTERVAL ' . $interval . ' DAY)) > 0 AS new
                                        ' . $agile_sql_parts['selects'] . '
                                FROM `' . _DB_PREFIX_ . 'product_sale` ps
                                LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON ps.`id_product` = p.`id_product`
                                ' . $agile_sql_parts['joins'] . '
                                ' . Shop::addSqlAssociation('product', 'p', false) . '
 
                                LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa
                                        ON (p.`id_product` = pa.`id_product`)
                                ' . Shop::addSqlAssociation('product_attribute', 'pa', false, 'product_attribute_shop.`default_on` = 1') . '
                                ' . Product::sqlStock('p', 'product_attribute_shop', false, Context::getContext()->shop) . '
 
                                LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
                                        ON p.`id_product` = pl.`id_product`
                                        AND pl.`id_lang` = ' . (int) $id_lang . (_PS_VERSION_ > '1.5' ? Shop::addSqlRestrictionOnLang('pl') : '') . '
                                LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product`)' . Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1') . '
                                LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
                                LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
                                LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group`)
                                        AND tr.`id_country` = ' . (_PS_VERSION_ > '1.5' ? (int) Context::getContext()->country->id : Country::getDefaultCountryId()) . '
                                        AND tr.`id_state` = 0
                                LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
                                WHERE product_shop.`active` = 1
                                ' . $agile_sql_parts['wheres'] . '
                                        AND p.`id_product` IN (
                                                SELECT cp.`id_product`
                                                FROM `' . _DB_PREFIX_ . 'category_group` cg
                                                LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)
                                                WHERE cg.`id_group` ' . $sql_groups . '
                                        )
                                        AND ((image_shop.id_image IS NOT NULL OR i.id_image IS NULL) OR (image_shop.id_image IS NULL AND i.cover=1))
                                ORDER BY `' . pSQL($order_by) . '` ' . pSQL($order_way) . '
                                LIMIT ' . (int) ($page_number * $nb_products) . ', ' . (int) $nb_products;
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
        if ($final_order_by == 'price') {
            Tools::orderbyPrice($result, $order_way);
        }
        if (!$result) {
            return false;
        }
        $finalResults = Product::getProductsProperties($id_lang, $result);
        $finalResults = AgileSellerManager::prepareSellerRattingInfo($finalResults);
        return $finalResults;
    }
    protected function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1)
    {
        global $cookie, $smarty;
        $id_seller_country = (int) Tools::getValue('id_seller_country');
        if ($p < 1) {
            $p = 1;
        }
        if ($n <= 0) {
            $n = 10;
        }
        if (empty($orderBy)) {
            $orderBy = 'price';
        } else {
            $orderBy = strtolower($orderBy);
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if ($orderBy == 'id_product' or $orderBy == 'date_add') {
            $orderByPrefix = 'p';
        } elseif ($orderBy == 'name') {
            $orderByPrefix = 'pl';
        } elseif ($orderBy == 'manufacturer') {
            $orderByPrefix = 'm';
            $orderBy = 'name';
        }
        if ($orderBy == 'price') {
            $orderBy = 'orderprice';
        }
        if (!Validate::isBool($active) or !Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $requiredcond = '';
        if (intval(Configuration::get('AGILE_MS_PRODUCT_APPROVAL')) == 1) {
            $requiredcond = ' AND po.approved = 1 ';
        }
        $joins = '';
        $wheres = '';
        if (Module::isInstalled('agilesellerlistoptions')) {
            require_once _PS_ROOT_DIR_ . "/modules/agilesellerlistoptions/agilesellerlistoptions.php";
            $joins = $joins . '
                LEFT JOIN `' . _DB_PREFIX_ . 'seller_listoption` slb ON (p.id_product = slb.id_product AND slb.id_option = ' . AgileSellerListOptions::ASLO_OPTION_LIST . ')
                ';
            $aslo_list_prod_id = intval(Configuration::get('ASLO_PROD_FOR_OPTION' . AgileSellerListOptions::ASLO_OPTION_LIST));
            $wheres = $wheres . ' 
    		    AND (slb.status = ' . AgileSellerListOptions::ASLO_STATUS_IN_EFFECT . '  OR IFNULL(po.id_owner,0) = 0 OR ' . $aslo_list_prod_id . '=' . AgileSellerListOptions::ASLO_ALWAYS_FREE . ')
                ';
        }
        $location_conditions = '';
        switch ($this->location_level) {
            case 'country':
                if ((int) $this->id_location > 0) {
                    $location_conditions = ' AND si.id_country=' . (int) $this->id_location;
                }
                break;
            case 'state':
                if ((int) $this->id_location > 0) {
                    $location_conditions = ' AND si.id_state=' . (int) $this->id_location;
                }
                break;
            case 'city':
                if (!empty($this->id_location)) {
                    $location_conditions = ' AND sil.city=\'' . $this->id_location . '\'';
                }
                break;
            case 'sellertype':
                if (!empty($this->id_location)) {
                    $location_conditions = ' AND si.id_sellertype1=' . $this->id_location;
                }
                break;
            case 'custom':
                if (!empty($this->id_location)) {
                    if (AgileMultipleShop::SHOP_BY_CUSTOM_LANG) {
                        $location_conditions = ' AND sil.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . '=\'' . $this->id_location . '\'';
                    } else {
                        $location_conditions = ' AND si.' . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . '=\'' . $this->id_location . '\'';
                    }
                }
                break;
        }
        if ($getTotal) {
            $sql = '
			SELECT COUNT(po.`id_product`) AS total
			FROM `' . _DB_PREFIX_ . 'product` p
			LEFT JOIN `' . _DB_PREFIX_ . 'product_owner` po ON p.`id_product` = po.`id_product`
	        LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo` si ON si.`id_seller` = po.`id_owner`
	        LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_lang` sil ON si.`id_sellerinfo` = sil.`id_sellerinfo` AND sil.id_lang = ' . $cookie->id_lang . '
			' . $joins . '
			WHERE p.active=1 
				' . $location_conditions . '
			    ' . ($active ? ' AND p.`active` = 1' : '') . '
				' . $requiredcond . '
				' . $wheres . '
			    ';
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
            return isset($result) ? $result['total'] : 0;
        }
        $sql = '
		        SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			        (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice, si.`id_seller`
		        FROM `' . _DB_PREFIX_ . 'product_owner` po
		        LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo` si ON si.`id_seller` = po.`id_owner`
		        LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_lang` sil ON si.`id_sellerinfo` = sil.`id_sellerinfo` AND sil.id_lang = ' . $cookie->id_lang . '
		        LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = po.`id_product`
		        LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		        LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		        LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                                   AND tr.`id_country` = ' . (int) (_PS_VERSION_ > '1.5' ? Context::getContext()->country->id : Country::getDefaultCountryId()) . '
	                                           	           AND tr.`id_state` = 0)
	            LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		        LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $cookie->id_lang . ')
		        LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
				' . $joins . '
		        WHERE p.active=1 
					' . $location_conditions . '
        			' . $requiredcond . '
					' . $wheres . '
		        ';
        if ($random === true) {
            $sql .= ' ORDER BY RAND()';
            $sql .= ' LIMIT 0, ' . (int) $randomNumberProducts;
        } else {
            $sql .= ' ORDER BY ' . (isset($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
			LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if ($orderBy == 'orderprice') {
            Tools::orderbyPrice($result, $orderWay);
        }
        if (!$result) {
            return false;
        }
        $last_result = Product::getProductsProperties($id_lang, $result);
        foreach ($last_result as $key => $value) {
            $seller_id = $value['id_seller'];
            $flagIds = Product::getFlagsId($seller_id);
            foreach ($flagIds as $k => $flgId) {
                $last_result[$key]['img_exist'][$k] = file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini' . DS . $flgId . '.jpg') ? 1 : 0;
                $last_result[$key]['img_name'][$k] = $flgId . '.jpg';
            }
        }
        // die('<pre>' . print_r($last_result, true));
        return $last_result;
    }
Exemple #17
0
 /**
  * Admin panel product search
  *
  * @param integer $id_lang Language id
  * @param string $query Search query
  * @return array Matching products
  */
 public static function searchByName($id_lang, $query)
 {
     $result = Db::getInstance()->ExecuteS('
     SELECT p.`id_product`, pl.`name`, pl.`link_rewrite`, p.`weight`, p.`active`, p.`ecotax`, i.`id_image`, p.`reference`, p.`cache_is_pack`,
     il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name
     FROM `' . _DB_PREFIX_ . 'category_product` cp
     LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
     LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
     LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
        AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
        AND tr.`id_state` = 0)
     LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
     LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
     LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
     LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product`) AND i.`cover` = 1
     LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
     WHERE pl.`name` LIKE \'%' . pSQL($query) . '%\' OR p.`reference` LIKE \'%' . pSQL($query) . '%\' OR p.`supplier_reference` LIKE \'%' . pSQL($query) . '%\'
     GROUP BY `id_product`
     ORDER BY pl.`name` ASC');
     if (!$result) {
         return false;
     }
     $resultsArray = array();
     foreach ($result as $k => $row) {
         $row['price'] = Product::getPriceStatic($row['id_product'], true, NULL, 2);
         $row['quantity'] = Product::getQuantity($row['id_product'], NULL, $row['cache_is_pack']);
         $resultsArray[] = $row;
     }
     return $resultsArray;
 }
    /**
     * 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;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (!$this->active) {
            die(Tools::displayError());
        }
        if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) {
            if ($secure_key !== false && $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->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $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_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
            $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->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            // 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($order->total_paid, 2) != number_format($order->total_paid_real, 2)) {
                $id_order_state = Configuration::get('PS_OS_ERROR');
            }
            // Creating order
            if ($cart->OrderExists() == false) {
                $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`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                $store_all_taxes = array();
                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 != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('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;
                        }
                        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')});
                    /* Store tax info */
                    $id_country = (int) Country::getDefaultCountryId();
                    $id_state = 0;
                    $id_county = 0;
                    $rate = 0;
                    $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
                    $address_infos = Address::getCountryAndState($id_address);
                    if ($address_infos['id_country']) {
                        $id_country = (int) $address_infos['id_country'];
                        $id_state = (int) $address_infos['id_state'];
                        $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']);
                    }
                    $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county);
                    // If its a freeOrder, there will be no calculation
                    if ($order->total_products > 0) {
                        // remove order discount quotepart on product price in order to obtain the real tax
                        $ratio = $price / $order->total_products;
                        $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio;
                        $tmp_price = $price - $order_reduction_amount;
                        foreach ($allTaxes as $res) {
                            if (!isset($store_all_taxes[$res->id])) {
                                $store_all_taxes[$res->id] = array();
                                $store_all_taxes[$res->id]['amount'] = 0;
                            }
                            $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang];
                            $store_all_taxes[$res->id]['rate'] = $res->rate;
                            $unit_tax_amount = $tmp_price * ($res->rate * 0.01);
                            $tmp_price = $tmp_price + $unit_tax_amount;
                            $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity'];
                        }
                    }
                    /* End */
                    // 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 (!_PS_TAX_) {
                        $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')});
                    }
                    $product_price = (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, false);
                    $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100;
                    if (!$group_reduction) {
                        $group_reduction = (double) Group::getReduction((int) $order->id_customer);
                    }
                    $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;
                    $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 . ',
						' . $product_price . ',
						' . (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) . ',
						' . $group_reduction . ',
						' . $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) . '\'),';
                    $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) {
                                    $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />';
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= count($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;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : '&nbsp;') . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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 * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : '&nbsp;') . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $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) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                /* Add carrier tax */
                $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false);
                $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county);
                $nTax = 0;
                foreach ($allTaxes as $tax) {
                    if (!isset($tax->id)) {
                        continue;
                    }
                    if (!isset($store_all_taxes[$tax->id])) {
                        $store_all_taxes[$tax->id] = array();
                    }
                    if (!isset($store_all_taxes[$tax->id]['amount'])) {
                        $store_all_taxes[$tax->id]['amount'] = 0;
                    }
                    $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang];
                    $store_all_taxes[$tax->id]['rate'] = $tax->rate;
                    if (!$nTax++) {
                        $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl;
                    } else {
                        $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01);
                    }
                }
                /* Store taxes */
                foreach ($store_all_taxes as $tax) {
                    Db::getInstance()->Execute('
					INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`)
					VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')');
                }
                // 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']);
                    $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 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;
                            $params['{firstname}'] = $customer->firstname;
                            $params['{lastname}'] = $customer->lastname;
                            $params['{id_order}'] = $order->id;
                            $params['{order_name}'] = sprintf("#%06d", (int) $order->id);
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $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 != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('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) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(Configuration::get('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);
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                // Send an e-mail to customer
                if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) {
                    $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;
                    $data = array('{firstname}' => $customer->firstname, '{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}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{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_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_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'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = null;
                    }
                    if (Validate::isEmail($customer->email)) {
                        Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                    }
                }
                $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 cannot be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }
 /**
  * @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;
 }
    /**
     * Get data source: 
     */
    function getProductsV14($where = '', $limiStart = 0, $limit = 10, $order = '')
    {
        global $cookie, $link;
        $id_lang = intval($cookie->id_lang);
        $sql = '
		SELECT DISTINCT p.id_product, p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice


		FROM `' . _DB_PREFIX_ . 'category_product` cp
		LEFT JOIN `' . _DB_PREFIX_ . 'product` p ON p.`id_product` = cp.`id_product`
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`		
		WHERE  p.`active` = 1' . $where;
        $sql .= ' ORDER BY ' . $order . ' LIMIT ' . $limiStart . ',' . $limit;
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        return Product::getProductsProperties($id_lang, $result);
    }
Exemple #21
0
	/**
	 *
	 * @param int $id_zone
	 * @param Array $groups group of the customer
	 * @return Array
	 */
	public static function getCarriersForOrder($id_zone, $groups = null, $cart = null)
	{
		$context = Context::getContext();
		$id_lang = $context->language->id;
		if (is_null($cart))
			$cart = $context->cart;
		$id_currency = $context->currency->id;

		if (is_array($groups) && !empty($groups))
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		else
			$result = Carrier::getCarriers($id_lang, true, false, (int)$id_zone, array(Configuration::get('PS_UNIDENTIFIED_GROUP')), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
		$results_array = array();
                
		foreach ($result as $k => $row)
		{
			$carrier = new Carrier((int)$row['id_carrier']);
			$shipping_method = $carrier->getShippingMethod();
			if ($shipping_method != Carrier::SHIPPING_METHOD_FREE)
			{
				// Get only carriers that are compliant with shipping method
				if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false)
					|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false))
				{
					unset($result[$k]);
					continue;
				}

				// If out-of-range behavior carrier is set on "Desactivate carrier"
				if ($row['range_behavior'])
				{
					// Get id zone
					if (!$id_zone)
							$id_zone = Country::getIdZone(Country::getDefaultCountryId());

					// Get only carriers that have a range compatible with cart
					if (($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT
						&& (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone)))
						|| ($shipping_method == Carrier::SHIPPING_METHOD_PRICE
						&& (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency))))
					{
						unset($result[$k]);
						continue;
					}
				}
			}

			$row['name'] = (strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME'));
			$row['price'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], true, null, null, $id_zone));
			$row['price_tax_exc'] = (($shipping_method == Carrier::SHIPPING_METHOD_FREE) ? 0 : $cart->getPackageShippingCost((int)$row['id_carrier'], false, null, null, $id_zone));
			$row['img'] = file_exists(_PS_SHIP_IMG_DIR_.(int)$row['id_carrier']).'.jpg' ? _THEME_SHIP_DIR_.(int)$row['id_carrier'].'.jpg' : '';

			// If price is false, then the carrier is unavailable (carrier module)
			if ($row['price'] === false)
			{
                            $row['price'] = 0;
//				unset($result[$k]);
//				continue;
			}

			//Проверка, если способ доставки - DP, то этот способ доставки доступен, если в корзине только книги
			$DeutschePostCarrierName = "Deutsche Post"; //название службы доставки "Deutsche post"
			$books_cat_id = 12; //id категории книги
			if ($row['name'] == $DeutschePostCarrierName) {
				$cart_products = $cart->getProducts();
				if (!empty($cart_products))
				{
					$all_books = true;
					foreach ($cart_products as $key => $cart_product)
					{
						$product = new Product($cart_product['id_product']);
						$categories = $product->getCategories();
						if (!empty($categories))
						{
							$product_is_book = false;
							foreach ($categories as $key => $category) 
							{
								$log .= "категория = ".var_export($category,true)."; ";
								if ($category == $books_cat_id)
								{
									$product_is_book = true;
									break;
								}
							}
						}
						if (!$product_is_book) {
							$all_books = false;
							break;
						}
					}
					if (!$all_books){
						unset($result[$k]);
						continue;
					}
				}
				
			}
			//Конец проверки

			$results_array[] = $row;
		}
		file_put_contents($log_file, $log);

		// if we have to sort carriers by price
		$prices = array();
		if (Configuration::get('PS_CARRIER_DEFAULT_SORT') == Carrier::SORT_BY_PRICE)
		{
			foreach ($results_array as $r)
				$prices[] = $r['price'];
			if (Configuration::get('PS_CARRIER_DEFAULT_ORDER') == Carrier::SORT_BY_ASC)
				array_multisort($prices, SORT_ASC, SORT_NUMERIC, $results_array);
			else
				array_multisort($prices, SORT_DESC, SORT_NUMERIC, $results_array);
		}

		return $results_array;
	}
Exemple #22
0
 public static function getCarrierTaxRate($id_carrier, $id_address = null)
 {
     global $cookie, $defaultCountry;
     $id_country = (int) Country::getDefaultCountryId();
     if ($id_country == _PS_COUNTRY_DEFAULT_ && isset($cookie->id_country) && $cookie->id_country != (int) _PS_COUNTRY_DEFAULT_) {
         $country = new Country((int) $cookie->id_country, $cookie->id_lang);
         if (ValidaTe::isLoadedObject($country) && $country->active) {
             $id_country = (int) $country->id;
             $defaultCountry = $country;
         }
     }
     $id_state = 0;
     $id_county = 0;
     if (!empty($id_address)) {
         $address_infos = Address::getCountryAndState($id_address);
         if ($address_infos['id_country']) {
             $id_country = (int) $address_infos['id_country'];
             $id_state = (int) $address_infos['id_state'];
             $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']);
         }
         if (!empty($address_infos['vat_number']) && $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) {
             return 0;
         }
     }
     return TaxRulesGroup::getTaxesRate((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $id_carrier), (int) $id_country, (int) $id_state, (int) $id_county);
 }
Exemple #23
0
    public static function getPacksTable($id_product, $id_lang, $full = false, $limit = NULL)
    {
        $packs = Db::getInstance()->getValue('
		SELECT GROUP_CONCAT(a.`id_product_pack`)
		FROM `' . _DB_PREFIX_ . 'pack` a
		WHERE a.`id_product_item` = ' . (int) $id_product);
        if (!(int) $packs) {
            return array();
        }
        $sql = '
		SELECT p.*, pl.*, i.`id_image`, il.`legend`, t.`rate`
		FROM `' . _DB_PREFIX_ . 'product` p
		NATURAL LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		WHERE pl.`id_lang` = ' . (int) $id_lang . '
		AND p.`id_product` IN (' . $packs . ')';
        if ($limit) {
            $sql .= ' LIMIT ' . (int) $limit;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if (!$full) {
            return $result;
        }
        $arrayResult = array();
        foreach ($result as $row) {
            if (!Pack::isPacked($row['id_product'])) {
                $arrayResult[] = Product::getProductProperties($id_lang, $row);
            }
        }
        return $arrayResult;
    }
 protected function getProducts($id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $random = false, $randomNumberProducts = 1)
 {
     $lgngixep = "orderBy";
     ${"GLOBALS"}["xbbxtwtpju"] = "orderBy";
     ${"GLOBALS"}["oswfwomb"] = "orderBy";
     global $cookie, $smarty;
     ${"GLOBALS"}["sxnzkqefjkv"] = "p";
     ${"GLOBALS"}["kjemucya"] = "id_seller_country";
     ${"GLOBALS"}["plbenbkqq"] = "orderBy";
     $suwenwdcxtu = "orderByPrefix";
     ${${"GLOBALS"}["kjemucya"]} = (int) Tools::getValue("id_seller_country");
     $ljwznznuwp = "n";
     ${"GLOBALS"}["vwrkkkltgp"] = "orderWay";
     ${"GLOBALS"}["kgoezfvpcfs"] = "orderBy";
     ${"GLOBALS"}["iiuykexa"] = "requiredcond";
     $eqwznppjxw = "orderWay";
     ${"GLOBALS"}["juwlrd"] = "orderWay";
     $ycvcyogg = "n";
     ${"GLOBALS"}["ejwtvva"] = "wheres";
     ${"GLOBALS"}["lkqzhjp"] = "p";
     ${"GLOBALS"}["vmpjiojlv"] = "orderBy";
     ${"GLOBALS"}["qksmteq"] = "orderBy";
     if (${${"GLOBALS"}["sxnzkqefjkv"]} < 1) {
         ${${"GLOBALS"}["lkqzhjp"]} = 1;
     }
     if (${$ycvcyogg} <= 0) {
         ${$ljwznznuwp} = 10;
     }
     $yciweepkl = "orderBy";
     ${"GLOBALS"}["xmtrrpsmnv"] = "wheres";
     $hjhvngkubb = "location_conditions";
     if (empty(${${"GLOBALS"}["sqkchfbmzgt"]})) {
         ${${"GLOBALS"}["sqkchfbmzgt"]} = "price";
     } else {
         ${${"GLOBALS"}["vmpjiojlv"]} = strtolower(${${"GLOBALS"}["oswfwomb"]});
     }
     $qsfzjtrtvb = "result";
     if (empty(${$eqwznppjxw})) {
         ${${"GLOBALS"}["vwrkkkltgp"]} = "ASC";
     }
     if (${${"GLOBALS"}["xbbxtwtpju"]} == "id_product" or ${$lgngixep} == "date_add") {
         ${${"GLOBALS"}["holuwdvhswv"]} = "p";
     } elseif (${${"GLOBALS"}["kgoezfvpcfs"]} == "name") {
         ${$suwenwdcxtu} = "pl";
     } elseif (${${"GLOBALS"}["sqkchfbmzgt"]} == "manufacturer") {
         ${"GLOBALS"}["obzythrk"] = "orderByPrefix";
         ${"GLOBALS"}["ijxsporb"] = "orderBy";
         ${${"GLOBALS"}["obzythrk"]} = "m";
         ${${"GLOBALS"}["ijxsporb"]} = "name";
     }
     if (${$yciweepkl} == "price") {
         ${${"GLOBALS"}["qksmteq"]} = "orderprice";
     }
     if (!Validate::isBool(${${"GLOBALS"}["mjjjizv"]}) or !Validate::isOrderBy(${${"GLOBALS"}["plbenbkqq"]}) or !Validate::isOrderWay(${${"GLOBALS"}["juwlrd"]})) {
         die(Tools::displayError());
     }
     ${"GLOBALS"}["durjvvw"] = "joins";
     ${"GLOBALS"}["byhruvgfcplf"] = "orderWay";
     ${${"GLOBALS"}["ccpfwfk"]} = "";
     $kaqgrgykux = "sql";
     if (intval(Configuration::get("AGILE_MS_PRODUCT_APPROVAL")) == 1) {
         ${${"GLOBALS"}["iiuykexa"]} = " AND po.approved = 1 ";
     }
     ${${"GLOBALS"}["durjvvw"]} = "";
     ${${"GLOBALS"}["xmtrrpsmnv"]} = "";
     if (Module::isInstalled("agilesellerlistoptions")) {
         require_once _PS_ROOT_DIR_ . "/modules/agilesellerlistoptions/agilesellerlistoptions.php";
         ${"GLOBALS"}["yyvptwoqtsy"] = "wheres";
         ${${"GLOBALS"}["qjbfcmajvhyd"]} = ${${"GLOBALS"}["qjbfcmajvhyd"]} . "\n                LEFT JOIN `" . _DB_PREFIX_ . "seller_listoption` slb ON (p.id_product = slb.id_product AND slb.id_option = " . AgileSellerListOptions::ASLO_OPTION_LIST . ")\n                ";
         $ghjluom = "aslo_list_prod_id";
         ${${"GLOBALS"}["ppufwe"]} = intval(Configuration::get("ASLO_PROD_FOR_OPTION" . AgileSellerListOptions::ASLO_OPTION_LIST));
         ${${"GLOBALS"}["hylelef"]} = ${${"GLOBALS"}["yyvptwoqtsy"]} . " \n    \t\t    AND (slb.status = " . AgileSellerListOptions::ASLO_STATUS_IN_EFFECT . "  OR IFNULL(po.id_owner,0) = 0 OR " . ${$ghjluom} . "=" . AgileSellerListOptions::ASLO_ALWAYS_FREE . ")\n                ";
     }
     ${${"GLOBALS"}["lrjoesxigovv"]} = "";
     switch ($this->location_level) {
         case "country":
             if ((int) $this->id_location > 0) {
                 ${$hjhvngkubb} = " AND si.id_country=" . (int) $this->id_location;
             }
             break;
         case "state":
             if ((int) $this->id_location > 0) {
                 ${${"GLOBALS"}["lrjoesxigovv"]} = " AND si.id_state=" . (int) $this->id_location;
             }
             break;
         case "city":
             if (!empty($this->id_location)) {
                 ${${"GLOBALS"}["lrjoesxigovv"]} = " AND sil.city='" . $this->id_location . "'";
             }
             break;
         case "sellertype":
             if (!empty($this->id_location)) {
                 ${${"GLOBALS"}["lrjoesxigovv"]} = " AND si.id_sellertype1=" . $this->id_location;
             }
             break;
         case "custom":
             if (!empty($this->id_location)) {
                 if (AgileMultipleShop::SHOP_BY_CUSTOM_LANG) {
                     ${${"GLOBALS"}["lrjoesxigovv"]} = " AND sil." . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . "='" . $this->id_location . "'";
                 } else {
                     ${${"GLOBALS"}["lrjoesxigovv"]} = " AND si." . AgileMultipleShop::SHOP_BY_CUSTOM_FIELD . "='" . $this->id_location . "'";
                 }
             }
             break;
     }
     if (${${"GLOBALS"}["jizkwekrhsnv"]}) {
         $nlecsweh = "wheres";
         ${"GLOBALS"}["yngbfuljr"] = "location_conditions";
         $dhfiohgz = "result";
         $rgelmcniqy = "requiredcond";
         $ccechvvirsfn = "result";
         $htkduiwgscwl = "sql";
         ${$htkduiwgscwl} = "\n\t\t\tSELECT COUNT(po.`id_product`) AS total\n\t\t\tFROM `" . _DB_PREFIX_ . "product` p\n\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "product_owner` po ON p.`id_product` = po.`id_product`\n\t        LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo` si ON si.`id_seller` = po.`id_owner`\n\t        LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo_lang` sil ON si.`id_sellerinfo` = sil.`id_sellerinfo` AND sil.id_lang = " . $cookie->id_lang . "\n\t\t\t" . ${${"GLOBALS"}["qjbfcmajvhyd"]} . "\n\t\t\tWHERE p.active=1 \n\t\t\t\t" . ${${"GLOBALS"}["yngbfuljr"]} . "\n\t\t\t    " . (${${"GLOBALS"}["mjjjizv"]} ? " AND p.`active` = 1" : "") . "\n\t\t\t\t" . ${$rgelmcniqy} . "\n\t\t\t\t" . ${$nlecsweh} . "\n\t\t\t    ";
         ${$dhfiohgz} = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(${${"GLOBALS"}["zrrhonhgudxt"]});
         $ygrlibnhobc = "result";
         return isset(${$ygrlibnhobc}) ? ${$ccechvvirsfn}["total"] : 0;
     }
     ${${"GLOBALS"}["zrrhonhgudxt"]} = "\n\t\t        SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, cl.`name` AS category_default, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL " . (Validate::isUnsignedInt(Configuration::get("PS_NB_DAYS_NEW_PRODUCT")) ? Configuration::get("PS_NB_DAYS_NEW_PRODUCT") : 20) . " DAY)) > 0 AS new,\n\t\t\t        (p.`price` * IF(t.`rate`,((100 + (t.`rate`))/100),1)) AS orderprice\n\t\t        FROM `" . _DB_PREFIX_ . "product_owner` po\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo` si ON si.`id_seller` = po.`id_owner`\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "sellerinfo_lang` sil ON si.`id_sellerinfo` = sil.`id_sellerinfo` AND sil.id_lang = " . $cookie->id_lang . "\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "product` p ON p.`id_product` = po.`id_product`\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = " . (int) $cookie->id_lang . ")\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = " . (int) $cookie->id_lang . ")\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = " . (int) $cookie->id_lang . ")\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`\n\t\t                                                   AND tr.`id_country` = " . (int) (_PS_VERSION_ > "1.5" ? Context::getContext()->country->id : Country::getDefaultCountryId()) . "\n\t                                           \t           AND tr.`id_state` = 0)\n\t            LEFT JOIN `" . _DB_PREFIX_ . "tax` t ON (t.`id_tax` = tr.`id_tax`)\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = " . (int) $cookie->id_lang . ")\n\t\t        LEFT JOIN `" . _DB_PREFIX_ . "manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`\n\t\t\t\t" . ${${"GLOBALS"}["qjbfcmajvhyd"]} . "\n\t\t        WHERE p.active=1 \n\t\t\t\t\t" . ${${"GLOBALS"}["lrjoesxigovv"]} . "\n        \t\t\t" . ${${"GLOBALS"}["ccpfwfk"]} . "\n\t\t\t\t\t" . ${${"GLOBALS"}["ejwtvva"]} . "\n\t\t        ";
     if (${${"GLOBALS"}["urnpvrvfs"]} === true) {
         ${"GLOBALS"}["xeqntuoo"] = "sql";
         $igirpiqeuqmm = "sql";
         ${${"GLOBALS"}["xeqntuoo"]} .= " ORDER BY RAND()";
         ${$igirpiqeuqmm} .= " LIMIT 0, " . (int) ${${"GLOBALS"}["qbznfx"]};
     } else {
         $mwoxesiw = "orderByPrefix";
         ${"GLOBALS"}["mokqqxt"] = "n";
         $tydfnpg = "n";
         ${${"GLOBALS"}["zrrhonhgudxt"]} .= " ORDER BY " . (isset(${${"GLOBALS"}["holuwdvhswv"]}) ? ${$mwoxesiw} . "." : "") . "`" . pSQL(${${"GLOBALS"}["sqkchfbmzgt"]}) . "` " . pSQL(${${"GLOBALS"}["cfsjhhbwbqgs"]}) . "\n\t\t\tLIMIT " . ((int) ${${"GLOBALS"}["vtcbvfsc"]} - 1) * (int) ${${"GLOBALS"}["mokqqxt"]} . "," . (int) ${$tydfnpg};
     }
     ${$qsfzjtrtvb} = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(${$kaqgrgykux});
     if (${${"GLOBALS"}["sqkchfbmzgt"]} == "orderprice") {
         Tools::orderbyPrice(${${"GLOBALS"}["hrmrbao"]}, ${${"GLOBALS"}["byhruvgfcplf"]});
     }
     if (!${${"GLOBALS"}["hrmrbao"]}) {
         return false;
     }
     return Product::getProductsProperties(${${"GLOBALS"}["ytuoqlidml"]}, ${${"GLOBALS"}["hrmrbao"]});
 }
    public static function getProducts($id_supplier, $id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $active_category = true)
    {
        if ($p < 1) {
            $p = 1;
        }
        if (empty($orderBy) or $orderBy == 'position') {
            $orderBy = 'name';
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if (!Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $groups = FrontController::getCurrentCustomerGroups();
        $sqlGroups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
        /* Return only the number of products */
        if ($getTotal) {
            $sql = '
				SELECT p.`id_product`
				FROM `' . _DB_PREFIX_ . 'product` p
				WHERE p.id_supplier = ' . (int) $id_supplier . ($active ? ' AND p.`active` = 1' : '') . '
				AND p.`id_product` IN (
					SELECT cp.`id_product`
					FROM `' . _DB_PREFIX_ . 'category_group` cg
					LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)' . ($active_category ? ' INNER JOIN `' . _DB_PREFIX_ . 'category` ca ON cp.`id_category` = ca.`id_category` AND ca.`active` = 1' : '') . '
					WHERE cg.`id_group` ' . $sqlGroups . '
				)';
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
            return (int) sizeof($result);
        }
        $sql = '
		SELECT p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, s.`name` AS supplier_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * ((100 + (t.`rate`))/100)) AS orderprice, m.`name` AS manufacturer_name
		FROM `' . _DB_PREFIX_ . 'product` p
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'supplier` s ON s.`id_supplier` = p.`id_supplier`
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
		WHERE p.`id_supplier` = ' . (int) $id_supplier . ($active ? ' AND p.`active` = 1' : '') . '
		AND p.`id_product` IN (
					SELECT cp.`id_product`
					FROM `' . _DB_PREFIX_ . 'category_group` cg
					LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)' . ($active_category ? ' INNER JOIN `' . _DB_PREFIX_ . 'category` ca ON cp.`id_category` = ca.`id_category` AND ca.`active` = 1' : '') . '
					WHERE cg.`id_group` ' . $sqlGroups . '
				)
		ORDER BY ' . ($orderBy == 'id_product' ? 'p.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
		LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if (!$result) {
            return false;
        }
        if ($orderBy == 'price') {
            Tools::orderbyPrice($result, $orderWay);
        }
        return Product::getProductsProperties($id_lang, $result);
    }
    function displayFormInformations($obj, $currency)
    {
        parent::displayForm(false);
        global $currentIndex, $cookie, $link;
        $default_country = new Country((int) Configuration::get('PS_COUNTRY_DEFAULT'));
        $iso = Language::getIsoById((int) $cookie->id_lang);
        $has_attribute = false;
        $qty_state = 'readonly';
        $qty = Attribute::getAttributeQty($this->getFieldValue($obj, 'id_product'));
        if ($qty === false) {
            if (Validate::isLoadedObject($obj)) {
                $qty = $this->getFieldValue($obj, 'quantity');
            } else {
                $qty = 1;
            }
            $qty_state = '';
        } else {
            $has_attribute = true;
        }
        $cover = Product::getCover($obj->id);
        $this->_applyTaxToEcotax($obj);
        echo '
		<div class="tab-page" id="step1">
			<h4 class="tab">1. ' . $this->l('Info.') . '</h4>
			<script type="text/javascript">
				$(document).ready(function() {
					updateCurrentText();
					updateFriendlyURL();
					$.ajax({
						url: "' . dirname($currentIndex) . '/ajax.php",
						cache: false,
						dataType: "json",
						data: "ajaxProductManufacturers=1",
						success: function(j) {
							var options = $("select#id_manufacturer").html();
							if (j)
							for (var i = 0; i < j.length; i++)
								options += \'<option value="\' + j[i].optionValue + \'">\' + j[i].optionDisplay + \'</option>\';
							$("select#id_manufacturer").html(options);
						},
						error: function(XMLHttpRequest, textStatus, errorThrown)
						{
							alert(\'Manufacturer ajax error: \'+textStatus);
						}

					});
					$.ajax({
						url: "' . dirname($currentIndex) . '/ajax.php",
						cache: false,
						dataType: "json",
						data: "ajaxProductSuppliers=1",
						success: function(j) {
							var options = $("select#id_supplier").html();
							if (j)
							for (var i = 0; i < j.length; i++)
								options += \'<option value="\' + j[i].optionValue + \'">\' + j[i].optionDisplay + \'</option>\';
							$("select#id_supplier").html(options);
						},
						error: function(XMLHttpRequest, textStatus, errorThrown)
						{
							alert(\'Supplier ajax error: \'+textStatus);
						}

					});
					if ($(\'#available_for_order\').is(\':checked\')){
						$(\'#show_price\').attr(\'checked\', \'checked\');
						$(\'#show_price\').attr(\'disabled\', \'disabled\');
					}
					else {
						$(\'#show_price\').attr(\'disabled\', \'\');
					}
				});
			</script>
			<b>' . $this->l('Product global information') . '</b>&nbsp;-&nbsp;';
        $preview_url = '';
        if (isset($obj->id)) {
            $preview_url = $link->getProductLink($this->getFieldValue($obj, 'id'), $this->getFieldValue($obj, 'link_rewrite', $this->_defaultFormLanguage), Category::getLinkRewrite($this->getFieldValue($obj, 'id_category_default'), (int) $cookie->id_lang));
            if (!$obj->active) {
                $admin_dir = dirname($_SERVER['PHP_SELF']);
                $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
                $token = Tools::encrypt('PreviewProduct' . $obj->id);
                $preview_url .= $obj->active ? '' : '&adtoken=' . $token . '&ad=' . $admin_dir;
            }
            echo '
			<a href="index.php?tab=AdminCatalog&id_product=' . $obj->id . '&deleteproduct&token=' . $this->token . '" style="float:right;"
			onclick="return confirm(\'' . $this->l('Are you sure?', __CLASS__, true, false) . '\');">
			<img src="../img/admin/delete.gif" alt="' . $this->l('Delete this product') . '" title="' . $this->l('Delete this product') . '" /> ' . $this->l('Delete this product') . '</a>
			<a href="' . $preview_url . '" target="_blank"><img src="../img/admin/details.gif" alt="' . $this->l('View product in shop') . '" title="' . $this->l('View product in shop') . '" /> ' . $this->l('View product in shop') . '</a>';
            if (file_exists(_PS_MODULE_DIR_ . 'statsproduct/statsproduct.php')) {
                echo '&nbsp;-&nbsp;<a href="index.php?tab=AdminStats&module=statsproduct&id_product=' . $obj->id . '&token=' . Tools::getAdminToken('AdminStats' . (int) Tab::getIdFromClassName('AdminStats') . (int) $cookie->id_employee) . '"><img src="../modules/statsproduct/logo.gif" alt="' . $this->l('View product sales') . '" title="' . $this->l('View product sales') . '" /> ' . $this->l('View product sales') . '</a>';
            }
        }
        echo '
			<hr class="clear"/>
			<br />
				<table cellpadding="5" style="width: 50%; float: left; margin-right: 20px; border-right: 1px solid #E0D0B1;">
					<tr>
						<td class="col-left">' . $this->l('Name:') . '</td>
						<td style="padding-bottom:5px;" class="translatable">';
        foreach ($this->_languages as $language) {
            echo '		<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
								<input size="43" type="text" id="name_' . $language['id_lang'] . '" name="name_' . $language['id_lang'] . '"
								value="' . stripslashes(htmlspecialchars($this->getFieldValue($obj, 'name', $language['id_lang']))) . '"' . (!$obj->id ? ' onkeyup="if (isArrowKey(event)) return; copy2friendlyURL();"' : '') . ' onkeyup="if (isArrowKey(event)) return; updateCurrentText();" onchange="updateCurrentText();" /><sup> *</sup>
								<span class="hint" name="help_box">' . $this->l('Invalid characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
							</div>';
        }
        echo '		</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Reference:') . '</td>
						<td style="padding-bottom:5px;">
							<input size="55" type="text" name="reference" value="' . htmlentities($this->getFieldValue($obj, 'reference'), ENT_COMPAT, 'UTF-8') . '" style="width: 130px; margin-right: 44px;" />
							<span class="hint" name="help_box">' . $this->l('Special characters allowed:') . ' .-_#\\<span class="hint-pointer">&nbsp;</span></span>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Supplier Reference:') . '</td>
						<td style="padding-bottom:5px;">
							<input size="55" type="text" name="supplier_reference" value="' . htmlentities($this->getFieldValue($obj, 'supplier_reference'), ENT_COMPAT, 'UTF-8') . '" style="width: 130px; margin-right: 44px;" />
							<span class="hint" name="help_box">' . $this->l('Special characters allowed:') . ' .-_#\\<span class="hint-pointer">&nbsp;</span></span>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('EAN13 or JAN:') . '</td>
						<td style="padding-bottom:5px;">
							<input size="55" maxlength="13" type="text" name="ean13" value="' . htmlentities($this->getFieldValue($obj, 'ean13'), ENT_COMPAT, 'UTF-8') . '" style="width: 130px; margin-right: 5px;" /> <span class="small">' . $this->l('(Europe, Japan)') . '</span>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('UPC:') . '</td>
						<td style="padding-bottom:5px;">
							<input size="55" maxlength="12" type="text" name="upc" value="' . htmlentities($this->getFieldValue($obj, 'upc'), ENT_COMPAT, 'UTF-8') . '" style="width: 130px; margin-right: 5px;" /> <span class="small">' . $this->l('(US, Canada)') . '</span>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Location (warehouse):') . '</td>
						<td style="padding-bottom:5px;">
							<input size="55" type="text" name="location" value="' . htmlentities($this->getFieldValue($obj, 'location'), ENT_COMPAT, 'UTF-8') . '" style="width: 130px; margin-right: 44px;" />
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Width ( package ) :') . '</td>
						<td style="padding-bottom:5px;">
							<input size="6" maxlength="6" name="width" type="text" value="' . htmlentities($this->getFieldValue($obj, 'width'), ENT_COMPAT, 'UTF-8') . '" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_DIMENSION_UNIT') . '
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Height ( package ) :') . '</td>
						<td style="padding-bottom:5px;">
							<input size="6" maxlength="6" name="height" type="text" value="' . htmlentities($this->getFieldValue($obj, 'height'), ENT_COMPAT, 'UTF-8') . '" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_DIMENSION_UNIT') . '
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Deep ( package ) :') . '</td>
						<td style="padding-bottom:5px;">
							<input size="6" maxlength="6" name="depth" type="text" value="' . htmlentities($this->getFieldValue($obj, 'depth'), ENT_COMPAT, 'UTF-8') . '" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_DIMENSION_UNIT') . '
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Weight ( package ) :') . '</td>
						<td style="padding-bottom:5px;">
							<input size="6" maxlength="6" name="weight" type="text" value="' . htmlentities($this->getFieldValue($obj, 'weight'), ENT_COMPAT, 'UTF-8') . '" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_WEIGHT_UNIT') . '
						</td>
					</tr>
				</table>
				<table cellpadding="5" style="width: 40%; float: left; margin-left: 10px;">
					<tr>
						<td style="vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Status:') . '</td>
						<td style="padding-bottom:5px;">
							<input style="float:left;" onclick="toggleDraftWarning(false);showOptions(true);" type="radio" name="active" id="active_on" value="1" ' . ($this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '') . '/>
							<label for="active_on" class="t"><img src="../img/admin/enabled.gif" alt="' . $this->l('Enabled') . '" title="' . $this->l('Enabled') . '" style="float:left; padding:0px 5px 0px 5px;" />' . $this->l('Enabled') . '</label>
							<br class="clear" />
							<input style="float:left;" onclick="toggleDraftWarning(true);showOptions(false);"  type="radio" name="active" id="active_off" value="0" ' . (!$this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '') . '/>
							<label for="active_off" class="t"><img src="../img/admin/disabled.gif" alt="' . $this->l('Disabled') . '" title="' . $this->l('Disabled') . '" style="float:left; padding:0px 5px 0px 5px" />' . $this->l('Disabled') . ($obj->active ? '' : ' (<a href="' . $preview_url . '" alt="" target="_blank">' . $this->l('View product in shop') . '</a>)') . '</label>
						</td>
					</tr>
					<tr id="product_options" ' . (!$obj->active ? 'style="display:none"' : '') . '>
						<td style="vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Options:') . '</td>
						<td style="padding-bottom:5px;">
							<input style="float: left;" type="checkbox" name="available_for_order" id="available_for_order" value="1" ' . ($this->getFieldValue($obj, 'available_for_order') ? 'checked="checked" ' : '') . ' onclick="if ($(this).is(\':checked\')){$(\'#show_price\').attr(\'checked\', \'checked\');$(\'#show_price\').attr(\'disabled\', \'disabled\');}else{$(\'#show_price\').attr(\'disabled\', \'\');}"/>
							<label for="available_for_order" class="t"><img src="../img/admin/products.gif" alt="' . $this->l('available for order') . '" title="' . $this->l('available for order') . '" style="float:left; padding:0px 5px 0px 5px" />' . $this->l('available for order') . '</label>
							<br class="clear" />
							<input style="float: left;" type="checkbox" name="show_price" id="show_price" value="1" ' . ($this->getFieldValue($obj, 'show_price') ? 'checked="checked" ' : '') . ' />
							<label for="show_price" class="t"><img src="../img/admin/gold.gif" alt="' . $this->l('display price') . '" title="' . $this->l('show price') . '" style="float:left; padding:0px 5px 0px 5px" />' . $this->l('show price') . '</label>
							<br class="clear" />
							<input style="float: left;" type="checkbox" name="online_only" id="online_only" value="1" ' . ($this->getFieldValue($obj, 'online_only') ? 'checked="checked" ' : '') . ' />
							<label for="online_only" class="t"><img src="../img/admin/basket_error.png" alt="' . $this->l('online only') . '" title="' . $this->l('online only') . '" style="float:left; padding:0px 5px 0px 5px" />' . $this->l('online only (not sold in store)') . '</label>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Condition:') . '</td>
						<td style="padding-bottom:5px;">
							<select name="condition" id="condition">
								<option value="new" ' . ($obj->condition == 'new' ? 'selected="selected"' : '') . '>' . $this->l('New') . '</option>
								<option value="used" ' . ($obj->condition == 'used' ? 'selected="selected"' : '') . '>' . $this->l('Used') . '</option>
								<option value="refurbished" ' . ($obj->condition == 'refurbished' ? 'selected="selected"' : '') . '>' . $this->l('Refurbished') . '</option>
							</select>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Manufacturer:') . '</td>
						<td style="padding-bottom:5px;">
							<select name="id_manufacturer" id="id_manufacturer">
								<option value="0">-- ' . $this->l('Choose (optional)') . ' --</option>';
        if ($id_manufacturer = $this->getFieldValue($obj, 'id_manufacturer')) {
            echo '				<option value="' . $id_manufacturer . '" selected="selected">' . Manufacturer::getNameById($id_manufacturer) . '</option>
								<option disabled="disabled">----------</option>';
        }
        echo '
							</select>&nbsp;&nbsp;&nbsp;<a href="?tab=AdminManufacturers&addmanufacturer&token=' . Tools::getAdminToken('AdminManufacturers' . (int) Tab::getIdFromClassName('AdminManufacturers') . (int) $cookie->id_employee) . '" onclick="return confirm(\'' . $this->l('Are you sure you want to delete product information entered?', __CLASS__, true, false) . '\');"><img src="../img/admin/add.gif" alt="' . $this->l('Create') . '" title="' . $this->l('Create') . '" /> <b>' . $this->l('Create') . '</b></a>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Supplier:') . '</td>
						<td style="padding-bottom:5px;">
							<select name="id_supplier" id="id_supplier">
								<option value="0">-- ' . $this->l('Choose (optional)') . ' --</option>';
        if ($id_supplier = $this->getFieldValue($obj, 'id_supplier')) {
            echo '				<option value="' . $id_supplier . '" selected="selected">' . Supplier::getNameById($id_supplier) . '</option>
								<option disabled="disabled">----------</option>';
        }
        echo '
							</select>&nbsp;&nbsp;&nbsp;<a href="?tab=AdminSuppliers&addsupplier&token=' . Tools::getAdminToken('AdminSuppliers' . (int) Tab::getIdFromClassName('AdminSuppliers') . (int) $cookie->id_employee) . '" onclick="return confirm(\'' . $this->l('Are you sure you want to delete entered product information?', __CLASS__, true, false) . '\');"><img src="../img/admin/add.gif" alt="' . $this->l('Create') . '" title="' . $this->l('Create') . '" /> <b>' . $this->l('Create') . '</b></a>
						</td>
					</tr>
				</table>
				<div class="clear"></div>
				<table cellpadding="5" style="width: 100%;">
					<tr><td colspan="2"><hr style="width:100%;" /></td></tr>';
        $this->displayPack($obj);
        echo '		<tr><td colspan="2"><hr style="width:100%;" /></td></tr>';
        /*
         * Form for add a virtual product like software, mp3, etc...
         */
        $productDownload = new ProductDownload();
        if ($id_product_download = $productDownload->getIdFromIdProduct($this->getFieldValue($obj, 'id'))) {
            $productDownload = new ProductDownload($id_product_download);
        }
        ?>
	<script type="text/javascript">
	// <![CDATA[
		ThickboxI18nImage = '<?php 
        echo $this->l('Image');
        ?>
';
		ThickboxI18nOf = '<?php 
        echo $this->l('of');
        ?>
';
		ThickboxI18nClose = '<?php 
        echo $this->l('Close');
        ?>
';
		ThickboxI18nOrEscKey = '<?php 
        echo $this->l('(or "Esc")');
        ?>
';
		ThickboxI18nNext = '<?php 
        echo $this->l('Next >');
        ?>
';
		ThickboxI18nPrev = '<?php 
        echo $this->l('< Previous');
        ?>
';
		tb_pathToImage = '../img/loadingAnimation.gif';
	//]]>
	</script>
	<script type="text/javascript" src="<?php 
        echo _PS_JS_DIR_;
        ?>
jquery/thickbox-modified.js"></script>
	<script type="text/javascript" src="<?php 
        echo _PS_JS_DIR_;
        ?>
jquery/ajaxfileupload.js"></script>
	<script type="text/javascript" src="<?php 
        echo _PS_JS_DIR_;
        ?>
date.js"></script>
	<style type="text/css">
		<!--
		@import url(<?php 
        echo _PS_CSS_DIR_;
        ?>
thickbox.css);
		-->
	</style>
	<script type="text/javascript">
	//<![CDATA[
	function toggleVirtualProduct(elt)
	{
		if (elt.checked)
		{
			$('#virtual_good').show('slow');
			$('#virtual_good_more').show('slow');
			getE('out_of_stock_1').checked = 'checked';
			getE('out_of_stock_2').disabled = 'disabled';
			getE('out_of_stock_3').disabled = 'disabled';
			getE('label_out_of_stock_2').setAttribute('for', '');
			getE('label_out_of_stock_3').setAttribute('for', '');
		}
		else
		{
			$('#virtual_good').hide('slow');
			$('#virtual_good_more').hide('slow');
			getE('out_of_stock_2').disabled = false;
			getE('out_of_stock_3').disabled = false;
			getE('label_out_of_stock_2').setAttribute('for', 'out_of_stock_2');
			getE('label_out_of_stock_3').setAttribute('for', 'out_of_stock_3');
		}
	}

	function uploadFile()
	{
		$.ajaxFileUpload (
			{
				url:'./uploadProductFile.php',
				secureuri:false,
				fileElementId:'virtual_product_file',
				dataType: 'xml',

				success: function (data, status)
				{
					data = data.getElementsByTagName('return')[0];
					var result = data.getAttribute("result");
					var msg = data.getAttribute("msg");
					var fileName = data.getAttribute("filename");

					if (result == "error")
					{
						$("#upload-confirmation").html('<p>error: ' + msg + '</p>');
					}
					else
					{
						$('#virtual_product_file').remove();
						$('#virtual_product_file_label').hide();
						$('#file_missing').hide();
						new_href = $('#delete_downloadable_product').attr('href').replace('%26deleteVirtualProduct%3Dtrue', '%26file%3D'+msg+'%26deleteVirtualProduct%3Dtrue');
						$('#delete_downloadable_product').attr('href', new_href);
						$('#delete_downloadable_product').show();
						$('#virtual_product_name').attr('value', fileName);
						$('#upload-confirmation').html(
							'<a class="link" href="get-file-admin.php?file='+msg+'&filename='+fileName+'"><?php 
        echo $this->l('The file');
        ?>
&nbsp;"' + fileName + '"&nbsp;<?php 
        echo $this->l('has successfully been uploaded');
        ?>
</a>' +
							'<input type="hidden" id="virtual_product_filename" name="virtual_product_filename" value="' + msg + '" />');
					}
				}
			}
		);
	}

	//]]>
	</script>
	<?php 
        echo '
		<script type="text/javascript" src="../js/price.js"></script>
		<script type="text/javascript">
			var newLabel = \'' . $this->l('New label') . '\';
			var choose_language = \'' . $this->l('Choose language:') . '\';
			var required = \'' . $this->l('required') . '\';
			var customizationUploadableFileNumber = ' . (int) $this->getFieldValue($obj, 'uploadable_files') . ';
			var customizationTextFieldNumber = ' . (int) $this->getFieldValue($obj, 'text_fields') . ';
			var uploadableFileLabel = 0;
			var textFieldLabel = 0;
		</script>';
        ?>
	<tr>
		<td colspan="2">
			<p><input type="checkbox" id="is_virtual_good" name="is_virtual_good" value="true" onclick="toggleVirtualProduct(this);" <?php 
        if (($productDownload->id or Tools::getValue('is_virtual_good') == 'true') and $productDownload->active) {
            echo 'checked="checked"';
        }
        ?>
 />
			<label for="is_virtual_good" class="t bold" style="color: black;"><?php 
        echo $this->l('Is this a downloadable product?');
        ?>
</label></p>
			<div id="virtual_good" <?php 
        if (!$productDownload->id or !$productDownload->active) {
            echo 'style="display:none;"';
        }
        ?>
 >
	<?php 
        if (!ProductDownload::checkWritableDir()) {
            ?>
		<p class="alert">
			<?php 
            echo $this->l('Your download repository is not writable.');
            ?>
<br/>
			<?php 
            echo realpath(_PS_DOWNLOAD_DIR_);
            ?>
		</p>
	<?php 
        } else {
            ?>
			<?php 
            if ($productDownload->id) {
                echo '<input type="hidden" id="virtual_product_id" name="virtual_product_id" value="' . $productDownload->id . '" />';
            }
            ?>
				<p class="block">
	<?php 
            if (!$productDownload->checkFile()) {
                ?>

				<div style="padding:5px;width:50%;float:left;margin-right:20px;border-right:1px solid #E0D0B1">
		<?php 
                if ($productDownload->id) {
                    ?>
					<p class="alert" id="file_missing">
						<?php 
                    echo $this->l('This product is missing');
                    ?>
:<br/>
						<?php 
                    echo realpath(_PS_DOWNLOAD_DIR_) . '/' . $productDownload->physically_filename;
                    ?>
					</p>
		<?php 
                }
                ?>
					<p><?php 
                $max_upload = (int) ini_get('upload_max_filesize');
                $max_post = (int) ini_get('post_max_size');
                $upload_mb = min($max_upload, $max_post);
                echo $this->l('Your server\'s maximum upload file size is') . ':&nbsp;' . $upload_mb . $this->l('Mb');
                ?>
</p>
					<?php 
                if (!strval(Tools::getValue('virtual_product_filename'))) {
                    ?>
					<label id="virtual_product_file_label" for="virtual_product_file" class="t"><?php 
                    echo $this->l('Upload a file');
                    ?>
</label>
					<p><input type="file" id="virtual_product_file" name="virtual_product_file" onchange="uploadFile();" /></p>
					<?php 
                }
                ?>
					<div id="upload-confirmation">
					<?php 
                if ($up_filename = strval(Tools::getValue('virtual_product_filename'))) {
                    ?>
						<input type="hidden" id="virtual_product_filename" name="virtual_product_filename" value="<?php 
                    echo $up_filename;
                    ?>
" />
					<?php 
                }
                ?>
					</div>
					<a id="delete_downloadable_product" style="display:none;" href="confirm.php?height=200&amp;width=300&amp;modal=true&amp;referer=<?php 
                echo rawurlencode($_SERVER['REQUEST_URI'] . '&deleteVirtualProduct=true');
                ?>
" class="thickbox red" title="<?php 
                echo $this->l('Delete this file');
                ?>
"><?php 
                echo $this->l('Delete this file');
                ?>
</a>
	<?php 
            } else {
                ?>
					<input type="hidden" id="virtual_product_filename" name="virtual_product_filename" value="<?php 
                echo $productDownload->physically_filename;
                ?>
" />
					<?php 
                echo $this->l('This is the link') . ':&nbsp;' . $productDownload->getHtmlLink(false, true);
                ?>
					<a href="confirm.php?height=200&amp;width=300&amp;modal=true&amp;referer=<?php 
                echo rawurlencode($_SERVER['REQUEST_URI'] . '&deleteVirtualProduct=true');
                ?>
" class="thickbox red" title="<?php 
                echo $this->l('Delete this file');
                ?>
"><?php 
                echo $this->l('Delete this file');
                ?>
</a>
	<?php 
            }
            // check if file exists
            ?>
				</p>
				<p class="block">
					<label for="virtual_product_name" class="t"><?php 
            echo $this->l('Filename');
            ?>
</label>
					<input type="text" id="virtual_product_name" name="virtual_product_name" style="width:200px" value="<?php 
            echo $productDownload->id > 0 ? $productDownload->display_filename : htmlentities(Tools::getValue('virtual_product_name'), ENT_COMPAT, 'UTF-8');
            ?>
" />
					<span class="hint" name="help_box" style="display:none;"><?php 
            echo $this->l('The full filename with its extension (e.g., Book.pdf)');
            ?>
</span>
				</p>

				</div>
				<div id="virtual_good_more" style="<?php 
            if (!$productDownload->id or !$productDownload->active) {
                echo 'display:none;';
            }
            ?>
padding:5px;width:40%;float:left;margin-left:10px">

				<p class="block">
					<label for="virtual_product_nb_downloable" class="t"><?php 
            echo $this->l('Number of downloads');
            ?>
</label>
					<input type="text" id="virtual_product_nb_downloable" name="virtual_product_nb_downloable" value="<?php 
            echo $productDownload->id > 0 ? $productDownload->nb_downloadable : htmlentities(Tools::getValue('virtual_product_nb_downloable'), ENT_COMPAT, 'UTF-8');
            ?>
" class="" size="6" />
					<span class="hint" name="help_box" style="display:none"><?php 
            echo $this->l('Number of authorized downloads per customer');
            ?>
</span>
				</p>
				<p class="block">
					<label for="virtual_product_expiration_date" class="t"><?php 
            echo $this->l('Expiration date');
            ?>
</label>
					<input type="text" id="virtual_product_expiration_date" name="virtual_product_expiration_date" value="<?php 
            echo $productDownload->id > 0 ? (!empty($productDownload->date_expiration) and $productDownload->date_expiration != '0000-00-00 00:00:00') ? date('Y-m-d', strtotime($productDownload->date_expiration)) : '' : htmlentities(Tools::getValue('virtual_product_expiration_date'), ENT_COMPAT, 'UTF-8');
            ?>
" size="11" maxlength="10" autocomplete="off" /> <?php 
            echo $this->l('Format: YYYY-MM-DD');
            ?>
					<span class="hint" name="help_box" style="display:none"><?php 
            echo $this->l('No expiration date if you leave this blank');
            ?>
</span>
				</p>
				<p class="block">
					<label for="virtual_product_nb_days" class="t"><?php 
            echo $this->l('Number of days');
            ?>
</label>
					<input type="text" id="virtual_product_nb_days" name="virtual_product_nb_days" value="<?php 
            echo $productDownload->id > 0 ? $productDownload->nb_days_accessible : htmlentities(Tools::getValue('virtual_product_nb_days'), ENT_COMPAT, 'UTF-8');
            ?>
" class="" size="4" /><sup> *</sup>
					<span class="hint" name="help_box" style="display:none"><?php 
            echo $this->l('How many days this file can be accessed by customers');
            ?>
 - <em>(<?php 
            echo $this->l('set to zero for unlimited access');
            ?>
)</em></span>
				</p>
				</div>
	<?php 
        }
        // check if download directory is writable
        ?>
			</div>
		</td>
	</tr>
	<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:100%;" /></td></tr>
	<script type="text/javascript">
		if ($('#is_virtual_good').attr('checked'))
		{
			$('#virtual_good').show('slow');
			$('#virtual_good_more').show('slow');
		}
	</script>

<?php 
        echo '
					<tr>
						<td class="col-left">' . $this->l('Pre-tax wholesale price:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" name="wholesale_price" type="text" value="' . htmlentities($this->getFieldValue($obj, 'wholesale_price'), ENT_COMPAT, 'UTF-8') . '" onchange="this.value = this.value.replace(/,/g, \'.\');" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '
							<span style="margin-left:10px">' . $this->l('The wholesale price at which you bought this product') . '</span>
						</td>
					</tr>';
        echo '
					<tr>
						<td class="col-left">' . $this->l('Pre-tax retail price:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" id="priceTE" name="price" type="text" value="' . htmlentities($this->getFieldValue($obj, 'price'), ENT_COMPAT, 'UTF-8') . '" onchange="this.value = this.value.replace(/,/g, \'.\');" onkeyup="if (isArrowKey(event)) return; calcPriceTI();" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '<sup> *</sup>
							<span style="margin-left:2px">' . $this->l('The pre-tax retail price to sell this product') . '</span>
						</td>
					</tr>';
        $tax_rules_groups = TaxRulesGroup::getTaxRulesGroups(true);
        $taxesRatesByGroup = TaxRulesGroup::getAssociatedTaxRatesByIdCountry(Country::getDefaultCountryId());
        $ecotaxTaxRate = Tax::getProductEcotaxRate();
        echo '<script type="text/javascript">';
        echo 'noTax = ' . (Tax::excludeTaxeOption() ? 'true' : 'false'), ";\n";
        echo 'taxesArray = new Array ();' . "\n";
        echo 'taxesArray[0] = 0', ";\n";
        foreach ($tax_rules_groups as $tax_rules_group) {
            $tax_rate = array_key_exists($tax_rules_group['id_tax_rules_group'], $taxesRatesByGroup) ? $taxesRatesByGroup[$tax_rules_group['id_tax_rules_group']] : 0;
            echo 'taxesArray[' . $tax_rules_group['id_tax_rules_group'] . ']=' . $tax_rate . "\n";
        }
        echo '
						ecotaxTaxRate = ' . $ecotaxTaxRate / 100 . ';
					</script>';
        echo '
					<tr>
						<td class="col-left">' . $this->l('Tax rule:') . '</td>
						<td style="padding-bottom:5px;">
					<span ' . (Tax::excludeTaxeOption() ? 'style="display:none;"' : '') . '>
					 <select onChange="javascript:calcPriceTI(); unitPriceWithTax(\'unit\');" name="id_tax_rules_group" id="id_tax_rules_group" ' . (Tax::excludeTaxeOption() ? 'disabled="disabled"' : '') . '>
						 <option value="0">' . $this->l('No Tax') . '</option>';
        foreach ($tax_rules_groups as $tax_rules_group) {
            echo '<option value="' . $tax_rules_group['id_tax_rules_group'] . '" ' . ($this->getFieldValue($obj, 'id_tax_rules_group') == $tax_rules_group['id_tax_rules_group'] ? ' selected="selected"' : '') . '>' . Tools::htmlentitiesUTF8($tax_rules_group['name']) . '</option>';
        }
        echo '</select>

				<a href="?tab=AdminTaxRulesGroup&addtax_rules_group&token=' . Tools::getAdminToken('AdminTaxRulesGroup' . (int) Tab::getIdFromClassName('AdminTaxRulesGroup') . (int) $cookie->id_employee) . '&id_product=' . (int) $obj->id . '" onclick="return confirm(\'' . $this->l('Are you sure you want to delete entered product information?', __CLASS__, true, false) . '\');"><img src="../img/admin/add.gif" alt="' . $this->l('Create') . '" title="' . $this->l('Create') . '" /> <b>' . $this->l('Create') . '</b></a></span>
				';
        if (Tax::excludeTaxeOption()) {
            echo '<span style="margin-left:10px; color:red;">' . $this->l('Taxes are currently disabled') . '</span> (<b><a href="index.php?tab=AdminTaxes&token=' . Tools::getAdminToken('AdminTaxes' . (int) Tab::getIdFromClassName('AdminTaxes') . (int) $cookie->id_employee) . '">' . $this->l('Tax options') . '</a></b>)';
            echo '<input type="hidden" value="' . (int) $this->getFieldValue($obj, 'id_tax_rules_group') . '" name="id_tax_rules_group" />';
        }
        echo '</td>
					</tr>
				';
        if (Configuration::get('PS_USE_ECOTAX')) {
            echo '
					<tr>
						<td class="col-left">' . $this->l('Eco-tax (tax incl.):') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" id="ecotax" name="ecotax" type="text" value="' . $this->getFieldValue($obj, 'ecotax') . '" onkeyup="if (isArrowKey(event))return; calcPriceTE(); this.value = this.value.replace(/,/g, \'.\'); if (parseInt(this.value) > getE(\'priceTE\').value) this.value = getE(\'priceTE\').value; if (isNaN(this.value)) this.value = 0;" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '
							<span style="margin-left:10px">(' . $this->l('already included in price') . ')</span>
						</td>
					</tr>';
        }
        if ($default_country->display_tax_label) {
            echo '
						<tr ' . (Tax::excludeTaxeOption() ? 'style="display:none"' : '') . '>
							<td class="col-left">' . $this->l('Retail price with tax:') . '</td>
							<td style="padding-bottom:5px;">
								' . ($currency->format % 2 != 0 ? ' ' . $currency->sign : '') . ' <input size="11" maxlength="14" id="priceTI" type="text" value="" onchange="noComma(\'priceTI\');" onkeyup="if (isArrowKey(event)) return;  calcPriceTE();" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '
							</td>
						</tr>';
        } else {
            echo '<input size="11" maxlength="14" id="priceTI" type="hidden" value="" onchange="noComma(\'priceTI\');" onkeyup="if (isArrowKey(event)) return;  calcPriceTE();" />';
        }
        echo '
					<tr id="tr_unit_price">
						<td class="col-left">' . $this->l('Unit price without tax:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format % 2 != 0 ? ' ' . $currency->sign : '') . ' <input size="11" maxlength="14" id="unit_price" name="unit_price" type="text" value="' . ($this->getFieldValue($obj, 'unit_price_ratio') != 0 ? Tools::ps_round($this->getFieldValue($obj, 'price') / $this->getFieldValue($obj, 'unit_price_ratio'), 2) : 0) . '" onkeyup="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\'); unitPriceWithTax(\'unit\');"/>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' ' . $this->l('per') . ' <input size="6" maxlength="10" id="unity" name="unity" type="text" value="' . (Validate::isCleanHtml($this->getFieldValue($obj, 'unity')) ? htmlentities($this->getFieldValue($obj, 'unity'), ENT_QUOTES, 'UTF-8') : '') . '" onkeyup="if (isArrowKey(event)) return ;unitySecond();" onchange="unitySecond();"/>' . (Configuration::get('PS_TAX') && $default_country->display_tax_label ? '<span style="margin-left:15px">' . $this->l('or') . ' ' . ($currency->format % 2 != 0 ? ' ' . $currency->sign : '') . '<span id="unit_price_with_tax">0.00</span>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' ' . $this->l('per') . ' <span id="unity_second">' . (Validate::isCleanHtml($this->getFieldValue($obj, 'unity')) ? htmlentities($this->getFieldValue($obj, 'unity'), ENT_QUOTES, 'UTF-8') : '') . '</span> ' . $this->l('with tax') : '') . '</span>
							<p>' . $this->l('Eg. $15 per Lb') . '</p>
						</td>
					</tr>
					<tr>
						<td class="col-left">&nbsp;</td>
						<td style="padding-bottom:5px;">
							<input type="checkbox" name="on_sale" id="on_sale" style="padding-top: 5px;" ' . ($this->getFieldValue($obj, 'on_sale') ? 'checked="checked"' : '') . 'value="1" />&nbsp;<label for="on_sale" class="t">' . $this->l('Display "on sale" icon on product page and text on product listing') . '</label>
						</td>
					</tr>
					<tr>
						<td class="col-left"><b>' . $this->l('Final retail price:') . '</b></td>
						<td style="padding-bottom:5px;">
							<span style="' . ($default_country->display_tax_label ? '' : 'display:none') . '">
							' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<span id="finalPrice" style="font-weight: bold;"></span>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '<span' . (!Configuration::get('PS_TAX') ? ' style="display:none;"' : '') . '> (' . $this->l('tax incl.') . ')</span>
							</span>
							<span' . (!Configuration::get('PS_TAX') ? ' style="display:none;"' : '') . '>';
        if ($default_country->display_tax_label) {
            echo ' / ';
        }
        echo ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<span id="finalPriceWithoutTax" style="font-weight: bold;"></span>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' ' . ($default_country->display_tax_label ? '(' . $this->l('tax excl.') . ')' : '') . '</span>
						</td>
					</tr>
					<tr>
						<td class="col-left">&nbsp;</td>
						<td>
							<div class="hint clear" style="display: block;width: 70%;">' . $this->l('You can define many discounts and specific price rules in the Prices tab') . '</div>
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:100%;" /></td></tr>';
        if ((int) Configuration::get('PS_STOCK_MANAGEMENT')) {
            if (!$has_attribute) {
                if ($obj->id) {
                    echo '
							<tr><td class="col-left">' . $this->l('Stock Movement:') . '</td>
								<td style="padding-bottom:5px;">
									<select id="id_mvt_reason" name="id_mvt_reason">
										<option value="-1">--</option>';
                    $reasons = StockMvtReason::getStockMvtReasons((int) $cookie->id_lang);
                    foreach ($reasons as $reason) {
                        echo '<option rel="' . $reason['sign'] . '" value="' . $reason['id_stock_mvt_reason'] . '" ' . (Configuration::get('PS_STOCK_MVT_REASON_DEFAULT') == $reason['id_stock_mvt_reason'] ? 'selected="selected"' : '') . '>' . $reason['name'] . '</option>';
                    }
                    echo '</select>
									<input id="mvt_quantity" type="text" name="mvt_quantity" size="3" maxlength="10" value="0"/>&nbsp;&nbsp;
									<span style="display:none;" id="mvt_sign"></span>
								</td>
							</tr>
							<tr>
								<td class="col-left">&nbsp;</td>
								<td>
									<div class="hint clear" style="display: block;width: 70%;">' . $this->l('Choose the reason and enter the quantity that you want to increase or decrease in your stock') . '</div>
								</td>
							</tr>';
                } else {
                    echo '<tr><td class="col-left">' . $this->l('Initial stock:') . '</td>
									<td style="padding-bottom:5px;">
										<input size="3" maxlength="10" name="quantity" type="text" value="0" />
									</td>';
                }
                echo '<tr>
								<td class="col-left">' . $this->l('Minimum quantity:') . '</td>
									<td style="padding-bottom:5px;">
										<input size="3" maxlength="10" name="minimal_quantity" id="minimal_quantity" type="text" value="' . ($this->getFieldValue($obj, 'minimal_quantity') ? $this->getFieldValue($obj, 'minimal_quantity') : 1) . '" />
										<p>' . $this->l('The minimum quantity to buy this product (set to 1 to disable this feature)') . '</p>
									</td>
								</tr>';
            }
            if ($obj->id) {
                echo '
							<tr><td class="col-left">' . $this->l('Quantity in stock:') . '</td>
								<td style="padding-bottom:5px;"><b>' . $qty . '</b><input type="hidden" name="quantity" value="' . $qty . '" /></td>
							</tr>
						';
            }
            if ($has_attribute) {
                echo '<tr>
								<td class="col-left">&nbsp;</td>
								<td>
									<div class="hint clear" style="display: block;width: 70%;">' . $this->l('You used combinations, for this reason you cannot edit your stock quantity here, but in the Combinations tab') . '</div>
								</td>
							</tr>';
            }
        } else {
            echo '<tr>
							<td colspan="2">' . $this->l('The stock management is disabled') . '</td>
						</tr>';
            echo '
						<tr>
							<td class="col-left">' . $this->l('Minimum quantity:') . '</td>
							<td style="padding-bottom:5px;">
								<input size="3" maxlength="10" name="minimal_quantity" id="minimal_quantity" type="text" value="' . ($this->getFieldValue($obj, 'minimal_quantity') ? $this->getFieldValue($obj, 'minimal_quantity') : 1) . '" />
								<p>' . $this->l('The minimum quantity to buy this product (set to 1 to disable this feature)') . '</p>
							</td>
						</tr>
					';
        }
        echo '
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:100%;" /></td></tr>
					<tr>
						<td class="col-left">' . $this->l('Additional shipping cost:') . '</td>
						<td style="padding-bottom:5px;">
							<input type="text" name="additional_shipping_cost" value="' . Tools::safeOutput($this->getFieldValue($obj, 'additional_shipping_cost')) . '" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '');
        if ($default_country->display_tax_label) {
            echo ' (' . $this->l('tax excl.') . ')';
        }
        echo '<p>' . $this->l('Carrier tax will be applied.') . '</p>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Displayed text when in-stock:') . '</td>
						<td style="padding-bottom:5px;" class="translatable">';
        foreach ($this->_languages as $language) {
            echo '		<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
								<input size="30" type="text" id="available_now_' . $language['id_lang'] . '" name="available_now_' . $language['id_lang'] . '"
								value="' . stripslashes(htmlentities($this->getFieldValue($obj, 'available_now', $language['id_lang']), ENT_COMPAT, 'UTF-8')) . '" />
								<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
							</div>';
        }
        echo '			</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Displayed text when allowed to be back-ordered:') . '</td>
						<td style="padding-bottom:5px;" class="translatable">';
        foreach ($this->_languages as $language) {
            echo '		<div  class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
								<input size="30" type="text" id="available_later_' . $language['id_lang'] . '" name="available_later_' . $language['id_lang'] . '"
								value="' . stripslashes(htmlentities($this->getFieldValue($obj, 'available_later', $language['id_lang']), ENT_COMPAT, 'UTF-8')) . '" />
								<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
							</div>';
        }
        echo '	</td>
					</tr>

					<script type="text/javascript">
						calcPriceTI();
					</script>

					<tr>
						<td class="col-left">' . $this->l('When out of stock:') . '</td>
						<td style="padding-bottom:5px;">
							<input type="radio" name="out_of_stock" id="out_of_stock_1" value="0" ' . ((int) $this->getFieldValue($obj, 'out_of_stock') == 0 ? 'checked="checked"' : '') . '/> <label for="out_of_stock_1" class="t" id="label_out_of_stock_1">' . $this->l('Deny orders') . '</label>
							<br /><input type="radio" name="out_of_stock" id="out_of_stock_2" value="1" ' . ($this->getFieldValue($obj, 'out_of_stock') == 1 ? 'checked="checked"' : '') . '/> <label for="out_of_stock_2" class="t" id="label_out_of_stock_2">' . $this->l('Allow orders') . '</label>
							<br /><input type="radio" name="out_of_stock" id="out_of_stock_3" value="2" ' . ($this->getFieldValue($obj, 'out_of_stock') == 2 ? 'checked="checked"' : '') . '/> <label for="out_of_stock_3" class="t" id="label_out_of_stock_3">' . $this->l('Default:') . ' <i>' . $this->l((int) Configuration::get('PS_ORDER_OUT_OF_STOCK') ? 'Allow orders' : 'Deny orders') . '</i> (' . $this->l('as set in') . ' <a href="index.php?tab=AdminPPreferences&token=' . Tools::getAdminToken('AdminPPreferences' . (int) Tab::getIdFromClassName('AdminPPreferences') . (int) $cookie->id_employee) . '"  onclick="return confirm(\'' . $this->l('Are you sure you want to delete entered product information?', __CLASS__, true, false) . '\');">' . $this->l('Preferences') . '</a>)</label>
						</td>
					</tr>
					<tr>
						<td colspan="2" style="padding-bottom:5px;">
							<hr style="width:100%;" />
						</td>
					</tr>
					<tr>
						<td class="col-left"><label for="id_category_default" class="t">' . $this->l('Default category:') . '</label></td>
						<td>
						<div id="no_default_category" style="color: red;font-weight: bold;display: none;">' . $this->l('Please check a category in order to select the default category.') . '</div>
						<script type="text/javascript">
							var post_selected_cat;
						</script>';
        $default_category = Tools::getValue('id_category', 1);
        if (!$obj->id) {
            $selectedCat = Category::getCategoryInformations(Tools::getValue('categoryBox', array($default_category)), $this->_defaultFormLanguage);
            echo '
							<script type="text/javascript">
								post_selected_cat = \'' . implode(',', array_keys($selectedCat)) . '\';
							</script>';
        } else {
            if (Tools::isSubmit('categoryBox')) {
                $selectedCat = Category::getCategoryInformations(Tools::getValue('categoryBox', array($default_category)), $this->_defaultFormLanguage);
            } else {
                $selectedCat = Product::getProductCategoriesFull($obj->id, $this->_defaultFormLanguage);
            }
        }
        echo '<select id="id_category_default" name="id_category_default">';
        foreach ($selectedCat as $cat) {
            echo '<option value="' . $cat['id_category'] . '" ' . ($obj->id_category_default == $cat['id_category'] ? 'selected' : '') . '>' . $cat['name'] . '</option>';
        }
        echo '</select>
						</td>
					</tr>
					<tr id="tr_categories">
						<td colspan="2">
						';
        // Translations are not automatic for the moment ;)
        $trads = array('Home' => $this->l('Home'), 'selected' => $this->l('selected'), 'Collapse All' => $this->l('Collapse All'), 'Expand All' => $this->l('Expand All'), 'Check All' => $this->l('Check All'), 'Uncheck All' => $this->l('Uncheck All'));
        echo Helper::renderAdminCategorieTree($trads, $selectedCat) . '
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:100%;" /></td></tr>
					<tr><td colspan="2">
						<span onclick="$(\'#seo\').slideToggle();" style="cursor: pointer"><img src="../img/admin/arrow.gif" alt="' . $this->l('SEO') . '" title="' . $this->l('SEO') . '" style="float:left; margin-right:5px;"/>' . $this->l('Click here to improve product\'s rank in search engines (SEO)') . '</span><br />
						<div id="seo" style="display: none; padding-top: 15px;">
							<table>
								<tr>
									<td class="col-left">' . $this->l('Meta title:') . '</td>
									<td class="translatable">';
        foreach ($this->_languages as $language) {
            echo '					<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
											<input size="55" type="text" id="meta_title_' . $language['id_lang'] . '" name="meta_title_' . $language['id_lang'] . '"
											value="' . htmlentities($this->getFieldValue($obj, 'meta_title', $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" />
											<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
										</div>';
        }
        echo '						<p class="clear">' . $this->l('Product page title; leave blank to use product name') . '</p>
									</td>
								</tr>
								<tr>
									<td class="col-left">' . $this->l('Meta description:') . '</td>
									<td class="translatable">';
        foreach ($this->_languages as $language) {
            echo '					<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
											<input size="55" type="text" id="meta_description_' . $language['id_lang'] . '" name="meta_description_' . $language['id_lang'] . '"
											value="' . htmlentities($this->getFieldValue($obj, 'meta_description', $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" />
											<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
										</div>';
        }
        echo '						<p class="clear">' . $this->l('A single sentence for HTML header') . '</p>
									</td>
								</tr>
								<tr>
									<td class="col-left">' . $this->l('Meta keywords:') . '</td>
									<td class="translatable">';
        foreach ($this->_languages as $language) {
            echo '					<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
											<input size="55" type="text" id="meta_keywords_' . $language['id_lang'] . '" name="meta_keywords_' . $language['id_lang'] . '"
											value="' . htmlentities($this->getFieldValue($obj, 'meta_keywords', $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" />
											<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
										</div>';
        }
        echo '						<p class="clear">' . $this->l('Keywords for HTML header, separated by a comma') . '</p>
									</td>
								</tr>
								<tr>
									<td class="col-left">' . $this->l('Friendly URL:') . '</td>
									<td class="translatable">';
        foreach ($this->_languages as $language) {
            echo '					<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
											<input size="55" type="text" id="link_rewrite_' . $language['id_lang'] . '" name="link_rewrite_' . $language['id_lang'] . '"
											value="' . htmlentities($this->getFieldValue($obj, 'link_rewrite', $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" onkeyup="if (isArrowKey(event)) return ;updateFriendlyURL();" onchange="updateFriendlyURL();" /><sup> *</sup>
											<span class="hint" name="help_box">' . $this->l('Only letters and the "less" character are allowed') . '<span class="hint-pointer">&nbsp;</span></span>
										</div>';
        }
        echo '						<p class="clear" style="padding:10px 0 0 0">' . '<a style="cursor:pointer" class="button" onmousedown="updateFriendlyURLByName();">' . $this->l('Generate') . '</a>&nbsp;' . $this->l('Friendly-url from product\'s name.') . '<br /><br />';
        echo '						' . $this->l('Product link will look like this:') . ' ' . (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . '/<b>id_product</b>-<span id="friendly-url"></span>.html</p>
									</td>
								</tr>';
        echo '</td></tr></table>
						</div>
					</td></tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:100%;" /></td></tr>
					<tr>
						<td class="col-left">' . $this->l('Short description:') . '<br /><br /><i>(' . $this->l('appears in the product lists and on the top of the product page') . ')</i></td>
						<td style="padding-bottom:5px;" class="translatable">';
        foreach ($this->_languages as $language) {
            echo '		<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . ';float: left;">
								<textarea class="rte" cols="100" rows="10" id="description_short_' . $language['id_lang'] . '" name="description_short_' . $language['id_lang'] . '">' . htmlentities(stripslashes($this->getFieldValue($obj, 'description_short', $language['id_lang'])), ENT_COMPAT, 'UTF-8') . '</textarea>
							</div>';
        }
        echo '		</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Description:') . '<br /><br /><i>(' . $this->l('appears in the body of the product page') . ')</i></td>
						<td style="padding-bottom:5px;" class="translatable">';
        foreach ($this->_languages as $language) {
            echo '		<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . ';float: left;">
								<textarea class="rte" cols="100" rows="20" id="description_' . $language['id_lang'] . '" name="description_' . $language['id_lang'] . '">' . htmlentities(stripslashes($this->getFieldValue($obj, 'description', $language['id_lang'])), ENT_COMPAT, 'UTF-8') . '</textarea>
							</div>';
        }
        echo '		</td>
					</tr>';
        echo '
					<tr>
						<td class="col-left">' . $this->l('Tags:') . '</td>
						<td style="padding-bottom:5px;" class="translatable">';
        if ($obj->id) {
            $obj->tags = Tag::getProductTags((int) $obj->id);
        }
        foreach ($this->_languages as $language) {
            echo '<div class="lang_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
							<input size="55" type="text" id="tags_' . $language['id_lang'] . '" name="tags_' . $language['id_lang'] . '"
							value="' . htmlentities(Tools::getValue('tags_' . $language['id_lang'], $obj->getTags($language['id_lang'], true)), ENT_COMPAT, 'UTF-8') . '" />
							<span class="hint" name="help_box">' . $this->l('Forbidden characters:') . ' !<>;?=+#"&deg;{}_$%<span class="hint-pointer">&nbsp;</span></span>
						  </div>';
        }
        echo '	<p class="clear">' . $this->l('Tags separated by commas (e.g., dvd, dvd player, hifi)') . '</p>
						</td>
					</tr>';
        $accessories = Product::getAccessoriesLight((int) $cookie->id_lang, $obj->id);
        if ($postAccessories = Tools::getValue('inputAccessories')) {
            $postAccessoriesTab = explode('-', Tools::getValue('inputAccessories'));
            foreach ($postAccessoriesTab as $accessoryId) {
                if (!$this->haveThisAccessory($accessoryId, $accessories) and $accessory = Product::getAccessoryById($accessoryId)) {
                    $accessories[] = $accessory;
                }
            }
        }
        echo '
					<tr>
						<td class="col-left">' . $this->l('Accessories:') . '<br /><br /><i>' . $this->l('(Do not forget to Save the product afterward)') . '</i></td>
						<td style="padding-bottom:5px;">
							<div id="divAccessories">';
        foreach ($accessories as $accessory) {
            echo htmlentities($accessory['name'], ENT_COMPAT, 'UTF-8') . (!empty($accessory['reference']) ? ' (' . $accessory['reference'] . ')' : '') . ' <span onclick="delAccessory(' . $accessory['id_product'] . ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" class="middle" alt="" /></span><br />';
        }
        echo '</div>
							<input type="hidden" name="inputAccessories" id="inputAccessories" value="';
        foreach ($accessories as $accessory) {
            echo (int) $accessory['id_product'] . '-';
        }
        echo '" />
							<input type="hidden" name="nameAccessories" id="nameAccessories" value="';
        foreach ($accessories as $accessory) {
            echo htmlentities($accessory['name'], ENT_COMPAT, 'UTF-8') . '¤';
        }
        echo '" />
							<script type="text/javascript">
								var formProduct;
								var accessories = new Array();
							</script>

							<link rel="stylesheet" type="text/css" href="' . __PS_BASE_URI__ . 'css/jquery.autocomplete.css" />
							<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/jquery/jquery.autocomplete.js"></script>
							<div id="ajax_choose_product" style="padding:6px; padding-top:2px; width:600px;">
								<p class="clear">' . $this->l('Begin typing the first letters of the product name, then select the product from the drop-down list:') . '</p>
								<input type="text" value="" id="product_autocomplete_input" />
								<img onclick="$(this).prev().search();" style="cursor: pointer;" src="../img/admin/add.gif" alt="' . $this->l('Add an accessory') . '" title="' . $this->l('Add an accessory') . '" />
							</div>
							<script type="text/javascript">
								urlToCall = null;
								/* function autocomplete */
								$(function() {
									$(\'#product_autocomplete_input\')
										.autocomplete(\'ajax_products_list.php\', {
											minChars: 1,
											autoFill: true,
											max:20,
											matchContains: true,
											mustMatch:true,
											scroll:false,
											cacheLength:0,
											formatItem: function(item) {
												return item[1]+\' - \'+item[0];
											}
										}).result(addAccessory);
									$(\'#product_autocomplete_input\').setOptions({
										extraParams: {excludeIds : getAccessorieIds()}
									});
								});
							</script>
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:10px;"><hr style="width:100%;" /></td></tr>
					<tr>
						<td colspan="2" style="text-align:center;">
							<input type="submit" value="' . $this->l('Save') . '" name="submitAdd' . $this->table . '" class="button" />
							&nbsp;<input type="submit" value="' . $this->l('Save and stay') . '" name="submitAdd' . $this->table . 'AndStay" class="button" /></td>
					</tr>
				</table>
			<br />
			</div>';
        // TinyMCE
        global $cookie;
        $iso = Language::getIsoById((int) $cookie->id_lang);
        $isoTinyMCE = file_exists(_PS_ROOT_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
        $ad = dirname($_SERVER["PHP_SELF"]);
        echo '
			<script type="text/javascript">
			var iso = \'' . $isoTinyMCE . '\' ;
			var pathCSS = \'' . _THEME_CSS_DIR_ . '\' ;
			var ad = \'' . $ad . '\' ;
			</script>
			<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/tinymce.inc.js"></script>
			<script type="text/javascript">
					toggleVirtualProduct(getE(\'is_virtual_good\'));
					unitPriceWithTax(\'unit\');
			</script>';
        $categoryBox = Tools::getValue('categoryBox', array());
    }
Exemple #27
0
    public static function getProducts($id_manufacturer, $id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true, $active_category = true, Context $context = NULL)
    {
        global $cookie;
        $agile_sql_parts = AgileSellerManager::getAdditionalSqlForProducts("p");
        if (empty($agile_sql_parts['joins']) or empty($agile_sql_parts['wheres'])) {
            parent::getProducts($id_manufacturer, $id_lang, $p, $n, $orderBy, $orderWay, $getTotal, $active, $active_category);
        }
        if ($p < 1) {
            $p = 1;
        }
        if (empty($orderBy) || $orderBy == 'position') {
            $orderBy = 'name';
        }
        if (empty($orderWay)) {
            $orderWay = 'ASC';
        }
        if (!Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            die(Tools::displayError());
        }
        $groups = FrontController::getCurrentCustomerGroups();
        $sqlGroups = count($groups) ? 'IN (' . implode(',', $groups) . ')' : '= 1';
        if ($getTotal) {
            $sql = '
				SELECT p.`id_product`
				FROM `' . _DB_PREFIX_ . 'product` p
			    ' . $agile_sql_parts['joins'] . '
				WHERE p.id_manufacturer = ' . (int) $id_manufacturer . ($active ? ' AND p.`active` = 1' : '') . '
    			' . $agile_sql_parts['wheres'] . '
				AND p.`id_product` IN (
					SELECT cp.`id_product`
					FROM `' . _DB_PREFIX_ . 'category_group` cg
					LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)' . ($active_category ? ' INNER JOIN `' . _DB_PREFIX_ . 'category` ca ON cp.`id_category` = ca.`id_category` AND ca.`active` = 1' : '') . '
					WHERE cg.`id_group` ' . $sqlGroups . '
				)';
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
            return (int) sizeof($result);
        }
        $sql = '
		SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 AS new,
			(p.`price` * ((100 + (t.`rate`))/100)) AS orderprice
			' . $agile_sql_parts['selects'] . '
		FROM `' . _DB_PREFIX_ . 'product` p
			    ' . $agile_sql_parts['joins'] . '
		LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) (_PS_VERSION_ > '1.5' ? Context::getContext()->country->id : Country::getDefaultCountryId()) . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` t ON (t.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
		WHERE p.`id_manufacturer` = ' . (int) $id_manufacturer . ($active ? ' AND p.`active` = 1' : '') . '
			' . $agile_sql_parts['wheres'] . '
		AND p.`id_product` IN (
					SELECT cp.`id_product`
					FROM `' . _DB_PREFIX_ . 'category_group` cg
					LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = cg.`id_category`)' . ($active_category ? ' INNER JOIN `' . _DB_PREFIX_ . 'category` ca ON cp.`id_category` = ca.`id_category` AND ca.`active` = 1' : '') . '
					WHERE cg.`id_group` ' . $sqlGroups . '
				)
		ORDER BY ' . ($orderBy == 'id_product' ? 'p.' : '') . '`' . pSQL($orderBy) . '` ' . pSQL($orderWay) . '
		LIMIT ' . ((int) $p - 1) * (int) $n . ',' . (int) $n;
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
        if (!$result) {
            return false;
        }
        if ($orderBy == 'price') {
            Tools::orderbyPrice($result, $orderWay);
        }
        $finalResults = Product::getProductsProperties($id_lang, $result);
        $finalResults = AgileSellerManager::prepareSellerRattingInfo($finalResults);
        return $finalResults;
    }
Exemple #28
0
 /**
  *
  * @param int $id_zone
  * @param Array $groups group of the customer
  * @return Array 
  */
 public static function getCarriersForOrder($id_zone, $groups = null)
 {
     global $cookie, $cart;
     if (is_array($groups) && !empty($groups)) {
         $result = Carrier::getCarriers((int) $cookie->id_lang, true, false, (int) $id_zone, $groups, self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
     } else {
         $result = Carrier::getCarriers((int) $cookie->id_lang, true, false, (int) $id_zone, array(1), self::PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
     }
     $resultsArray = array();
     foreach ($result as $k => $row) {
         $carrier = new Carrier((int) $row['id_carrier']);
         $shippingMethod = $carrier->getShippingMethod();
         if ($shippingMethod != Carrier::SHIPPING_METHOD_FREE) {
             // Get only carriers that are compliant with shipping method
             if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false || $shippingMethod == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 // Get id zone
                 if (!$id_zone) {
                     $id_zone = Country::getIdZone(Country::getDefaultCountryId());
                 }
                 // Get only carriers that have a range compatible with cart
                 if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone) || $shippingMethod == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $cart->id_currency)) {
                     unset($result[$k]);
                     continue;
                 }
             }
         }
         $row['name'] = strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME');
         $row['price'] = $shippingMethod == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getOrderShippingCost((int) $row['id_carrier']);
         $row['price_tax_exc'] = $shippingMethod == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getOrderShippingCost((int) $row['id_carrier'], false);
         $row['img'] = file_exists(_PS_SHIP_IMG_DIR_ . (int) $row['id_carrier'] . '.jpg') ? _THEME_SHIP_DIR_ . (int) $row['id_carrier'] . '.jpg' : '';
         // If price is false, then the carrier is unavailable (carrier module)
         if ($row['price'] === false) {
             unset($result[$k]);
             continue;
         }
         $resultsArray[] = $row;
     }
     return $resultsArray;
 }
Exemple #29
0
    public static function find($id_lang, $expr, $pageNumber = 1, $pageSize = 1, $orderBy = 'position', $orderWay = 'desc', $ajax = false, $useCookie = true, Context $context = null)
    {
        global $cookie;
        if (!Module::isInstalled('agilemultipleseller') and !Module::isInstalled('agilesellerlistoptions')) {
            return parent::find($id_lang, $expr, $pageNumber, $pageSize, $orderBy, $orderWay, $ajax, $useCookie);
        }
        $agile_sql_parts = AgileSellerManager::getAdditionalSqlForProducts("p");
        $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
        if ($useCookie) {
            $id_customer = (int) $cookie->id_customer;
        } else {
            $id_customer = 0;
        }
        if ($pageNumber < 1) {
            $pageNumber = 1;
        }
        if ($pageSize < 1) {
            $pageSize = 1;
        }
        if (!Validate::isOrderBy($orderBy) or !Validate::isOrderWay($orderWay)) {
            return false;
        }
        $intersectArray = array();
        $scoreArray = array();
        $words = explode(' ', Search::sanitize($expr, (int) $id_lang));
        foreach ($words as $key => $word) {
            if (!empty($word) and strlen($word) >= (int) Configuration::get('PS_SEARCH_MINWORDLEN')) {
                $word = str_replace('%', '\\%', $word);
                $word = str_replace('_', '\\_', $word);
                $intersectArray[] = 'SELECT id_product
					FROM ' . _DB_PREFIX_ . 'search_word sw
					LEFT JOIN ' . _DB_PREFIX_ . 'search_index si ON sw.id_word = si.id_word
					WHERE sw.id_lang = ' . (int) $id_lang . '
					AND sw.word LIKE 
					' . ($word[0] == '-' ? ' \'' . pSQL(Tools::substr($word, 1, PS_SEARCH_MAX_WORD_LENGTH)) . '%\'' : '\'' . pSQL(Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH)) . '%\'');
                if ($word[0] != '-') {
                    $scoreArray[] = 'sw.word LIKE \'' . pSQL(Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH)) . '%\'';
                }
            } else {
                unset($words[$key]);
            }
        }
        if (!sizeof($words)) {
            return $ajax ? array() : array('total' => 0, 'result' => array());
        }
        $score = '';
        if (sizeof($scoreArray)) {
            $score = ',(
				SELECT SUM(weight)
				FROM ' . _DB_PREFIX_ . 'search_word sw
				LEFT JOIN ' . _DB_PREFIX_ . 'search_index si ON sw.id_word = si.id_word
				WHERE sw.id_lang = ' . (int) $id_lang . '
				AND si.id_product = p.id_product
				AND (' . implode(' OR ', $scoreArray) . ')
			) position';
        }
        $result = $db->ExecuteS('
		SELECT cp.`id_product`
		FROM `' . _DB_PREFIX_ . 'category_group` cg
		INNER JOIN `' . _DB_PREFIX_ . 'category_product` cp ON cp.`id_category` = cg.`id_category`
		INNER JOIN `' . _DB_PREFIX_ . 'category` c ON cp.`id_category` = c.`id_category`
		INNER JOIN `' . _DB_PREFIX_ . 'product` p ON cp.`id_product` = p.`id_product`
		WHERE c.`active` = 1 AND p.`active` = 1 AND indexed = 1
		AND cg.`id_group` ' . (!$id_customer ? '= 1' : 'IN (
			SELECT id_group FROM ' . _DB_PREFIX_ . 'customer_group
			WHERE id_customer = ' . (int) $id_customer . '
		)'), false);
        $eligibleProducts = array();
        while ($row = $db->nextRow($result)) {
            $eligibleProducts[] = $row['id_product'];
        }
        foreach ($intersectArray as $query) {
            $result = $db->ExecuteS($query, false);
            $eligibleProducts2 = array();
            while ($row = $db->nextRow($result)) {
                $eligibleProducts2[] = $row['id_product'];
            }
            $eligibleProducts = array_intersect($eligibleProducts, $eligibleProducts2);
            if (!count($eligibleProducts)) {
                return $ajax ? array() : array('total' => 0, 'result' => array());
            }
        }
        array_unique($eligibleProducts);
        $productPool = '';
        foreach ($eligibleProducts as $id_product) {
            if ($id_product) {
                $productPool .= (int) $id_product . ',';
            }
        }
        if (empty($productPool)) {
            return $ajax ? array() : array('total' => 0, 'result' => array());
        }
        $productPool = strpos($productPool, ',') === false ? ' = ' . (int) $productPool . ' ' : ' IN (' . rtrim($productPool, ',') . ') ';
        if ($ajax) {
            $sql = 'SELECT DISTINCT p.id_product, pl.name pname, cl.name cname,
						cl.link_rewrite crewrite, pl.link_rewrite prewrite ' . $score . '
						' . $agile_sql_parts['selects'] . '
					FROM ' . _DB_PREFIX_ . 'product p
					INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (
						p.`id_product` = pl.`id_product`
						AND pl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl') . '
					)
					' . Shop::addSqlAssociation('product', 'p') . '
					INNER JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (
						product_shop.`id_category_default` = cl.`id_category`
						AND cl.`id_lang` = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('cl') . '
					)
					' . $agile_sql_parts['joins'] . '
					WHERE p.`id_product` ' . $productPool . '
					' . $agile_sql_parts['wheres'] . '
					ORDER BY position DESC LIMIT 10';
            return $db->executeS($sql);
        }
        $from_conds = '
		FROM ' . _DB_PREFIX_ . 'product p
            ' . $agile_sql_parts['joins'] . '
		INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) (_PS_VERSION_ > '1.5' ? Context::getContext()->country->id : Country::getDefaultCountryId()) . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` tax ON (tax.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		WHERE p.`id_product` ' . $productPool . '
		' . $agile_sql_parts['wheres'] . '
		';
        $sort_limit = ($orderBy ? 'ORDER BY  ' . $orderBy : '') . ($orderWay ? ' ' . $orderWay : '') . '
			LIMIT ' . (int) (($pageNumber - 1) * $pageSize) . ',' . (int) $pageSize;
        $total = $db->getValue(' SELECT COUNT(*) ' . $from_conds);
        $queryResults = '	SELECT p.*, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`name`,
			tax.`rate`, i.`id_image`, il.`legend`, m.`name` manufacturer_name ' . $score . ', DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 new
            ' . $agile_sql_parts['selects'] . '
			' . $from_conds . '
			' . $sort_limit . '
			';
        $result = $db->ExecuteS($queryResults);
        if (!$result) {
            $resultProperties = false;
        } else {
            $resultProperties = Product::getProductsProperties((int) $id_lang, $result);
        }
        $resultProperties = AgileSellerManager::prepareSellerRattingInfo($resultProperties);
        return array('total' => $total, 'result' => $resultProperties);
    }
Exemple #30
0
    public static function searchTag($id_lang, $tag, $count = false, $pageNumber = 0, $pageSize = 10, $orderBy = false, $orderWay = false, $useCookie = true)
    {
        global $link, $cookie;
        // Only use cookie if id_customer is not present
        if ($useCookie) {
            $id_customer = (int) $cookie->id_customer;
        } else {
            $id_customer = 0;
        }
        if (!is_numeric($pageNumber) or !is_numeric($pageSize) or !Validate::isBool($count) or !Validate::isValidSearch($tag) or $orderBy and !$orderWay or $orderBy and !Validate::isOrderBy($orderBy) or $orderWay and !Validate::isOrderBy($orderWay)) {
            return false;
        }
        if ($pageNumber < 1) {
            $pageNumber = 1;
        }
        if ($pageSize < 1) {
            $pageSize = 10;
        }
        if ($count) {
            $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT COUNT(DISTINCT pt.`id_product`) nb
			FROM `' . _DB_PREFIX_ . 'product` p
			LEFT JOIN `' . _DB_PREFIX_ . 'product_tag` pt ON (p.`id_product` = pt.`id_product`)
			LEFT JOIN `' . _DB_PREFIX_ . 'tag` t ON (pt.`id_tag` = t.`id_tag` AND t.`id_lang` = ' . (int) $id_lang . ')
			LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_product` = p.`id_product`)
			LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cg.`id_category` = cp.`id_category`)
			WHERE p.`active` = 1
			AND cg.`id_group` ' . (!$id_customer ? '= 1' : 'IN (
				SELECT id_group FROM ' . _DB_PREFIX_ . 'customer_group
				WHERE id_customer = ' . (int) $id_customer . ')') . '
			AND t.`name` LIKE \'%' . pSQL($tag) . '%\'');
            return isset($result['nb']) ? $result['nb'] : 0;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT DISTINCT p.*, pl.`description_short`, pl.`link_rewrite`, pl.`name`, tax.`rate`, i.`id_image`, il.`legend`, m.`name` manufacturer_name, 1 position,
			DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL ' . (Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20) . ' DAY)) > 0 new
		FROM `' . _DB_PREFIX_ . 'product` p
		INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
		                                           AND tr.`id_country` = ' . (int) Country::getDefaultCountryId() . '
	                                           	   AND tr.`id_state` = 0)
	    LEFT JOIN `' . _DB_PREFIX_ . 'tax` tax ON (tax.`id_tax` = tr.`id_tax`)
		LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
		LEFT JOIN `' . _DB_PREFIX_ . 'product_tag` pt ON (p.`id_product` = pt.`id_product`)
		LEFT JOIN `' . _DB_PREFIX_ . 'tag` t ON (pt.`id_tag` = t.`id_tag` AND t.`id_lang` = ' . (int) $id_lang . ')
		LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_product` = p.`id_product`)
		LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cg.`id_category` = cp.`id_category`)
		WHERE p.`active` = 1
		AND cg.`id_group` ' . (!$id_customer ? '= 1' : 'IN (
			SELECT id_group FROM ' . _DB_PREFIX_ . 'customer_group
			WHERE id_customer = ' . (int) $id_customer . ')') . '
		AND t.`name` LIKE \'%' . pSQL($tag) . '%\'
		ORDER BY position DESC' . ($orderBy ? ', ' . $orderBy : '') . ($orderWay ? ' ' . $orderWay : '') . '
		LIMIT ' . (int) (($pageNumber - 1) * $pageSize) . ',' . (int) $pageSize);
        if (!$result) {
            return false;
        }
        return Product::getProductsProperties((int) $id_lang, $result);
    }