Example #1
0
 function getPriceList()
 {
     $this->data = $this->getYamarketShopData();
     if ($this->data['yam_name'] == "") {
         return '';
     }
     $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
     if ($currency->iso_code == 'RUB') {
         $currency->iso_code = 'RUR';
     }
     $desc_type = Configuration::get('YAMARKET_DESC_TYPE');
     $link = $this->context->link;
     $this->ensureHttpPrefix($link);
     $xml = $this->getDocBody();
     // Offers
     $offers = $xml->createElement("offers");
     // Get products
     $categorys = $this->excluded_cats;
     foreach ($categorys as $category) {
         $products = Product::getProducts($this->id_lang, 0, 0, 'name', 'asc', $category);
         foreach ($products as $product) {
             //	if ($product['id_product'] == 228 ){
             $id_category_default = $product['id_category_default'];
             $prod_obj = new Product($product['id_product']);
             $crewrite = Category::getLinkRewrite($product['id_category_default'], $this->id_lang);
             $accessories = $this->getAccessories($product);
             $features = $this->getFeatures($product['id_product']);
             $combinations = $this->getCombinations($prod_obj, $currency);
             // template array
             $product_item = array('name' => html_entity_decode($product['name']), 'description' => html_entity_decode($product['description']), 'id_category_default' => $id_category_default, 'ean13' => $product['ean13'], 'accessories' => implode(',', $accessories), 'vendor' => $product['manufacturer_name']);
             if ($desc_type == 1) {
                 $product_item['description'] = html_entity_decode(strip_tags(str_replace("ยฎ", '', $product['description_short'])));
             }
             if ($this->country_of_origin_attr != '' && array_key_exists($this->country_of_origin_attr, $features)) {
                 $product_item['country_of_origin'] = $features[$this->country_of_origin_attr];
                 unset($features[$this->country_of_origin_attr]);
             }
             if ($this->model_name_attr != '' && array_key_exists($this->model_name_attr, $features)) {
                 $product_item['name'] = $features[$this->model_name_attr];
                 unset($features[$this->model_name_attr]);
             }
             if (!$product['available_for_order'] or !$product['active']) {
                 continue;
             }
             if (!empty($combinations)) {
                 foreach ($combinations as $combination) {
                     $prod_obj->id_product_attribute = $combination['id_product_attribute'];
                     $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], $combination['id_product_attribute']);
                     if (!$available_for_order && !$prod_obj->checkQty(1)) {
                         continue;
                     }
                     $params = $this->getParams($combination);
                     $size = $params[0]['value'];
                     $sizes = $this->sizeConvert($size);
                     $pictures = array();
                     $pictures = $this->getPictures($product['id_product'], $product['link_rewrite']);
                     foreach ($combination['id_images'] as $id_image) {
                         $pictures[] = $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $id_image, $this->image_type);
                     }
                     $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite, '?utm_source=rsy', null, null, $combination['id_product_attribute'], Configuration::get('PS_REWRITING_SETTINGS'), false, true);
                     //$url = $link->getProductLink($product['link_rewrite'], null, null, null, null, null, $combination['id_product_attribute'], Configuration::get('PS_REWRITING_SETTINGS'), false, true);
                     $extra_product_item = array('id_product' => $product['id_product'] . 'c' . $combination['id_product_attribute'], 'available_for_order' => $available_for_order, 'group_id' => $product['id_product'], 'price' => $prod_obj->getPrice(true, $combination['id_product_attribute']), 'oldprice' => $prod_obj->getPriceWithoutReduct(true, $combination['id_product_attribute']), 'pictures' => $pictures, 'manufacturer_warranty' => 'true', 'market_category' => $product['id_category_default'] == 102 ? Configuration::get('YAMARKET_CATEGORY') : Configuration::get('YAMARKET_CATEGORY2'), 'params' => array_merge($sizes, $features), 'url' => $url);
                     $offer = array_merge($product_item, $extra_product_item);
                     $offer['name'] = $offer['name'] . ' ' . $size;
                     $offers->appendChild($this->getOfferElem($offer, $xml, $currency));
                 }
             } else {
                 $pictures = $this->getPictures($product['id_product'], $product['link_rewrite']);
                 $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0);
                 if (!$available_for_order && !$prod_obj->checkQty(1)) {
                     continue;
                 }
                 $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite);
                 $extra_product_item = array('id_product' => $product['id_product'], 'available_for_order' => $available_for_order, 'price' => $prod_obj->getPrice(), 'pictures' => $pictures, 'params' => $features, 'url' => $url);
                 $offer = array_merge($product_item, $extra_product_item);
                 $offers->appendChild($this->getOfferElem($offer, $xml, $currency));
             }
             $prod_obj->clearCache(true);
         }
     }
     //}
     $shop = $xml->getElementsByTagName("shop")->item(0);
     $shop->appendChild($offers);
     return $xml->saveXML();
 }
Example #2
0
    public function getFilterBlock($selectedFilters = array())
    {
        global $cookie;
        static $cache = null;
        if (version_compare(_PS_VERSION_, '1.5', '>')) {
            $currency = Context::getContext()->currency;
        } else {
            $currency = Currency::getCurrent();
        }
        if (is_array($cache)) {
            return $cache;
        }
        $id_parent = (int) Tools::getValue('id_category', Tools::getValue('id_category_layered', 1));
        if ($id_parent == 1) {
            return;
        }
        $parent = new Category((int) $id_parent);
        if (version_compare(_PS_VERSION_, '1.5', '>')) {
            $id_shop = (int) Context::getContext()->shop->getId(true);
        } else {
            $id_shop = 0;
        }
        /* Get the filters for the current category */
        $filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'layered_category
			WHERE id_category = ' . (int) $id_parent . '
				AND id_shop = ' . $id_shop . '
			GROUP BY `type`, id_value ORDER BY position ASC');
        // Remove all empty selected filters
        foreach ($selectedFilters as $key => $value) {
            switch ($key) {
                case 'price':
                case 'weight':
                    if ($value[0] === '' && $value[1] === '') {
                        unset($selectedFilters[$key]);
                    }
                    break;
                default:
                    if ($value == '') {
                        unset($selectedFilters[$key]);
                    }
                    break;
            }
        }
        $filterBlocks = array();
        foreach ($filters as $filter) {
            $sqlQuery = array('select' => '', 'from' => '', 'join' => '', 'where' => '', 'group' => '');
            switch ($filter['type']) {
                // conditions + quantities + weight + price
                case 'price':
                case 'weight':
                case 'condition':
                case 'quantity':
                    if (version_compare(_PS_VERSION_, '1.5', '>')) {
                        $sqlQuery['select'] = 'SELECT p.`id_product`, p.`condition`, p.`id_manufacturer`, sa.`quantity`, p.`weight` ';
                    } else {
                        $sqlQuery['select'] = 'SELECT p.`id_product`, p.`condition`, p.`id_manufacturer`, p.`quantity`, p.`weight` ';
                    }
                    $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'product p ';
                    $sqlQuery['join'] = '
					INNER JOIN ' . _DB_PREFIX_ . 'category_product cp ON (cp.id_product = p.id_product)
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1) ';
                    if (version_compare(_PS_VERSION_, '1.5', '>')) {
                        $sqlQuery['join'] .= 'LEFT JOIN ' . _DB_PREFIX_ . 'stock_available sa
							ON (sa.id_product = p.id_product AND sa.id_shop = ' . (int) $this->context->shop->getID(true) . ') ';
                    }
                    $sqlQuery['where'] = 'WHERE p.`active` = 1 ';
                    $sqlQuery['group'] = ' GROUP BY p.id_product ';
                    break;
                case 'manufacturer':
                    $sqlQuery['select'] = 'SELECT m.name, COUNT(DISTINCT p.id_product) nbr, m.id_manufacturer ';
                    $sqlQuery['from'] = '
					FROM `' . _DB_PREFIX_ . 'category_product` cp
					INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1)
					INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer) ';
                    $sqlQuery['where'] = 'WHERE 
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1 ';
                    $sqlQuery['group'] = ' GROUP BY p.id_manufacturer ';
                    break;
                case 'id_attribute_group':
                    // attribute group
                    $sqlQuery['select'] = '
					SELECT COUNT(DISTINCT p.id_product) nbr, lpa.id_attribute_group,
					a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
					liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title';
                    $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa
					INNER JOIN ' . _DB_PREFIX_ . 'attribute a
					ON a.id_attribute = lpa.id_attribute
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
					ON al.id_attribute = a.id_attribute
					AND al.id_lang = ' . (int) $cookie->id_lang . '
					INNER JOIN ' . _DB_PREFIX_ . 'product as p
					ON p.id_product = lpa.id_product
					AND p.active = 1
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
					ON ag.id_attribute_group = lpa.id_attribute_group
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
					ON agl.id_attribute_group = lpa.id_attribute_group
					AND agl.id_lang = ' . (int) $cookie->id_lang . '
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
					ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
					ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $cookie->id_lang . ') ';
                    $sqlQuery['where'] = 'WHERE a.id_attribute_group = ' . (int) $filter['id_value'] . '
					AND p.id_product IN (
					SELECT id_product
					FROM ' . _DB_PREFIX_ . 'category_product cp
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND 
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1)) ';
                    $sqlQuery['group'] = '
					GROUP BY lpa.id_attribute
					ORDER BY id_attribute_group, id_attribute ';
                    break;
                case 'id_feature':
                    $sqlQuery['select'] = 'SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
					COUNT(DISTINCT p.id_product) nbr,
					lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title ';
                    $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'feature_product fp
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product AND p.active = 1)
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $cookie->id_lang . ')
					INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
					ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
					ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . (int) $cookie->id_lang . ') ';
                    $sqlQuery['where'] = 'WHERE p.`active` = 1 AND fp.id_feature = ' . (int) $filter['id_value'] . '
					AND p.id_product IN (
					SELECT id_product
					FROM ' . _DB_PREFIX_ . 'category_product cp
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND
					' . (Configuration::get('PS_LAYERED_FULL_TREE') ? 'c.nleft >= ' . (int) $parent->nleft . '
					AND c.nright <= ' . (int) $parent->nright : 'c.id_category = ' . (int) $id_parent) . '
					AND c.active = 1)) ';
                    $sqlQuery['group'] = 'GROUP BY fv.id_feature_value ';
                    break;
                case 'category':
                    $sqlQuery['select'] = '
					SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                    $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'category_product cp
					LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) ';
                    $sqlQuery['where'] = '
					WHERE cp.id_category = c.id_category ';
                    $sqlQuery['group'] = ') count_products
					FROM ' . _DB_PREFIX_ . 'category c
					LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . (int) $cookie->id_lang . ')
					WHERE c.id_parent = ' . (int) $id_parent . '
					GROUP BY c.id_category ORDER BY level_depth, c.position';
            }
            foreach ($filters as $filterTmp) {
                $methodName = 'get' . ucfirst($filterTmp['type']) . 'FilterSubQuery';
                if (method_exists('BlockLayered', $methodName) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filterTmp['type'] || $filter['type'] == $filterTmp['type'])) {
                    if ($filter['type'] == $filterTmp['type'] && $filter['id_value'] == $filterTmp['id_value']) {
                        $subQueryFilter = self::$methodName(array(), true);
                    } else {
                        if (!is_null($filterTmp['id_value'])) {
                            $selected_filters_cleaned = $this->cleanFilterByIdValue(@$selectedFilters[$filterTmp['type']], $filterTmp['id_value']);
                        } else {
                            $selected_filters_cleaned = @$selectedFilters[$filterTmp['type']];
                        }
                        $subQueryFilter = self::$methodName($selected_filters_cleaned, $filter['type'] == $filterTmp['type']);
                    }
                    foreach ($subQueryFilter as $key => $value) {
                        $sqlQuery[$key] .= $value;
                    }
                }
            }
            $products = false;
            if (!empty($sqlQuery['from'])) {
                if (version_compare(_PS_VERSION_, '1.5', '>')) {
                    $sqlQuery['from'] .= Context::getContext()->shop->addSqlAssociation('product', 'p');
                }
                $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sqlQuery['select'] . "\n" . $sqlQuery['from'] . "\n" . $sqlQuery['join'] . "\n" . $sqlQuery['where'] . "\n" . $sqlQuery['group']);
            }
            foreach ($filters as $filterTmp) {
                $methodName = 'filterProductsBy' . ucfirst($filterTmp['type']);
                if (method_exists('BlockLayered', $methodName) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filterTmp['type'] || $filter['type'] == $filterTmp['type'])) {
                    if ($filter['type'] == $filterTmp['type']) {
                        $products = self::$methodName(array(), $products);
                    } else {
                        $products = self::$methodName(@$selectedFilters[$filterTmp['type']], $products);
                    }
                }
            }
            switch ($filter['type']) {
                case 'price':
                    $priceArray = array('type_lite' => 'price', 'type' => 'price', 'id_key' => 0, 'name' => $this->l('Price'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => $currency->sign, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($priceArray['min'])) {
                                $priceArray['min'] = $product['price_min'];
                                $priceArray['values'][0] = $product['price_min'];
                            } else {
                                if ($priceArray['min'] > $product['price_min']) {
                                    $priceArray['min'] = $product['price_min'];
                                    $priceArray['values'][0] = $product['price_min'];
                                }
                            }
                            if ($priceArray['max'] < $product['price_max']) {
                                $priceArray['max'] = $product['price_max'];
                                $priceArray['values'][1] = $product['price_max'];
                            }
                        }
                    }
                    if ($priceArray['max'] != $priceArray['min'] && $priceArray['min'] != null) {
                        if ($filter['filter_type'] == 2) {
                            $priceArray['list_of_values'] = array();
                            $nbr_of_value = $filter['filter_show_limit'];
                            if ($nbr_of_value < 2) {
                                $nbr_of_value = 4;
                            }
                            $delta = ($priceArray['max'] - $priceArray['min']) / $nbr_of_value;
                            $current_step = $priceArray['min'];
                            for ($i = 0; $i < $nbr_of_value; $i++) {
                                $priceArray['list_of_values'][] = array((int) ($priceArray['min'] + $i * $delta), (int) ($priceArray['min'] + ($i + 1) * $delta));
                            }
                        }
                        if (isset($selectedFilters['price']) && isset($selectedFilters['price'][0]) && isset($selectedFilters['price'][1])) {
                            $priceArray['values'][0] = $selectedFilters['price'][0];
                            $priceArray['values'][1] = $selectedFilters['price'][1];
                        }
                        $filterBlocks[] = $priceArray;
                    }
                    break;
                case 'weight':
                    $weightArray = array('type_lite' => 'weight', 'type' => 'weight', 'id_key' => 0, 'name' => $this->l('Weight'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => Configuration::get('PS_WEIGHT_UNIT'), 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($weightArray['min'])) {
                                $weightArray['min'] = $product['weight'];
                                $weightArray['values'][0] = $product['weight'];
                            } else {
                                if ($weightArray['min'] > $product['weight']) {
                                    $weightArray['min'] = $product['weight'];
                                    $weightArray['values'][0] = $product['weight'];
                                }
                            }
                            if ($weightArray['max'] < $product['weight']) {
                                $weightArray['max'] = $product['weight'];
                                $weightArray['values'][1] = $product['weight'];
                            }
                        }
                    }
                    if ($weightArray['max'] != $weightArray['min'] && $weightArray['min'] != null) {
                        if (isset($selectedFilters['weight']) && isset($selectedFilters['weight'][0]) && isset($selectedFilters['weight'][1])) {
                            $weightArray['values'][0] = $selectedFilters['weight'][0];
                            $weightArray['values'][1] = $selectedFilters['weight'][1];
                        }
                        $filterBlocks[] = $weightArray;
                    }
                    break;
                case 'condition':
                    $conditionArray = array('new' => array('name' => $this->l('New'), 'nbr' => 0), 'used' => array('name' => $this->l('Used'), 'nbr' => 0), 'refurbished' => array('name' => $this->l('Refurbished'), 'nbr' => 0));
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($selectedFilters['condition']) && in_array($product['condition'], $selectedFilters['condition'])) {
                                $conditionArray[$product['condition']]['checked'] = true;
                            }
                        }
                    }
                    foreach ($conditionArray as $key => $condition) {
                        if (isset($selectedFilters['condition']) && in_array($key, $selectedFilters['condition'])) {
                            $conditionArray[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($conditionArray[$product['condition']])) {
                                $conditionArray[$product['condition']]['nbr']++;
                            }
                        }
                    }
                    $filterBlocks[] = array('type_lite' => 'condition', 'type' => 'condition', 'id_key' => 0, 'name' => $this->l('Condition'), 'values' => $conditionArray, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    break;
                case 'quantity':
                    $quantityArray = array(0 => array('name' => $this->l('Not available'), 'nbr' => 0), 1 => array('name' => $this->l('In stock'), 'nbr' => 0));
                    foreach ($quantityArray as $key => $quantity) {
                        if (isset($selectedFilters['quantity']) && in_array($key, $selectedFilters['quantity'])) {
                            $quantityArray[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            $quantityArray[(int) ($product['quantity'] > 0)]['nbr']++;
                        }
                    }
                    $filterBlocks[] = array('type_lite' => 'quantity', 'type' => 'quantity', 'id_key' => 0, 'name' => $this->l('Availability'), 'values' => $quantityArray, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    break;
                case 'manufacturer':
                    if (isset($products) && $products) {
                        $manufaturersArray = array();
                        foreach ($products as $manufacturer) {
                            $manufaturersArray[$manufacturer['id_manufacturer']] = array('name' => $manufacturer['name'], 'nbr' => $manufacturer['nbr']);
                            if (isset($selectedFilters['manufacturer']) && in_array((int) $manufacturer['id_manufacturer'], $selectedFilters['manufacturer'])) {
                                $manufaturersArray[$manufacturer['id_manufacturer']]['checked'] = true;
                            }
                        }
                        $filterBlocks[] = array('type_lite' => 'manufacturer', 'type' => 'manufacturer', 'id_key' => 0, 'name' => $this->l('Manufacturer'), 'values' => $manufaturersArray, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    }
                    break;
                case 'id_attribute_group':
                    $attributesArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $attributes) {
                            if (!isset($attributesArray[$attributes['id_attribute_group']])) {
                                $attributesArray[$attributes['id_attribute_group']] = array('type_lite' => 'id_attribute_group', 'type' => 'id_attribute_group', 'id_key' => (int) $attributes['id_attribute_group'], 'name' => $attributes['attribute_group_name'], 'is_color_group' => (bool) $attributes['is_color_group'], 'values' => array(), 'url_name' => $attributes['name_url_name'], 'meta_title' => $attributes['name_meta_title'], 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                            }
                            $attributesArray[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']] = array('color' => $attributes['color'], 'name' => $attributes['attribute_name'], 'nbr' => (int) $attributes['nbr'], 'url_name' => $attributes['value_url_name'], 'meta_title' => $attributes['value_meta_title']);
                            if (isset($selectedFilters['id_attribute_group'][$attributes['id_attribute']])) {
                                $attributesArray[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']]['checked'] = true;
                            }
                        }
                        $filterBlocks = array_merge($filterBlocks, $attributesArray);
                    }
                    break;
                case 'id_feature':
                    $featureArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $feature) {
                            if (!isset($featureArray[$feature['id_feature']])) {
                                $featureArray[$feature['id_feature']] = array('type_lite' => 'id_feature', 'type' => 'id_feature', 'id_key' => (int) $feature['id_feature'], 'values' => array(), 'name' => $feature['feature_name'], 'url_name' => $feature['name_url_name'], 'meta_title' => $feature['name_meta_title'], 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                            }
                            $featureArray[$feature['id_feature']]['values'][$feature['id_feature_value']] = array('nbr' => (int) $feature['nbr'], 'name' => $feature['value'], 'url_name' => $feature['value_url_name'], 'meta_title' => $feature['value_meta_title']);
                            if (isset($selectedFilters['id_feature'][$feature['id_feature_value']])) {
                                $featureArray[$feature['id_feature']]['values'][$feature['id_feature_value']]['checked'] = true;
                            }
                        }
                        $filterBlocks = array_merge($filterBlocks, $featureArray);
                    }
                    break;
                case 'category':
                    $tmpArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $category) {
                            $tmpArray[$category['id_category']] = array('name' => $category['name'], 'nbr' => (int) $category['count_products']);
                            if (isset($selectedFilters['category']) && in_array($category['id_category'], $selectedFilters['category'])) {
                                $tmpArray[$category['id_category']]['checked'] = true;
                            }
                        }
                        $filterBlocks[] = array('type_lite' => 'category', 'type' => 'category', 'id_key' => 0, 'name' => $this->l('Categories'), 'values' => $tmpArray, 'filter_show_limit' => $filter['filter_show_limit'], 'filter_type' => $filter['filter_type']);
                    }
                    break;
            }
        }
        // All non indexable attribute and feature
        $nonIndexable = array();
        // Get all non indexable attribute groups
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT public_name
		FROM `' . _DB_PREFIX_ . 'attribute_group_lang` agl
		LEFT JOIN `' . _DB_PREFIX_ . 'layered_indexable_attribute_group` liag
		ON liag.id_attribute_group = agl.id_attribute_group
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . (int) $cookie->id_lang) as $attribute) {
            $nonIndexable[] = Tools::link_rewrite($attribute['public_name']);
        }
        // Get all non indexable features
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT name
		FROM `' . _DB_PREFIX_ . 'feature_lang` fl
		LEFT JOIN  `' . _DB_PREFIX_ . 'layered_indexable_feature` lif
		ON lif.id_feature = fl.id_feature
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . (int) $cookie->id_lang) as $attribute) {
            $nonIndexable[] = Tools::link_rewrite($attribute['name']);
        }
        //generate SEO link
        $paramSelected = '';
        $param_product_url = '';
        $optionCheckedArray = array();
        $paramGroupSelectedArray = array();
        $titleValues = array();
        $link = new Link();
        $linkBase = $link->getCategoryLink($id_parent, Category::getLinkRewrite($id_parent, (int) $cookie->id_lang), (int) $cookie->id_lang);
        $filterBlockList = array();
        //get filters checked by group
        foreach ($filterBlocks as $typeFilter) {
            $filterName = !empty($typeFilter['url_name']) ? $typeFilter['url_name'] : $typeFilter['name'];
            $paramGroupSelected = '';
            foreach ($typeFilter['values'] as $key => $value) {
                if (is_array($value) && array_key_exists('checked', $value)) {
                    $valueName = !empty($value['url_name']) ? $value['url_name'] : $value['name'];
                    $paramGroupSelected .= '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                    $paramGroupSelectedArray[Tools::link_rewrite($filterName)][] = Tools::link_rewrite($valueName);
                    if (!isset($titleValues[$filterName])) {
                        $titleValues[$filterName] = array();
                    }
                    $titleValues[$filterName][] = $valueName;
                } else {
                    $paramGroupSelectedArray[Tools::link_rewrite($filterName)][] = array();
                }
            }
            if (!empty($paramGroupSelected)) {
                $paramSelected .= '/' . str_replace('-', '_', Tools::link_rewrite($filterName)) . $paramGroupSelected;
                $optionCheckedArray[Tools::link_rewrite($filterName)] = $paramGroupSelected;
            }
            // select only attribute and group attribute to display an unique product combination link
            if (!empty($paramGroupSelected) && $typeFilter['type'] == 'id_attribute_group') {
                $param_product_url .= '/' . str_replace('-', '_', Tools::link_rewrite($filterName)) . $paramGroupSelected;
            }
        }
        if ($this->page > 1) {
            $paramSelected .= '/page-' . $this->page;
        }
        $blackList = array('weight', 'price');
        $nofollow = false;
        foreach ($filterBlocks as &$typeFilter) {
            $filterName = !empty($typeFilter['url_name']) ? $typeFilter['url_name'] : $typeFilter['name'];
            if (count($typeFilter) > 0 && !in_array($typeFilter['type'], $blackList)) {
                foreach ($typeFilter['values'] as $key => $values) {
                    $nofollow = false;
                    $optionCheckedCloneArray = $optionCheckedArray;
                    //if not filters checked, add parameter
                    $valueName = !empty($values['url_name']) ? $values['url_name'] : $values['name'];
                    if (!in_array(Tools::link_rewrite($valueName), $paramGroupSelectedArray[Tools::link_rewrite($filterName)])) {
                        //update parameter filter checked before
                        if (array_key_exists(Tools::link_rewrite($filterName), $optionCheckedArray)) {
                            $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = $optionCheckedCloneArray[Tools::link_rewrite($filterName)] . '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                            $nofollow = true;
                        } else {
                            $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                        }
                    } else {
                        // Remove selected parameters
                        $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = str_replace('-' . str_replace('-', '_', Tools::link_rewrite($valueName)), '', $optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
                        if (empty($optionCheckedCloneArray[Tools::link_rewrite($filterName)])) {
                            unset($optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
                        }
                    }
                    $parameters = '';
                    foreach ($optionCheckedCloneArray as $keyGroup => $valueGroup) {
                        $parameters .= '/' . str_replace('-', '_', $keyGroup) . $valueGroup;
                    }
                    // Check if there is an non indexable attribute or feature in the url
                    foreach ($nonIndexable as $value) {
                        if (strpos($parameters, '/' . $value) !== false) {
                            $nofollow = true;
                        }
                    }
                    //write link by mode rewriting
                    if (!Configuration::get('PS_REWRITING_SETTINGS')) {
                        $typeFilter['values'][$key]['link'] = $linkBase . '&selected_filters=' . $parameters;
                    } else {
                        $typeFilter['values'][$key]['link'] = $linkBase . $parameters;
                    }
                    $typeFilter['values'][$key]['rel'] = $nofollow ? 'nofollow' : '';
                }
            }
        }
        $nFilters = 0;
        if (isset($selectedFilters['price'])) {
            if ($priceArray['min'] == $selectedFilters['price'][0] && $priceArray['max'] == $selectedFilters['price'][1]) {
                unset($selectedFilters['price']);
            }
        }
        if (isset($selectedFilters['weight'])) {
            if ($weightArray['min'] == $selectedFilters['weight'][0] && $weightArray['max'] == $selectedFilters['weight'][1]) {
                unset($selectedFilters['weight']);
            }
        }
        foreach ($selectedFilters as $filters) {
            $nFilters += count($filters);
        }
        $cache = array('layered_show_qties' => (int) Configuration::get('PS_LAYERED_SHOW_QTIES'), 'id_category_layered' => (int) $id_parent, 'selected_filters' => $selectedFilters, 'n_filters' => (int) $nFilters, 'nbr_filterBlocks' => count($filterBlocks), 'filters' => $filterBlocks, 'title_values' => $titleValues, 'current_friendly_url' => htmlentities($paramSelected), 'param_product_url' => htmlentities($param_product_url), 'nofollow' => !empty($paramSelected) || $nofollow);
        return $cache;
    }
    public function viewcustomer()
    {
        global $currentIndex, $cookie, $link;
        $irow = 0;
        $configurations = Configuration::getMultiple(array('PS_LANG_DEFAULT', 'PS_CURRENCY_DEFAULT'));
        $defaultLanguage = (int) $configurations['PS_LANG_DEFAULT'];
        $defaultCurrency = (int) $configurations['PS_CURRENCY_DEFAULT'];
        if (!($customer = $this->loadObject())) {
            return;
        }
        $customerStats = $customer->getStats();
        $addresses = $customer->getAddresses($defaultLanguage);
        $products = $customer->getBoughtProducts();
        $discounts = Discount::getCustomerDiscounts($defaultLanguage, (int) $customer->id, false, false);
        $orders = Order::getCustomerOrders((int) $customer->id, true);
        $carts = Cart::getCustomerCarts((int) $customer->id);
        $groups = $customer->getGroups();
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $referrers = Referrer::getReferrers((int) $customer->id);
        if ($totalCustomer = Db::getInstance()->getValue('SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . $customer->id . ' AND valid = 1')) {
            Db::getInstance()->getValue('SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 GROUP BY id_customer HAVING SUM(total_paid_real) > ' . $totalCustomer);
            $countBetterCustomers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $countBetterCustomers = '-';
        }
        echo '
		<fieldset style="width:400px;float: left"><div style="float: right"><a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a></div>
			<span style="font-weight: bold; font-size: 14px;">' . $customer->firstname . ' ' . $customer->lastname . '</span>
			<img src="../img/admin/' . ($customer->id_gender == 2 ? 'female' : ($customer->id_gender == 1 ? 'male' : 'unknown')) . '.gif" style="margin-bottom: 5px" /><br />
			<a href="mailto:' . $customer->email . '" style="text-decoration: underline; color: blue">' . $customer->email . '</a><br /><br />
			' . $this->l('ID:') . ' ' . sprintf('%06d', $customer->id) . '<br />
			' . $this->l('Registration date:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Last visit:') . ' ' . ($customerStats['last_visit'] ? Tools::displayDate($customerStats['last_visit'], (int) $cookie->id_lang, true) : $this->l('never')) . '<br />
			' . ($countBetterCustomers != '-' ? $this->l('Rank: #') . ' ' . (int) $countBetterCustomers . '<br />' : '') . '
		</fieldset>
		<fieldset style="width:300px;float:left;margin-left:50px">
			<div style="float: right">
				<a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a>
			</div>
			' . $this->l('Newsletter:') . ' ' . ($customer->newsletter ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Opt-in:') . ' ' . ($customer->optin ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Age:') . ' ' . $customerStats['age'] . ' ' . (!empty($customer->birthday['age']) ? '(' . Tools::displayDate($customer->birthday, (int) $cookie->id_lang) . ')' : $this->l('unknown')) . '<br /><br />
			' . $this->l('Last update:') . ' ' . Tools::displayDate($customer->date_upd, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Status:') . ' ' . ($customer->active ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />');
        if ($customer->isGuest()) {
            echo '
			<div>
			' . $this->l('This customer is registered as') . ' <b>' . $this->l('guest') . '</b>';
            if (!Customer::customerExists($customer->email)) {
                echo '
					<form method="POST" action="index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&token=' . Tools::getAdminTokenLite('AdminCustomers') . '">
						<input type="hidden" name="id_lang" value="' . (int) (sizeof($orders) ? $orders[0]['id_lang'] : Configuration::get('PS_LANG_DEFAULT')) . '" />
						<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="' . $this->l('Transform to customer') . '" /></p>
						' . $this->l('This feature generates a random password and sends an e-mail to the customer') . '</form>';
            } else {
                echo '</div><div><b style="color:red;">' . $this->l('A registered customer account exists with the same email address') . '</b>';
            }
            echo '
			</div>
			';
        }
        echo '
		</fieldset>
		<div class="clear">&nbsp;</div>';
        echo '<fieldset style="height:190px"><legend><img src="../img/admin/cms.gif" /> ' . $this->l('Add a private note') . '</legend>
			<p>' . $this->l('This note will be displayed to all the employees but not to the customer.') . '</p>
			<form action="ajax.php" method="post" onsubmit="saveCustomerNote();return false;" id="customer_note">
				<textarea name="note" id="noteContent" style="width:600px;height:100px" onkeydown="$(\'#submitCustomerNote\').removeAttr(\'disabled\');">' . Tools::htmlentitiesUTF8($customer->note) . '</textarea><br />
				<input type="submit" id="submitCustomerNote" class="button" value="' . $this->l('   Save   ') . '" style="float:left;margin-top:5px" disabled="disabled" />
				<span id="note_feedback" style="float:left;margin:10px 0 0 10px"></span>
			</form>
		</fieldset>
		<div class="clear">&nbsp;</div>
		<script type="text/javascript">
			function saveCustomerNote()
			{
				$("#note_feedback").html("<img src=\\"../img/loader.gif\\" />").show();
				var noteContent = $("#noteContent").val();
				$.post("ajax.php", {submitCustomerNote:1,id_customer:' . (int) $customer->id . ',note:noteContent}, function (r) {
					$("#note_feedback").html("").hide();
					if (r == "ok")
					{
						$("#note_feedback").html("<b style=\\"color:green\\">' . addslashes($this->l('Your note has been saved')) . '</b>").fadeIn(400);
						$("#submitCustomerNote").attr("disabled", "disabled");
					}
					else if (r == "error:validation")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: your note is not valid')) . '</b>").fadeIn(400);
					else if (r == "error:update")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: cannot save your note')) . '</b>").fadeIn(400);
					$("#note_feedback").fadeOut(3000);
				});
			}
		</script>';
        echo '<h2>' . $this->l('Messages') . ' (' . sizeof($messages) . ')</h2>';
        if (sizeof($messages)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Status') . '</th>
					<th class="center">' . $this->l('Message') . '</th>
					<th class="center">' . $this->l('Sent on') . '</th>
				</tr>';
            foreach ($messages as $message) {
                echo '<tr>
					<td>' . $message['status'] . '</td>
					<td><a href="index.php?tab=AdminCustomerThreads&id_customer_thread=' . (int) $message['id_customer_thread'] . '&viewcustomer_thread&token=' . Tools::getAdminTokenLite('AdminCustomerThreads') . '">' . substr(strip_tags(html_entity_decode($message['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75) . '...</a></td>
					<td>' . Tools::displayDate($message['date_add'], (int) $cookie->id_lang, true) . '</td>
				</tr>';
            }
            echo '</table>
			<div class="clear">&nbsp;</div>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has never contacted you.');
        }
        // display hook specified to this page : AdminCustomers
        if (($hook = Module::hookExec('adminCustomers', array('id_customer' => $customer->id))) !== false) {
            echo '<div>' . $hook . '</div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Groups') . ' (' . sizeof($groups) . ')</h2>';
        if ($groups and sizeof($groups)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenGroups = Tools::getAdminToken('AdminGroups' . (int) Tab::getIdFromClassName('AdminGroups') . (int) $cookie->id_employee);
            foreach ($groups as $group) {
                $objGroup = new Group($group);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '\'">
					<td class="center">' . $objGroup->id . '</td>
					<td>' . $objGroup->name[$defaultLanguage] . '</td>
					<td align="center"><a href="?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Orders') . ' (' . sizeof($orders) . ')</h2>';
        if ($orders and sizeof($orders)) {
            $totalOK = 0;
            $ordersOK = array();
            $ordersKO = array();
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($orders as $order) {
                if ($order['valid']) {
                    $ordersOK[] = $order;
                    $totalOK += $order['total_paid_real'];
                } else {
                    $ordersKO[] = $order;
                }
            }
            $orderHead = '
			<table cellspacing="0" cellpadding="0" class="table float">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Products') . '</th>
					<th class="center">' . $this->l('Total paid') . '</th>
					<th class="center">' . $this->l('Payment') . '</th>
					<th class="center">' . $this->l('State') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $orderFoot = '</table>';
            if ($countOK = sizeof($ordersOK)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:green;font-weight:700">' . $this->l('Valid orders:') . ' ' . $countOK . ' ' . $this->l('for') . ' ' . Tools::displayPrice($totalOK, new Currency($defaultCurrency)) . '</h3>' . $orderHead;
                foreach ($ordersOK as $order) {
                    echo '<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
						<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div>';
            }
            if ($countKO = sizeof($ordersKO)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:red;font-weight:700">' . $this->l('Invalid orders:') . ' ' . $countKO . '</h3>' . $orderHead;
                foreach ($ordersKO as $order) {
                    echo '
						<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
							<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div><div class="clear">&nbsp;</div>';
            }
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not placed any orders yet');
        }
        if ($products and sizeof($products)) {
            echo '<div class="clear">&nbsp;</div>
			<h2>' . $this->l('Products') . ' (' . sizeof($products) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Quantity') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($products as $product) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
					<td>' . Tools::displayDate($product['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td>' . $product['product_name'] . '</td>
					<td align="right">' . $product['product_quantity'] . '</td>
					<td align="center"><a href="?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Addresses') . ' (' . sizeof($addresses) . ')</h2>';
        if (sizeof($addresses)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('Company') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Address') . '</th>
					<th>' . $this->l('Country') . '</th>
					<th>' . $this->l('Phone number(s)') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenAddresses = Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee);
            foreach ($addresses as $address) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td>' . ($address['company'] ? $address['company'] : '--') . '</td>
					<td>' . $address['firstname'] . ' ' . $address['lastname'] . '</td>
					<td>' . $address['address1'] . ($address['address2'] ? ' ' . $address['address2'] : '') . ' ' . $address['postcode'] . ' ' . $address['city'] . '</td>
					<td>' . $address['country'] . '</td>
					<td>' . ($address['phone'] ? $address['phone'] . ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '') : ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '--')) . '</td>
					<td align="center">
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&addaddress&token=' . $tokenAddresses . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&deleteaddress&token=' . $tokenAddresses . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not registered any addresses yet') . '.';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Discounts') . ' (' . sizeof($discounts) . ')</h2>';
        if (sizeof($discounts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('ID') . '</th>
					<th>' . $this->l('Code') . '</th>
					<th>' . $this->l('Type') . '</th>
					<th>' . $this->l('Value') . '</th>
					<th>' . $this->l('Qty available') . '</th>
					<th>' . $this->l('Status') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenDiscounts = Tools::getAdminToken('AdminDiscounts' . (int) Tab::getIdFromClassName('AdminDiscounts') . (int) $cookie->id_employee);
            foreach ($discounts as $discount) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td align="center">' . $discount['id_discount'] . '</td>
					<td>' . $discount['name'] . '</td>
					<td>' . $discount['type'] . '</td>
					<td align="right">' . $discount['value'] . '</td>
					<td align="center">' . $discount['quantity_for_user'] . '</td>
					<td align="center"><img src="../img/admin/' . ($discount['active'] ? 'enabled.gif' : 'disabled.gif') . '" alt="' . $this->l('Status') . '" title="' . $this->l('Status') . '" /></td>
					<td align="center">
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&adddiscount&token=' . $tokenDiscounts . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&deletediscount&token=' . $tokenDiscounts . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has no discount vouchers') . '.';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<div style="float:left">
		<h2>' . $this->l('Carts') . ' (' . sizeof($carts) . ')</h2>';
        if ($carts and sizeof($carts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Total') . '</th>
					<th class="center">' . $this->l('Carrier') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenCarts = Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $cookie->id_employee);
            foreach ($carts as $cart) {
                $cartI = new Cart((int) $cart['id_cart']);
                $summary = $cartI->getSummaryDetails();
                $currency = new Currency((int) $cart['id_currency']);
                $carrier = new Carrier((int) $cart['id_carrier']);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '\'">
					<td class="center">' . sprintf('%06d', $cart['id_cart']) . '</td>
					<td>' . Tools::displayDate($cart['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td align="right">' . Tools::displayPrice($summary['total_price'], $currency) . '</td>
					<td>' . $carrier->name . '</td>
					<td align="center"><a href="index.php?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $this->l('No cart available') . '.';
        }
        echo '</div>';
        $interested = Db::getInstance()->ExecuteS('SELECT DISTINCT id_product FROM ' . _DB_PREFIX_ . 'cart_product cp INNER JOIN ' . _DB_PREFIX_ . 'cart c on c.id_cart = cp.id_cart WHERE c.id_customer = ' . (int) $customer->id . ' AND cp.id_product NOT IN (
		SELECT product_id FROM ' . _DB_PREFIX_ . 'orders o inner join ' . _DB_PREFIX_ . 'order_detail od ON o.id_order = od.id_order WHERE o.valid = 1 AND o.id_customer = ' . (int) $customer->id . ')');
        if (count($interested)) {
            echo '<div style="float:left;margin-left:20px">
			<h2>' . $this->l('Products') . ' (' . count($interested) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">';
            foreach ($interested as $p) {
                $product = new Product((int) $p['id_product'], false, $cookie->id_lang);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '\'">
					<td>' . (int) $product->id . '</td>
					<td>' . Tools::htmlentitiesUTF8($product->name) . '</td>
					<td align="center"><a href="' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '</table></div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        /* Last connections */
        $connections = $customer->getLastConnections();
        if (sizeof($connections)) {
            echo '<h2>' . $this->l('Last connections') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 100px">' . $this->l('Pages viewed') . '</th>
					<th style="width: 100px">' . $this->l('Total time') . '</th>
					<th style="width: 100px">' . $this->l('Origin') . '</th>
					<th style="width: 100px">' . $this->l('IP Address') . '</th>
				</tr>';
            foreach ($connections as $connection) {
                echo '<tr>
						<td>' . Tools::displayDate($connection['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . (int) $connection['pages'] . '</td>
						<td>' . $connection['time'] . '</td>
						<td>' . ($connection['http_referer'] ? preg_replace('/^www./', '', parse_url($connection['http_referer'], PHP_URL_HOST)) : $this->l('Direct link')) . '</td>
						<td>' . $connection['ipaddress'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        if (sizeof($referrers)) {
            echo '<h2>' . $this->l('Referrers') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 200px">' . $this->l('Name') . '</th>
				</tr>';
            foreach ($referrers as $referrer) {
                echo '<tr>
						<td>' . Tools::displayDate($referrer['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . $referrer['name'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        echo '<a href="' . $currentIndex . '&token=' . $this->token . '"><img src="../img/admin/arrow2.gif" /> ' . $this->l('Back to customer list') . '</a><br />';
    }
Example #4
0
 function getPriceList()
 {
     $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
     if ($currency->iso_code == 'RUB') {
         $currency->iso_code = 'RUR';
     }
     $desc_type = Configuration::get('YAMARKET_DESC_TYPE');
     $link = $this->context->link;
     $this->ensureHttpPrefix($link);
     // Get products
     $products = Product::getProducts($this->id_lang, 0, 0, 'name', 'asc');
     $xml = $this->getDocBody();
     // Offers
     $offers = $xml->createElement("offers");
     foreach ($products as $product) {
         // Get home category
         $category = $product['id_category_default'];
         if ($category == 1) {
             $temp_categories = Product::getProductCategories($product['id_product']);
             foreach ($temp_categories as $category) {
                 if ($category != 1) {
                     break;
                 }
             }
             if ($category == 1) {
                 continue;
             }
         }
         if (in_array($category, $this->excluded_cats)) {
             continue;
         }
         $prod_obj = new Product($product['id_product']);
         $crewrite = Category::getLinkRewrite($product['id_category_default'], $this->id_lang);
         $accessories = $this->getAccessories($product);
         $features = $this->getFeatures($product['id_product']);
         $combinations = $this->getCombinations($prod_obj, $currency);
         // template array
         $product_item = array('name' => html_entity_decode($product['name']), 'description' => html_entity_decode($product['description']), 'id_category_default' => $category, 'ean13' => $product['ean13'], 'accessories' => implode(',', $accessories), 'vendor' => $product['manufacturer_name']);
         if ($desc_type == 1) {
             $product_item['description'] = html_entity_decode($product['description_short']);
         }
         if ($this->country_of_origin_attr != '' && array_key_exists($this->country_of_origin_attr, $features)) {
             $product_item['country_of_origin'] = $features[$this->country_of_origin_attr];
             unset($features[$this->country_of_origin_attr]);
         }
         if ($this->model_name_attr != '' && array_key_exists($this->model_name_attr, $features)) {
             $product_item['name'] = $features[$this->model_name_attr];
             unset($features[$this->model_name_attr]);
         }
         if (!$product['available_for_order'] or !$product['active']) {
             continue;
         }
         if (!empty($combinations)) {
             foreach ($combinations as $combination) {
                 $prod_obj->id_product_attribute = $combination['id_product_attribute'];
                 $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], $combination['id_product_attribute']);
                 if (!$available_for_order && !$prod_obj->checkQty(1)) {
                     continue;
                 }
                 $params = $this->getParams($combination);
                 $pictures = array();
                 foreach ($combination['id_images'] as $id_image) {
                     $pictures[] = $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $id_image, $this->image_type);
                 }
                 $mainPicture = array_shift($pictures);
                 $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite, null, null, null, $combination['id_product_attribute']);
                 $extra_product_item = array('id_product' => $product['id_product'] . 'c' . $combination['id_product_attribute'], 'available_for_order' => $available_for_order, 'price' => $prod_obj->getPrice(true, $combination['id_product_attribute']), 'pictures' => $pictures, 'main_picture' => $mainPicture, 'params' => array_merge($params, $features), 'url' => $url);
                 $offer = array_merge($product_item, $extra_product_item);
                 $offers->appendChild($this->getOfferElem($offer, $xml, $currency));
             }
         } else {
             $pictures = $this->getPictures($product['id_product'], $product['link_rewrite']);
             $mainPicture = array_shift($pictures);
             $available_for_order = 1 <= StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0);
             if (!$available_for_order && !$prod_obj->checkQty(1)) {
                 continue;
             }
             $url = $link->getProductLink($prod_obj, $product['link_rewrite'], $crewrite);
             $extra_product_item = array('id_product' => $product['id_product'], 'available_for_order' => $available_for_order, 'price' => $prod_obj->getPrice(), 'pictures' => $pictures, 'main_picture' => $mainPicture, 'params' => $features, 'url' => $url);
             $offer = array_merge($product_item, $extra_product_item);
             $offers->appendChild($this->getOfferElem($offer, $xml, $currency));
         }
         $prod_obj->clearCache(true);
     }
     $shop = $xml->getElementsByTagName("shop")->item(0);
     $shop->appendChild($offers);
     return $xml->saveXML();
 }
Example #5
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $link = new Link();
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     $row['link'] = $link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? (double) Product::getProductAttributePrice($row['id_product_attribute']) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, false);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2), 2);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6, NULL, false, false);
     }
     $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
     $row['specific_prices'] = $specific_prices;
     if ($row['id_product_attribute']) {
         $row['quantity_all_versions'] = $row['quantity'];
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     $row['attachments'] = (!isset($row['cache_has_attachments']) or $row['cache_has_attachments']) ? Product::getAttachmentsStatic((int) $id_lang, $row['id_product']) : array();
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
Example #6
0
			<url><?php 
echo _PS_BASE_URL_ . __PS_BASE_URI__ . 'img/logo.jpg';
?>
</url>
			<link><?php 
echo _PS_BASE_URL_ . __PS_BASE_URI__;
?>
</link>
		</image>
<?php 
foreach ($products as $product) {
    $image = Image::getImages(intval($cookie->id_lang), $product['id_product']);
    echo "\t\t<item>\n";
    echo "\t\t\t<title><![CDATA[" . $product['name'] . " - " . html_entity_decode(Tools::displayPrice(Product::getPriceStatic($product['id_product']), $currency), ENT_COMPAT, 'UTF-8') . " ]]></title>\n";
    echo "\t\t\t<description>";
    $cdata = true;
    if (is_array($image) and sizeof($image)) {
        echo "<![CDATA[<img src='" . _PS_BASE_URL_ . __PS_BASE_URI__ . "img/p/" . $image[0]['id_product'] . "-" . $image[0]['id_image'] . "-small.jpg' title='" . str_replace('&', '', $product['name']) . "' alt='thumb' />";
        $cdata = false;
    }
    if ($cdata) {
        echo "<![CDATA[";
    }
    echo $product['description_short'] . "]]></description>\n";
    echo "\t\t\t<link><![CDATA[" . htmlspecialchars($link->getproductLink($product['id_product'], $product['link_rewrite'], Category::getLinkRewrite(intval($product['id_category_default']), $cookie->id_lang))) . $affiliate . "]]></link>\n";
    echo "\t\t</item>\n";
}
?>
	</channel>
</rss>
Example #7
0
    public static function getProductProperties($id_lang, $row)
    {
        if (!$row['id_product']) {
            return false;
        }
        // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
        $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
        if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
            $row['id_product_attribute'] = $ipa_default;
        }
        if (!isset($row['id_product_attribute'])) {
            $row['id_product_attribute'] = 0;
        }
        // Tax
        $usetax = Tax::excludeTaxeOption();
        $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
        if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
            return self::$producPropertiesCache[$cacheKey];
        }
        // Datas mbj
        $link = new Link();
        $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
        $row['link'] = $link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
        //usado link
        //init
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT p.*
		FROM `' . _DB_PREFIX_ . 'product` p 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product
		WHERE p.id_product = ' . (int) $ro1w['supplier_reference']) as $subrow) {
            $row_us['id_category_default'] = $subrow['id_category_default'];
            $row_us['link_rewrite'] = $subrow['link_rewrite'];
            $row_us['ean13'] = $subrow['ean13'];
        }
        $row['category_used'] = Category::getLinkRewrite((int) $row_us['id_category_default'], (int) $id_lang);
        $row['link_used'] = $link->getProductLink((int) $row['supplier_reference'], $row_us['link_rewrite'], $row['category_used'], $row_us['ean13']);
        $row['link_extr'] = 'id::' . $row['id_product'];
        //precio mall - distribuidor - lista - internet
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT pa.price
                    FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                        INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                    WHERE pac.id_attribute = 25 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_distribuidor_p'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT pa.price
                    FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                        INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                    WHERE pac.id_attribute = 24 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_distribuidor'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 23 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_tienda'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 22 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_mall'] = round($subrow['price']);
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT pa.price
		FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                    INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
		WHERE pac.id_attribute = 21 and  pa.id_product = ' . (int) $row['id_product']) as $subrow) {
            $row['price_internet'] = round($subrow['price']);
        }
        $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? (double) Product::getProductAttributePrice($row['id_product_attribute']) : 0;
        $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
        if (self::$_taxCalculationMethod == PS_TAX_EXC) {
            $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6);
            $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, false);
        } else {
            $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2), 2);
            $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6, NULL, false, false);
        }
        $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
        $row['specific_prices'] = $specific_prices;
        if ($row['id_product_attribute']) {
            $row['quantity_all_versions'] = $row['quantity'];
            $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
        }
        $row['id_image'] = Product::defineProductImage($row, $id_lang);
        $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
        $row['attachments'] = (!isset($row['cache_has_attachments']) or $row['cache_has_attachments']) ? Product::getAttachmentsStatic((int) $id_lang, $row['id_product']) : array();
        // Pack management
        $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
        $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
        $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
        if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
            $row['quantity'] = 0;
        }
        self::$producPropertiesCache[$cacheKey] = $row;
        return self::$producPropertiesCache[$cacheKey];
    }
 public function initFormSeo($product)
 {
     if (!$this->default_form_language) {
         $this->getLanguages();
     }
     $data = $this->createTemplate($this->tpl_form);
     $context = Context::getContext();
     $rewritten_links = array();
     foreach ($this->_languages as $language) {
         $category = Category::getLinkRewrite((int) $product->id_category_default, (int) $language['id_lang']);
         $rewritten_links[(int) $language['id_lang']] = explode('[REWRITE]', $context->link->getProductLink($product, '[REWRITE]', $category, null, (int) $language['id_lang']));
     }
     $data->assign(array('product' => $product, 'languages' => $this->_languages, 'id_lang' => $this->context->language->id, 'ps_ssl_enabled' => Configuration::get('PS_SSL_ENABLED'), 'curent_shop_url' => $this->context->shop->getBaseURL(), 'default_form_language' => $this->default_form_language, 'rewritten_links' => $rewritten_links));
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
 private function generateFile($lang)
 {
     $path_parts = pathinfo(__FILE__);
     if (Configuration::get('GENERATE_FILE_IN_ROOT')) {
         $generate_file_path = dirname(__FILE__) . '/../../' . $this->_getOutputFileName($lang['iso_code']);
     } else {
         $generate_file_path = dirname(__FILE__) . '/file_exports/' . $this->_getOutputFileName($lang['iso_code']);
     }
     //Google Shopping XML
     $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
     $xml .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0" encoding="UTF-8" >' . "\n";
     $xml .= '<title>' . Configuration::get('PS_SHOP_NAME') . '</title>' . "\n";
     $xml .= '<link href="' . htmlspecialchars($this->uri, self::REPLACE_FLAGS, self::CHARSET, false) . '" rel="alternate" type="text/html"/>' . "\n";
     $xml .= '<modified>' . date('Y-m-d') . 'T01:01:01Z</modified><author><name>' . Configuration::get('PS_SHOP_NAME') . '</name></author>' . "\n";
     $googleshoppingfile = fopen($generate_file_path, 'w');
     // add UTF-8 byte order mark
     fwrite($googleshoppingfile, pack("CCC", 0xef, 0xbb, 0xbf));
     //file header
     fwrite($googleshoppingfile, $xml);
     $sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'product p' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product' . ' WHERE p.active = 1 AND pl.id_lang=' . $lang['id_lang'];
     $products = Db::getInstance()->ExecuteS($sql);
     $title_limit = 70;
     $description_limit = 10000;
     $languages = Language::getLanguages();
     $tailleTabLang = sizeof($languages);
     foreach ($products as $product) {
         $xml_googleshopping = '';
         $cat_link_rew = Category::getLinkRewrite($product['id_category_default'], intval($lang));
         //continue if product not have price
         $price = Product::getPriceStatic($product['id_product'], true, NULL, 2);
         if (empty($price)) {
             continue;
         }
         $product_link = $this->context->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $cat_link_rew, $product['ean13'], (int) $product['id_lang'], 1, 0, true);
         $title_crop = $product['name'];
         if (strlen($product['name']) > $title_limit) {
             $title_crop = substr($title_crop, 0, $title_limit - 1);
             $title_crop = substr($title_crop, 0, strrpos($title_crop, " "));
         }
         if (intval(Configuration::get('DESCRIPTION')) === intval(2)) {
             $description_crop = $product['description'];
         } else {
             $description_crop = $product['description_short'];
         }
         $description_crop = $this->rip_tags($description_crop);
         if (strlen($description_crop) > $description_limit) {
             $description_crop = substr($description_crop, 0, $description_limit - 1);
             $description_crop = substr($description_crop, 0, strrpos($description_crop, " "));
         }
         $xml_googleshopping .= '<entry>' . "\n";
         $xml_googleshopping .= '<g:id>' . $product['id_product'] . '-' . $lang['iso_code'] . '</g:id>' . "\n";
         $xml_googleshopping .= '<title>' . htmlentities(ucfirst(mb_strtolower($title_crop, self::CHARSET)), self::REPLACE_FLAGS, self::CHARSET) . '</title>' . "\n";
         $xml_googleshopping .= '<link>' . htmlspecialchars($product_link, self::REPLACE_FLAGS, self::CHARSET, false) . '</link>' . "\n";
         $xml_googleshopping .= '<g:price>' . $price . '</g:price>' . "\n";
         $xml_googleshopping .= '<g:description>' . htmlentities($description_crop, self::REPLACE_FLAGS, self::CHARSET) . '</g:description>' . "\n";
         $xml_googleshopping .= '<g:condition>new</g:condition>' . "\n";
         // condition = new, used, refurbished
         $images = Image::getImages($lang['id_lang'], $product['id_product']);
         $indexTabLang = 0;
         if ($tailleTabLang > 1) {
             while (sizeof($images) < 1 && $indexTabLang < $tailleTabLang) {
                 if ($languages[$indexTabLang]['id_lang'] != $lang['id_lang']) {
                     $images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']);
                 }
                 $indexTabLang++;
             }
         }
         $nbimages = 0;
         $image_type = Configuration::get('GS_IMAGE');
         if ($image_type == '') {
             $image_type = 'large_default';
         }
         /* create image links */
         foreach ($images as $im) {
             $image = $this->context->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $im['id_image'], $image_type);
             $xml_googleshopping .= '<g:image_link>' . $image . '</g:image_link>' . "\n";
             //max images by product
             if (++$nbimages == 10) {
                 break;
             }
         }
         if (Configuration::get('QUANTITY') == 1) {
             $quantity = StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0);
             if ($quantity > 0) {
                 $xml_googleshopping .= '<g:quantity>' . $quantity . '</g:quantity>' . "\n";
                 $xml_googleshopping .= '<g:availability>in stock</g:availability>' . "\n";
             } else {
                 $xml_googleshopping .= '<g:quantity>0</g:quantity>' . "\n";
                 $xml_googleshopping .= '<g:availability>out of stock</g:availability>' . "\n";
             }
         }
         // Brand
         $identifier_exists = false;
         if (Configuration::get('BRAND') && $product['id_manufacturer'] != '0') {
             $xml_googleshopping .= '<g:brand>' . htmlspecialchars(Manufacturer::getNameById(intval($product['id_manufacturer'])), self::REPLACE_FLAGS, self::CHARSET, false) . '</g:brand>' . "\n";
             $identifier_exists = true;
         }
         if (Configuration::get('MPN') && $product['supplier_reference'] != '') {
             $xml_googleshopping .= '<g:mpn>' . $product['supplier_reference'] . '</g:mpn>';
             $identifier_exists = true;
         }
         if (Configuration::get('GTIN') && $product['ean13'] != '') {
             $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n";
             $identifier_exists = true;
         }
         if (!$identifier_exists) {
             $xml_googleshopping .= '<g:identifier_exists>FALSE</g:identifier_exists>' . "\n";
         }
         // Category google
         if (Configuration::get('GS_PRODUCT_TYPE_' . $lang['iso_code'])) {
             $product_type = str_replace('>', '&gt;', Configuration::get('GS_PRODUCT_TYPE_' . $lang['iso_code']));
             $product_type = str_replace('&', '&amp;', $product_type);
             $xml_googleshopping .= '<g:google_product_category>' . $product_type . '</g:google_product_category>' . "\n";
         }
         // Category shop
         if (Configuration::get('CATEGORY_SHOP')) {
             $categories = $this->getBreadcrumbCategory($product['id_category_default'], $product['id_lang']);
             $categories = str_replace('>', '&gt;', $categories);
             $categories = str_replace('&', '&amp;', $categories);
             $xml_googleshopping .= '<g:product_type>' . $categories . '</g:product_type>' . "\n";
         }
         //Shipping
         $xml_googleshopping .= '<g:shipping>' . "\n";
         $xml_googleshopping .= '<g:country>' . Configuration::get('GS_COUNTRY') . '</g:country>' . "\n";
         $xml_googleshopping .= '<g:service>Standard</g:service>' . "\n";
         $xml_googleshopping .= '<g:price>' . Configuration::get('GS_SHIPPING') . '</g:price>' . "\n";
         $xml_googleshopping .= '</g:shipping>' . "\n";
         //weight
         if ($product['weight'] != '0') {
             $xml_googleshopping .= '<g:shipping_weight>' . $product['weight'] . ' kilograms</g:shipping_weight>' . "\n";
         }
         //featured product
         if (Configuration::get('FEATURED_PRODUCT') == 1 && $product['on_sale'] != '0') {
             $xml_googleshopping .= '<g:featured_product>true</g:featured_product>' . "\n";
         }
         if (Configuration::get('GTIN') && $product['ean13'] != '') {
             $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n";
         }
         $xml_googleshopping .= '</entry>' . "\n";
         // Write element
         fwrite($googleshoppingfile, $xml_googleshopping);
     }
     $xml = '</feed>';
     fwrite($googleshoppingfile, $xml);
     fclose($googleshoppingfile);
     @chmod($generate_file_path, 0777);
     return true;
 }
 private function getItemXML($product, $lang, $id_curr, $id_shop, $combination = false)
 {
     $xml_googleshopping = '';
     $id_lang = (int) $lang['id_lang'];
     $title_limit = 70;
     $description_limit = 4990;
     $languages = Language::getLanguages();
     $tailleTabLang = sizeof($languages);
     $this->context->language->id = $id_lang;
     $this->context->shop->id = $id_shop;
     $p = new Product($product['id_product'], true, $id_lang, $id_shop, $this->context);
     // Get module configuration for this shop
     if (!$combination) {
         $product['quantity'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0, $id_shop);
     }
     // Exclude non-available products
     if ($this->module_conf['export_nap'] === 0 && $product['quantity'] < 1) {
         $this->nb_not_exported_products++;
         return;
     }
     // Check minimum product price
     $price = Product::getPriceStatic((int) $product['id_product'], true);
     if ((double) $this->module_conf['export_min_price'] > 0 && (double) $this->module_conf['export_min_price'] > (double) $price) {
         return;
     }
     $cat_link_rew = Category::getLinkRewrite($product['id_gcategory'], (int) $lang);
     $product_link = $this->context->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $cat_link_rew, $product['ean13'], (int) $product['id_lang'], $id_shop, $combination, true);
     // Product name
     $title_crop = $product['name'];
     //  Product color attribute, if any
     if (!empty($product['color'])) {
         $title_crop .= ' ' . $product['color'];
     }
     if (!empty($product['material'])) {
         $title_crop .= ' ' . $product['material'];
     }
     if (!empty($product['pattern'])) {
         $title_crop .= ' ' . $product['pattern'];
     }
     if (!empty($product['size'])) {
         $title_crop .= ' ' . $product['size'];
     }
     if (Tools::strlen($product['name']) > $title_limit) {
         $title_crop = Tools::substr($title_crop, 0, $title_limit - 1);
         $title_crop = Tools::substr($title_crop, 0, strrpos($title_crop, " "));
     }
     // Description type
     if ($this->module_conf['description'] == 'long') {
         $description_crop = $product['description'];
     } else {
         if ($this->module_conf['description'] == 'short') {
             $description_crop = $product['description_short'];
         } else {
             if ($this->module_conf['description'] == 'meta') {
                 $description_crop = $product['meta_description'];
             }
         }
     }
     $description_crop = $this->rip_tags($description_crop);
     if (Tools::strlen($description_crop) > $description_limit) {
         $description_crop = Tools::substr($description_crop, 0, $description_limit - 1);
         $description_crop = Tools::substr($description_crop, 0, strrpos($description_crop, " ")) . ' ...';
     }
     $xml_googleshopping .= '<item>' . "\n";
     $xml_googleshopping .= '<g:id>' . $product['gid'] . '</g:id>' . "\n";
     $xml_googleshopping .= '<title><![CDATA[' . $title_crop . ']]></title>' . "\n";
     $xml_googleshopping .= '<description><![CDATA[' . $description_crop . ']]></description>' . "\n";
     $xml_googleshopping .= '<link><![CDATA[' . htmlspecialchars($product_link, self::REPLACE_FLAGS, self::CHARSET, false) . ']]></link>' . "\n";
     // Image links
     $images = Image::getImages($lang['id_lang'], $product['id_product'], $combination);
     $indexTabLang = 0;
     if ($tailleTabLang > 1) {
         while (sizeof($images) < 1 && $indexTabLang < $tailleTabLang) {
             if ($languages[$indexTabLang]['id_lang'] != $lang['id_lang']) {
                 $images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']);
             }
             $indexTabLang++;
         }
     }
     $nbimages = 0;
     $image_type = $this->module_conf['img_type'];
     if ($image_type == '') {
         $image_type = 'large_default';
     }
     foreach ($images as $im) {
         $image = $this->context->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $im['id_image'], $image_type);
         $image = preg_replace('*http://' . Tools::getHttpHost() . '/*', $this->uri, $image);
         if ($im['cover'] == 1) {
             $xml_googleshopping .= '<g:image_link><![CDATA[' . $image . ']]></g:image_link>' . "\n";
         } else {
             $xml_googleshopping .= '<g:additional_image_link><![CDATA[' . $image . ']]></g:additional_image_link>' . "\n";
         }
         // max images by product
         if (++$nbimages == 10) {
             break;
         }
     }
     // Product condition, or category's condition attribute, or its parent one...
     // Product condition = new, used, refurbished
     if (empty($product['condition'])) {
         $product['condition'] = $this->categories_values[$product['id_gcategory']]['gcat_condition'];
     }
     if (!empty($product['condition'])) {
         $xml_googleshopping .= '<g:condition><![CDATA[' . $product['condition'] . ']]></g:condition>' . "\n";
     }
     // Shop category
     $breadcrumb = GCategories::getPath($product['id_gcategory'], '', $id_lang, $id_shop, $this->id_root);
     $product_type = '';
     if (!empty($this->module_conf['product_type[]'][$id_lang])) {
         $product_type = $this->module_conf['product_type[]'][$id_lang];
         if (!empty($breadcrumb)) {
             $product_type .= " > ";
         }
     }
     $product_type .= $breadcrumb;
     $xml_googleshopping .= '<g:product_type><![CDATA[' . $product_type . ']]></g:product_type>' . "\n";
     // Matching Google category, or parent categories' one
     $product['gcategory'] = $this->categories_values[$product['category_default']]['gcategory'];
     $xml_googleshopping .= '<g:google_product_category><![CDATA[' . $product['gcategory'] . ']]></g:google_product_category>' . "\n";
     // Product quantity & availability
     if (empty($this->categories_values[$product['category_default']]['gcat_avail'])) {
         if ($this->module_conf['quantity'] == 1) {
             $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n";
         }
         if ($product['quantity'] > 0 && $product['available_for_order']) {
             $xml_googleshopping .= '<g:availability>in stock</g:availability>' . "\n";
         } elseif ($p->isAvailableWhenOutOfStock((int) $p->out_of_stock) && $product['available_for_order']) {
             $xml_googleshopping .= '<g:availability>preorder</g:availability>' . "\n";
         } else {
             $xml_googleshopping .= '<g:availability>out of stock</g:availability>' . "\n";
         }
     } else {
         if ($this->module_conf['quantity'] == 1 && $product['quantity'] > 0) {
             $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n";
         }
         $xml_googleshopping .= '<g:availability>' . $this->categories_values[$product['category_default']]['gcat_avail'] . '</g:availability>' . "\n";
     }
     // Price(s)
     $currency = new Currency((int) $id_curr);
     $use_tax = $product['tax_included'] ? true : false;
     $no_tax = !$use_tax ? true : false;
     $product['price'] = (double) $p->getPriceStatic($product['id_product'], $use_tax, $combination) * $currency->conversion_rate;
     $product['price_without_reduct'] = (double) $p->getPriceWithoutReduct($no_tax, $combination) * $currency->conversion_rate;
     $product['price'] = number_format(round($product['price'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' ');
     $product['price_without_reduct'] = number_format(round($product['price_without_reduct'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' ');
     if ((double) $product['price'] < (double) $product['price_without_reduct']) {
         $xml_googleshopping .= '<g:price>' . $product['price_without_reduct'] . ' ' . $currency->iso_code . '</g:price>' . "\n";
         $xml_googleshopping .= '<g:sale_price>' . $product['price'] . ' ' . $currency->iso_code . '</g:sale_price>' . "\n";
     } else {
         $xml_googleshopping .= '<g:price>' . $product['price'] . ' ' . $currency->iso_code . '</g:price>' . "\n";
     }
     $identifier_exists = 0;
     // GTIN (EAN, UPC, JAN, ISBN)
     if (!empty($product['ean13'])) {
         $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n";
         $identifier_exists++;
     }
     // Brand
     if ($this->module_conf['no_brand'] != 0 && !empty($product['id_manufacturer'])) {
         $xml_googleshopping .= '<g:brand><![CDATA[' . htmlspecialchars(Manufacturer::getNameById((int) $product['id_manufacturer']), self::REPLACE_FLAGS, self::CHARSET, false) . ']]></g:brand>' . "\n";
         $identifier_exists++;
     }
     // MPN
     if (empty($product['supplier_reference'])) {
         $product['supplier_reference'] = ProductSupplier::getProductSupplierReference($product['id_product'], 0, $product['id_supplier']);
     }
     if ($this->module_conf['mpn_type'] == 'reference' && !empty($product['reference'])) {
         $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['reference'] . ']]></g:mpn>' . "\n";
         $identifier_exists++;
     } else {
         if ($this->module_conf['mpn_type'] == 'supplier_reference' && !empty($product['supplier_reference'])) {
             $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['supplier_reference'] . ']]></g:mpn>' . "\n";
             $identifier_exists++;
         }
     }
     // Tag "identifier_exists"
     if ($this->module_conf['id_exists_tag'] && $identifier_exists < 2) {
         $xml_googleshopping .= '<g:identifier_exists>FALSE</g:identifier_exists>' . "\n";
     }
     // Product gender and age_group attributes association
     $product_features = $this->getProductFeatures($product['id_product'], $id_lang, $id_shop);
     $product['gender'] = $this->categories_values[$product['category_default']]['gcat_gender'];
     $product['age_group'] = $this->categories_values[$product['category_default']]['gcat_age_group'];
     foreach ($product_features as $feature) {
         switch ($feature['id_feature']) {
             case $this->module_conf['gender']:
                 $product['gender'] = $feature['value'];
                 continue 2;
             case $this->module_conf['age_group']:
                 $product['age_group'] = $feature['value'];
                 continue 2;
         }
         if (!$product['color']) {
             foreach ($this->module_conf['color[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['color'] = $feature['value'];
                 }
             }
         }
         if (!$product['material']) {
             foreach ($this->module_conf['material[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['material'] = $feature['value'];
                 }
             }
         }
         if (!$product['pattern']) {
             foreach ($this->module_conf['pattern[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['pattern'] = $feature['value'];
                 }
             }
         }
         if (!$product['size']) {
             foreach ($this->module_conf['size[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['size'] = $feature['value'];
                 }
             }
         }
     }
     //  Product gender attribute, or category gender attribute, or parent's one
     if (!empty($product['gender'])) {
         $xml_googleshopping .= '<g:gender><![CDATA[' . $product['gender'] . ']]></g:gender>' . "\n";
     }
     // Product age_group attribute, or category age_group attribute, or parent's one
     if (!empty($product['age_group'])) {
         $xml_googleshopping .= '<g:age_group><![CDATA[' . $product['age_group'] . ']]></g:age_group>' . "\n";
     }
     // Product attributes combination groups
     if ($combination && !empty($product['item_group_id'])) {
         $xml_googleshopping .= '<g:item_group_id>' . $product['item_group_id'] . '</g:item_group_id>' . "\n";
     }
     // Product color attribute, or category color attribute, or parent's one
     if (!empty($product['color'])) {
         $xml_googleshopping .= '<g:color><![CDATA[' . $product['color'] . ']]></g:color>' . "\n";
     }
     // Product material attribute, or category material attribute, or parent's one
     if (!empty($product['material'])) {
         $xml_googleshopping .= '<g:material><![CDATA[' . $product['material'] . ']]></g:material>' . "\n";
     }
     // Product pattern attribute, or category pattern attribute, or parent's one
     if (!empty($product['pattern'])) {
         $xml_googleshopping .= '<g:pattern><![CDATA[' . $product['pattern'] . ']]></g:pattern>' . "\n";
     }
     // Product size attribute, or category size attribute, or parent's one
     if (!empty($product['size'])) {
         $xml_googleshopping .= '<g:size><![CDATA[' . $product['size'] . ']]></g:size>' . "\n";
     }
     // Featured products
     if ($this->module_conf['featured_products'] == 1 && $product['on_sale'] != '0') {
         $xml_googleshopping .= '<g:featured_product>true</g:featured_product>' . "\n";
     }
     // Shipping
     $xml_googleshopping .= '<g:shipping>' . "\n";
     $xml_googleshopping .= "\t" . '<g:country>' . $this->module_conf['shipping_country'] . '</g:country>' . "\n";
     $xml_googleshopping .= "\t" . '<g:service>Standard</g:service>' . "\n";
     $xml_googleshopping .= "\t" . '<g:price>' . number_format($this->module_conf['shipping_price'], 2, '.', ' ') . ' ' . $currency->iso_code . '</g:price>' . "\n";
     $xml_googleshopping .= '</g:shipping>' . "\n";
     // Shipping weight
     if ($product['weight'] != '0') {
         $xml_googleshopping .= '<g:shipping_weight>' . number_format($product['weight'], 2, '.', '') . ' ' . Configuration::get('PS_WEIGHT_UNIT') . '</g:shipping_weight>' . "\n";
     }
     $xml_googleshopping .= '</item>' . "\n\n";
     if ($combination) {
         $this->nb_combinations++;
         $this->nb_prd_w_attr[$product['id_product']] = 1;
     }
     $this->nb_total_products++;
     return $xml_googleshopping;
 }
Example #11
0
 public function header15($params)
 {
     // get current protocol
     $s = empty($_SERVER["HTTPS"]) ? '' : $_SERVER["HTTPS"] == "on" ? "s" : "";
     $sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
     $protocol = substr($sp, 0, strpos($sp, "/")) . $s;
     // Choose if you have to display open graphs. Only show them on the index, category pages, cms pages, product pages
     if (isset($this->context->controller->php_self)) {
         $og_site_name = Configuration::get('PS_SHOP_NAME');
         $og_type = '';
         // set nothing as default, we will hide og for this case
         $og_image = $this->getCustomImage('indexImage', $protocol);
         // check if a default custom image exists
         switch ($this->context->controller->php_self) {
             case 'index':
                 $og_type = 'website';
                 break;
             case 'best-sales':
                 $og_type = 'website';
                 $og_image = $this->getCustomImage('bestSalesImage', $protocol);
                 break;
             case 'new-products':
                 $og_type = 'website';
                 $og_image = $this->getCustomImage('newProductsImage', $protocol);
                 break;
             case 'prices-drop':
                 $og_type = 'website';
                 $og_image = $this->getCustomImage('priceDropImage', $protocol);
                 break;
             case 'cms':
                 $og_type = 'website';
                 break;
             case 'manufacturer':
                 $og_type = 'website';
                 $id_manufacturer = Tools::getValue('id_manufacturer');
                 // check if a manufacturer logo is set
                 if (file_exists(_PS_MANU_IMG_DIR_ . (int) $id_manufacturer . '.jpg')) {
                     $og_image = $protocol . '://' . Tools::getHttpHost() . __PS_BASE_URI__ . 'img/m/' . (int) $id_manufacturer . '.jpg';
                 } else {
                     if (file_exists(_PS_MANU_IMG_DIR_ . (int) $id_manufacturer . '.png')) {
                         $og_image = $protocol . '://' . Tools::getHttpHost() . __PS_BASE_URI__ . 'img/m/' . (int) $id_manufacturer . '.png';
                     }
                 }
                 break;
             case 'supplier':
                 $og_type = 'website';
                 $id_supplier = Tools::getValue('id_supplier');
                 // check if a manufacturer logo is set
                 if (file_exists(_PS_MANU_IMG_DIR_ . (int) $id_supplier . '.jpg')) {
                     $og_image = $protocol . '://' . Tools::getHttpHost() . __PS_BASE_URI__ . 'img/su/' . (int) $id_supplier . '.jpg';
                 } else {
                     if (file_exists(_PS_MANU_IMG_DIR_ . (int) $id_supplier . '.png')) {
                         $og_image = $protocol . '://' . Tools::getHttpHost() . __PS_BASE_URI__ . 'img/su/' . (int) $id_supplier . '.png';
                     }
                 }
                 break;
             case 'category':
                 $og_type = 'website';
                 $id_category = (int) Tools::getValue('id_category');
                 $category_image_id = $id_category && file_exists(_PS_CAT_IMG_DIR_ . (int) $id_category . '.jpg') ? (int) $id_category : false;
                 $link_rewrite = Category::getLinkRewrite($id_category, $this->context->language->id);
                 $og_image = $this->context->link->getCatImageLink($link_rewrite, $category_image_id, 'category_default');
                 break;
             case 'product':
                 $og_type = 'og:product';
                 $this->assignProductOG();
                 break;
         }
         $this->context->smarty->assign(array('og_type' => $og_type, 'og_image' => $og_image, 'og_site_name' => $og_site_name, 'remove_site_name_title' => Configuration::get('PSOGRAPH_REMOVE_SITE_NAME')));
     }
     return $this->display(__FILE__, 'psograph.tpl');
 }
Example #12
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     $link = new Link();
     // Tax
     $usetax = true;
     $tax = floatval(Tax::getApplicableTax(intval($row['id_tax']), floatval($row['rate'])));
     if (Tax::excludeTaxeOption() or !$tax) {
         $usetax = false;
     }
     // Datas
     $row['category'] = Category::getLinkRewrite($row['id_category_default'], intval($id_lang));
     $row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])) {
         $row['id_product_attribute'] = $ipa_default;
     }
     $row['attribute_price'] = isset($row['id_product_attribute']) and $row['id_product_attribute'] ? floatval(Product::getProductAttributePrice($row['id_product_attribute'])) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic($row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2);
     $row['price'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2);
     $row['reduction'] = self::getReductionValue($row['reduction_price'], $row['reduction_percent'], $row['reduction_from'], $row['reduction_to'], $row['price'], $usetax, floatval($row['rate']));
     $row['price_without_reduction'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 2, NULL, false, false);
     $row['quantity'] = Product::getQuantity($row['id_product']);
     $row['id_image'] = Product::defineProductImage($row);
     $row['features'] = Product::getFrontFeaturesStatic(intval($id_lang), $row['id_product']);
     $row['attachments'] = Product::getAttachmentsStatic(intval($id_lang), $row['id_product']);
     $row['pack'] = Pack::isPack($row['id_product']);
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     return $row;
 }
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!Validate::isLoadedObject($this->product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!$this->product->active and Tools::getValue('adtoken') != Tools::encrypt('PreviewProduct' . $this->product->id) || !file_exists(dirname(__FILE__) . '/../' . Tools::getValue('ad') . '/ajax.php')) {
             header('HTTP/1.1 404 page not found');
             $this->errors[] = Tools::displayError('Product is no longer available.');
         } elseif (!$this->product->checkAccess((int) self::$cookie->id_customer)) {
             $this->errors[] = Tools::displayError('You do not have access to this product.');
         } else {
             self::$smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
             if (!$this->product->active) {
                 self::$smarty->assign('adminActionDisplay', true);
             }
             /* Product pictures management */
             require_once 'images.inc.php';
             if ($this->product->customizable) {
                 self::$smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
                 if (Tools::isSubmit('submitCustomizedDatas')) {
                     $this->pictureUpload($this->product, $cart);
                     $this->textRecord($this->product, $cart);
                     $this->formTargetFormat();
                 } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct((int) $this->product->id, (int) Tools::getValue('deletePicture'))) {
                     $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture');
                 }
                 $files = self::$cookie->getFamily('pictures_' . (int) $this->product->id);
                 $textFields = self::$cookie->getFamily('textFields_' . (int) $this->product->id);
                 foreach ($textFields as $key => $textField) {
                     $textFields[$key] = str_replace('<br />', "\n", $textField);
                 }
                 self::$smarty->assign(array('pictures' => $files, 'textFields' => $textFields));
             }
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->cache_has_attachments ? $this->product->getAttachments((int) self::$cookie->id_lang) : array();
             /* Category */
             $category = false;
             if (isset($_SERVER['HTTP_REFERER']) and preg_match('!^(.*)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) and !strstr($_SERVER['HTTP_REFERER'], '.html')) {
                 if (isset($regs[2]) and is_numeric($regs[2])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[2])))) {
                         $category = new Category((int) $regs[2], (int) self::$cookie->id_lang);
                     }
                 } elseif (isset($regs[5]) and is_numeric($regs[5])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[5])))) {
                         $category = new Category((int) $regs[5], (int) self::$cookie->id_lang);
                     }
                 }
             }
             if (!$category) {
                 $category = new Category($this->product->id_category_default, (int) self::$cookie->id_lang);
             }
             if (isset($category) and Validate::isLoadedObject($category)) {
                 self::$smarty->assign(array('path' => Tools::getPath((int) $category->id, $this->product->name, true), 'category' => $category, 'subCategories' => $category->getSubCategories((int) self::$cookie->id_lang, true), 'id_category_current' => (int) $category->id, 'id_category_parent' => (int) $category->id_parent, 'return_category_name' => Tools::safeOutput($category->name)));
             } else {
                 self::$smarty->assign('path', Tools::getPath((int) $this->product->id_category_default, $this->product->name));
             }
             self::$smarty->assign('return_link', (isset($category->id) and $category->id) ? Tools::safeOutput(self::$link->getCategoryLink($category)) : 'javascript: history.back();');
             if (Pack::isPack((int) $this->product->id) and !Pack::isInStock((int) $this->product->id)) {
                 $this->product->quantity = 0;
             }
             $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0;
             $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_;
             $id_country = (int) ($id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT'));
             $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
             if ($group_reduction == 0) {
                 $group_reduction = Group::getReduction((int) self::$cookie->id_customer) / 100;
             }
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $ecotax_rate = (double) Tax::getProductEcotaxRate($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $ecotaxTaxAmount = Tools::ps_round($this->product->ecotax, 2);
             if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
                 $ecotaxTaxAmount = Tools::ps_round($ecotaxTaxAmount * (1 + $ecotax_rate / 100), 2);
             }
             //usado link
             //init
             $link = new Link();
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT p.*
                             FROM `' . _DB_PREFIX_ . 'product` p 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_lang pl ON p.id_product = pl.id_product
                             WHERE p.id_product = ' . (int) $this->product->supplier_reference) as $subrow) {
                 $row_us['id_category_default'] = $subrow['id_category_default'];
                 $row_us['link_rewrite'] = $subrow['link_rewrite'];
                 $row_us['ean13'] = $subrow['ean13'];
             }
             $row['category_used'] = Category::getLinkRewrite((int) $row_us['id_category_default'], (int) $id_lang);
             $row['link_used'] = $link->getProductLink((int) $this->product->supplier_reference, $row_us['link_rewrite'], $row['category_used'], $row_us['ean13']);
             //precio mall - distribuidor - lista - internet
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT pa.price
                             FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                             WHERE pac.id_attribute = 25 and  pa.id_product = ' . (int) $this->product->id) as $subrow) {
                 $row['price_distribuidor_p'] = round($subrow['price']);
             }
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT pa.price
                             FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                             WHERE pac.id_attribute = 24 and  pa.id_product = ' . (int) $this->product->id) as $subrow) {
                 $row['price_distribuidor'] = round($subrow['price']);
             }
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT pa.price
                             FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                             WHERE pac.id_attribute = 23 and  pa.id_product = ' . (int) $this->product->id) as $subrow) {
                 $row['price_tienda'] = round($subrow['price']);
             }
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT pa.price
                             FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                             WHERE pac.id_attribute = 22 and  pa.id_product = ' . (int) $this->product->id) as $subrow) {
                 $row['price_mall'] = round($subrow['price']);
             }
             foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                             SELECT pa.price
                             FROM `' . _DB_PREFIX_ . 'product_attribute` pa 
                                 INNER JOIN ' . _DB_PREFIX_ . 'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
                             WHERE pac.id_attribute = 21 and  pa.id_product = ' . (int) $this->product->id) as $subrow) {
                 $row['price_internet'] = round($subrow['price']);
             }
             self::$smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts(SpecificPrice::getQuantityDiscounts((int) $this->product->id, (int) Shop::getCurrentShop(), (int) self::$cookie->id_currency, $id_country, $id_group), $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false), (double) $tax), 'product' => $this->product, 'link_used' => $row['link_used'], 'price_distribuidor_p' => $row['price_distribuidor_p'], 'price_distribuidor' => $row['price_distribuidor'], 'price_tienda' => $row['price_tienda'], 'price_mall' => $row['price_mall'], 'price_internet' => $row['price_internet'], 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, self::$cookie->id_lang), 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => (double) $productPriceWithoutEcoTax, 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'group_reduction' => 1 - $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_));
             self::$smarty->assign(array('HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($this->product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($this->product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent')));
             $images = $this->product->getImages((int) self::$cookie->id_lang);
             $productImages = array();
             foreach ($images as $k => $image) {
                 if ($image['cover']) {
                     self::$smarty->assign('mainImage', $images[0]);
                     $cover = $image;
                     $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image'];
                     $cover['id_image_only'] = (int) $image['id_image'];
                 }
                 $productImages[(int) $image['id_image']] = $image;
             }
             if (!isset($cover)) {
                 $cover = array('id_image' => Language::getIsoById(self::$cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture');
             }
             $size = Image::getSize('large');
             self::$smarty->assign(array('cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize('medium'), 'largeSize' => Image::getSize('large'), 'accessories' => $this->product->getAccessories((int) self::$cookie->id_lang)));
             if (count($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             /* Attributes / Groups & colors */
             $colors = array();
             $attributesGroups = $this->product->getAttributesGroups((int) self::$cookie->id_lang);
             // @todo (RM) should only get groups and not all declination ?
             if (is_array($attributesGroups) and $attributesGroups) {
                 $groups = array();
                 $combinationImages = $this->product->getCombinationImages((int) self::$cookie->id_lang);
                 foreach ($attributesGroups as $k => $row) {
                     /* Color management */
                     if ((isset($row['attribute_color']) and $row['attribute_color'] or file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) and $row['id_attribute_group'] == $this->product->id_color_default) {
                         $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                         $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                         if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                             $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                         }
                         $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                     }
                     if (!isset($groups[$row['id_attribute_group']])) {
                         $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'is_color_group' => $row['is_color_group'], 'default' => -1);
                     }
                     $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
                     if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                         $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                     }
                     if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                         $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                     }
                     $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                     $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                     $combinations[$row['id_product_attribute']]['price'] = (double) $row['price'];
                     $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
                     $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
                     $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                     $combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];
                     $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                     $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                     $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1;
                 }
                 //wash attributes list (if some attributes are unavailables and if allowed to wash it)
                 if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                     foreach ($groups as &$group) {
                         foreach ($group['attributes_quantity'] as $key => &$quantity) {
                             if (!$quantity) {
                                 unset($group['attributes'][$key]);
                             }
                         }
                     }
                     foreach ($colors as $key => $color) {
                         if (!$color['attributes_quantity']) {
                             unset($colors[$key]);
                         }
                     }
                 }
                 foreach ($groups as &$group) {
                     natcasesort($group['attributes']);
                 }
                 foreach ($combinations as $id_product_attribute => $comb) {
                     $attributeList = '';
                     foreach ($comb['attributes'] as $id_attribute) {
                         $attributeList .= '\'' . (int) $id_attribute . '\',';
                     }
                     $attributeList = rtrim($attributeList, ',');
                     $combinations[$id_product_attribute]['list'] = $attributeList;
                 }
                 self::$smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $this->product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages));
             }
             self::$smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields((int) self::$cookie->id_lang) : false));
             // Pack management
             self::$smarty->assign('packItems', $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, (int) self::$cookie->id_lang, true) : array());
             self::$smarty->assign('packs', Pack::getPacksTable($this->product->id, (int) self::$cookie->id_lang, true, 1));
         }
     }
     self::$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'categories' => Category::getHomeCategories((int) self::$cookie->id_lang), 'have_image' => isset($cover) ? (int) $cover['id_image'] : false, 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'ecotax' => !sizeof($this->errors) and $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM')));
 }
    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());
    }
 /**
  * @return array
  */
 public function getItems()
 {
     $categoryItems = array();
     $result = array();
     $exportRootCategories = Configuration::get('SG_EXPORT_ROOT_CATEGORIES') == 1 ? true : false;
     $skippedRootCategories = array();
     foreach (Category::getSimpleCategories($this->getPlugin()->getLanguageId()) as $category) {
         /** @var CategoryCore $categoryInfo */
         $categoryInfo = new Category($category['id_category']);
         $categoryLinkRewrite = $categoryInfo->getLinkRewrite($categoryInfo->id_category, $this->getPlugin()->getLanguageId());
         $isRootCategory = $categoryInfo->is_root_category;
         /**
          * skip root categories
          */
         if ($categoryInfo->is_root_category && !$exportRootCategories) {
             $skippedRootCategories[] = $categoryInfo->id_category;
             continue;
         }
         $categoryItem = array();
         $categoryItem['category_number'] = $categoryInfo->id_category;
         $categoryItem['category_name'] = $categoryInfo->getName($this->getPlugin()->getLanguageId());
         $categoryItem['parent_id'] = $isRootCategory || in_array($categoryInfo->id_category, $skippedRootCategories) ? '' : $categoryInfo->id_parent;
         $categoryItem['is_active'] = $categoryInfo->active;
         $categoryItem['url_deeplink'] = $this->getPlugin()->getContext()->link->getCategoryLink($categoryInfo->id_category, $categoryLinkRewrite, $this->getPlugin()->getLanguageId());
         $categoryImageUrl = $this->getPlugin()->getContext()->link->getCatImageLink($categoryLinkRewrite, $categoryInfo->id_category, sprintf(self::PS_CONST_IMAGE_TYPE_CATEGORY_DEFAULT, '_'));
         $categoryItem['url_image'] = $categoryImageUrl;
         $categoryItem['order_index'] = $categoryInfo->position;
         $categoryItems[] = $categoryItem;
     }
     /**
      * clean root categories
      */
     if (!$exportRootCategories) {
         foreach ($categoryItems as $key => $categoryItem) {
             if (in_array($categoryItem['parent_id'], $skippedRootCategories)) {
                 $categoryItems[$key]['parent_id'] = '';
             }
         }
     }
     $categoryPositionData = array();
     foreach ($categoryItems as $categoryItem) {
         $key = $categoryItem['parent_id'] == '' ? 'root' : $categoryItem['parent_id'];
         if (!array_key_exists($key, $categoryPositionData)) {
             $categoryPositionData[$key] = 0;
         } else {
             $categoryPositionData[$key]++;
         }
     }
     $categoryNewPositionData = array();
     foreach ($categoryItems as $categoryItem) {
         $key = $categoryItem['parent_id'] == '' ? 'root' : $categoryItem['parent_id'];
         if (!array_key_exists($key, $categoryNewPositionData)) {
             $categoryNewPositionData[$key] = 0;
         } else {
             $categoryNewPositionData[$key]++;
         }
         $categoryItem['order_index'] = $categoryPositionData[$key] - $categoryNewPositionData[$key];
         $result[] = $categoryItem;
     }
     return $result;
 }
Example #16
0
 public static function getProductProperties($id_lang, $row, Context $context = null)
 {
     if (!$row['id_product']) {
         return false;
     }
     if ($context == null) {
         $context = Context::getContext();
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it:
     // consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if (Combination::isFeatureActive() && (!isset($row['id_product_attribute']) || !$row['id_product_attribute']) && (isset($row['cache_default_attribute']) && ($ipa_default = $row['cache_default_attribute']) !== null || ($ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!Combination::isFeatureActive() || !isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cache_key = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (isset($row['id_product_pack'])) {
         $cache_key .= '-pack' . $row['id_product_pack'];
     }
     if (isset(self::$producPropertiesCache[$cache_key])) {
         return self::$producPropertiesCache[$cache_key];
     }
     // Datas
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     $row['link'] = $context->link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = 0;
     if (isset($row['id_product_attribute']) && $row['id_product_attribute']) {
         $row['attribute_price'] = (double) Product::getProductAttributePrice($row['id_product_attribute']);
     }
     $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, false);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2), 2);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, false);
     }
     $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, null, true, true, 1, true, null, null, null, $specific_prices);
     $row['specific_prices'] = $specific_prices;
     if ($row['id_product_attribute']) {
         $row['quantity_all_versions'] = $row['quantity'];
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null);
     } else {
         $row['quantity'] = Product::getQuantity((int) $row['id_product']);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     $row['attachments'] = array();
     if (!isset($row['cache_has_attachments']) || $row['cache_has_attachments']) {
         $row['attachments'] = Product::getAttachmentsStatic((int) $id_lang, $row['id_product']);
     }
     $row['virtual'] = !isset($row['is_virtual']) || $row['is_virtual'] ? 1 : 0;
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] && !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     self::$producPropertiesCache[$cache_key] = $row;
     return self::$producPropertiesCache[$cache_key];
 }
Example #17
0
    public function getFilterBlock($selectedFilters = array())
    {
        global $cookie;
        static $cache = null;
        $whereLikeFilter = $this->getSelectedFiltersByQ();
        if (!$whereLikeFilter or $whereLikeFilter == '' or $whereLikeFilter == 0) {
            $whereLikeFilter = $_SESSION['search_q'];
        }
        $whereLikeFilter = str_replace("+", " ", $whereLikeFilter);
        if (is_array($cache)) {
            return $cache;
        }
        $id_parent = (int) Tools::getValue('id_category', Tools::getValue('id_category_layered', 1));
        if ($id_parent == 1) {
            return;
        }
        if ($id_parent != 4012) {
            $whereLikeFilter = '';
        }
        if ($id_parent == 4017) {
            $usado = true;
        }
        $parent = new Category((int) $id_parent);
        $descrypt_reg = "";
        //echo var_dump($tmp_lett);
        $wLikeArr = explode(" ", ltrim(rtrim($whereLikeFilter)));
        if ($wLikeArr[0] != "") {
            $descrypt_reg = ' pl.description REGEXP "[[:<:]]' . $wLikeArr[0] . '[[:>:]]" ';
            if ($wLikeArr[1] != "") {
                $descrypt_reg .= ' AND pl.description REGEXP "[[:<:]]' . $wLikeArr[1] . '[[:>:]]" ';
            }
            if ($wLikeArr[2] != "") {
                $descrypt_reg .= ' AND pl.description REGEXP "[[:<:]]' . $wLikeArr[2] . '[[:>:]]" ';
            }
            if ($wLikeArr[3] != "") {
                $descrypt_reg .= ' AND pl.description REGEXP "[[:<:]]' . $wLikeArr[3] . '[[:>:]]" ';
            }
        }
        /* Get the filters for the current category */
        $filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM ' . _DB_PREFIX_ . 'layered_category WHERE id_category = ' . (int) $id_parent . '
		GROUP BY `type`, id_value ORDER BY position ASC');
        // Remove all empty selected filters
        foreach ($selectedFilters as $key => $value) {
            switch ($key) {
                case 'price':
                case 'weight':
                    if ($value[0] == '' && $value[1] == '' || $value[0] == 0 && $value[1] == 0) {
                        unset($selectedFilters[$key]);
                    }
                    break;
                default:
                    if ($value == '') {
                        unset($selectedFilters[$key]);
                    }
                    break;
            }
        }
        $filterBlocks = array();
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT level_depth
		FROM `' . _DB_PREFIX_ . 'category` agl
		WHERE id_category = ' . $id_parent) as $catlevl) {
            $level_depth = $catlevl['level_depth'];
        }
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT id_category
		FROM `' . _DB_PREFIX_ . 'category` 
		WHERE id_parent = ' . $id_parent) as $cat2) {
            $catg2do[] = $cat2['id_category'];
        }
        $catg2do_filter = array();
        $catg2do_filter_none = array();
        foreach ($catg2do as $ctg2) {
            foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT id_category
                    FROM `' . _DB_PREFIX_ . 'category` 
                    WHERE id_parent = ' . $ctg2) as $cat22) {
                $catg2do_filter[] = $cat22['id_category'];
                $catg2do_filter_none[] = 0;
            }
            $catg2do_filter[] = $ctg2;
        }
        $catg2do = $catg2do_filter;
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT distinct cc.id_category,cl.name,id_parent
		FROM `' . _DB_PREFIX_ . 'category` cc inner join ' . _DB_PREFIX_ . 'category_lang cl on cc.id_category=cl.id_category 
		WHERE cc.id_parent in (' . implode(",", $catg2do) . ')') as $cat3) {
            $catg3do[] = $cat3['id_category'];
            foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                    SELECT distinct cc.id_category,cl.name
                    FROM `' . _DB_PREFIX_ . 'category` cc inner join ' . _DB_PREFIX_ . 'category_lang cl on cc.id_category=cl.id_category 
                    WHERE cc.id_category="' . $cat3['id_parent'] . '"') as $cat33) {
                $catg3do_dat['name'][$cat3['id_category']] = $cat33['name'];
                $catg3do_dat['id_category'][$cat3['id_category']] = $cat33['id_category'];
            }
        }
        foreach ($filters as $filter) {
            $sqlQuery = array('select' => '', 'from' => '', 'join' => '', 'where' => '', 'group' => '');
            switch ($filter['type']) {
                // conditions + quantities + weight + price
                case 'price':
                case 'weight':
                case 'condition':
                case 'quantity':
                    if ($whereLikeFilter != '') {
                        $sqlQuery['select'] = '
					SELECT p.`id_product`, p.`condition`, p.`id_manufacturer`, p.`quantity`, p.`weight`
					';
                        $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'product p ';
                        $sqlQuery['join'] = '
					INNER JOIN ' . _DB_PREFIX_ . 'category_product cp ON (cp.id_product = p.id_product)
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category ) 
                                        LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product)  
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category
                                        ';
                        $sqlQuery['where'] = 'WHERE p.`active` = 1 and (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
)  ';
                        $sqlQuery['group'] = ' GROUP BY p.id_product ';
                    } else {
                        if ($usado == true) {
                            $sqlQuery['select'] = '
                                            SELECT p.`id_product`, p.`condition`, p.`id_manufacturer`, p.`quantity`, p.`weight`
                                            ';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'product p ';
                            $sqlQuery['join'] = '
                                            INNER JOIN ' . _DB_PREFIX_ . 'category_product cp ON (cp.id_product = p.id_product)
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category) 

                                            ';
                            $sqlQuery['where'] = 'WHERE p.`active` = 1 and p.condition="used"';
                            $sqlQuery['group'] = ' GROUP BY p.id_product ';
                        } else {
                            $sqlQuery['select'] = '
                                            SELECT p.`id_product`, p.`condition`, p.`id_manufacturer`, p.`quantity`, p.`weight`
                                            ';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'product p ';
                            $sqlQuery['join'] = '
                                            INNER JOIN ' . _DB_PREFIX_ . 'category_product cp ON (cp.id_product = p.id_product)
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright . ') 

                                            ';
                            $sqlQuery['where'] = 'WHERE p.`active` = 1 ';
                            $sqlQuery['group'] = ' GROUP BY p.id_product ';
                        }
                    }
                    break;
                case 'manufacturer':
                    if ($whereLikeFilter != '') {
                        $sqlQuery['select'] = 'SELECT m.name, COUNT(DISTINCT p.id_product) nbr, m.id_manufacturer ';
                        $sqlQuery['from'] = '
					FROM `' . _DB_PREFIX_ . 'category_product` cp
					INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1)
					INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer)
                                        LEFT JOIN ps_product_lang pl ON (pl.id_product = p.id_product)   
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category    
';
                        $sqlQuery['where'] = '
					WHERE (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
) ';
                        $sqlQuery['group'] = ' GROUP BY p.id_manufacturer order by m.name asc ';
                    } else {
                        if ($usado == true) {
                            $sqlQuery['select'] = 'SELECT m.name, COUNT(DISTINCT p.id_product) nbr, m.id_manufacturer ';
                            $sqlQuery['from'] = '
                                            FROM `' . _DB_PREFIX_ . 'category_product` cp
                                            INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
                                            INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1)
                                            INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer) ';
                            $sqlQuery['where'] = '
                                            WHERE  p.condition="used" ';
                            $sqlQuery['group'] = ' GROUP BY p.id_manufacturer  order by m.name asc ';
                        } else {
                            $sqlQuery['select'] = 'SELECT m.name, COUNT(DISTINCT p.id_product) nbr, m.id_manufacturer ';
                            $sqlQuery['from'] = '
                                            FROM `' . _DB_PREFIX_ . 'category_product` cp
                                            INNER JOIN  `' . _DB_PREFIX_ . 'category` c ON (c.id_category = cp.id_category)
                                            INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1)
                                            INNER JOIN ' . _DB_PREFIX_ . 'manufacturer m ON (m.id_manufacturer = p.id_manufacturer) ';
                            $sqlQuery['where'] = '
                                            WHERE c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright . ' ';
                            $sqlQuery['group'] = ' GROUP BY p.id_manufacturer  order by m.name asc ';
                        }
                    }
                    break;
                case 'id_attribute_group':
                    // attribute group
                    if ($whereLikeFilter != '') {
                        $sqlQuery['select'] = '
					SELECT COUNT(DISTINCT p.id_product) nbr, lpa.id_attribute_group,
					a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
					liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title';
                        $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa
					INNER JOIN ' . _DB_PREFIX_ . 'attribute a
					ON a.id_attribute = lpa.id_attribute
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
					ON al.id_attribute = a.id_attribute
					AND al.id_lang = ' . (int) $cookie->id_lang . '
					INNER JOIN ' . _DB_PREFIX_ . 'product as p
					ON p.id_product = lpa.id_product
					AND p.active = 1
                                        LEFT JOIN ps_product_lang pl ON (pl.id_product = p.id_product)
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
					ON ag.id_attribute_group = lpa.id_attribute_group
					INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
					ON agl.id_attribute_group = lpa.id_attribute_group
					AND agl.id_lang = ' . (int) $cookie->id_lang . '
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
					ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
					ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $cookie->id_lang . ') ';
                        $sqlQuery['where'] = 'WHERE a.id_attribute_group = ' . (int) $filter['id_value'] . '
					AND (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
)  AND p.id_product IN (
					SELECT id_product
					FROM ' . _DB_PREFIX_ . 'category_product cp
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category)) ';
                        $sqlQuery['group'] = '
					GROUP BY lpa.id_attribute
					ORDER BY id_attribute_group, id_attribute ';
                    } else {
                        if ($usado == true) {
                            $sqlQuery['select'] = '
                                            SELECT COUNT(DISTINCT p.id_product) nbr, lpa.id_attribute_group,
                                            a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
                                            liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute a
                                            ON a.id_attribute = lpa.id_attribute
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
                                            ON al.id_attribute = a.id_attribute
                                            AND al.id_lang = ' . (int) $cookie->id_lang . '
                                            INNER JOIN ' . _DB_PREFIX_ . 'product as p
                                            ON p.id_product = lpa.id_product
                                            AND p.active = 1
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
                                            ON ag.id_attribute_group = lpa.id_attribute_group
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
                                            ON agl.id_attribute_group = lpa.id_attribute_group
                                            AND agl.id_lang = ' . (int) $cookie->id_lang . '
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
                                            ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
                                            ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $cookie->id_lang . ') ';
                            $sqlQuery['where'] = 'WHERE a.id_attribute_group = ' . (int) $filter['id_value'] . ' and p.condition="used" 
                                            AND p.id_product IN (
                                            SELECT id_product
                                            FROM ' . _DB_PREFIX_ . 'category_product cp
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category )) ';
                            $sqlQuery['group'] = '
                                            GROUP BY lpa.id_attribute
                                            ORDER BY id_attribute_group, id_attribute ';
                        } else {
                            $sqlQuery['select'] = '
                                            SELECT COUNT(DISTINCT p.id_product) nbr, lpa.id_attribute_group,
                                            a.color, al.name attribute_name, agl.public_name attribute_group_name , lpa.id_attribute, ag.is_color_group,
                                            liagl.url_name name_url_name, liagl.meta_title name_meta_title, lial.url_name value_url_name, lial.meta_title value_meta_title';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'layered_product_attribute lpa
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute a
                                            ON a.id_attribute = lpa.id_attribute
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_lang al
                                            ON al.id_attribute = a.id_attribute
                                            AND al.id_lang = ' . (int) $cookie->id_lang . '
                                            INNER JOIN ' . _DB_PREFIX_ . 'product as p
                                            ON p.id_product = lpa.id_product
                                            AND p.active = 1
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_group ag
                                            ON ag.id_attribute_group = lpa.id_attribute_group
                                            INNER JOIN ' . _DB_PREFIX_ . 'attribute_group_lang agl
                                            ON agl.id_attribute_group = lpa.id_attribute_group
                                            AND agl.id_lang = ' . (int) $cookie->id_lang . '
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_group_lang_value liagl
                                            ON (liagl.id_attribute_group = lpa.id_attribute_group AND liagl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_attribute_lang_value lial
                                            ON (lial.id_attribute = lpa.id_attribute AND lial.id_lang = ' . (int) $cookie->id_lang . ') ';
                            $sqlQuery['where'] = 'WHERE a.id_attribute_group = ' . (int) $filter['id_value'] . '
                                            AND p.id_product IN (
                                            SELECT id_product
                                            FROM ' . _DB_PREFIX_ . 'category_product cp
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright . ')) ';
                            $sqlQuery['group'] = '
                                            GROUP BY lpa.id_attribute
                                            ORDER BY id_attribute_group, id_attribute ';
                        }
                    }
                    break;
                case 'id_feature':
                    if ($whereLikeFilter != '') {
                        $sqlQuery['select'] = 'SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
					COUNT(DISTINCT p.id_product) nbr,
					lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title ';
                        $sqlQuery['from'] = '
					FROM ' . _DB_PREFIX_ . 'feature_product fp
					INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product AND p.active = 1)
                                        LEFT JOIN ps_product_lang pl ON (pl.id_product = p.id_product) 
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $cookie->id_lang . ')
					INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
					LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
					ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . (int) $cookie->id_lang . ')
					LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
					ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . (int) $cookie->id_lang . ') ';
                        $sqlQuery['where'] = 'WHERE p.`active` = 1 AND fp.id_feature = ' . (int) $filter['id_value'] . '
					AND (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
)  AND p.id_product IN (
					SELECT id_product
					FROM ' . _DB_PREFIX_ . 'category_product cp
					INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category)) ';
                        $sqlQuery['group'] = 'GROUP BY fv.id_feature_value order by CAST(fvl.value as UNSIGNED) asc,fvl.value asc';
                    } else {
                        if ($usado == true) {
                            $sqlQuery['select'] = 'SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
                                            COUNT(DISTINCT p.id_product) nbr,
                                            lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title ';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'feature_product fp
                                            INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product AND p.active = 1)
                                            LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $cookie->id_lang . ')
                                            INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
                                            LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
                                            ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
                                            ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . (int) $cookie->id_lang . ') ';
                            $sqlQuery['where'] = 'WHERE p.`active` = 1 AND fp.id_feature = ' . (int) $filter['id_value'] . ' and p.condition="used" 
                                            AND p.id_product IN (
                                            SELECT id_product
                                            FROM ' . _DB_PREFIX_ . 'category_product cp
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category )) ';
                            $sqlQuery['group'] = 'GROUP BY fv.id_feature_value order by CAST(fvl.value as UNSIGNED) asc,fvl.value asc';
                        } else {
                            $sqlQuery['select'] = 'SELECT fl.name feature_name, fp.id_feature, fv.id_feature_value, fvl.value,
                                            COUNT(DISTINCT p.id_product) nbr,
                                            lifl.url_name name_url_name, lifl.meta_title name_meta_title, lifvl.url_name value_url_name, lifvl.meta_title value_meta_title ';
                            $sqlQuery['from'] = '
                                            FROM ' . _DB_PREFIX_ . 'feature_product fp
                                            INNER JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = fp.id_product AND p.active = 1)
                                            LEFT JOIN ' . _DB_PREFIX_ . 'feature_lang fl ON (fl.id_feature = fp.id_feature AND fl.id_lang = ' . (int) $cookie->id_lang . ')
                                            INNER JOIN ' . _DB_PREFIX_ . 'feature_value fv ON (fv.id_feature_value = fp.id_feature_value AND (fv.custom IS NULL OR fv.custom = 0))
                                            LEFT JOIN ' . _DB_PREFIX_ . 'feature_value_lang fvl ON (fvl.id_feature_value = fp.id_feature_value AND fvl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_lang_value lifl
                                            ON (lifl.id_feature = fp.id_feature AND lifl.id_lang = ' . (int) $cookie->id_lang . ')
                                            LEFT JOIN ' . _DB_PREFIX_ . 'layered_indexable_feature_value_lang_value lifvl
                                            ON (lifvl.id_feature_value = fp.id_feature_value AND lifvl.id_lang = ' . (int) $cookie->id_lang . ') ';
                            $sqlQuery['where'] = 'WHERE p.`active` = 1 AND fp.id_feature = ' . (int) $filter['id_value'] . '
                                            AND p.id_product IN (
                                            SELECT id_product
                                            FROM ' . _DB_PREFIX_ . 'category_product cp
                                            INNER JOIN ' . _DB_PREFIX_ . 'category c ON (c.id_category = cp.id_category AND c.nleft >= ' . (int) $parent->nleft . ' AND c.nright <= ' . (int) $parent->nright . ')) ';
                            $sqlQuery['group'] = 'GROUP BY fv.id_feature_value order by CAST(fvl.value as UNSIGNED) asc,fvl.value asc';
                        }
                    }
                    break;
                case 'category':
                    //$level_depth
                    if ($whereLikeFilter != '') {
                        $sqlQuery['select'] = ' SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                        $sqlQuery['from'] = 'FROM ' . _DB_PREFIX_ . 'category_product cp
					LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) 
                                        LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product)
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category
';
                        $sqlQuery['where'] = ' WHERE cp.id_category = c.id_category and (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
)  ';
                        $sqlQuery['group'] = ') count_products
					FROM ' . _DB_PREFIX_ . 'category c
					LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . (int) $cookie->id_lang . ')
					WHERE (SELECT count(DISTINCT p.id_product) cont FROM ' . _DB_PREFIX_ . 'category_product cp 
                                            LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) 
                                            LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product) 
                                            WHERE cp.id_category = c.id_category and (
(
' . $descrypt_reg . '
) 
OR 
(p.id_product ="' . $whereLikeFilter . '" OR p.reference = "' . $whereLikeFilter . '") 
OR
(cl.name REGEXP "[[:<:]]' . $whereLikeFilter . '[[:>:]]")
)   )>=1
					GROUP BY cl.name ORDER BY count_products desc,level_depth, c.position';
                    } else {
                        if ($usado == true) {
                            $sqlQuery['select'] = ' SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                            $sqlQuery['from'] = 'FROM ' . _DB_PREFIX_ . 'category_product cp
					LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) 
                                        LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product)
                                        LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON p.`id_category_default` = cl.id_category
';
                            $sqlQuery['where'] = ' WHERE cp.id_category = c.id_category and (p.condition="used")   ';
                            $sqlQuery['group'] = ') count_products
					FROM ' . _DB_PREFIX_ . 'category c
					LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . (int) $cookie->id_lang . ')
					WHERE (SELECT count(DISTINCT p.id_product) cont FROM ' . _DB_PREFIX_ . 'category_product cp 
                                            LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) 
                                            LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = p.id_product) 
                                            WHERE cp.id_category = c.id_category and p.condition="used"    )>=1
					GROUP BY cl.name ORDER BY level_depth, c.position';
                        } else {
                            if ($level_depth < 3 and count($catg3do) > 0) {
                                $sqlQuery['select'] = '
                                                SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                                $sqlQuery['from'] = '
                                                FROM ' . _DB_PREFIX_ . 'category_product cp
                                                LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) ';
                                $sqlQuery['where'] = '
                                                WHERE cp.id_category = c.id_category ';
                                $sqlQuery['group'] = ') count_products
                                                FROM ' . _DB_PREFIX_ . 'category c
                                                LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . (int) $cookie->id_lang . ')
                                                WHERE   (c.id_category in (' . implode(",", $catg3do) . ') or c.id_parent=' . $id_parent . ' )
                                                GROUP BY c.id_category HAVING count_products>0 ORDER BY c.id_parent,cl.name,c.id_category,level_depth, c.position';
                            } else {
                                $sqlQuery['select'] = '
                                                SELECT c.id_category, c.id_parent, cl.name, (SELECT count(DISTINCT p.id_product) # ';
                                $sqlQuery['from'] = '
                                                FROM ' . _DB_PREFIX_ . 'category_product cp
                                                LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = cp.id_product AND p.active = 1) ';
                                $sqlQuery['where'] = '
                                                WHERE cp.id_category = c.id_category ';
                                $sqlQuery['group'] = ') count_products
                                                FROM ' . _DB_PREFIX_ . 'category c
                                                LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = c.id_category AND cl.id_lang = ' . (int) $cookie->id_lang . ')
                                                WHERE c.id_parent = ' . (int) $id_parent . ' 
                                                GROUP BY c.id_category ORDER BY level_depth, c.position';
                            }
                        }
                    }
            }
            foreach ($filters as $filterTmp) {
                $methodName = 'get' . ucfirst($filterTmp['type']) . 'FilterSubQuery';
                if (method_exists('BlockLayered', $methodName) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filterTmp['type'] || $filter['type'] == $filterTmp['type'])) {
                    if ($filter['type'] == $filterTmp['type'] && $filter['id_value'] == $filterTmp['id_value']) {
                        $subQueryFilter = self::$methodName(array(), true);
                    } else {
                        if (!is_null($filterTmp['id_value'])) {
                            $selected_filters_cleaned = $this->cleanFilterByIdValue(@$selectedFilters[$filterTmp['type']], $filterTmp['id_value']);
                        } else {
                            $selected_filters_cleaned = @$selectedFilters[$filterTmp['type']];
                        }
                        $subQueryFilter = self::$methodName($selected_filters_cleaned, $filter['type'] == $filterTmp['type']);
                    }
                    if ($filter['type'] != "category") {
                        foreach ($subQueryFilter as $key => $value) {
                            $sqlQuery[$key] .= $value;
                        }
                    }
                }
            }
            $products = false;
            if (!empty($sqlQuery['from'])) {
                $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sqlQuery['select'] . "\n" . $sqlQuery['from'] . "\n" . $sqlQuery['join'] . "\n" . $sqlQuery['where'] . "\n" . $sqlQuery['group']);
            }
            foreach ($filters as $filterTmp) {
                $methodName = 'filterProductsBy' . ucfirst($filterTmp['type']);
                if (method_exists('BlockLayered', $methodName) && (!in_array($filter['type'], array('price', 'weight')) && $filter['type'] != $filterTmp['type'] || $filter['type'] == $filterTmp['type'])) {
                    if ($filter['type'] == $filterTmp['type']) {
                        $products = self::$methodName(array(), $products);
                    } else {
                        $products = self::$methodName(@$selectedFilters[$filterTmp['type']], $products);
                    }
                }
            }
            switch ($filter['type']) {
                case 'price':
                    $priceArray = array('type_lite' => 'price', 'type' => 'price', 'id_key' => 0, 'name' => $this->l('Price'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => Currency::getCurrent()->sign);
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($priceArray['min'])) {
                                $priceArray['min'] = $product['price_min'];
                                $priceArray['values'][0] = $product['price_min'];
                            } else {
                                if ($priceArray['min'] > $product['price_min']) {
                                    $priceArray['min'] = $product['price_min'];
                                    $priceArray['values'][0] = $product['price_min'];
                                }
                            }
                            if ($priceArray['max'] < $product['price_max']) {
                                $priceArray['max'] = $product['price_max'];
                                $priceArray['values'][1] = $product['price_max'];
                            }
                        }
                    }
                    if ($priceArray['max'] != $priceArray['min'] && $priceArray['min'] != null) {
                        if (isset($selectedFilters['price']) && isset($selectedFilters['price'][0]) && isset($selectedFilters['price'][1])) {
                            $priceArray['values'][0] = $selectedFilters['price'][0];
                            $priceArray['values'][1] = $selectedFilters['price'][1];
                        }
                        $filterBlocks[] = $priceArray;
                    }
                    break;
                case 'weight':
                    $weightArray = array('type_lite' => 'weight', 'type' => 'weight', 'id_key' => 0, 'name' => $this->l('Weight'), 'slider' => true, 'max' => '0', 'min' => null, 'values' => array('1' => 0), 'unit' => Configuration::get('PS_WEIGHT_UNIT'));
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (is_null($weightArray['min'])) {
                                $weightArray['min'] = $product['weight'];
                                $weightArray['values'][0] = $product['weight'];
                            } else {
                                if ($weightArray['min'] > $product['weight']) {
                                    $weightArray['min'] = $product['weight'];
                                    $weightArray['values'][0] = $product['weight'];
                                }
                            }
                            if ($weightArray['max'] < $product['weight']) {
                                $weightArray['max'] = $product['weight'];
                                $weightArray['values'][1] = $product['weight'];
                            }
                        }
                    }
                    if ($weightArray['max'] != $weightArray['min'] && $weightArray['min'] != null) {
                        if (isset($selectedFilters['weight']) && isset($selectedFilters['weight'][0]) && isset($selectedFilters['weight'][1])) {
                            $weightArray['values'][0] = $selectedFilters['weight'][0];
                            $weightArray['values'][1] = $selectedFilters['weight'][1];
                        }
                        $filterBlocks[] = $weightArray;
                    }
                    break;
                case 'condition':
                    $conditionArray = array('new' => array('name' => $this->l('New'), 'nbr' => 0), 'used' => array('name' => $this->l('Used'), 'nbr' => 0), 'refurbished' => array('name' => $this->l('Refurbished'), 'nbr' => 0));
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($selectedFilters['condition']) && in_array($product['condition'], $selectedFilters['condition'])) {
                                $conditionArray[$product['condition']]['checked'] = true;
                            }
                        }
                    }
                    foreach ($conditionArray as $key => $condition) {
                        if (isset($selectedFilters['condition']) && in_array($key, $selectedFilters['condition'])) {
                            $conditionArray[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            if (isset($conditionArray[$product['condition']])) {
                                $conditionArray[$product['condition']]['nbr']++;
                            }
                        }
                    }
                    $filterBlocks[] = array('type_lite' => 'condition', 'type' => 'condition', 'id_key' => 0, 'name' => $this->l('Condition'), 'values' => $conditionArray);
                    break;
                case 'quantity':
                    $quantityArray = array(0 => array('name' => $this->l('Not available'), 'nbr' => 0), 1 => array('name' => $this->l('In stock'), 'nbr' => 0));
                    foreach ($quantityArray as $key => $quantity) {
                        if (isset($selectedFilters['quantity']) && in_array($key, $selectedFilters['quantity'])) {
                            $quantityArray[$key]['checked'] = true;
                        }
                    }
                    if (isset($products) && $products) {
                        foreach ($products as $product) {
                            $quantityArray[(int) ($product['quantity'] > 0)]['nbr']++;
                        }
                    }
                    $filterBlocks[] = array('type_lite' => 'quantity', 'type' => 'quantity', 'id_key' => 0, 'name' => $this->l('Availability'), 'values' => $quantityArray);
                    break;
                case 'manufacturer':
                    if (isset($products) && $products) {
                        $manufaturersArray = array();
                        foreach ($products as $manufacturer) {
                            $manufaturersArray[$manufacturer['id_manufacturer']] = array('name' => $manufacturer['name'], 'nbr' => $manufacturer['nbr']);
                            if (isset($selectedFilters['manufacturer']) && in_array((int) $manufacturer['id_manufacturer'], $selectedFilters['manufacturer'])) {
                                $manufaturersArray[$manufacturer['id_manufacturer']]['checked'] = true;
                            }
                        }
                        $filterBlocks[] = array('type_lite' => 'manufacturer', 'type' => 'manufacturer', 'id_key' => 0, 'name' => $this->l('Manufacturer'), 'values' => $manufaturersArray);
                    }
                    break;
                case 'id_attribute_group':
                    $attributesArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $attributes) {
                            if (!isset($attributesArray[$attributes['id_attribute_group']])) {
                                $attributesArray[$attributes['id_attribute_group']] = array('type_lite' => 'id_attribute_group', 'type' => 'id_attribute_group', 'id_key' => (int) $attributes['id_attribute_group'], 'name' => $attributes['attribute_group_name'], 'is_color_group' => (bool) $attributes['is_color_group'], 'values' => array(), 'url_name' => $attributes['name_url_name'], 'meta_title' => $attributes['name_meta_title']);
                            }
                            $attributesArray[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']] = array('color' => $attributes['color'], 'name' => $attributes['attribute_name'], 'nbr' => (int) $attributes['nbr'], 'url_name' => $attributes['value_url_name'], 'meta_title' => $attributes['value_meta_title']);
                            if (isset($selectedFilters['id_attribute_group'][$attributes['id_attribute']])) {
                                $attributesArray[$attributes['id_attribute_group']]['values'][$attributes['id_attribute']]['checked'] = true;
                            }
                        }
                        $filterBlocks = array_merge($filterBlocks, $attributesArray);
                    }
                    break;
                case 'id_feature':
                    $featureArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $feature) {
                            if (!isset($featureArray[$feature['id_feature']])) {
                                $featureArray[$feature['id_feature']] = array('type_lite' => 'id_feature', 'type' => 'id_feature', 'id_key' => (int) $feature['id_feature'], 'values' => array(), 'name' => $feature['feature_name'], 'url_name' => $feature['name_url_name'], 'meta_title' => $feature['name_meta_title']);
                            }
                            $featureArray[$feature['id_feature']]['values'][$feature['id_feature_value']] = array('nbr' => (int) $feature['nbr'], 'name' => $feature['value'], 'url_name' => $feature['value_url_name'], 'meta_title' => $feature['value_meta_title']);
                            if (isset($selectedFilters['id_feature'][$feature['id_feature_value']])) {
                                $featureArray[$feature['id_feature']]['values'][$feature['id_feature_value']]['checked'] = true;
                            }
                        }
                        $filterBlocks = array_merge($filterBlocks, $featureArray);
                    }
                    break;
                case 'category':
                    $tmpArray = array();
                    if (isset($products) && $products) {
                        foreach ($products as $category) {
                            //mbj
                            $tmpArray[$category['id_category']] = array('name' => $category['name'], 'nbr' => (int) $category['count_products']);
                            if (isset($selectedFilters['category']) && in_array($category['id_category'], $selectedFilters['category'])) {
                                $tmpArray[$category['id_category']]['checked'] = true;
                            }
                        }
                        $filterBlocks[] = array('type_lite' => 'category', 'type' => 'category', 'id_key' => 0, 'name' => $this->l('Categories'), 'values' => $tmpArray);
                    }
                    break;
            }
        }
        // All non indexable attribute and feature
        $nonIndexable = array();
        // Get all non indexable attribute groups
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT public_name
		FROM `' . _DB_PREFIX_ . 'attribute_group_lang` agl
		LEFT JOIN `' . _DB_PREFIX_ . 'layered_indexable_attribute_group` liag
		ON liag.id_attribute_group = agl.id_attribute_group
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . (int) $cookie->id_lang) as $attribute) {
            $nonIndexable[] = Tools::link_rewrite($attribute['public_name']);
        }
        // Get all non indexable features
        foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT name
		FROM `' . _DB_PREFIX_ . 'feature_lang` fl
		LEFT JOIN  `' . _DB_PREFIX_ . 'layered_indexable_feature` lif
		ON lif.id_feature = fl.id_feature
		WHERE indexable IS NULL OR indexable = 0
		AND id_lang = ' . (int) $cookie->id_lang) as $attribute) {
            $nonIndexable[] = Tools::link_rewrite($attribute['name']);
        }
        //generate SEO link
        $paramSelected = '';
        $optionCheckedArray = array();
        $paramGroupSelectedArray = array();
        $titleValues = array();
        $link = new Link();
        $linkBase = $link->getCategoryLink($id_parent, Category::getLinkRewrite($id_parent, (int) $cookie->id_lang), (int) $cookie->id_lang);
        $filterBlockList = array();
        //get filters checked by group
        foreach ($filterBlocks as $typeFilter) {
            $filterName = !empty($typeFilter['url_name']) ? $typeFilter['url_name'] : $typeFilter['name'];
            $paramGroupSelected = '';
            foreach ($typeFilter['values'] as $key => $value) {
                if (is_array($value) && array_key_exists('checked', $value)) {
                    $valueName = !empty($value['url_name']) ? $value['url_name'] : $value['name'];
                    $paramGroupSelected .= '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                    $paramGroupSelectedArray[Tools::link_rewrite($filterName)][] = Tools::link_rewrite($valueName);
                    if (!isset($titleValues[$filterName])) {
                        $titleValues[$filterName] = array();
                    }
                    $titleValues[$filterName][] = $valueName;
                } else {
                    $paramGroupSelectedArray[Tools::link_rewrite($filterName)][] = array();
                }
            }
            if (!empty($paramGroupSelected)) {
                $paramSelected .= '/' . str_replace('-', '_', Tools::link_rewrite($filterName)) . $paramGroupSelected;
                $optionCheckedArray[Tools::link_rewrite($filterName)] = $paramGroupSelected;
            }
        }
        $blackList = array('weight', 'price');
        $nofollow = false;
        foreach ($filterBlocks as &$typeFilter) {
            $filterName = !empty($typeFilter['url_name']) ? $typeFilter['url_name'] : $typeFilter['name'];
            if (count($typeFilter) > 0 && !in_array($typeFilter['type'], $blackList)) {
                foreach ($typeFilter['values'] as $key => $values) {
                    $nofollow = false;
                    $optionCheckedCloneArray = $optionCheckedArray;
                    //if not filters checked, add parameter
                    $valueName = !empty($values['url_name']) ? $values['url_name'] : $values['name'];
                    if (!in_array(Tools::link_rewrite($valueName), $paramGroupSelectedArray[Tools::link_rewrite($filterName)])) {
                        //update parameter filter checked before
                        if (array_key_exists(Tools::link_rewrite($filterName), $optionCheckedArray)) {
                            $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = $optionCheckedCloneArray[Tools::link_rewrite($filterName)] . '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                            $nofollow = true;
                        } else {
                            $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = '-' . str_replace('-', '_', Tools::link_rewrite($valueName));
                        }
                    } else {
                        // Remove selected parameters
                        $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = str_replace('-' . str_replace('-', '_', Tools::link_rewrite($valueName)), '', $optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
                        if (empty($optionCheckedCloneArray[Tools::link_rewrite($filterName)])) {
                            unset($optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
                        }
                    }
                    $parameters = '';
                    foreach ($optionCheckedCloneArray as $keyGroup => $valueGroup) {
                        $parameters .= '/' . str_replace('-', '_', $keyGroup) . $valueGroup;
                    }
                    // Check if there is an non indexable attribute or feature in the url
                    foreach ($nonIndexable as $value) {
                        if (strpos($parameters, '/' . $value) !== false) {
                            $nofollow = true;
                        }
                    }
                    //write link by mode rewriting
                    if (!Configuration::get('PS_REWRITING_SETTINGS')) {
                        $typeFilter['values'][$key]['link'] = $linkBase . '&selected_filters=' . $parameters;
                    } else {
                        $typeFilter['values'][$key]['link'] = $linkBase . $parameters;
                    }
                    $typeFilter['values'][$key]['rel'] = $nofollow ? 'nofollow' : '';
                }
            }
        }
        $nFilters = 0;
        if (isset($selectedFilters['price'])) {
            if ($priceArray['min'] == $selectedFilters['price'][0] && $priceArray['max'] == $selectedFilters['price'][1]) {
                unset($selectedFilters['price']);
            }
        }
        if (isset($selectedFilters['weight'])) {
            if ($weightArray['min'] == $selectedFilters['weight'][0] && $weightArray['max'] == $selectedFilters['weight'][1]) {
                unset($selectedFilters['weight']);
            }
        }
        foreach ($selectedFilters as $filters) {
            $nFilters += count($filters);
        }
        $cache = array('layered_show_qties' => (int) Configuration::get('PS_LAYERED_SHOW_QTIES'), 'id_category_layered' => (int) $id_parent, 'level_depth' => $level_depth, 'catg3do' => $catg3do_dat, 'selected_filters' => $selectedFilters, 'n_filters' => (int) $nFilters, 'nbr_filterBlocks' => count($filterBlocks), 'filters' => $filterBlocks, 'title_values' => $titleValues, 'current_friendly_url' => htmlentities($paramSelected), 'nofollow' => !empty($paramSelected) || $nofollow);
        return $cache;
    }
    public function renderView()
    {
        /** @var Customer $customer */
        if (!($customer = $this->loadObject())) {
            return;
        }
        $this->context->customer = $customer;
        $gender = new Gender($customer->id_gender, $this->context->language->id);
        $gender_image = $gender->getImage();
        $customer_stats = $customer->getStats();
        $sql = 'SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = %d AND valid = 1';
        if ($total_customer = Db::getInstance()->getValue(sprintf($sql, $customer->id))) {
            $sql = 'SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 AND id_customer != ' . (int) $customer->id . ' GROUP BY id_customer HAVING SUM(total_paid_real) > %d';
            Db::getInstance()->getValue(sprintf($sql, (int) $total_customer));
            $count_better_customers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $count_better_customers = '-';
        }
        $orders = Order::getCustomerOrders($customer->id, true);
        $total_orders = count($orders);
        for ($i = 0; $i < $total_orders; $i++) {
            $orders[$i]['total_paid_real_not_formated'] = $orders[$i]['total_paid_real'];
            $orders[$i]['total_paid_real'] = Tools::displayPrice($orders[$i]['total_paid_real'], new Currency((int) $orders[$i]['id_currency']));
        }
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $total_messages = count($messages);
        for ($i = 0; $i < $total_messages; $i++) {
            $messages[$i]['message'] = substr(strip_tags(html_entity_decode($messages[$i]['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75);
            $messages[$i]['date_add'] = Tools::displayDate($messages[$i]['date_add'], null, true);
            if (isset(self::$meaning_status[$messages[$i]['status']])) {
                $messages[$i]['status'] = self::$meaning_status[$messages[$i]['status']];
            }
        }
        $groups = $customer->getGroups();
        $total_groups = count($groups);
        for ($i = 0; $i < $total_groups; $i++) {
            $group = new Group($groups[$i]);
            $groups[$i] = array();
            $groups[$i]['id_group'] = $group->id;
            $groups[$i]['name'] = $group->name[$this->default_form_language];
        }
        $total_ok = 0;
        $orders_ok = array();
        $orders_ko = array();
        foreach ($orders as $order) {
            if (!isset($order['order_state'])) {
                $order['order_state'] = $this->l('There is no status defined for this order.');
            }
            if ($order['valid']) {
                $orders_ok[] = $order;
                $total_ok += $order['total_paid_real_not_formated'];
            } else {
                $orders_ko[] = $order;
            }
        }
        $products = $customer->getBoughtProducts();
        $carts = Cart::getCustomerCarts($customer->id);
        $total_carts = count($carts);
        for ($i = 0; $i < $total_carts; $i++) {
            $cart = new Cart((int) $carts[$i]['id_cart']);
            $this->context->cart = $cart;
            $summary = $cart->getSummaryDetails();
            $currency = new Currency((int) $carts[$i]['id_currency']);
            $carrier = new Carrier((int) $carts[$i]['id_carrier']);
            $carts[$i]['id_cart'] = sprintf('%06d', $carts[$i]['id_cart']);
            $carts[$i]['date_add'] = Tools::displayDate($carts[$i]['date_add'], null, true);
            $carts[$i]['total_price'] = Tools::displayPrice($summary['total_price'], $currency);
            $carts[$i]['name'] = $carrier->name;
        }
        $sql = 'SELECT DISTINCT cp.id_product, c.id_cart, c.id_shop, cp.id_shop AS cp_id_shop
				FROM ' . _DB_PREFIX_ . 'cart_product cp
				JOIN ' . _DB_PREFIX_ . 'cart c ON (c.id_cart = cp.id_cart)
				JOIN ' . _DB_PREFIX_ . 'product p ON (cp.id_product = p.id_product)
				WHERE c.id_customer = ' . (int) $customer->id . '
					AND NOT EXISTS (
							SELECT 1
							FROM ' . _DB_PREFIX_ . 'orders o
							JOIN ' . _DB_PREFIX_ . 'order_detail od ON (o.id_order = od.id_order)
							WHERE product_id = cp.id_product AND o.valid = 1 AND o.id_customer = ' . (int) $customer->id . '
						)';
        $interested = Db::getInstance()->executeS($sql);
        $total_interested = count($interested);
        for ($i = 0; $i < $total_interested; $i++) {
            $product = new Product($interested[$i]['id_product'], false, $this->default_form_language, $interested[$i]['id_shop']);
            if (!Validate::isLoadedObject($product)) {
                continue;
            }
            $interested[$i]['url'] = $this->context->link->getProductLink($product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, $this->default_form_language), null, null, $interested[$i]['cp_id_shop']);
            $interested[$i]['id'] = (int) $product->id;
            $interested[$i]['name'] = Tools::htmlentitiesUTF8($product->name);
        }
        $emails = $customer->getLastEmails();
        $connections = $customer->getLastConnections();
        if (!is_array($connections)) {
            $connections = array();
        }
        $total_connections = count($connections);
        for ($i = 0; $i < $total_connections; $i++) {
            $connections[$i]['http_referer'] = $connections[$i]['http_referer'] ? preg_replace('/^www./', '', parse_url($connections[$i]['http_referer'], PHP_URL_HOST)) : $this->l('Direct link');
        }
        $referrers = Referrer::getReferrers($customer->id);
        $total_referrers = count($referrers);
        for ($i = 0; $i < $total_referrers; $i++) {
            $referrers[$i]['date_add'] = Tools::displayDate($referrers[$i]['date_add'], null, true);
        }
        $customerLanguage = new Language($customer->id_lang);
        $shop = new Shop($customer->id_shop);
        $this->tpl_view_vars = array('customer' => $customer, 'gender' => $gender, 'gender_image' => $gender_image, 'registration_date' => Tools::displayDate($customer->date_add, null, true), 'customer_stats' => $customer_stats, 'last_visit' => Tools::displayDate($customer_stats['last_visit'], null, true), 'count_better_customers' => $count_better_customers, 'shop_is_feature_active' => Shop::isFeatureActive(), 'name_shop' => $shop->name, 'customer_birthday' => Tools::displayDate($customer->birthday), 'last_update' => Tools::displayDate($customer->date_upd, null, true), 'customer_exists' => Customer::customerExists($customer->email), 'id_lang' => $customer->id_lang, 'customerLanguage' => $customerLanguage, 'customer_note' => Tools::htmlentitiesUTF8($customer->note), 'messages' => $messages, 'groups' => $groups, 'orders' => $orders, 'orders_ok' => $orders_ok, 'orders_ko' => $orders_ko, 'total_ok' => Tools::displayPrice($total_ok, $this->context->currency->id), 'products' => $products, 'addresses' => $customer->getAddresses($this->default_form_language), 'discounts' => CartRule::getCustomerCartRules($this->default_form_language, $customer->id, false, false), 'carts' => $carts, 'interested' => $interested, 'emails' => $emails, 'connections' => $connections, 'referrers' => $referrers, 'show_toolbar' => true);
        return parent::renderView();
    }
Example #19
0
 public static function getProductLink($product, $id_shop = null, $context = false, $id_lang = false)
 {
     if (!$context) {
         $context = Context::getContext();
     }
     $dispatcher = Dispatcher::getInstance();
     if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && $id_shop !== null) {
         $shop = new Shop($id_shop);
     } else {
         $shop = $context->shop;
     }
     $force_routes = (bool) Configuration::get('PS_REWRITING_SETTINGS');
     $base = 'http://' . $shop->domain . $shop->getBaseURI();
     if (!$force_routes && in_array($id_shop, array($context->shop->id, null)) || !Language::isMultiLanguageActivated($id_shop) || !(int) Configuration::get('PS_REWRITING_SETTINGS', null, null, $id_shop)) {
         $base .= '';
     } else {
         $base .= self::$_exportLanguageObj->iso_code . '/';
     }
     //$base.= self::$_exportLanguageObj->iso_code . '/';
     $params = array();
     $params['id'] = $product['id_product'];
     $params['rewrite'] = $product['link_rewrite'];
     $params['ean13'] = $product['ean13'];
     $params['category'] = Category::getLinkRewrite((int) $product['id_category_default'], (int) $id_lang);
     //Tools::str2url($product['categories'][$product['id_category_default']]);
     return $base . $dispatcher->createUrl('product_rule', self::$_exportLanguageObj->id, $params, $force_routes, '', $id_shop);
 }
Example #20
0
			<url><?php 
echo _PS_BASE_URL_ . __PS_BASE_URI__ . 'img/logo.jpg';
?>
</url>
			<link><?php 
echo _PS_BASE_URL_ . __PS_BASE_URI__;
?>
</link>
		</image>
<?php 
foreach ($products as $product) {
    $image = Image::getImages((int) $cookie->id_lang, $product['id_product']);
    echo "\t\t<item>\n";
    echo "\t\t\t<title><![CDATA[" . $product['name'] . " - " . html_entity_decode(Tools::displayPrice(Product::getPriceStatic($product['id_product']), $currency), ENT_COMPAT, 'UTF-8') . " ]]></title>\n";
    echo "\t\t\t<description>";
    $cdata = true;
    if (is_array($image) and sizeof($image)) {
        $imageObj = new Image($image[0]['id_image']);
        echo "<![CDATA[<img src='" . $link->getImageLink($product['link_rewrite'], $image[0]['id_image'], 'small_default') . "' title='" . str_replace('&', '', $product['name']) . "' alt='thumb' />";
        $cdata = false;
    }
    if ($cdata) {
        echo "<![CDATA[";
    }
    echo $product['description_short'] . "]]></description>\n";
    echo "\t\t\t<link><![CDATA[" . str_replace('&amp;', '&', htmlspecialchars($link->getproductLink($product['id_product'], $product['link_rewrite'], Category::getLinkRewrite((int) $product['id_category_default'], $cookie->id_lang)))) . $affiliate . "]]></link>\n";
    echo "\t\t</item>\n";
}
?>
	</channel>
</rss>
Example #21
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = Tax::excludeTaxeOption();
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax;
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     if (!preg_match("/^1.3.*/", _PS_VERSION_)) {
         // Not available in Prestashop 1.3.x
         $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices);
         $row['specific_prices'] = $specific_prices;
     }
     if ($row['id_product_attribute']) {
         $row['quantity_all_versions'] = $row['quantity'];
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] and !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     $sql_combination = '
   SELECT pa.id_product_attribute, pa.price, pa.quantity, pa.id_product
   FROM `' . _DB_PREFIX_ . 'product` p
   LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`)
   WHERE p.`id_product` =' . $row['id_product'];
     $result_combination = ProductExtended::getDbInstance()->ExecuteS($sql_combination);
     $row['combinations'] = array();
     if ($result_combination) {
         foreach ($result_combination as $combination) {
             $combination['attributes'] = array();
             /* New combinations system Prestashop 1.5.x */
             if (!preg_match("/^1.(3|4).*/", _PS_VERSION_)) {
                 $combination['quantity'] = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $combination['id_product_attribute']);
             }
             if (isset($combination['id_product_attribute'])) {
                 $sql_attribute = '
         SELECT pa.id_product_attribute, agl.id_attribute_group, al.name as name_value, agl.name as name_option
         FROM `' . _DB_PREFIX_ . 'product_attribute` pa
         LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`)
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute` = pac.`id_attribute`)
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute` = a.`id_attribute` AND al.`id_lang` = ' . $id_lang . ')
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`)
         LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group` = ag.`id_attribute_group` AND agl.`id_lang` = ' . $id_lang . ')
         WHERE pa.`id_product_attribute` =' . $combination['id_product_attribute'];
                 $result_attribute = ProductExtended::getDbInstance()->ExecuteS($sql_attribute);
                 if ($result_attribute) {
                     foreach ($result_attribute as $attribute) {
                         array_push($combination['attributes'], $attribute);
                     }
                 }
                 array_push($row['combinations'], $combination);
             }
         }
     }
     $sql_image = '
   SELECT DISTINCT i.*, pl.link_rewrite
   FROM `' . _DB_PREFIX_ . 'product` p
   LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (p.`id_product` = i.`id_product`)
   LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product`)
   WHERE p.`id_product` =' . $row['id_product'];
     $result_image = ProductExtended::getDbInstance()->ExecuteS($sql_image);
     $row['images'] = array();
     $lang = new Language($id_lang);
     $row['url_locale'] = $lang->iso_code;
     if ($result_image) {
         $link = preg_match("/^1.(3|4).*/", _PS_VERSION_) ? new Link() : Context::getContext()->link;
         foreach ($result_image as $image) {
             if (!preg_match("/^1.3.*/", _PS_VERSION_)) {
                 // Image URL gives relative version using 1.3.x-
                 $image['image_url'] = $link->getImageLink($image['link_rewrite'], $image['id_product'] . '-' . $image['id_image']);
             }
             array_push($row['images'], $image);
         }
     }
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
Example #22
0
 public function getPreviewUrl(Product $product)
 {
     $id_lang = Configuration::get('PS_LANG_DEFAULT', null, null, Context::getContext()->shop->id);
     if (!ShopUrl::getMainShopDomain()) {
         return false;
     }
     $is_rewrite_active = (bool) Configuration::get('PS_REWRITING_SETTINGS');
     $preview_url = $this->context->link->getProductLink($product, $this->getFieldValue($product, 'link_rewrite', $this->context->language->id), Category::getLinkRewrite($this->getFieldValue($product, 'id_category_default'), $this->context->language->id), null, $id_lang, (int) Context::getContext()->shop->id, 0, $is_rewrite_active);
     if (!$product->active) {
         $admin_dir = dirname($_SERVER['PHP_SELF']);
         $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1);
         $preview_url .= (strpos($preview_url, '?') === false ? '?' : '&') . 'adtoken=' . $this->token . '&ad=' . $admin_dir . '&id_employee=' . (int) $this->context->employee->id;
     }
     return $preview_url;
 }
Example #23
0
 public static function getProductProperties($id_lang, $row)
 {
     if (!$row['id_product']) {
         return false;
     }
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])) {
         $row['id_product_attribute'] = $ipa_default;
     }
     if (!isset($row['id_product_attribute'])) {
         $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = true;
     $tax = floatval(Tax::getApplicableTax(intval($row['id_tax']), floatval($row['rate'])));
     if (Tax::excludeTaxeOption() or !$tax) {
         $usetax = false;
     }
     $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . intval($usetax);
     if (array_key_exists($cacheKey, self::$producPropertiesCache)) {
         return self::$producPropertiesCache[$cacheKey];
     }
     // Datas
     $link = new Link();
     $row['category'] = Category::getLinkRewrite($row['id_category_default'], intval($id_lang));
     $row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? floatval(Product::getProductAttributePrice($row['id_product_attribute'])) : 0;
     $row['price_tax_exc'] = Product::getPriceStatic($row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6), 2);
     }
     $row['reduction'] = self::getReductionValue($row['reduction_price'], $row['reduction_percent'], $row['reduction_from'], $row['reduction_to'], $row['price'], $usetax, floatval($row['rate']));
     $row['price_without_reduction'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6, NULL, false, false);
     $row['quantity'] = Product::getQuantity($row['id_product']);
     $row['id_image'] = Product::defineProductImage($row);
     $row['features'] = Product::getFrontFeaturesStatic(intval($id_lang), $row['id_product']);
     $row['attachments'] = Product::getAttachmentsStatic(intval($id_lang), $row['id_product']);
     $row['pack'] = Pack::isPack($row['id_product']);
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     self::$producPropertiesCache[$cacheKey] = $row;
     return self::$producPropertiesCache[$cacheKey];
 }
 /**
  * Convert the entities data into an xml object and return the xml object as a string
  *
  * @param array $aEntity Entity data
  */
 public function formatEntityToXML($aEntity)
 {
     $sReturn = '';
     $dom = new DOMDocument('1.0', 'utf-8');
     $bUseRoutes = (bool) Configuration::get('PS_REWRITING_SETTINGS');
     $oDispatcher = Dispatcher::getInstance();
     // Force the dispatcher to use custom routes because the use of custom routes is disabled in the BO Context
     foreach ($oDispatcher->default_routes as $route_id => $route_data) {
         if ($custom_route = Configuration::get('PS_ROUTE_' . $route_id)) {
             foreach (Language::getLanguages() as $lang) {
                 $oDispatcher->addRoute($route_id, $custom_route, $route_data['controller'], $lang['id_lang'], $route_data['keywords'], isset($route_data['params']) ? $route_data['params'] : array());
             }
         }
     }
     $oPrediggoConfig = $this->aPrediggoConfigs[(int) $aEntity['id_shop']];
     $link = $oPrediggoConfig->getContext()->link;
     $oProduct = new Product((int) $aEntity['id_product'], true, null, (int) $aEntity['id_shop'], $oPrediggoConfig->getContext());
     if ((int) StockAvailable::getQuantityAvailableByProduct((int) $aEntity['id_product'], 0, (int) $aEntity['id_shop']) < (int) $oPrediggoConfig->export_product_min_quantity) {
         $this->nbEntitiesTreated--;
         $this->nbEntities--;
         return ' ';
     }
     $ps_tax = (int) Configuration::get('PS_TAX');
     foreach ($this->aLanguages as $aLanguage) {
         $id_lang = (int) $aLanguage['id_lang'];
         // Set the root of the XML
         $root = $dom->createElement($this->sEntity);
         $dom->appendChild($root);
         $root->setAttribute('timestamp', (int) strtotime($oProduct->date_add));
         $id = $dom->createElement('id', (int) $oProduct->id);
         $root->appendChild($id);
         $profile = $dom->createElement('profile', (int) $aEntity['id_shop']);
         $root->appendChild($profile);
         $name = $dom->createElement('name');
         $name->appendChild($dom->createCDATASection($oProduct->name[$id_lang]));
         $root->appendChild($name);
         $oCategory = new Category((int) $oProduct->id_category_default);
         $aCategories = $oCategory->getParentsCategories($id_lang);
         if (is_array($aCategories) && count($aCategories) > 0) {
             foreach ($aCategories as $aCategory) {
                 $oCategoryTmp = new Category((int) $aCategory['id_category'], $id_lang);
                 if (!empty($oCategoryTmp->name)) {
                     $genre = $dom->createElement('genre');
                     $genre->appendChild($dom->createCDATASection($oCategoryTmp->name));
                     $root->appendChild($genre);
                 }
                 unset($oCategoryTmp);
             }
         }
         unset($aCategories);
         unset($oCategory);
         if (!empty($oProduct->ean13)) {
             $ean = $dom->createElement('ean');
             $ean->appendChild($dom->createCDATASection($oProduct->ean13));
             $root->appendChild($ean);
         }
         $price = $dom->createElement('price', number_format($oProduct->getPrice($ps_tax), 2, '.', ''));
         $root->appendChild($price);
         if (isset($oProduct->tags[$id_lang]) && ($aTags = $oProduct->tags[$id_lang])) {
             $tag = $dom->createElement('tag');
             $tag->appendChild($dom->createCDATASection(join(',', $aTags)));
             $root->appendChild($tag);
         }
         $sDesc = trim(strip_tags($oProduct->description[$id_lang]));
         if ($oPrediggoConfig->export_product_description && !empty($sDesc)) {
             $description = $dom->createElement('description');
             $description->appendChild($dom->createCDATASection($sDesc));
             $root->appendChild($description);
         }
         if (!empty($oProduct->id_manufacturer)) {
             $supplierid = $dom->createElement('supplierid', (int) $oProduct->id_manufacturer);
             $root->appendChild($supplierid);
         }
         $recommendable = $dom->createElement('recommendable', in_array((int) $oProduct->id, explode(',', $oPrediggoConfig->products_ids_not_recommendable)) ? 'false' : 'true');
         $root->appendChild($recommendable);
         $searchable = $dom->createElement('searchable', in_array((int) $oProduct->id, explode(',', $oPrediggoConfig->products_ids_not_searchable)) ? 'false' : 'true');
         $root->appendChild($searchable);
         // Set product URL
         $attribute = $dom->createElement('attribute');
         $root->appendChild($attribute);
         $attName = $dom->createElement('attName', 'producturl');
         $attribute->appendChild($attName);
         $attValue = $dom->createElement('attValue');
         $attValue->appendChild($dom->createCDATASection($link->getProductLink((int) $oProduct->id, $oProduct->link_rewrite[$id_lang], Category::getLinkRewrite((int) $oProduct->id_category_default, $id_lang), NULL, $id_lang, (int) $aEntity['id_shop'], 0, $bUseRoutes)));
         $attribute->appendChild($attValue);
         // Set product picture
         if ($oPrediggoConfig->export_product_image) {
             $attribute = $dom->createElement('attribute');
             $root->appendChild($attribute);
             $attName = $dom->createElement('attName', 'imageurl');
             $attribute->appendChild($attName);
             $aCover = $oProduct->getCover((int) $oProduct->id);
             $attValue = $dom->createElement('attValue');
             $attValue->appendChild($dom->createCDATASection($link->getImageLink($oProduct->link_rewrite[$id_lang], (int) $aCover['id_image'], 'large')));
             $attribute->appendChild($attValue);
         }
         // Set combinations
         $aProductCombinations = Product::getAttributesInformationsByProduct((int) $oProduct->id);
         if (sizeof($aProductCombinations)) {
             foreach ($aProductCombinations as $aProductCombination) {
                 if (!empty($oPrediggoConfig->attributes_groups_ids) && in_array((int) $aProductCombination['id_attribute_group'], explode(',', $oPrediggoConfig->attributes_groups_ids))) {
                     $attribute = $dom->createElement('attribute');
                     $root->appendChild($attribute);
                     $attName = $dom->createElement('attName');
                     $attName->appendChild($dom->createCDATASection($aProductCombination['group']));
                     $attribute->appendChild($attName);
                     $attValue = $dom->createElement('attValue');
                     $attValue->appendChild($dom->createCDATASection($aProductCombination['attribute']));
                     $attribute->appendChild($attValue);
                 }
             }
         }
         unset($aProductCombinations);
         // Set features
         $aProductFeatures = $oProduct->getFrontFeatures($id_lang);
         if (sizeof($aProductFeatures)) {
             foreach ($aProductFeatures as $aProductFeature) {
                 if (!empty($oPrediggoConfig->features_ids) && in_array((int) $aProductFeature['id_feature'], explode(',', $oPrediggoConfig->features_ids))) {
                     $attribute = $dom->createElement('attribute');
                     $root->appendChild($attribute);
                     $attName = $dom->createElement('attName');
                     $attName->appendChild($dom->createCDATASection($aProductFeature['name']));
                     $attribute->appendChild($attName);
                     $attValue = $dom->createElement('attValue');
                     $attValue->appendChild($dom->createCDATASection($aProductFeature['value']));
                     $attribute->appendChild($attValue);
                 }
             }
         }
         unset($aProductFeatures);
         $aAccessories = Product::getAccessoriesLight($id_lang, (int) $oProduct->id);
         if (sizeof($aAccessories)) {
             foreach ($aAccessories as $aAccessory) {
                 $attribute = $dom->createElement('attribute');
                 $root->appendChild($attribute);
                 $attName = $dom->createElement('attName');
                 $attName->appendChild($dom->createCDATASection('accessory'));
                 $attribute->appendChild($attName);
                 $attValue = $dom->createElement('attValue');
                 $attValue->appendChild($dom->createCDATASection((int) $aAccessory['id_product']));
                 $attribute->appendChild($attValue);
             }
         }
         unset($aAccessories);
         $sReturn .= $dom->saveXML($root);
     }
     unset($dom);
     unset($oProduct);
     return $sReturn;
 }
Example #25
0
 public static function getProductProperties($id_lang, $row, Context $context = null)
 {
     Hook::exec('actionGetProductPropertiesBefore', ['id_lang' => $id_lang, 'product' => $row, 'context' => $context]);
     if (!$row['id_product']) {
         return false;
     }
     if ($context == null) {
         $context = Context::getContext();
     }
     $id_product_attribute = $row['id_product_attribute'] = !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null;
     // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it:
     // consider adding it in order to avoid unnecessary queries
     $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
     if (Combination::isFeatureActive() && $id_product_attribute === null && (isset($row['cache_default_attribute']) && ($ipa_default = $row['cache_default_attribute']) !== null || ($ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])))) {
         $id_product_attribute = $row['id_product_attribute'] = $ipa_default;
     }
     if (!Combination::isFeatureActive() || !isset($row['id_product_attribute'])) {
         $id_product_attribute = $row['id_product_attribute'] = 0;
     }
     // Tax
     $usetax = !Tax::excludeTaxeOption();
     $cache_key = $row['id_product'] . '-' . $id_product_attribute . '-' . $id_lang . '-' . (int) $usetax;
     if (isset($row['id_product_pack'])) {
         $cache_key .= '-pack' . $row['id_product_pack'];
     }
     if (isset(self::$producPropertiesCache[$cache_key])) {
         return array_merge($row, self::$producPropertiesCache[$cache_key]);
     }
     // Datas
     $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang);
     $row['category_name'] = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'category_lang WHERE id_shop = ' . (int) $context->shop->id . ' AND id_lang = ' . (int) $id_lang . ' AND id_category = ' . (int) $row['id_category_default']);
     $row['link'] = $context->link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
     $row['attribute_price'] = 0;
     if ($id_product_attribute) {
         $row['attribute_price'] = (double) Combination::getPrice($id_product_attribute);
     }
     if (isset($row['quantity_wanted'])) {
         // 'quantity_wanted' may very well be zero even if set
         $quantity = max((int) $row['minimal_quantity'], (int) $row['quantity_wanted']);
     } else {
         $quantity = (int) $row['minimal_quantity'];
     }
     $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, $id_product_attribute, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6, null, false, true, $quantity);
     if (self::$_taxCalculationMethod == PS_TAX_EXC) {
         $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2);
         $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, true, $quantity);
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, $id_product_attribute, 2, null, false, false, $quantity);
     } else {
         $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, true, $quantity), (int) Configuration::get('PS_PRICE_DISPLAY_PRECISION'));
         $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, false, $quantity);
     }
     $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, $id_product_attribute, 6, null, true, true, $quantity, true, null, null, null, $specific_prices);
     $row['specific_prices'] = $specific_prices;
     $row['quantity'] = Product::getQuantity((int) $row['id_product'], 0, isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null);
     $row['quantity_all_versions'] = $row['quantity'];
     if ($row['id_product_attribute']) {
         $row['quantity'] = Product::getQuantity((int) $row['id_product'], $id_product_attribute, isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null);
         $row['available_date'] = Product::getAvailableDate((int) $row['id_product'], $id_product_attribute);
     }
     $row['id_image'] = Product::defineProductImage($row, $id_lang);
     $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']);
     $row['attachments'] = array();
     if (!isset($row['cache_has_attachments']) || $row['cache_has_attachments']) {
         $row['attachments'] = Product::getAttachmentsStatic((int) $id_lang, $row['id_product']);
     }
     $row['virtual'] = !isset($row['is_virtual']) || $row['is_virtual'] ? 1 : 0;
     // Pack management
     $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack'];
     $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array();
     $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0;
     if ($row['pack'] && !Pack::isInStock($row['id_product'])) {
         $row['quantity'] = 0;
     }
     $row['customization_required'] = false;
     if (isset($row['customizable']) && $row['customizable'] && Customization::isFeatureActive()) {
         if (count(Product::getRequiredCustomizableFieldsStatic((int) $row['id_product']))) {
             $row['customization_required'] = true;
         }
     }
     $attributes = Product::getAttributesParams($row['id_product'], $row['id_product_attribute']);
     foreach ($attributes as $attribute) {
         $row['attributes'][$attribute['id_attribute_group']] = $attribute;
     }
     $row = Product::getTaxesInformations($row, $context);
     $row['ecotax_rate'] = (double) Tax::getProductEcotaxRate($context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     Hook::exec('actionGetProductPropertiesAfter', ['id_lang' => $id_lang, 'product' => $row, 'context' => $context]);
     $combination = new Combination($id_product_attribute);
     if (0 != $combination->unit_price_impact && 0 != $row['unit_price_ratio']) {
         $unitPrice = $row['price_tax_exc'] / $row['unit_price_ratio'] + $combination->unit_price_impact;
         $row['unit_price_ratio'] = $row['price_tax_exc'] / $unitPrice;
     }
     $row['unit_price'] = $row['unit_price_ratio'] != 0 ? $row['price'] / $row['unit_price_ratio'] : 0;
     self::$producPropertiesCache[$cache_key] = $row;
     return self::$producPropertiesCache[$cache_key];
 }
    function displayFormInformations($obj, $currency, $languages, $defaultLanguage)
    {
        global $currentIndex, $cookie;
        $iso = Language::getIsoById(intval($cookie->id_lang));
        $divLangName = 'cnameยคcdescยคcdesc_shortยคclink_rewriteยคcmeta_descriptionยคcmeta_titleยคcmeta_keywordsยคctagsยคcavailable_nowยคcavailable_later';
        $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 = '';
        }
        $cover = Product::getCover($obj->id);
        $link = new Link();
        //includeDatepicker(array('reduction_from', 'reduction_to'));
        echo '
		<div class="tab-page" id="step1">
			<h4 class="tab">1. ' . $this->l('Info.') . '</h4>
			<b>' . $this->l('Product global informations') . '</b>&nbsp;-&nbsp;';
        if (isset($obj->id)) {
            echo '
			<a href="' . $link->getProductLink($this->getFieldValue($obj, 'id'), $this->getFieldValue($obj, 'link_rewrite', $defaultLanguage), Category::getLinkRewrite($this->getFieldValue($obj, 'id_category_default'), intval($cookie->id_lang))) . '"><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=AdminStatsModules&module=statsproduct&id_product=' . $obj->id . '&token=' . Tools::getAdminToken('AdminStatsModules' . intval(Tab::getIdFromClassName('AdminStatsModules')) . intval($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:100%">
					<tr>
						<td class="col-left">' . $this->l('Name:') . '</td>
						<td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '			<div id="cname_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? 'block' : 'none') . '; float: left;">
								<input size="55" 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="copy2friendlyURL();"' : '') . ' onchange="updateCurrentText();" /><sup> *</sup>
								<span class="hint" name="help_box">' . $this->l('Invalid characters:') . ' <>;=#{}<span class="hint-pointer">&nbsp;</span></span>
							</div>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cname');
        echo '<script type="text/javascript">updateCurrentText();</script>
						</td>
					</tr>
					<tr>
						<td style="vertical-align:top">' . $this->l('Status:') . '</td>
						<td style="padding-bottom:5px;">
							<input style="float:left;" 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 style="clear:both;" />
							<input style="float:left;" 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') . '</label>
						</td>
					</tr>
					<tr>
						<td>' . $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' . intval(Tab::getIdFromClassName('AdminManufacturers')) . intval($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>
							<script type="text/javascript">
								var ajaxManufacturersClicked = false;
								$("select#id_manufacturer").focus(
									function() {
										if (ajaxManufacturersClicked == true) return; else ajaxManufacturersClicked = true;
										$.getJSON("' . dirname($currentIndex) . '/ajax.php",{ajaxProductManufacturers:1},
											function(j) {
												var options = \'\';
												for (var i = 0; i < getE("id_manufacturer").options.length; i++)
												{
													if (getE("id_manufacturer").options[i].innerHTML == \'----------\')
														options += \'<option disabled="disabled">----------</option>\';
													else
														options += \'<option value="\' +  getE("id_manufacturer").options[i].value + \'">\' + getE("id_manufacturer").options[i].innerHTML + \'</option>\';
												}
												for (var i = 0; i < j.length; i++)
													options += \'<option value="\' + j[i].optionValue + \'">\' + j[i].optionDisplay + \'</option>\';
												$("select#id_manufacturer").html(options);
											}
										)
									}
								);
							</script>
						</td>
					</tr>
					<tr>
						<td>' . $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' . intval(Tab::getIdFromClassName('AdminSuppliers')) . intval($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>
							<script type="text/javascript">
								var ajaxSuppliersClicked = false;
								$("select#id_supplier").focus(
									function() {
										if (ajaxSuppliersClicked == true) return; else ajaxSuppliersClicked = true;
										$.getJSON("' . dirname($currentIndex) . '/ajax.php",{ajaxProductSuppliers:1},
											function(j) {
												var options = \'\';
												for (var i = 0; i < getE("id_supplier").options.length; i++)
												{
													if (getE("id_supplier").options[i].innerHTML == \'----------\')
														options += \'<option disabled="disabled">----------</option>\';
													else
														options += \'<option value="\' +  getE("id_supplier").options[i].value + \'">\' + getE("id_supplier").options[i].innerHTML + \'</option>\';
												}
												for (var i = 0; i < j.length; i++)
													options += \'<option value="\' + j[i].optionValue + \'">\' + j[i].optionDisplay + \'</option>\';
												$("select#id_supplier").html(options);
											}
										)
									}
								);
							</script>
						</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;" />
							' . $this->l('EAN13:') . '<input size="55" maxlength="13" type="text" name="ean13" value="' . $this->getFieldValue($obj, 'ean13') . '" style="width: 110px; margin-left: 10px;" />
							<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;" />
							' . $this->l('Location:') . '<input size="55" type="text" name="location" value="' . $this->getFieldValue($obj, 'location') . '" style="width: 101px; margin-left: 10px;" />
							<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('Weight:') . '</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="javascript:this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_WEIGHT_UNIT') . '
						</td>
					</tr>
					<tr><td colspan="2"><hr style="width:730px;"></td></tr>';
        $this->displayPack($obj);
        echo '		<tr><td colspan="2"><hr style="width:730px;"></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">
	<!--	
	function toggleVirtualProduct(elt)
	{
		if (elt.checked)
		{
			$('#virtual_good').show('slow');
			getE('out_of_stock_1').checked = 'checked';
			getE('out_of_stock_2').readOnly = true;
			getE('out_of_stock_3').readOnly = true;
			getE('label_out_of_stock_2').setAttribute('for', '');
			getE('label_out_of_stock_3').setAttribute('for', '');
		}
		else
		{
			$('#virtual_good').hide('slow');
			getE('out_of_stock_2').readOnly = false;
			getE('out_of_stock_3').readOnly = 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();
						$('#virtual_product_name').attr('value', fileName);
						$('#upload-confirmation').html(
							'<a class="link" href="get-file-admin.php?file=' + msg + '"><?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">
			var newLabel = \'' . $this->l('New label') . '\';
			var choose_language = \'' . $this->l('Choose language:') . '\';
			var required = \'' . $this->l('required') . '\';
			var customizationUploadableFileNumber = ' . intval($this->getFieldValue($obj, 'uploadable_files')) . ';
			var customizationTextFieldNumber = ' . intval($this->getFieldValue($obj, 'text_fields')) . ';
			var uploadableFileLabel = 0;
			var textFieldLabel = 0;
			var defaultLanguage = ' . intval($defaultLanguage) . ';
			var languages = new Array();';
        $i = 0;
        foreach ($languages as $language) {
            echo 'languages[' . $i++ . '] = new Array(' . intval($language['id_lang']) . ', \'' . $language['iso_code'] . '\', \'' . htmlentities($language['name'], ENT_COMPAT, 'UTF-8') . '\');' . "\n";
        }
        echo '
		</script>';
        ?>
	<tr>
		<td colspan="2">
			<input type="checkbox" id="is_virtual_good" name="is_virtual_good" value="true" onchange="toggleVirtualProduct(this)" 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"><?php 
        echo $this->l('Is this a downloadable product?');
        ?>
</label>
			<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()) {
                ?>
		<?php 
                if ($productDownload->id) {
                    ?>
					<p class="alert">
						<?php 
                    echo $this->l('This product is missing');
                    ?>
:<br/>
						<?php 
                    echo realpath(_PS_DOWNLOAD_DIR_) . '/' . $productDownload->physically_filename;
                    ?>
					</p>
		<?php 
                }
                ?>
					<p><?php 
                echo $this->l('Your server\'s maximum upload file size is') . ':&nbsp;' . ini_get('upload_max_filesize');
                ?>
</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>
					<input type="file" id="virtual_product_file" name="virtual_product_file" value="" class="" onchange="uploadFile()" maxlength="<?php 
                    echo $this->maxFileSize;
                    ?>
" />
					<?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>
	<?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" class="" 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 complete filename with its extension (e.g., Our best song.mp3)');
            ?>
</span>
				</p>
				<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');
            ?>
</span>
				</p>
	<?php 
        }
        // check if download directory is writable
        ?>
			</div>
		</td>
	</tr>
	<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:730px;"></td></tr>
	<script type="text/javascript">
		if ($('#is_virtual_good').attr('checked'))
			$('#virtual_good').show('slow');
	</script>

<?php 
        echo '
					<tr>
						<td class="col-left">' . $this->l('Pre-tax wholesale price:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format == 1 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" name="wholesale_price" type="text" value="' . htmlentities($this->getFieldValue($obj, 'wholesale_price'), ENT_COMPAT, 'UTF-8') . '" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\');" />' . ($currency->format == 2 ? ' ' . $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 == 1 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" id="priceTE" name="price" type="text" value="' . $this->getFieldValue($obj, 'price') . '" onKeyUp="javascript:this.value = this.value.replace(/,/g, \'.\'); calcPriceTI();" />' . ($currency->format == 2 ? ' ' . $currency->sign : '') . '<sup> *</sup>
							<span style="margin-left:2px">' . $this->l('The pre-tax retail price to sell this product') . '</span>
						</td>
					</tr>';
        $taxes = Tax::getTaxes(intval($cookie->id_lang));
        echo '<script type="text/javascript">';
        echo 'noTax = ' . (Tax::excludeTaxeOption() ? 'true' : 'false'), ";\n";
        echo 'taxesArray = new Array ();' . "\n";
        echo 'taxesArray[0] = 0', ";\n";
        foreach ($taxes as $k => $tax) {
            echo 'taxesArray[' . $tax['id_tax'] . ']=' . $tax['rate'] . "\n";
        }
        echo '
					</script>';
        echo '
					<tr>
						<td class="col-left">' . $this->l('Tax:') . '</td>
						<td style="padding-bottom:5px;">
							<select onChange="javascript:calcPriceTI();" name="id_tax" id="id_tax" ' . (Tax::excludeTaxeOption() ? 'disabled="disabled"' : '') . '>
								<option value="0"' . ($this->getFieldValue($obj, 'id_tax') == 0 ? ' selected="selected"' : '') . '>' . $this->l('No tax') . '</option>';
        foreach ($taxes as $k => $tax) {
            echo '
								<option value="' . $tax['id_tax'] . '"' . ($this->getFieldValue($obj, 'id_tax') == $tax['id_tax'] ? ' selected="selected"' : '') . '>' . stripslashes($tax['name']) . ' (' . $tax['rate'] . '%)</option>';
        }
        echo '
							</select>';
        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' . intval(Tab::getIdFromClassName('AdminTaxes')) . intval($cookie->id_employee)) . '">' . $this->l('Tax options') . '</a></b>)';
            echo '<input type="hidden" value="' . intval($this->getFieldValue($obj, 'id_tax')) . '" name="id_tax" />';
        }
        echo '</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Retail price with tax:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format == 1 ? ' ' . $currency->sign : '') . ' <input size="11" maxlength="14" id="priceTI" type="text" value="" onKeyUp="noComma(\'priceTI\'); calcPriceTE();" />' . ($currency->format == 2 ? ' ' . $currency->sign : '') . '
							<span style="margin-left:10px">
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Eco-tax:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format == 1 ? $currency->sign . ' ' : '') . '<input size="11" maxlength="14" id="ecotax" name="ecotax" type="text" value="' . $this->getFieldValue($obj, 'ecotax') . '" onKeyUp="javascript: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 ? ' ' . $currency->sign : '') . '
							<span style="margin-left:10px">(' . $this->l('already included in price') . ')</span>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Reduction amount:') . '</td>
						<td style="padding-bottom:5px;">
							' . ($currency->format == 1 ? ' ' . $currency->sign . ' ' : '') . '<input size="11" maxlength="14" type="text" name="reduction_price" id="reduction_price" value="' . $this->getFieldValue($obj, 'reduction_price') . '" onkeyup="javascript:this.value = this.value.replace(/,/g, \'.\'); var key = window.event ? window.event.keyCode : event.which; if (key != 9) reductionPrice();" /> ' . ($currency->format == 2 ? ' ' . $currency->sign : '') . '
							<span style="padding-right: 15px; padding-left: 15px; font-weight: bold">' . $this->l('OR') . '</span>
							<input size="10" maxlength="14" type="text" name="reduction_percent" id="reduction_percent" value="' . $this->getFieldValue($obj, 'reduction_percent') . '" onkeyup="javascript:this.value = this.value.replace(/,/g, \'.\'); var key = window.event ? window.event.keyCode : event.which; if (key != 9) reductionPercent();" /> %
						</td>
					</tr>
					<tr>
						<td class="col-left">&nbsp;</td>
						<td>' . $this->l('available from') . ' <input type="text" id="reduction_from" name="reduction_from" value="' . (($from = $this->getFieldValue($obj, 'reduction_from') and $from != '0000-00-00' and $from != '1942-01-01') ? $from : date('Y-m-d')) . '" />
							' . $this->l('to') . ' <input type="text" id="reduction_to" name="reduction_to" value="' . (($to = $this->getFieldValue($obj, 'reduction_to') and $to != '0000-00-00' and $to != '1942-01-01') ? $to : date('Y-m-d')) . '" />
							<p>' . $this->l('Leave same dates for undefined duration') . '</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;">
							' . ($currency->format == 1 ? $currency->sign . ' ' : '') . '<span id="finalPrice" style="font-weight: bold;"></span>' . ($currency->format == 2 ? ' ' . $currency->sign : '') . '
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:730px;"></td></tr>
					<tr>
						<td class="col-left">' . $this->l('Quantity:') . '</td>
						<td style="padding-bottom:5px;"><input size="3" maxlength="6" ' . $qty_state . ' name="quantity" type="text" value="' . $qty . '" ' . ((isset($_POST['attQty']) and $_POST['attQty']) ? 'onclick="alert(\'' . $this->l('Quantity is already defined by Attributes') . '.<br />' . $this->l('Delete attributes first') . '.\');" readonly="readonly" ' : '') . '/><sup> *</sup>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Displayed text when in-stock:') . '</td>
						<td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '
							<div id="cavailable_now_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cavailable_now');
        echo '			</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Displayed text when allowed to be back-ordered:') . '</td>
						<td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '
							<div id="cavailable_later_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cavailable_later');
        echo '			</td>
					</tr>

					<script type="text/javascript" src="../js/price.js"></script>
					<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" ' . (intval($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(intval(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' . intval(Tab::getIdFromClassName('AdminPPreferences')) . intval($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:730px;"></td></tr>
					<tr>
						<td class="col-left"><label for="id_category_default" class="t">' . $this->l('Default category:') . '</label></td>
						<td>
							<select id="id_category_default" name="id_category_default" onchange="checkDefaultCategory(this.value);">';
        $categories = Category::getCategories(intval($cookie->id_lang), false);
        Category::recurseCategory($categories, $categories[0][1], 1, $this->getFieldValue($obj, 'id_category_default') ? $this->getFieldValue($obj, 'id_category_default') : Tools::getValue('id_category', 1));
        echo '
							</select>
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Catalog:') . '</td>
						<td>
							<div style="overflow: auto; min-height: 300px; padding-top: 0.6em;" id="categoryList">
							<table cellspacing="0" cellpadding="0" class="table">
									<tr>
										<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'categoryBox[]\', this.checked)" /></th>
										<th>' . $this->l('ID') . '</th>
										<th style="width: 400px">' . $this->l('Name') . '</th>
									</tr>';
        $done = array();
        $index = array();
        $indexedCategories = isset($_POST['categoryBox']) ? $_POST['categoryBox'] : ($obj->id ? Product::getIndexedCategories($obj->id) : array());
        foreach ($indexedCategories as $k => $row) {
            $index[] = $row['id_category'];
        }
        $this->recurseCategoryForInclude($index, $categories, $categories[0][1], 1, $obj->id_category_default);
        echo '
							</table>
							<p style="padding:0px; margin:0px 0px 10px 0px;">' . $this->l('Mark all checkbox(es) of categories in which product is to appear') . '<sup> *</sup></p>
							</div>
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:730px;"></td></tr>
					<tr><td colspan="2">
						<span onclick="javascript:openCloseLayer(\'seo\');" 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>';
        foreach ($languages as $language) {
            echo '
										<div id="cmeta_title_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cmeta_title');
        echo '
										<p style="clear: both">' . $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>';
        foreach ($languages as $language) {
            echo '
										<div id="cmeta_description_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cmeta_description');
        echo '
										<p style="clear: both">' . $this->l('A single sentence for HTML header') . '</p>
									</td>
								</tr>
								<tr>
									<td class="col-left">' . $this->l('Meta keywords:') . '</td>
									<td>';
        foreach ($languages as $language) {
            echo '
										<div id="cmeta_keywords_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cmeta_keywords');
        echo '
										<p style="clear: both">' . $this->l('Keywords for HTML header, separated by a comma') . '</p>
									</td>
								</tr>
								<tr>
									<td class="col-left">' . $this->l('Friendly URL:') . '</td>
									<td>';
        foreach ($languages as $language) {
            echo '
										<div id="clink_rewrite_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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="this.value = str2url(this.value); 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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'clink_rewrite');
        global $cookie;
        $iso = Language::getIsoById(intval($cookie->id_lang));
        echo '
										<p style="clear: both; width: 360px; word-wrap: break-word; overflow: auto;">' . $this->l('Product link will look like this:') . ' ' . (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . '/id_product-<span id="friendly-url"></span>.html</p>
									</td>
								</tr>
								<script type="text/javascript">updateFriendlyURL();</script>';
        echo '</td></tr></table>
						</div>
					</td></tr>
					<tr><td colspan="2" style="padding-bottom:5px;"><hr style="width:730px;"></td></tr>
					<tr>
						<td class="col-left">' . $this->l('Short description:') . '<br /><br /><i>(' . $this->l('appears in search results') . ')</i></td>
						<td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '
							<div id="cdesc_short_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cdesc_short');
        echo '
						</td>
					</tr>
					<tr>
						<td class="col-left">' . $this->l('Description:') . '</td>
						<td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '
							<div id="cdesc_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'cdesc');
        echo '
						</td>
					</tr>';
        echo '<tr><td class="col-left">' . $this->l('Tags:') . '</td><td style="padding-bottom:5px;">';
        foreach ($languages as $language) {
            echo '<div id="ctags_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $defaultLanguage ? '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>';
        }
        $this->displayFlags($languages, $defaultLanguage, $divLangName, 'ctags');
        echo '<p style="clear: both">' . $this->l('Tags separated by commas (e.g., dvd, dvd player, hifi)') . '</p>';
        echo '</td>
					</tr>';
        $accessories = Product::getAccessoriesLight(intval($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 $accessory['name'] . '<span onclick="delAccessory(' . $accessory['id_product'] . ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" /></span><br />';
        }
        echo '</div>
							<input type="hidden" name="inputAccessories" id="inputAccessories" value="';
        foreach ($accessories as $accessory) {
            echo $accessory['id_product'] . '-';
        }
        echo '" />
							<input type="hidden" name="nameAccessories" id="nameAccessories" value="';
        foreach ($accessories as $accessory) {
            echo $accessory['name'] . 'ยค';
        }
        echo '" />
							<script type="text/javascript">
								var formProduct;
								var accessories = new Array();
								
								function fillAccessories()
								{
									$.getJSON("' . dirname($currentIndex) . '/ajax.php",{ajaxProductAccessories:1,id_lang:' . intval($cookie->id_lang) . ',id_product:' . ($obj->id ? intval($obj->id) : 0) . '},
										function(j)
										{
											for (var i = 0; i < j.length; i++)
												accessories[i] = new Array(j[i].value, j[i].text);
												
											formProduct = document.layers ? document.forms.product : document.product;
											formProduct.selectAccessories.length = accessories.length + 1;
											for (i = 0, j = 1; i < accessories.length; i++)
											{
												if (formProduct.filter.value)
													if (accessories[i][1].toLowerCase().indexOf(formProduct.filter.value.toLowerCase()) == -1)
														continue;
												formProduct.selectAccessories.options[j].value = accessories[i][0];
												formProduct.selectAccessories.options[j].text = accessories[i][1];
												j++;
											}
											if (j == 1)
											{
												formProduct.selectAccessories.length = 2;
												formProduct.selectAccessories.options[1].value = -1;
												formProduct.selectAccessories.options[1].text = \'' . $this->l('No match found') . '\';
												formProduct.selectAccessories.options.selectedIndex = 1;
											}
											else
											{
												formProduct.selectAccessories.length = j;
												formProduct.selectAccessories.options.selectedIndex = (formProduct.filter.value == \'\' ? 0 : 1);
											}
										}
									);
								}
							</script>
							<select id="selectAccessories" name="selectAccessories" style="width: 380px;">
								<option value="0" selected="selected">-- ' . $this->l('Choose') . ' --</option>
							</select>
							<script type="text/javascript">
								fillAccessories();
							</script>
							<span onclick="addAccessory();" style="cursor: pointer;"><img src="../img/admin/add.gif" alt="' . $this->l('Add an accessory') . '" title="' . $this->l('Add an accessory') . '" /></span>
							<br />' . $this->l('Filter:') . ' <input type="text" size="25" name="filter" onkeyup="fillAccessories();" class="space" />
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:10px;"><hr style="width:730px;"></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>
			</div>

			<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/tinymce/jscripts/tiny_mce/jquery.tinymce.js"></script>
			<script type="text/javascript">
			function tinyMCEInit(element)
			{
				$().ready(function() {
					$(element).tinymce({
						// Location of TinyMCE script
						script_url : \'' . __PS_BASE_URI__ . 'js/tinymce/jscripts/tiny_mce/tiny_mce.js\',
						// General options
						theme : "advanced",
						plugins : "safari,pagebreak,style,layer,table,advimage,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,fullscreen",
						// Theme options
						theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,pagebreak",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						width : "100",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true,
						content_css : "' . __PS_BASE_URI__ . 'themes/' . _THEME_NAME_ . '/css/global.css",
						// Drop lists for link/image/media/template dialogs
						template_external_list_url : "lists/template_list.js",
						external_link_list_url : "lists/link_list.js",
						external_image_list_url : "lists/image_list.js",
						media_external_list_url : "lists/media_list.js",
						elements : "nourlconvert",
						convert_urls : false,
						language : "' . (file_exists(_PS_ROOT_DIR_ . '/js/tinymce/jscripts/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en') . '"
					});
				});
			}
			tinyMCEInit(\'textarea.rte\');
			toggleVirtualProduct(getE(\'is_virtual_good\'));
			</script>
		';
    }
 /**
  * Convert the entities data into an xml object and return the xml object as a string
  *
  * @param array $aEntity Entity data
  */
 public function formatEntityToXML($aEntity)
 {
     global $link;
     $sReturn = '';
     $dom = new DOMDocument('1.0', 'utf-8');
     $oProduct = new Product((int) $aEntity['id_product'], true);
     if ((int) $oProduct->quantity < (int) $this->productMinQuantity) {
         $this->nbEntitiesTreated--;
         $this->nbEntities--;
         return ' ';
     }
     $ps_tax = (int) Configuration::get('PS_TAX');
     foreach ($this->aLanguages as $aLanguage) {
         $id_lang = (int) $aLanguage['id_lang'];
         // Set the root of the XML
         $root = $dom->createElement($this->sEntity);
         $dom->appendChild($root);
         //$root->setAttribute('timestamp', date('c',strtotime($oProduct->date_add)));
         $root->setAttribute('timestamp', (int) strtotime($oProduct->date_add));
         $id = $dom->createElement('id', (int) $oProduct->id);
         $root->appendChild($id);
         $profile = $dom->createElement('profile', $id_lang);
         $root->appendChild($profile);
         $name = $dom->createElement('name');
         $name->appendChild($dom->createCDATASection($oProduct->name[$id_lang]));
         $root->appendChild($name);
         $oCategory = new Category((int) $oProduct->id_category_default);
         $aCategories = $oCategory->getParentsCategories($id_lang);
         if (is_array($aCategories) && count($aCategories) > 0) {
             foreach ($aCategories as $aCategory) {
                 $oCategoryTmp = new Category((int) $aCategory['id_category'], $id_lang);
                 if (!empty($oCategoryTmp->name)) {
                     $genre = $dom->createElement('genre');
                     $genre->appendChild($dom->createCDATASection($oCategoryTmp->name));
                     $root->appendChild($genre);
                 }
                 unset($oCategoryTmp);
             }
         }
         unset($aCategories);
         unset($oCategory);
         if (!empty($oProduct->ean13)) {
             $ean = $dom->createElement('ean');
             $ean->appendChild($dom->createCDATASection($oProduct->ean13));
             $root->appendChild($ean);
         }
         $price = $dom->createElement('price', number_format($oProduct->getPrice($ps_tax), 2, '.', ''));
         $root->appendChild($price);
         if (isset($oProduct->tags[$id_lang]) && ($aTags = $oProduct->tags[$id_lang])) {
             $tag = $dom->createElement('tag');
             $tag->appendChild($dom->createCDATASection(join(',', $aTags)));
             $root->appendChild($tag);
         }
         $sDesc = trim(strip_tags($oProduct->description[$id_lang]));
         if ($this->descInExport && !empty($sDesc)) {
             $description = $dom->createElement('description');
             $description->appendChild($dom->createCDATASection($sDesc));
             $root->appendChild($description);
         }
         if (!empty($oProduct->id_manufacturer)) {
             $supplierid = $dom->createElement('supplierid', (int) $oProduct->id_manufacturer);
             $root->appendChild($supplierid);
         }
         $recommendable = $dom->createElement('recommendable', in_array((int) $oProduct->id, $this->aProductsNotRecommendable) ? 'false' : 'true');
         $root->appendChild($recommendable);
         $searchable = $dom->createElement('searchable', in_array((int) $oProduct->id, $this->aProductsNotSearchable) ? 'false' : 'true');
         $root->appendChild($searchable);
         // Set product URL
         $attribute = $dom->createElement('attribute');
         $root->appendChild($attribute);
         $attName = $dom->createElement('attName', 'producturl');
         $attribute->appendChild($attName);
         $attValue = $dom->createElement('attValue');
         $attValue->appendChild($dom->createCDATASection($link->getProductLink((int) $oProduct->id, $oProduct->link_rewrite[$id_lang], Category::getLinkRewrite((int) $oProduct->id_category_default, $id_lang), NULL, $id_lang)));
         $attribute->appendChild($attValue);
         // Set product picture
         if ($this->imageInExport) {
             $attribute = $dom->createElement('attribute');
             $root->appendChild($attribute);
             $attName = $dom->createElement('attName', 'imageurl');
             $attribute->appendChild($attName);
             $aCover = $oProduct->getCover((int) $oProduct->id);
             $attValue = $dom->createElement('attValue');
             $attValue->appendChild($dom->createCDATASection($link->getImageLink($oProduct->link_rewrite[$id_lang], (int) $aCover['id_image'], 'large')));
             $attribute->appendChild($attValue);
         }
         // Set combinations
         $aProductCombinations = $oProduct->getAttributeCombinaisons($id_lang);
         if (sizeof($aProductCombinations)) {
             foreach ($aProductCombinations as $aProductCombination) {
                 if (!is_array($this->aAttributesGroupsIds) || in_array((int) $aProductCombination['id_attribute_group'], $this->aAttributesGroupsIds)) {
                     $attribute = $dom->createElement('attribute');
                     $root->appendChild($attribute);
                     $attName = $dom->createElement('attName');
                     $attName->appendChild($dom->createCDATASection($aProductCombination['group_name']));
                     $attribute->appendChild($attName);
                     $attValue = $dom->createElement('attValue');
                     $attValue->appendChild($dom->createCDATASection($aProductCombination['attribute_name']));
                     $attribute->appendChild($attValue);
                 }
             }
         }
         unset($aProductCombinations);
         // Set features
         $aProductFeatures = $oProduct->getFrontFeatures($id_lang);
         if (sizeof($aProductFeatures)) {
             foreach ($aProductFeatures as $aProductFeature) {
                 if (!is_array($this->aFeaturesIds) || in_array((int) $aProductFeature['id_feature'], $this->aFeaturesIds)) {
                     $attribute = $dom->createElement('attribute');
                     $root->appendChild($attribute);
                     $attName = $dom->createElement('attName');
                     $attName->appendChild($dom->createCDATASection($aProductFeature['name']));
                     $attribute->appendChild($attName);
                     $attValue = $dom->createElement('attValue');
                     $attValue->appendChild($dom->createCDATASection($aProductFeature['value']));
                     $attribute->appendChild($attValue);
                 }
             }
         }
         unset($aProductFeatures);
         $aAccessories = Product::getAccessoriesLight($id_lang, (int) $oProduct->id);
         if (sizeof($aAccessories)) {
             foreach ($aAccessories as $aAccessory) {
                 $attribute = $dom->createElement('attribute');
                 $root->appendChild($attribute);
                 $attName = $dom->createElement('attName');
                 $attName->appendChild($dom->createCDATASection('accessory'));
                 $attribute->appendChild($attName);
                 $attValue = $dom->createElement('attValue');
                 $attValue->appendChild($dom->createCDATASection($aAccessory['reference']));
                 $attribute->appendChild($attValue);
             }
         }
         unset($aAccessories);
         $sReturn .= $dom->saveXML($root);
     }
     unset($dom);
     unset($oProduct);
     return $sReturn;
 }