/**
  * Assign price and tax to the template
  */
 protected function assignPriceAndTax()
 {
     die('coucou');
     $id_customer = isset($this->context->customer) ? (int) $this->context->customer->id : 0;
     $id_group = (int) Group::getCurrent()->id;
     $id_country = $id_customer ? (int) Customer::getCurrentCountry($id_customer) : (int) Tools::getCountry();
     $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
     if ($group_reduction === false) {
         $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
     }
     // Tax
     $tax = (double) $this->product->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
     $this->context->smarty->assign('tax_rate', $tax);
     $product_price_with_tax = Product::getPriceStatic($this->product->id, true, null, 6) * 10;
     if (Product::$_taxCalculationMethod == PS_TAX_INC) {
         $product_price_with_tax = Tools::ps_round($product_price_with_tax, 2);
     }
     $product_price_without_eco_tax = (double) $product_price_with_tax - $this->product->ecotax;
     $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $ecotax_tax_amount = Tools::ps_round($this->product->ecotax, 2);
     if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
         $ecotax_tax_amount = Tools::ps_round($ecotax_tax_amount * (1 + $ecotax_rate / 100), 2);
     }
     $id_currency = (int) $this->context->cookie->id_currency;
     $id_product = (int) $this->product->id;
     $id_shop = $this->context->shop->id;
     $quantity_discounts = SpecificPrice::getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group, null, true, (int) $this->context->customer->id);
     foreach ($quantity_discounts as &$quantity_discount) {
         if ($quantity_discount['id_product_attribute']) {
             $combination = new Combination((int) $quantity_discount['id_product_attribute']);
             $attributes = $combination->getAttributesName((int) $this->context->language->id);
             foreach ($attributes as $attribute) {
                 $quantity_discount['attributes'] = $attribute['name'] . ' - ';
             }
             $quantity_discount['attributes'] = rtrim($quantity_discount['attributes'], ' - ');
         }
         if ((int) $quantity_discount['id_currency'] == 0 && $quantity_discount['reduction_type'] == 'amount') {
             $quantity_discount['reduction'] = Tools::convertPriceFull($quantity_discount['reduction'], null, Context::getContext()->currency);
         }
     }
     $product_price = $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false) * 10;
     $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $this->context->smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (double) $tax, $ecotax_tax_amount), 'ecotax_tax_inc' => $ecotax_tax_amount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'productPriceWithoutEcoTax' => (double) $product_price_without_eco_tax, 'group_reduction' => $group_reduction, 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'ecotax' => !count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'), 'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group)));
 }
 public function initContent()
 {
     if (!$this->ajax) {
         parent::initContent();
     }
     //  parent::initContent();
     $this->setTemplate(_PS_THEME_DIR_ . 'category.tpl');
     if (!$this->customer_access) {
         return;
     }
     if (isset($this->context->cookie->id_compare)) {
         $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) $this->context->cookie->id_compare));
     }
     $this->productSort();
     // Product sort must be called before assignProductList()
     $this->assignScenes();
     $this->assignSubcategories();
     $this->assignProductList();
     $products = isset($this->cat_products) && $this->cat_products ? $this->cat_products : null;
     $combinations = array();
     if ($products !== NULL) {
         foreach ($products as &$pro) {
             $product_obj = new Product($pro['id_product'], $this->context->language->id);
             $pro['groups'] = $product_obj->getProductCombinationsGroups($pro['id_product']);
             $combinations[$pro['id_product']] = $product_obj->getProductAttributeCombinations($pro['id_product']);
             $id_group = (int) Group::getCurrent()->id;
             $group_reduction = GroupReduction::getValueForProduct($pro['id_product'], $id_group);
             if ($group_reduction === false) {
                 $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
             }
             $pro['group_reduction'] = $group_reduction;
             $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $pro['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address);
             $pro['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group);
             $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
             $pro['tax_rate'] = $tax;
             $pro['unit_price_ratio'] = $product_obj->unit_price_ratio;
             $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $pro['ecotaxTax_rate'] = $ecotax_rate;
         }
     }
     $this->context->smarty->assign(array('category' => $this->category, 'description_short' => Tools::truncateString($this->category->description, 350), 'products' => $products, 'id_category' => (int) $this->category->id, 'id_category_parent' => (int) $this->category->id_parent, 'return_category_name' => Tools::safeOutput($this->category->name), 'path' => Tools::getPath($this->category->id), 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize(ImageType::getFormatedName('category')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'thumbSceneSize' => Image::getSize(ImageType::getFormatedName('m_scene')), 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers(), 'body_classes' => array($this->php_self . '-' . $this->category->id, $this->php_self . '-' . $this->category->link_rewrite), 'combinations' => $combinations));
 }
    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>
		';
    }
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!($id_product = (int) Tools::getValue('id_product')) or !Validate::isUnsignedId($id_product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!Validate::isLoadedObject($this->product) or !$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);
             }
             /* rewrited url set */
             $rewrited_url = self::$link->getProductLink($this->product->id, $this->product->link_rewrite);
             /* Product pictures management */
             require_once 'images.inc.php';
             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));
             if ((int) Tools::getValue('pp') == 1) {
                 echo 'here1';
             }
             $productPriceWithTax = Product::getPriceStatic($id_product, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time2 = time();
                 echo 'time2: ' . $time2;
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $configs = Configuration::getMultiple(array('PS_ORDER_OUT_OF_STOCK', 'PS_LAST_QTIES'));
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->getAttachments((int) self::$cookie->id_lang);
             /* 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();');
             $lang = Configuration::get('PS_LANG_DEFAULT');
             if (Pack::isPack((int) $this->product->id, (int) $lang) and !Pack::isInStock((int) $this->product->id, (int) $lang)) {
                 $this->product->quantity = 0;
             }
             $group_reduction = (100 - Group::getReduction((int) self::$cookie->id_customer)) / 100;
             $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'));
             if ((int) Tools::getValue('pp') == 1) {
                 $time3 = time();
                 echo 'time3: ' . $time3;
             }
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $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);
             }
             $manufacturer = new Manufacturer((int) $this->product->id_manufacturer, 1);
             $sizechart = new Sizechart((int) $this->product->id_sizechart, 1);
             //see if the product is already in the wishlist
             if ($id_customer) {
                 $sql = "select id from ps_wishlist where id_customer = " . $id_customer . " and id_product = " . $this->product->id;
                 $res = Db::getInstance()->ExecuteS($sql);
                 if ($res) {
                     self::$smarty->assign("in_wishlist", true);
                 } else {
                     self::$smarty->assign("in_wishlist", false);
                 }
             } else {
                 self::$smarty->assign("in_wishlist", false);
             }
             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, 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => $manufacturer, '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) $configs['PS_LAST_QTIES'], 'group_reduction' => $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_, 'sizechart' => $sizechart->sizechart, 'sizechart_data' => $sizechart->sizechart_data));
             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')));
             if ((int) Tools::getValue('pp') == 1) {
                 $time4 = time();
                 echo 'time4: ' . $time4;
             }
             $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 (sizeof($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time5 = time();
                 echo 'time5: ' . $time5;
             }
             /* Attributes / Groups & colors */
             $colors = array();
             //see if the product has shades
             if ($this->product->id_group && $this->product->id_group > 0) {
                 global $link;
                 $related_productIds = $this->product->getRelatedProducts();
                 $related_products = array();
                 foreach ($related_productIds as &$productId) {
                     $relProduct = new Product((int) $productId['id_product'], true, self::$cookie->id_lang);
                     $idImage = $relProduct->getCoverWs();
                     if ($idImage) {
                         $idImage = $relProduct->id . '-' . $idImage;
                     } else {
                         $idImage = Language::getIsoById(1) . '-default';
                     }
                     $relProduct->image_link = $link->getImageLink($relProduct->link_rewrite, $idImage, 'small');
                     $relProduct->link = $relProduct->getLink();
                     $related_products[] = $relProduct;
                 }
                 self::$smarty->assign('relatedProducts', $related_products);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time6 = time();
                 echo 'time6: ' . $time6;
             }
             $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']]['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;
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time7 = time();
                     echo 'time7: ' . $time7;
                 }
                 //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]);
                         }
                     }
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time71 = time();
                     echo 'time71: ' . $time71;
                 }
                 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));
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time72 = time();
                 echo 'time72: ' . $time72;
             }
             //$newProducts = Product::getNewProducts((int)(self::$cookie->id_lang), 0, 10, false, 'date_add', 'desc');
             /*$categoryProducts = $this->getRandomCatProducts();
               self::$smarty->assign('cat_products', $categoryProducts);*/
             //$brandProducts = $this->getRandomBrandProducts();
             //self::$smarty->assign('brand_products', $brandProducts);
             if ((int) Tools::getValue('pp') == 1) {
                 $time73 = time();
                 echo ' time73: ' . $time73;
             }
             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->getCustomizationFields((int) self::$cookie->id_lang)));
             if ((int) Tools::getValue('pp') == 1) {
                 $time74 = time();
                 echo 'time74: ' . $time74;
             }
             // 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));
             if ((int) Tools::getValue('pp') == 1) {
                 print_r('pack done');
             }
         }
     }
     if ((int) Tools::getValue('pp') == 1) {
         $time8 = time();
         echo 'time8: ' . $time8;
     }
     if ($this->is_saree || $this->is_lehenga) {
         if ($this->is_lehenga) {
             self::$smarty->assign('is_lehenga', $this->is_lehenga);
         }
         self::$smarty->assign('as_shown', (bool) $this->product->as_shown);
         /*if($blouse_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 1))
               self::$smarty->assign('measurement_info', $blouse_measurements);
           if($skirt_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 2))
               self::$smarty->assign('skirt_measurement_info', $skirt_measurements);*/
         if ((int) Tools::getValue('pp') == 1) {
             $time81 = time();
             echo 'time81: ' . $time81;
         }
         if ($this->is_saree) {
             //count of all styles mapped to this product
             $res = Db::getInstance()->getRow("select count(s.id_style) as style_count from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1");
             $style_count = (int) $res['style_count'];
             if ($style_count === 0) {
                 // show the default style for sarees
                 $style = array('id_style' => 1, 'style_image_small' => '1-small.png', 'style_name' => 'Round');
             } else {
                 $res = Db::getInstance()->getRow("select s.id_style, s.style_name, s.style_image_small  from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1 and ps.is_default = 1");
                 if (!empty($res)) {
                     //show the default style for this product
                     $style = array('id_style' => $res['id_style'], 'style_image_small' => $res['style_image_small'], 'style_name' => $res['style_name']);
                 }
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time82 = time();
                 echo 'time82: ' . $time82;
             }
             self::$smarty->assign('blouse_style_count', $style_count);
             self::$smarty->assign('blouse_style', $style);
         }
     } else {
         if ($this->is_skd || $this->is_skd_rts) {
             self::$smarty->assign('is_anarkali', $this->is_anarkali);
             if ($this->is_anarkali) {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 5)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             } else {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 3)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             }
             if ($salwar_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 4)) {
                 self::$smarty->assign('salwar_measurement_info', $salwar_measurements);
             }
             //get default styles for this product (RTS)
             if ($this->is_skd_rts) {
                 $res = Db::getInstance()->ExecuteS("select count(s.id_style) as style_count, s.style_type, ps.id_product from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} group by ps.id_product,s.style_type");
                 foreach ($res as $s) {
                     $style_count = (int) $s['style_count'];
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style_count', $style_count);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style_count', $style_count);
                         }
                     }
                 }
                 $res = Db::getInstance()->ExecuteS("select s.id_style, s.style_type, s.style_image_small, s.style_name from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and ps.is_default = 1");
                 foreach ($res as $s) {
                     $style = array('id_style' => $s['id_style'], 'style_image_small' => $s['style_image_small'], 'style_name' => $s['style_name']);
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style', $style);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style', $style);
                         }
                     }
                 }
             }
         }
     }
     self::$smarty->assign('is_bottoms', $this->is_bottoms);
     self::$smarty->assign('is_abaya', $this->is_abaya);
     self::$smarty->assign('is_wristwear', $this->is_wristwear);
     self::$smarty->assign('is_pakistani_rts', $this->is_pakistani_rts);
     if ((int) Tools::getValue('pp') == 1) {
         $time85 = time();
         echo 'time85: ' . $time85;
     }
     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' => Product::getCover((int) Tools::getValue('id_product')), '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')));
     if ((int) Tools::getValue('pp') == 1) {
         $time9 = time();
         echo 'time9: ' . $time9;
     }
     //add this to product stats
     //Tools::captureActivity(PSTAT_VIEWS,$id_product);
     if ((int) Tools::getValue('pp') == 1) {
         $time1 = time();
         echo 'process end: ' . $time1;
     }
 }
Beispiel #5
0
 /**
  * Return shipping total
  *
  * @param integer $id_carrier Carrier ID (default : current carrier)
  * @return float Shipping total
  */
 function getOrderShippingCost($id_carrier = NULL, $useTax = true)
 {
     global $defaultCountry;
     if ($this->isVirtualCart()) {
         return 0;
     }
     // Checking discounts in cart
     $products = $this->getProducts();
     $discounts = $this->getDiscounts(true);
     if ($discounts) {
         foreach ($discounts as $id_discount) {
             if ($id_discount['id_discount_type'] == 3) {
                 if ($id_discount['minimal'] > 0) {
                     $total_cart = 0;
                     $categories = Discount::getCategories((int) $id_discount['id_discount']);
                     if (sizeof($categories)) {
                         foreach ($products as $product) {
                             if (Product::idIsOnCategoryId((int) $product['id_product'], $categories)) {
                                 $total_cart += $product['total_wt'];
                             }
                         }
                     }
                     if ($total_cart >= $id_discount['minimal']) {
                         return 0;
                     }
                 } else {
                     return 0;
                 }
             }
         }
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if ($order_total <= 0 and !(int) self::getNbProducts($this->id)) {
         return $shipping_cost;
     }
     // Get id zone
     if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
         $id_zone = Address::getZoneById((int) $this->id_address_delivery);
     } else {
         // This method can be called from the backend, and $defaultCountry won't be defined
         if (!Validate::isLoadedObject($defaultCountry)) {
             $defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
         }
         $id_zone = (int) $defaultCountry->id_zone;
     }
     // If no carrier, select default one
     if (!$id_carrier) {
         $id_carrier = $this->id_carrier;
     }
     if ($id_carrier && !$this->isCarrierInRange($id_carrier, $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange(Configuration::get('PS_CARRIER_DEFAULT'), $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and $carrier->getMaxDeliveryPriceByWeight($id_zone) === false or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and $carrier->getMaxDeliveryPriceByPrice($id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
             if (!isset($minShippingPrice)) {
                 $minShippingPrice = $shipping;
             }
             if ($shipping <= $minShippingPrice) {
                 $id_carrier = (int) $row['id_carrier'];
                 $minShippingPrice = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     if (!Validate::isLoadedObject($carrier)) {
         die(Tools::displayError('Fatal error: "no default carrier"'));
     }
     if (!$carrier->active) {
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         return 0;
     }
     // Select carrier tax
     if ($useTax and !Tax::excludeTaxeOption()) {
         $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price and (double) $free_fees_price > 0) {
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] and (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         // Get id zone
         if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             $id_zone = (int) $defaultCountry->id_zone;
         }
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $moduleName = $carrier->external_module_name;
         $module = Module::getInstanceByName($moduleName);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 return false;
             }
         } else {
             return false;
         }
     }
     // Apply tax
     if (isset($carrierTax)) {
         $shipping_cost *= 1 + $carrierTax / 100;
     }
     return (double) Tools::ps_round((double) $shipping_cost, 2);
 }
Beispiel #6
0
 public function getProducts($selected_filters, &$products, &$nb_products, &$p, &$n, &$pages_nb, &$start, &$stop, &$range, &$combinations)
 {
     global $cookie;
     $products = $this->getProductByFilters($selected_filters);
     $products = Product::getProductsProperties((int) $cookie->id_lang, $products);
     $nb_products = $this->nbr_products;
     $range = 2;
     /* how many pages around page selected */
     $n = (int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE'));
     if ($n <= 0) {
         $n = 1;
     }
     $p = $this->page;
     if ($p < 0) {
         $p = 0;
     }
     if ($p > $nb_products / $n) {
         $p = ceil($nb_products / $n);
     }
     $pages_nb = ceil($nb_products / (int) $n);
     $start = (int) ($p - $range);
     if ($start < 1) {
         $start = 1;
     }
     $stop = (int) ($p + $range);
     if ($stop > $pages_nb) {
         $stop = (int) $pages_nb;
     }
     foreach ($products as &$product) {
         if ($product['id_product_attribute'] && isset($product['product_attribute_minimal_quantity'])) {
             $product['minimal_quantity'] = $product['product_attribute_minimal_quantity'];
         }
         $product_obj = new Product((int) $product['id_product'], $this->context->language->id);
         $product['groups'] = $product_obj->getProductCombinationsGroups((int) $product['id_product']);
         $product['obj'] = $product_obj;
         $combinations[$product['id_product']] = $product_obj->getProductAttributeCombinations($product['id_product']);
         $id_group = (int) Group::getCurrent()->id;
         $group_reduction = GroupReduction::getValueForProduct($product['id_product'], $id_group);
         if ($group_reduction === false) {
             $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
         }
         $product['group_reduction'] = $group_reduction;
         $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $product['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address);
         $product['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group);
         $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
         $product['tax_rate'] = $tax;
         $product['unit_price_ratio'] = $product_obj->unit_price_ratio;
         $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $product['ecotaxTax_rate'] = $ecotax_rate;
     }
 }
 /**
  * Get Shipping By barrier
  * @param  int     $id_carrier ID Carrier
  * @param  Country $country    Country
  * @param  float   $subTotal   Total Products
  * @param  boolean $useTax    If use tax
  * @return float               Shipping Costs
  */
 private function getShippingCostByCarrier($products, Currency $currency, $id_carrier, Country $country, $useTax = false)
 {
     $productLists = $products;
     $shippingCost = 0;
     $id_zone = (int) $country->id_zone;
     $carrier = new Carrier($id_carrier, (int) $this->context->language->id);
     if (!$this->ifCarrierDeliveryZone($carrier, $id_zone)) {
         return false;
     }
     $address = new Address();
     $address->id_country = (int) $country->id;
     $address->id_state = 0;
     $address->postcode = 0;
     if ($useTax && !Tax::excludeTaxeOption()) {
         $carrier_tax = $carrier->getTaxesRate($address);
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     $shippingMethod = $carrier->getShippingMethod();
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($carrier->id, 0, (int) $id_zone) || $shippingMethod == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->subTotalWt, $id_zone, (int) $this->id_currency)) {
             $shippingCost += 0;
         } else {
             if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shippingCost += $carrier->getDeliveryPriceByWeight(0, $id_zone);
             } else {
                 // by price
                 $shippingCost += $carrier->getDeliveryPriceByPrice($this->subTotalWt, $id_zone, (int) $currency->id);
             }
         }
     } else {
         if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shippingCost += $carrier->getDeliveryPriceByWeight(0, $id_zone);
         } else {
             $shippingCost += $carrier->getDeliveryPriceByPrice($this->subTotalWt, $id_zone, (int) $currency->id);
         }
     }
     if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
         $shippingCost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     foreach ($productLists as $p) {
         $product = new Product($p->product->code);
         $shippingCost += $product->additional_shipping_cost * $p->quantity;
     }
     // Apply tax
     if ($useTax && isset($carrier_tax)) {
         $shippingCost *= 1 + $carrier_tax / 100;
     }
     $shippingCost = (double) Tools::ps_round((double) $shippingCost, 2);
     return $shippingCost;
 }
Beispiel #8
0
                            }
                        }
                    }
                }
                foreach ($groups as &$group) {
                    natcasesort($group['attributes']);
                }
                foreach ($combinations as $id_product_attribute => $comb) {
                    $attributeList = '';
                    foreach ($comb['attributes'] as $id_attribute) {
                        $attributeList .= '\'' . intval($id_attribute) . '\',';
                    }
                    $attributeList = rtrim($attributeList, ',');
                    $combinations[$id_product_attribute]['list'] = $attributeList;
                }
                $smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages));
            }
        }
        $smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getApplicableTax(intval($product->id_tax), 1), 'customizationFields' => $product->getCustomizationFields(intval($cookie->id_lang))));
        // Pack management
        $smarty->assign('packItems', Pack::getItemTable($product->id, intval($cookie->id_lang), true));
        $smarty->assign('packs', Pack::getPacksTable($product->id, intval($cookie->id_lang), true, 1));
    }
}
$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => intval(Configuration::get('PS_ORDER_OUT_OF_STOCK')), 'errors' => $errors, 'categories' => Category::getHomeCategories(intval($cookie->id_lang)), 'have_image' => Product::getCover(intval(Tools::getValue('id_product'))), 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => intval(Configuration::get('PS_DISPLAY_QTIES')), 'display_ht' => !Tax::excludeTaxeOption()));
if (file_exists(_PS_THEME_DIR_ . 'thickbox.tpl')) {
    $smarty->display(_PS_THEME_DIR_ . 'thickbox.tpl');
}
$smarty->assign(array('currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank));
$smarty->display(_PS_THEME_DIR_ . 'product.tpl');
include dirname(__FILE__) . '/footer.php';
Beispiel #9
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];
 }
Beispiel #10
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];
 }
 /**
  * Display the recommendations by hook
  *
  * @param string $sHookName Hook Name
  * @param array $params list of specific data
  * @return string Html
  */
 private function displayRecommendations($sHookName, $params)
 {
     if (!($this->aRecommendations[$sHookName] = $this->oPrediggoCallController->getListOfRecommendations($sHookName, $params))) {
         return false;
     }
     global $smarty;
     // Display Main Configuration management
     $smarty->assign(array('hook_name' => $sHookName, 'aRecommendations' => $this->aRecommendations, 'tax_enabled' => (int) Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption()));
     return $this->display(__FILE__, 'fo_list_reco.tpl');
 }
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
    {
        global $cart;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) {
            if ($secure_key !== false and $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            // Amount paid by customer is not the right one -> Status = payment error
            // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
            // if ($order->total_paid != $order->total_paid_real)
            // We use number_format in order to compare two string
            if (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2)) {
                $id_order_state = Configuration::get('PS_OS_ERROR');
            }
            // Creating order
            if ($cart->OrderExists() == false) {
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('PS_OS_ERROR')) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $product_price = (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, false, false);
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . $product_price . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . (double) Group::getReduction((int) $order->id_customer) . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\'),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />';
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount']);
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            $params['{firstname}'] = $customer->firstname;
                            $params['{lastname}'] = $customer->lastname;
                            $params['{id_order}'] = $order->id;
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED')) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                // Send an e-mail to customer
                if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) {
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if (Validate::isEmail($customer->email)) {
                        Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                    }
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }
Beispiel #13
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];
 }
 public function hookProductFooter($params)
 {
     global $cookie, $smarty;
     $pr = new Product($params['product']->id);
     $carriers = Carrier::getCarriers($cookie->id_lang);
     $c = array();
     foreach ($carriers as $carrier) {
         $a = new Carrier($carrier['id_carrier']);
         if (!Tax::excludeTaxeOption()) {
             $carrierTax = Tax::getCarrierTaxRate((int) $a->id);
         }
         $price = $a->getDeliveryPriceByPrice($pr->getPrice(true, null), 1) * (1 + $carrierTax / 100);
         $c[] = array('name' => $a->name, 'price' => $price);
     }
     $smarty->assign('carriers', $c);
     $smarty->assign('free', (int) Configuration::get('PS_SHIPPING_FREE_PRICE'));
     $smarty->assign(array('delivery' => $this->doruceni()));
     return $this->display(__FILE__, 'blank_deliverytime.tpl');
 }
Beispiel #15
0
 /**
  * This function returns the total cart amount
  *
  * Possible values for $type:
  * Cart::ONLY_PRODUCTS
  * Cart::ONLY_DISCOUNTS
  * Cart::BOTH
  * Cart::BOTH_WITHOUT_SHIPPING
  * Cart::ONLY_SHIPPING
  * Cart::ONLY_WRAPPING
  * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  *
  * @param bool $withTaxes With or without taxes
  * @param int $type Total type
  * @param bool $use_cache Allow using cache of the method CartRule::getContextualValue
  * @return float Order total
  */
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     // Dependencies
     $address_factory = Adapter_ServiceLocator::get('Adapter_AddressFactory');
     $price_calculator = Adapter_ServiceLocator::get('Adapter_ProductPriceCalculator');
     $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface');
     $ps_tax_address_type = $configuration->get('PS_TAX_ADDRESS_TYPE');
     $ps_use_ecotax = $configuration->get('PS_USE_ECOTAX');
     $ps_round_type = $configuration->get('PS_ROUND_TYPE');
     $ps_ecotax_tax_rules_group_id = $configuration->get('PS_ECOTAX_TAX_RULES_GROUP_ID');
     $compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_');
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
         if (is_null($products) && is_null($id_carrier)) {
             $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
         } else {
             $shipping_fees = $this->getPackageShippingCost((int) $id_carrier, (bool) $with_taxes, null, $products);
         }
     } else {
         $shipping_fees = 0;
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     $products_total = array();
     $ecotax_total = 0;
     foreach ($products as $product) {
         // products refer to the cart details
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if ($ps_tax_address_type == 'id_address_invoice') {
             $id_address = (int) $this->id_address_invoice;
         } else {
             $id_address = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!$address_factory->addressExists($id_address)) {
             $id_address = null;
         }
         // The $null variable below is not used,
         // but it is necessary to pass it to getProductPrice because
         // it expects a reference.
         $null = null;
         $price = Product::getPriceStatic((int) $product['id_product'], $with_taxes, !empty($product['delivery_date']) ? 0 : (int) $product['id_product_attribute'], 6, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $id_address, $null, $ps_use_ecotax, true, $virtual_context, NULL, $product['delivery_date'], $product['delivery_time_from'], $product['delivery_time_to']);
         $address = $address_factory->findOrCreate($id_address, true);
         if ($with_taxes) {
             $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
             $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
         } else {
             $id_tax_rules_group = 0;
         }
         if (in_array($ps_round_type, array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($products_total[$id_tax_rules_group])) {
                 $products_total[$id_tax_rules_group] = 0;
             }
         } elseif (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
             $products_total[$id_tax_rules_group . '_' . $id_address] = 0;
         }
         switch ($ps_round_type) {
             case Order::ROUND_TOTAL:
                 $products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
                 break;
             case Order::ROUND_LINE:
                 $product_price = $price * $product['cart_quantity'];
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision);
                 break;
             case Order::ROUND_ITEM:
             default:
                 $product_price = $price;
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, $compute_precision) * (int) $product['cart_quantity'];
                 break;
         }
     }
     foreach ($products_total as $key => $price) {
         $order_total += $price;
     }
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     // With PS_ATCP_SHIPWRAP on the gift wrapping cost computation calls getOrderTotal with $type === Cart::ONLY_PRODUCTS, so the flag below prevents an infinite recursion.
     $include_gift_wrapping = !$configuration->get('PS_ATCP_SHIPWRAP') || $type !== Cart::ONLY_PRODUCTS;
     if ($this->gift && $include_gift_wrapping) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), $compute_precision), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     $order_shipping_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         $flag = false;
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping && !$flag) {
                 $order_shipping_discount = (double) Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), $compute_precision);
                 $flag = true;
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), $compute_precision);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), (double) $order_total_products) + (double) $order_shipping_discount;
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, $compute_precision);
 }
Beispiel #16
0
 /**
  * Return shipping total
  *
  * @param integer $id_carrier Carrier ID (default : current carrier)
  * @return float Shipping total
  */
 function getOrderShippingCost($id_carrier = NULL, $useTax = true)
 {
     global $defaultCountry;
     if ($this->isVirtualCart()) {
         return 0;
     }
     // Checking discounts in cart
     $products = $this->getProducts();
     $discounts = $this->getDiscounts(true);
     if ($discounts) {
         foreach ($discounts as $id_discount) {
             $discount = new Discount(intval($id_discount['id_discount']));
             if (!Validate::isLoadedObject($discount)) {
                 die(Tools::displayError());
             }
             if ($discount->id_discount_type == 3) {
                 $total_cart = 0;
                 $categories = Discount::getCategories($discount->id);
                 foreach ($products as $product) {
                     if (count($categories)) {
                         if (Product::idIsOnCategoryId($product['id_product'], $categories)) {
                             $total_cart += $product['total_wt'];
                         }
                     }
                 }
                 if ($total_cart >= $discount->minimal) {
                     return 0;
                 }
             }
         }
     }
     // Order total without fees
     $orderTotal = $this->getOrderTotal(true, 7);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if ($orderTotal <= 0 and !intval(self::getNbProducts($this->id))) {
         return $shipping_cost;
     }
     // If no carrier, select default one
     if (!$id_carrier) {
         $id_carrier = $this->id_carrier;
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier(intval($id_carrier));
     }
     $carrier = self::$_carriers[$id_carrier];
     if (!Validate::isLoadedObject($carrier)) {
         die(Tools::displayError('Hack attempt: "no default carrier"'));
     }
     if (!$carrier->active) {
         return $shipping_cost;
     }
     // Get id zone
     if (isset($this->id_address_delivery) and $this->id_address_delivery) {
         $id_zone = Address::getZoneById(intval($this->id_address_delivery));
     } else {
         $id_zone = intval($defaultCountry->id_zone);
     }
     // Select carrier tax
     if ($useTax and $carrier->id_tax) {
         if (!isset(self::$_taxes[$carrier->id_tax])) {
             self::$_taxes[$carrier->id_tax] = new Tax(intval($carrier->id_tax));
         }
         $tax = self::$_taxes[$carrier->id_tax];
         if (Validate::isLoadedObject($tax) and Tax::zoneHasTax(intval($tax->id), intval($id_zone)) and !Tax::excludeTaxeOption()) {
             $carrierTax = $tax->rate;
         }
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     if (isset($configuration['PS_SHIPPING_FREE_PRICE']) and $orderTotal >= floatval($configuration['PS_SHIPPING_FREE_PRICE']) and floatval($configuration['PS_SHIPPING_FREE_PRICE']) > 0) {
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $this->getTotalWeight() >= floatval($configuration['PS_SHIPPING_FREE_WEIGHT']) and floatval($configuration['PS_SHIPPING_FREE_WEIGHT']) > 0) {
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         // Get id zone
         if (isset($this->id_address_delivery) and $this->id_address_delivery) {
             $id_zone = Address::getZoneById(intval($this->id_address_delivery));
         } else {
             $id_zone = intval($defaultCountry->id_zone);
         }
         if (Configuration::get('PS_SHIPPING_METHOD') and !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), $id_zone) or !Configuration::get('PS_SHIPPING_METHOD') and !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->getOrderTotal(true, 4), $id_zone)) {
             $shipping_cost += 0;
         } else {
             if (intval($configuration['PS_SHIPPING_METHOD'])) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
             } else {
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($orderTotal, $id_zone);
             }
         }
     } else {
         if (intval($configuration['PS_SHIPPING_METHOD'])) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($orderTotal, $id_zone);
         }
     }
     // Apply tax
     if (isset($carrierTax)) {
         $shipping_cost *= 1 + $carrierTax / 100;
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) {
         $shipping_cost += floatval($configuration['PS_SHIPPING_HANDLING']);
     }
     return floatval($shipping_cost);
 }
Beispiel #17
0
 public function getOrderShippingCostPerSellerCarrier($id_seller, $use_tax, $id_zone, $id_carrier, $carrier_amount, $carrier_weight)
 {
     $shipping_cost = 0;
     $carrier = new Carrier($id_carrier, $this->id_lang);
     if ($carrier->is_free == 1) {
         return 0;
     }
     if ($use_tax and !Tax::excludeTaxeOption()) {
         $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_FREE_WEIGHT'));
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $free_fees_weight = 0;
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT'])) {
         $free_fees_weight = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_WEIGHT'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $shipping_method = $carrier->getShippingMethod();
     if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE and $carrier_amount >= (double) $free_fees_price and (double) $free_fees_price > 0) {
     } else {
         if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT and $carrier_weight >= (double) $free_fees_weight and (double) $free_fees_weight > 0) {
         } else {
             if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $seller_shipping = $carrier->getDeliveryPriceByWeight($carrier_weight, $id_zone);
                 $shipping_cost += $seller_shipping;
             } else {
                 $seller_shipping = $carrier->getDeliveryPriceByPrice($carrier_amount, $id_zone, (int) $this->id_currency);
                 $shipping_cost += $seller_shipping;
             }
         }
     }
     $shipping_cost += $this->getAdditionalShippingCostOfSeller($id_carrier);
     if ($carrier->shipping_handling) {
         $shipping_cost += (double) Configuration::get('PS_SHIPPING_HANDLING');
     }
     if (isset($carrierTax)) {
         $shipping_cost *= 1 + $carrierTax / 100;
     }
     $shipping_cost = Tools::convertPrice($shipping_cost);
     return $shipping_cost;
 }
 public function initContentForCombinations()
 {
     ${${"GLOBALS"}["vmqqtmkyw"]} = $this->object;
     if (!Combination::isFeatureActive()) {
         $this->displayWarning($this->getMessage("This feature has been disabled, you can activate this feature at this page:") . $this->getMessage("link to Performances"));
         return;
     }
     ${"GLOBALS"}["weevwwkl"] = "product";
     if (Validate::isLoadedObject(${${"GLOBALS"}["weevwwkl"]})) {
         self::$smarty->assign("country_display_tax_label", $this->context->country->display_tax_label);
         $zsahvowoo = "lang";
         self::$smarty->assign("tax_exclude_taxe_option", Tax::excludeTaxeOption());
         self::$smarty->assign("id_tax_rules_group", $product->id_tax_rules_group);
         self::$smarty->assign("tax_rules_groups", TaxRulesGroup::getTaxRulesGroups(true));
         ${$zsahvowoo} = new Language($this->id_language);
         self::$smarty->assign("iso_code", $lang->iso_code);
         self::$smarty->assign("combinationImagesJs", $this->getCombinationImagesJs());
         if ($product->is_virtual) {
             $tpkpvyor = "product";
             self::$smarty->assign("product", ${$tpkpvyor});
             $this->displayWarning($this->getMessage("A virtual product cannot have combinations."));
         } else {
             ${"GLOBALS"}["qqjbnscylsi"] = "attribute_js";
             ${"GLOBALS"}["nqxaoftbn"] = "attribute";
             $bcesaxqdqqq = "images";
             ${"GLOBALS"}["zcxmuajd"] = "ps_stock_mvt_reason_default";
             $vmytjghdfi = "attribute_js";
             $nrkrfhirkx = "attributes";
             ${${"GLOBALS"}["qqjbnscylsi"]} = array();
             $cappytc = "k";
             ${"GLOBALS"}["jyaoxpe"] = "attribute";
             ${$nrkrfhirkx} = Attribute::getAttributes($this->context->language->id, true);
             foreach (${${"GLOBALS"}["ecblflvypvt"]} as ${$cappytc} => ${${"GLOBALS"}["jyaoxpe"]}) {
                 ${$vmytjghdfi}[${${"GLOBALS"}["iixdipeiyldv"]}["id_attribute_group"]][${${"GLOBALS"}["iixdipeiyldv"]}["id_attribute"]] = ${${"GLOBALS"}["nqxaoftbn"]}["name"];
             }
             ${"GLOBALS"}["higiwiyuxd"] = "k";
             ${${"GLOBALS"}["sxexnhlq"]} = new Currency((int) Configuration::get("PS_CURRENCY_DEFAULT"));
             self::$smarty->assign("attributeJs", ${${"GLOBALS"}["xenfvrjowsy"]});
             self::$smarty->assign("attributes_groups", AttributeGroup::getAttributesGroups($this->context->language->id));
             self::$smarty->assign("currency", ${${"GLOBALS"}["sxexnhlq"]});
             ${"GLOBALS"}["xzqtsdnlkv"] = "images";
             ${$bcesaxqdqqq} = Image::getImages($this->context->language->id, $product->id);
             self::$smarty->assign("tax_exclude_option", Tax::excludeTaxeOption());
             $rbxbrbxg = "product";
             self::$smarty->assign("ps_weight_unit", Configuration::get("PS_WEIGHT_UNIT"));
             self::$smarty->assign("ps_use_ecotax", Configuration::get("PS_USE_ECOTAX"));
             self::$smarty->assign("field_value_unity", $this->getFieldValue(${${"GLOBALS"}["vmqqtmkyw"]}, "unity"));
             ${"GLOBALS"}["vpcuib"] = "image_type";
             self::$smarty->assign("reasons", ${${"GLOBALS"}["nqegxbae"]} = StockMvtReason::getStockMvtReasons($this->context->language->id));
             self::$smarty->assign("ps_stock_mvt_reason_default", ${${"GLOBALS"}["zcxmuajd"]} = Configuration::get("PS_STOCK_MVT_REASON_DEFAULT"));
             self::$smarty->assign("minimal_quantity", $this->getFieldValue(${${"GLOBALS"}["vmqqtmkyw"]}, "minimal_quantity") ? $this->getFieldValue(${${"GLOBALS"}["vmqqtmkyw"]}, "minimal_quantity") : 1);
             self::$smarty->assign("available_date", $this->getFieldValue(${$rbxbrbxg}, "available_date") != 0 ? stripslashes(htmlentities(Tools::displayDate($this->getFieldValue(${${"GLOBALS"}["vmqqtmkyw"]}, "available_date"), version_compare(_PS_VERSION_, "1.5.5", ">=") ? null : $this->context->language->id))) : "0000-00-00");
             ${${"GLOBALS"}["tqkkuicfgax"]} = 0;
             ${"GLOBALS"}["ucamhp"] = "product";
             self::$smarty->assign("imageType", ImageType::getByNameNType("small_default", "products"));
             self::$smarty->assign("imageWidth", (isset(${${"GLOBALS"}["rvkjjxqs"]}["width"]) ? (int) ${${"GLOBALS"}["vpcuib"]}["width"] : 64) + 25);
             foreach (${${"GLOBALS"}["xzqtsdnlkv"]} as ${${"GLOBALS"}["higiwiyuxd"]} => ${${"GLOBALS"}["inpuwydsyk"]}) {
                 $cshrlmyryz = "image";
                 ${${"GLOBALS"}["dhvuermstcbs"]}[${${"GLOBALS"}["qtxqhylrbsm"]}]["obj"] = new Image(${$cshrlmyryz}["id_image"]);
                 $kcvbkys = "i";
                 ++${$kcvbkys};
             }
             self::$smarty->assign("images", ${${"GLOBALS"}["dhvuermstcbs"]});
             self::$smarty->assign(array("combinationArray" => $this->getCombinations(${${"GLOBALS"}["ucamhp"]}, ${${"GLOBALS"}["sxexnhlq"]}), "product" => ${${"GLOBALS"}["vmqqtmkyw"]}, "id_category" => $product->getDefaultCategory(), "token_generator" => "tokengenerator", "combination_exists" => Shop::isFeatureActive() && Shop::getContextShopGroup()->share_stock && count(AttributeGroup::getAttributesGroups($this->context->language->id)) > 0));
         }
     } else {
         self::$smarty->assign("product", ${${"GLOBALS"}["vmqqtmkyw"]});
         $this->displayWarning($this->getMessage("You must save this product before adding combinations."));
     }
 }
    public function displayForm($isMainTab = true)
    {
        global $currentIndex, $cookie;
        parent::displayForm();
        if (!($obj = $this->loadObject(true))) {
            return;
        }
        $currentLanguage = (int) $cookie->id_lang;
        echo '<script type="text/javascript">
			$(document).ready(function(){
				// At the loading
				($("input[name=\'is_free\']:checked").val() == 0) ? $("#shipping_costs_div").show(): $("#shipping_costs_div").hide();
			
				$("input[name=\'is_free\']").live("change", function(){
					($("input[name=\'is_free\']:checked").val() == 0) ? $("#shipping_costs_div").show(): $("#shipping_costs_div").hide();			
				});
			});
		</script>
		<form action="' . $currentIndex . '&submitAdd' . $this->table . '=1&token=' . $this->token . '" method="post" enctype="multipart/form-data">
		' . ($obj->id ? '<input type="hidden" name="id_' . $this->table . '" value="' . $obj->id . '" />' : '') . '
			<fieldset><legend><img src="../img/admin/delivery.gif" />' . $this->l('Carriers') . '</legend>
				<label>' . $this->l('Company:') . ' </label>
				<div class="margin-form">
					<input type="text" size="25" name="name" value="' . htmlentities($this->getFieldValue($obj, 'name'), ENT_COMPAT, 'UTF-8') . '" /> <sup>*</sup>
					<span class="hint" name="help_box">' . $this->l('Allowed characters: letters, spaces and') . ' ().-<span class="hint-pointer">&nbsp;</span></span>
					<p class="clear">' . $this->l('Carrier name displayed during checkout') . '<br />' . $this->l('With a value of 0, the carrier name will be replaced by the shop name') . '</p>
				</div>
				<label>' . $this->l('Logo:') . ' </label>
				<div class="margin-form">
					<input type="file" name="logo" />
					<p>' . $this->l('Upload logo from your computer') . ' (.gif, .jpg, .jpeg ' . $this->l('or') . ' .png)</p>
				</div>
				<label>' . $this->l('Transit time:') . ' </label>
				<div class="margin-form">';
        foreach ($this->_languages as $language) {
            echo '
					<div id="delay_' . $language['id_lang'] . '" style="display: ' . ($language['id_lang'] == $this->_defaultFormLanguage ? 'block' : 'none') . '; float: left;">
						<input type="text" size="41" maxlength="128" name="delay_' . $language['id_lang'] . '" value="' . htmlentities($this->getFieldValue($obj, 'delay', (int) $language['id_lang']), ENT_COMPAT, 'UTF-8') . '" /> <sup>*</sup>
					</div>';
        }
        $this->displayFlags($this->_languages, $this->_defaultFormLanguage, 'delay', 'delay');
        echo '
					<p style="clear: both">' . $this->l('Time taken for product delivery; displayed during checkout') . '</p>
				</div>
				<label>' . $this->l('URL:') . ' </label>
				<div class="margin-form">
					<input type="text" size="40" name="url" value="' . htmlentities($this->getFieldValue($obj, 'url'), ENT_COMPAT, 'UTF-8') . '" />
					<p class="clear">' . $this->l('URL for the tracking number; type \'@\' where the tracking number will appear') . '</p>
				</div>
				<label>' . $this->l('Zone') . '</label>
				<div class="margin-form">';
        $carrier_zones = $obj->getZones();
        $carrier_zones_ids = array();
        if (is_array($carrier_zones)) {
            foreach ($carrier_zones as $carrier_zone) {
                $carrier_zones_ids[] = $carrier_zone['id_zone'];
            }
        }
        $zones = Zone::getZones(false);
        foreach ($zones as $zone) {
            echo '<input type="checkbox" id="zone_' . $zone['id_zone'] . '" name="zone_' . $zone['id_zone'] . '" value="true" ' . Tools::getValue('zone_' . $zone['id_zone'], in_array($zone['id_zone'], $carrier_zones_ids) ? ' checked="checked"' : '') . '>
							<label class="t" for="zone_' . $zone['id_zone'] . '"> <b>' . $zone['name'] . '</b></label><br />';
        }
        echo '<p>' . $this->l('The zone in which this carrier is to be used') . '</p>
				</div>
				<label>' . $this->l('Group access') . '</label>
				<div class="margin-form">';
        $groups = Group::getGroups((int) $cookie->id_lang);
        if (sizeof($groups)) {
            echo '
					<table cellspacing="0" cellpadding="0" class="table" style="width: 28em;">
						<tr>
							<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'groupBox[]\', this.checked)"' . (!isset($obj->id) ? 'checked="checked" ' : '') . ' /></th>
							<th>' . $this->l('ID') . '</th>
							<th>' . $this->l('Group name') . '</th>
						</tr>';
            $irow = 0;
            foreach ($groups as $group) {
                echo '
							<tr class="' . ($irow++ % 2 ? 'alt_row' : '') . '">
								<td><input type="checkbox" name="groupBox[]" class="groupBox" id="groupBox_' . $group['id_group'] . '" value="' . $group['id_group'] . '" ' . ((Db::getInstance()->getValue('SELECT id_group FROM ' . _DB_PREFIX_ . 'carrier_group WHERE id_carrier=' . (int) $obj->id . ' AND id_group=' . (int) $group['id_group']) or !isset($obj->id)) ? 'checked="checked" ' : '') . '/></td>
								<td>' . $group['id_group'] . '</td>
								<td><label for="groupBox_' . $group['id_group'] . '" class="t">' . $group['name'] . '</label></td>
							</tr>';
            }
            echo '
					</table>
					<p style="padding:0px; margin:10px 0px 10px 0px;">' . $this->l('Mark all groups you want to give access to this carrier') . '</p>
					';
        } else {
            echo '<p>' . $this->l('No group created') . '</p>';
        }
        echo '				</div>
				<label>' . $this->l('Status:') . ' </label>
				<div class="margin-form">
					<input type="radio" name="active" id="active_on" value="1" ' . ($this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="active_on"> <img src="../img/admin/enabled.gif" alt="' . $this->l('Enabled') . '" title="' . $this->l('Enabled') . '" /></label>
					<input type="radio" name="active" id="active_off" value="0" ' . (!$this->getFieldValue($obj, 'active') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="active_off"> <img src="../img/admin/disabled.gif" alt="' . $this->l('Disabled') . '" title="' . $this->l('Disabled') . '" /></label>
					<p>' . $this->l('Include or exclude carrier from list of carriers on Front Office') . '</p>
				</div>
				<label>' . $this->l('Apply shipping cost:') . ' </label>
				<div class="margin-form">
					<input type="radio" name="is_free" id="is_free_on" value="0" ' . (!$this->getFieldValue($obj, 'is_free') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="active_on"> <img src="../img/admin/enabled.gif" alt="' . $this->l('Yes') . '" title="' . $this->l('Yes') . '" /></label>
					<input type="radio" name="is_free" id="is_free_off" value="1" ' . ($this->getFieldValue($obj, 'is_free') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="active_off"> <img src="../img/admin/disabled.gif" alt="' . $this->l('No') . '" title="' . $this->l('No') . '" /></label>
					<p>' . $this->l('Apply shipping costs and additional shipping costs by products in carrier price') . '</p>
				</div>
				<div id="shipping_costs_div">
				<label>' . $this->l('Tax') . '</label>
				<div class="margin-form">
					 <select name="id_tax_rules_group" id="id_tax_rules_group" ' . (Tax::excludeTaxeOption() ? 'disabled="disabled"' : '') . '>
					    <option value="0">' . $this->l('No Tax') . '</option>';
        foreach (TaxRulesGroup::getTaxRulesGroups(true) 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"' : '') . '>' . $tax_rules_group['name'] . '</option>';
        }
        echo '</select>
				</div>
				<label>' . $this->l('Shipping & handling:') . ' </label>
				<div class="margin-form">
					<input type="radio" name="shipping_handling" id="shipping_handling_on" value="1" ' . ($this->getFieldValue($obj, 'shipping_handling') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="shipping_handling_on"> <img src="../img/admin/enabled.gif" alt="' . $this->l('Enabled') . '" title="' . $this->l('Enabled') . '" /></label>
					<input type="radio" name="shipping_handling" id="shipping_handling_off" value="0" ' . (!$this->getFieldValue($obj, 'shipping_handling') ? 'checked="checked" ' : '') . '/>
					<label class="t" for="shipping_handling_off"> <img src="../img/admin/disabled.gif" alt="' . $this->l('Disabled') . '" title="' . $this->l('Disabled') . '" /></label>
					<p>' . $this->l('Include the shipping & handling costs in carrier price') . '</p>
				</div>
				<label>' . $this->l('Billing:') . ' </label>
				<div class="margin-form">
					<input type="radio" name="shipping_method" id="billing_default" value="' . Carrier::SHIPPING_METHOD_DEFAULT . '" ' . ($this->getFieldValue($obj, 'shipping_method') == Carrier::SHIPPING_METHOD_DEFAULT ? 'checked="checked" ' : '') . '/>
					<label class="t" for="billing_default">' . $this->l('Default behavior') . '</label><br />
					<input type="radio" name="shipping_method" id="billing_price" value="' . Carrier::SHIPPING_METHOD_PRICE . '" ' . ($this->getFieldValue($obj, 'shipping_method') == Carrier::SHIPPING_METHOD_PRICE ? 'checked="checked" ' : '') . '/>
					<label class="t" for="billing_price">' . $this->l('According to total price') . '</label><br />
					<input type="radio" name="shipping_method" id="billing_weight" value="' . Carrier::SHIPPING_METHOD_WEIGHT . '" ' . ($this->getFieldValue($obj, 'shipping_method') == Carrier::SHIPPING_METHOD_WEIGHT ? 'checked="checked" ' : '') . '/>
					<label class="t" for="billing_weight">' . $this->l('According to total weight') . '</label><br />
				</div>
				<label>' . $this->l('Out-of-range behavior:') . ' </label>
				<div class="margin-form">
					<select name="range_behavior">
						<option value="0"' . (!$this->getFieldValue($obj, 'range_behavior') ? ' selected="selected"' : '') . '>' . $this->l('Apply the cost of the highest defined range') . '</option>
						<option value="1"' . ($this->getFieldValue($obj, 'range_behavior') ? ' selected="selected"' : '') . '>' . $this->l('Disable carrier') . '</option>
					</select>
					<p>' . $this->l('Out-of-range behavior when none is defined (e.g., when a customer\'s cart weight is greater than the highest range limit)') . '</p>
				</div>';
        if ($this->getFieldValue($obj, 'is_module')) {
            echo '<label>' . $this->l('Module:') . ' </label>
						  <div class="margin-form"><p> - ' . $this->l('This carrier is bound to this module ') . ' => ' . $this->getFieldValue($obj, 'external_module_name') . '</p>
						  <input type="hidden" name="is_module" value="1">
						  <input type="hidden" name="external_module_name" value="' . $this->getFieldValue($obj, 'external_module_name') . '">';
            if ($this->getFieldValue($obj, 'shipping_external')) {
                echo '<p> - ' . $this->l('The shipping costs are calculated outside of your shop') . '</p>
						<input type="hidden" name="shipping_external" value="1">';
            }
            if ($this->getFieldValue($obj, 'need_range')) {
                echo '<p> - ' . $this->l('This carrier uses PrestaShop range to calculate shipping costs') . '</p>
						<input type="hidden" name="need_range" value="1">';
            }
            echo '</div>';
        }
        echo '</div>
				<div class="margin-form">
					<input type="submit" value="' . $this->l('   Save   ') . '" name="submitAdd' . $this->table . '" class="button" />
				</div>
				<div class="small"><sup>*</sup> ' . $this->l('Required field') . '</div>
			</fieldset>
		</form>';
    }
Beispiel #20
0
 public function getRoyalMailRates($id_zone, $is_cart, $cart, $product_weight, $dest_zip, $dest_state, $dest_country, $currency, $product, $id_product_attribute, $qty, $dest_city)
 {
     $rates = array();
     if (file_exists(dirname(__FILE__) . '/../../royalmail/classes/RateAvailableServices.php')) {
         include_once dirname(__FILE__) . '/../../royalmail/royalmail.php';
         include_once dirname(__FILE__) . '/../../royalmail/classes/RateAvailableServices.php';
         $rm = new RoyalMail();
         if ($rm->active) {
             $handling = Configuration::get('PS_SHIPPING_HANDLING');
             $carriers = $rm->getCarriers($id_zone, $cart, $is_cart, $product);
             foreach ($carriers as $carrier) {
                 if (get_parent_class($rm) == 'PrestoChangeoCarrierModule') {
                     $rm_rate = new RoyalMailRate();
                     $amount = $rm_rate->getRate($carrier['id_carrier'], $carrier['id_zone'], $is_cart != '' ? $cart->getTotalWeight() : max($product_weight, 0.001), $dest_zip, $dest_state, $dest_country, "", $is_cart != '' ? 0 : $product->getPrice(true, $id_product_attribute, 6, NULL, false, true, $qty), $is_cart != '' ? 0 : $product->id, $is_cart != '' ? 0 : $id_product_attribute, $qty);
                 } else {
                     $amount = getRoyalMailRate($carrier['id_carrier'], $carrier['id_zone'], $is_cart != '' ? $cart->getTotalWeight() : max($product_weight, 0.001), $dest_zip, $dest_country, $is_cart != '' ? 0 : $product->getPrice(true, $id_product_attribute, 6, NULL, false, true, $qty), $is_cart != '' ? 0 : $product->id);
                 }
                 // Add product spercific cost + handling fee
                 if ($amount > 0) {
                     $amount += $this->getExtraShippingCost($carrier, $handling, $is_cart != '' ? $cart->getProducts() : array(), $product, $qty);
                 }
                 // Apply shipping tax if needed
                 if (!Tax::excludeTaxeOption()) {
                     $carrierTax = Tax::getCarrierTaxRate($carrier['id_carrier']);
                 }
                 if (isset($carrierTax) && $amount !== false) {
                     $amount *= 1 + $carrierTax / 100;
                 }
                 $amount = $amount === false ? -1 : Tools::convertPrice($amount, $currency);
                 if ($amount > 0) {
                     $rates[$carrier['name']] = array(Tools::displayPrice($amount, $currency, false), $carrier['id_carrier']);
                 } elseif ($amount !== false && $amount == 0) {
                     $rates[$carrier['name']] = array($ap->l('Free!'), $carrier['id_carrier']);
                 }
             }
         }
     }
     return $rates;
 }
Beispiel #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
     $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];
 }
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit cart')
     * @param string $message Message to attach to order
     */
    function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false)
    {
        global $cart;
        $cart = new Cart(intval($id_cart));
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() === 0) {
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = intval($cart->id_carrier);
            $order->id_customer = intval($cart->id_customer);
            $order->id_address_invoice = intval($cart->id_address_invoice);
            $order->id_address_delivery = intval($cart->id_address_delivery);
            $vat_address = new Address(intval($order->id_address_delivery));
            $id_zone = Address::getZoneById(intval($vat_address->id));
            $order->id_currency = $currency_special ? intval($currency_special) : intval($cart->id_currency);
            $order->id_lang = intval($cart->id_lang);
            $order->id_cart = intval($cart->id);
            $customer = new Customer(intval($order->id_customer));
            $order->secure_key = pSQL($customer->secure_key);
            $order->payment = Tools::substr($paymentMethod, 0, 32);
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = intval($cart->gift);
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $amountPaid = !$dont_touch_amount ? Tools::ps_round(floatval($amountPaid), 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = floatval($cart->getOrderTotal(false, 1));
            $order->total_products_wt = floatval($cart->getOrderTotal(true, 1));
            $order->total_discounts = floatval(abs($cart->getOrderTotal(true, 2)));
            $order->total_shipping = floatval($cart->getOrderShippingCost());
            $order->total_wrapping = floatval(abs($cart->getOrderTotal(true, 6)));
            $order->total_paid = floatval(Tools::ps_round(floatval($cart->getOrderTotal(true, 3)), 2));
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            // Amount paid by customer is not the right one -> Status = payment error
            if ($order->total_paid != $order->total_paid_real) {
                $id_order_state = _PS_OS_ERROR_;
            }
            // Creating order
            if ($cart->OrderExists() === 0) {
                $result = $order->add();
            } else {
                die(Tools::displayError('An order has already been placed using this cart'));
            }
            // Next !
            if ($result and isset($order->id)) {
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (!Validate::isCleanHtml($message)) {
                        $message = $this->l('Payment message is not valid, please check your module!');
                    }
                    $msg->message = $message;
                    $msg->id_order = intval($order->id);
                    $msg->private = 1;
                    $msg->add();
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `product_quantity_discount`, `product_ean13`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `discount_quantity_applied`, `download_deadline`, `download_hash`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas(intval($order->id_cart));
                Product::addCustomizationPrice($products, $customizedDatas);
                foreach ($products as $key => $product) {
                    $outOfStock = false;
                    $productQuantity = intval(Product::getQuantity(intval($product['id_product']), $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL));
                    $quantityInStock = $productQuantity - intval($product['cart_quantity']) < 0 ? $productQuantity : intval($product['cart_quantity']);
                    if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) {
                        if (($updateResult = Product::updateQuantity($product)) === false or $updateResult === -1) {
                            $outOfStock = true;
                        }
                        if (!$outOfStock) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        Hook::updateQuantity($product, $order);
                    }
                    $price = Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 6, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery));
                    $price_wt = Product::getPriceStatic(intval($product['id_product']), true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery));
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct(intval($product['id_product']))) {
                        $productDownload = new ProductDownload(intval($id_product_download));
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax = 0;
                    } else {
                        $tax = Tax::getApplicableTax(intval($product['id_tax']), floatval($product['rate']), intval($order->id_address_delivery));
                    }
                    $currentDate = date('Y-m-d H:m:i');
                    if ($product['reduction_from'] != $product['reduction_to'] and ($currentDate > $product['reduction_to'] or $currentDate < $product['reduction_from'])) {
                        $reduction_percent = 0.0;
                        $reduction_amount = 0.0;
                    } else {
                        $reduction_percent = floatval($product['reduction_percent']);
                        $reduction_amount = Tools::ps_round(floatval($product['reduction_price']) / (1 + floatval($tax) / 100), 6);
                    }
                    // Quantity discount
                    $reduc = 0.0;
                    if ($product['cart_quantity'] > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($product['id_product'], $product['cart_quantity'])) {
                        $reduc = QuantityDiscount::getValue($price_wt, $qtyD->id_discount_type, $qtyD->value, new Currency(intval($order->id_currency)));
                    }
                    $query .= '(' . intval($order->id) . ',
						' . intval($product['id_product']) . ',
						' . (isset($product['id_product_attribute']) ? intval($product['id_product_attribute']) : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . intval($product['cart_quantity']) . ',
						' . $quantityInStock . ',
						' . floatval(Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, Product::getTaxCalculationMethod(intval($order->id_customer)) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery))) . ',
						' . floatval($reduction_percent) . ',
						' . floatval($reduction_amount) . ',
						' . floatval($reduc) . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . floatval($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (!$tax ? '' : pSQL($product['tax'])) . '\',
						' . floatval($tax) . ',
						' . floatval($product['ecotax']) . ',
						' . (int) QuantityDiscount::getDiscountFromQuantity(intval($product['id_product']), intval($product['cart_quantity'])) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\'),';
                    $priceWithTax = number_format($price * (($tax + 100) / 100), 2, '.', '');
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    $customizationText .= $text['name'] . $this->l(':') . ' ' . $text['value'] . ', ';
                                }
                            }
                        }
                        $customizationText = rtrim($customizationText, ', ');
                        $customizationQuantity = intval($product['customizationQuantityTotal']);
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or intval($product['cart_quantity']) > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . (intval($product['cart_quantity']) - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice((intval($product['cart_quantity']) - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td>
						</tr>';
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount(intval($discount['id_discount']));
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, 1), $order->total_shipping, $cart->id);
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $value);
                    if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">-' . Tools::displayPrice($value, $currency, false, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId(intval($cart->id));
                if ($oldMessage) {
                    $message = new Message(intval($oldMessage['id_message']));
                    $message->id_order = intval($order->id);
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState(intval($id_order_state));
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale(intval($product['id_product']), intval($product['cart_quantity']));
                        }
                    }
                }
                if (isset($outOfStock) and $outOfStock) {
                    $history = new OrderHistory();
                    $history->id_order = intval($order->id);
                    $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, intval($order->id));
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = intval($order->id);
                $new_history->changeIdOrderState(intval($id_order_state), intval($order->id));
                $new_history->addWithemail(true, $extraVars);
                // Send an e-mail to customer
                if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id) {
                    $invoice = new Address(intval($order->id_address_invoice));
                    $delivery = new Address(intval($order->id_address_delivery));
                    $carrier = new Carrier(intval($order->id_carrier));
                    $delivery_state = $delivery->id_state ? new State(intval($delivery->id_state)) : false;
                    $invoice_state = $invoice->id_state ? new State(intval($invoice->id_state)) : false;
                    $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", intval($order->id)), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), intval($order->id_lang), 1), '{carrier}' => strval($carrier->name) != '0' ? $carrier->name : Configuration::get('PS_SHOP_NAME'), '{payment}' => $order->payment, '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if (intval(Configuration::get('PS_INVOICE')) and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', intval($order->id_lang)) . sprintf('%06d', $order->invoice_number) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if ($orderStatus->send_email and Validate::isEmail($customer->email)) {
                        Mail::Send(intval($order->id_lang), 'order_conf', 'Order confirmation', $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                    }
                    $this->currentOrder = intval($order->id);
                    return true;
                }
                $this->currentOrder = intval($order->id);
                return true;
            } else {
                die(Tools::displayError('Order creation failed'));
            }
        } else {
            die(Tools::displayError('An order has already been placed using this cart'));
        }
    }
Beispiel #23
0
 public function initFormAttributes($product)
 {
     $data = $this->createTemplate($this->tpl_form);
     if (!Combination::isFeatureActive()) {
         $this->displayWarning($this->l('This feature has been disabled. ') . ' <a href="index.php?tab=AdminPerformance&token=' . Tools::getAdminTokenLite('AdminPerformance') . '#featuresDetachables">' . $this->l('Performances') . '</a>');
     } else {
         if (Validate::isLoadedObject($product)) {
             if ($this->product_exists_in_shop) {
                 if ($product->is_virtual) {
                     $data->assign('product', $product);
                     $this->displayWarning($this->l('A virtual product cannot have combinations.'));
                 } else {
                     $attribute_js = array();
                     $attributes = Attribute::getAttributes($this->context->language->id, true);
                     foreach ($attributes as $k => $attribute) {
                         $attribute_js[$attribute['id_attribute_group']][$attribute['id_attribute']] = $attribute['name'];
                     }
                     $currency = $this->context->currency;
                     $data->assign('attributeJs', $attribute_js);
                     $data->assign('attributes_groups', AttributeGroup::getAttributesGroups($this->context->language->id));
                     $data->assign('currency', $currency);
                     $images = Image::getImages($this->context->language->id, $product->id);
                     $data->assign('tax_exclude_option', Tax::excludeTaxeOption());
                     $data->assign('ps_weight_unit', Configuration::get('PS_WEIGHT_UNIT'));
                     $data->assign('ps_use_ecotax', Configuration::get('PS_USE_ECOTAX'));
                     $data->assign('field_value_unity', $this->getFieldValue($product, 'unity'));
                     $data->assign('reasons', $reasons = StockMvtReason::getStockMvtReasons($this->context->language->id));
                     $data->assign('ps_stock_mvt_reason_default', $ps_stock_mvt_reason_default = Configuration::get('PS_STOCK_MVT_REASON_DEFAULT'));
                     $data->assign('minimal_quantity', $this->getFieldValue($product, 'minimal_quantity') ? $this->getFieldValue($product, 'minimal_quantity') : 1);
                     $data->assign('available_date', $this->getFieldValue($product, 'available_date') != 0 ? stripslashes(htmlentities($this->getFieldValue($product, 'available_date'), $this->context->language->id)) : '0000-00-00');
                     $i = 0;
                     $type = ImageType::getByNameNType('%', 'products', 'height');
                     if (isset($type['name'])) {
                         $data->assign('imageType', $type['name']);
                     } else {
                         $data->assign('imageType', 'small_default');
                     }
                     $data->assign('imageWidth', (isset($image_type['width']) ? (int) $image_type['width'] : 64) + 25);
                     foreach ($images as $k => $image) {
                         $images[$k]['obj'] = new Image($image['id_image']);
                         ++$i;
                     }
                     $data->assign('images', $images);
                     $data->assign($this->tpl_form_vars);
                     $data->assign(array('list' => $this->renderListAttributes($product, $currency), 'product' => $product, 'id_category' => $product->getDefaultCategory(), 'token_generator' => Tools::getAdminTokenLite('AdminAttributeGenerator'), 'combination_exists' => Shop::isFeatureActive() && Shop::getContextShopGroup()->share_stock && count(AttributeGroup::getAttributesGroups($this->context->language->id)) > 0 && $product->hasAttributes()));
                 }
             } else {
                 $this->displayWarning($this->l('You must save the product in this shop before adding combinations.'));
             }
         } else {
             $data->assign('product', $product);
             $this->displayWarning($this->l('You must save this product before adding combinations.'));
         }
     }
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
Beispiel #24
0
 /**
  * Return package shipping cost
  *
  * @param integer $id_carrier Carrier ID (default : current carrier)
  * @param booleal $use_tax
  * @param Country $default_country
  * @param Array $product_list
  * @param array $product_list List of product concerned by the shipping. If null, all the product of the cart are used to calculate the shipping cost
  *
  * @return float Shipping total
  */
 public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null)
 {
     if ($this->isVirtualCart()) {
         return 0;
     }
     if (!$default_country) {
         $default_country = Context::getContext()->country;
     }
     $complete_product_list = $this->getProducts();
     if (is_null($product_list)) {
         $products = $complete_product_list;
     } else {
         $products = $product_list;
     }
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
         $address_id = (int) $this->id_address_invoice;
     } elseif (count($product_list)) {
         $prod = current($product_list);
         $address_id = (int) $prod['id_address_delivery'];
     } else {
         $address_id = null;
     }
     if (!Address::addressExists($address_id)) {
         $address_id = null;
     }
     $cache_id = 'getPackageShippingCost_' . (int) $this->id . '_' . (int) $address_id . '_' . (int) $id_carrier . '_' . (int) $use_tax . '_' . (int) $default_country->id;
     if ($products) {
         foreach ($products as $product) {
             $cache_id .= '_' . (int) $product['id_product'] . '_' . (int) $product['id_product_attribute'];
         }
     }
     if (Cache::isStored($cache_id)) {
         return Cache::retrieve($cache_id);
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if (!count($products)) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Get id zone
     if (!$this->isMultiAddressDelivery() && isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
         $id_zone = Address::getZoneById((int) $this->id_address_delivery);
     } else {
         if (!Validate::isLoadedObject($default_country)) {
             $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
         }
         $id_zone = (int) $default_country->id_zone;
     }
     if ($id_carrier && !$this->isCarrierInRange((int) $id_carrier, (int) $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange((int) Configuration::get('PS_CARRIER_DEFAULT'), (int) $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight((int) $id_zone) === false || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice((int) $id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), (int) $id_zone);
                 $total_order = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list);
                 $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $total_order, (int) $id_zone, (int) $this->id_currency);
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), (int) $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, (int) $id_zone, (int) $this->id_currency);
             }
             if (!isset($min_shipping_price)) {
                 $min_shipping_price = $shipping;
             }
             if ($shipping <= $min_shipping_price) {
                 $id_carrier = (int) $row['id_carrier'];
                 $min_shipping_price = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     if (!Validate::isLoadedObject($carrier)) {
         die(Tools::displayError('Fatal error: "no default carrier"'));
     }
     if (!$carrier->active) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         Cache::store($cache_id, 0);
         return 0;
     }
     // Select carrier tax
     if ($use_tax && !Tax::excludeTaxeOption()) {
         $address = Address::initialize((int) $address_id);
         $carrier_tax = $carrier->getTaxesRate($address);
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price && (double) $free_fees_price > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) && $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] && (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         // Get id zone
         if (isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             $id_zone = (int) $default_country->id_zone;
         }
         $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight((int) $carrier->id, $this->getTotalWeight(), (int) $id_zone);
         // Code Review V&V TO FINISH
         $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($carrier->id, $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list), $id_zone, (int) $this->id_currency);
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         if (!$product['is_virtual']) {
             $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
         }
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $module_name = $carrier->external_module_name;
         $module = Module::getInstanceByName($module_name);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 if (method_exists($module, 'getPackageShippingCost')) {
                     $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
                 } else {
                     $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
                 }
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 Cache::store($cache_id, false);
                 return false;
             }
         } else {
             Cache::store($cache_id, false);
             return false;
         }
     }
     // Apply tax
     if ($use_tax && isset($carrier_tax)) {
         $shipping_cost *= 1 + $carrier_tax / 100;
     }
     // ###############################################################
     $num = $this->getTotalWeight($product_list);
     $countryAndState = Address::getCountryAndState((int) $this->id_address_delivery);
     $state = $countryAndState['id_state'];
     $pri = false;
     if ($pri) {
         echo "carrierid =>" . $id_carrier . "-";
         echo 'products => ' . $num . '-';
         echo 'state => ' . $state . '-';
     }
     //Ground
     //if( $id_carrier == 21 ){
     if ($id_carrier == 31) {
         //NO CA
         if ($state == 313) {
             if ($num == 1) {
                 $shipping_cost = 19.75;
             } elseif ($num == 2) {
                 $shipping_cost = 20.5;
             } elseif ($num == 3) {
                 $shipping_cost = 22.0;
             } elseif ($num == 4) {
                 $shipping_cost = 24.5;
             } elseif ($num == 5) {
                 $shipping_cost = 25.75;
             } elseif ($num == 6) {
                 $shipping_cost = 27.0;
             } elseif ($num == 7) {
                 $shipping_cost = 30.5;
             } elseif ($num == 8) {
                 $shipping_cost = 31.5;
             } elseif ($num == 9) {
                 $shipping_cost = 32.25;
             } elseif ($num == 10) {
                 $shipping_cost = 33.5;
             } elseif ($num == 11) {
                 $shipping_cost = 34.25;
             } else {
                 $shipping_cost = 34.5;
             }
         } elseif ($state == 5 || $state == 28) {
             if ($num == 1) {
                 $shipping_cost = 19.75;
             } elseif ($num == 2) {
                 $shipping_cost = 20.5;
             } elseif ($num == 3) {
                 $shipping_cost = 22.25;
             } elseif ($num == 4) {
                 $shipping_cost = 25.25;
             } elseif ($num == 5) {
                 $shipping_cost = 26.5;
             } elseif ($num == 6) {
                 $shipping_cost = 28.0;
             } elseif ($num == 7) {
                 $shipping_cost = 32.5;
             } elseif ($num == 8) {
                 $shipping_cost = 33.25;
             } elseif ($num == 9) {
                 $shipping_cost = 34.5;
             } elseif ($num == 10) {
                 $shipping_cost = 35.25;
             } elseif ($num == 11) {
                 $shipping_cost = 36.75;
             } else {
                 $shipping_cost = 38.0;
             }
         } elseif ($state == 44 or $state == 37 or $state == 3 or $state == 47) {
             if ($num == 1) {
                 $shipping_cost = 22.75;
             } elseif ($num == 2) {
                 $shipping_cost = 23.75;
             } elseif ($num == 3) {
                 $shipping_cost = 25.0;
             } elseif ($num == 4) {
                 $shipping_cost = 25.75;
             } elseif ($num == 5) {
                 $shipping_cost = 27.5;
             } elseif ($num == 6) {
                 $shipping_cost = 28.25;
             } elseif ($num == 7) {
                 $shipping_cost = 33.25;
             } elseif ($num == 8) {
                 $shipping_cost = 34.5;
             } elseif ($num == 9) {
                 $shipping_cost = 35.5;
             } elseif ($num == 10) {
                 $shipping_cost = 36.75;
             } elseif ($num == 11) {
                 $shipping_cost = 38.0;
             } else {
                 $shipping_cost = 39.5;
             }
         } elseif ($state == 12 || $state == 26 || $state == 6 || $state == 31) {
             if ($num == 1) {
                 $shipping_cost = 23.0;
             } elseif ($num == 2) {
                 $shipping_cost = 24.5;
             } elseif ($num == 3) {
                 $shipping_cost = 25.75;
             } elseif ($num == 4) {
                 $shipping_cost = 26.5;
             } elseif ($num == 5) {
                 $shipping_cost = 28.0;
             } elseif ($num == 6) {
                 $shipping_cost = 29.5;
             } elseif ($num == 7) {
                 $shipping_cost = 34.75;
             } elseif ($num == 8) {
                 $shipping_cost = 36.75;
             } elseif ($num == 9) {
                 $shipping_cost = 38.25;
             } elseif ($num == 10) {
                 $shipping_cost = 39.5;
             } elseif ($num == 11) {
                 $shipping_cost = 41.25;
             } else {
                 $shipping_cost = 42.5;
             }
         } elseif ($state == 34 || $state == 41 || $state == 27 || $state == 16 || $state == 36 || $state == 50) {
             if ($num == 1) {
                 $shipping_cost = 24.0;
             } elseif ($num == 2) {
                 $shipping_cost = 24.75;
             } elseif ($num == 3) {
                 $shipping_cost = 26.25;
             } elseif ($num == 4) {
                 $shipping_cost = 27.75;
             } elseif ($num == 5) {
                 $shipping_cost = 30.25;
             } elseif ($num == 6) {
                 $shipping_cost = 33.25;
             } elseif ($num == 7) {
                 $shipping_cost = 38.5;
             } elseif ($num == 8) {
                 $shipping_cost = 41.25;
             } elseif ($num == 9) {
                 $shipping_cost = 44.0;
             } elseif ($num == 10) {
                 $shipping_cost = 45.75;
             } elseif ($num == 11) {
                 $shipping_cost = 47.75;
             } else {
                 $shipping_cost = 49.5;
             }
         } elseif ($state == 23 || $state == 15 || $state == 25 || $state == 4 || $state == 18 || $state == 24 || $state == 49) {
             if ($num == 1) {
                 $shipping_cost = 24.0;
             } elseif ($num == 2) {
                 $shipping_cost = 25.25;
             } elseif ($num == 3) {
                 $shipping_cost = 27.5;
             } elseif ($num == 4) {
                 $shipping_cost = 29.75;
             } elseif ($num == 5) {
                 $shipping_cost = 32.75;
             } elseif ($num == 6) {
                 $shipping_cost = 36.25;
             } elseif ($num == 7) {
                 $shipping_cost = 42.25;
             } elseif ($num == 8) {
                 $shipping_cost = 44.75;
             } elseif ($num == 9) {
                 $shipping_cost = 47.0;
             } elseif ($num == 10) {
                 $shipping_cost = 49.75;
             } elseif ($num == 11) {
                 $shipping_cost = 52.0;
             } else {
                 $shipping_cost = 54.0;
             }
         } elseif ($state == 2 || $state == 11) {
             if ($num == 1) {
                 $shipping_cost = 46.0;
             } elseif ($num == 2) {
                 $shipping_cost = 56.25;
             } elseif ($num == 3) {
                 $shipping_cost = 64.75;
             } elseif ($num == 4) {
                 $shipping_cost = 74.0;
             } elseif ($num == 5) {
                 $shipping_cost = 77.25;
             } elseif ($num == 6) {
                 $shipping_cost = 85.0;
             } elseif ($num == 7) {
                 $shipping_cost = 91.5;
             } elseif ($num == 8) {
                 $shipping_cost = 98.0;
             } elseif ($num == 9) {
                 $shipping_cost = 105.25;
             } elseif ($num == 10) {
                 $shipping_cost = 111.5;
             } elseif ($num == 11) {
                 $shipping_cost = 117.5;
             } else {
                 $shipping_cost = 124.25;
             }
         } else {
             if ($num == 1) {
                 $shipping_cost = 24.75;
             } elseif ($num == 2) {
                 $shipping_cost = 26.25;
             } elseif ($num == 3) {
                 $shipping_cost = 28.75;
             } elseif ($num == 4) {
                 $shipping_cost = 30.25;
             } elseif ($num == 5) {
                 $shipping_cost = 35.0;
             } elseif ($num == 6) {
                 $shipping_cost = 39.0;
             } elseif ($num == 7) {
                 $shipping_cost = 45.5;
             } elseif ($num == 8) {
                 $shipping_cost = 48.75;
             } elseif ($num == 9) {
                 $shipping_cost = 51.75;
             } elseif ($num == 10) {
                 $shipping_cost = 54.75;
             } elseif ($num == 11) {
                 $shipping_cost = 58.0;
             } else {
                 $shipping_cost = 60.5;
             }
         }
     } elseif ($id_carrier == 30) {
         //NO CA - 302
         if ($state == 313) {
             if ($num == 1) {
                 $shipping_cost = 24.0;
             } elseif ($num == 2) {
                 $shipping_cost = 24.75;
             } elseif ($num == 3) {
                 $shipping_cost = 25.25;
             } elseif ($num == 4) {
                 $shipping_cost = 26.25;
             } elseif ($num == 5) {
                 $shipping_cost = 27.75;
             } elseif ($num == 6) {
                 $shipping_cost = 29.75;
             } elseif ($num == 7) {
                 $shipping_cost = 32.25;
             } elseif ($num == 8) {
                 $shipping_cost = 34.5;
             } elseif ($num == 9) {
                 $shipping_cost = 36.25;
             } elseif ($num == 10) {
                 $shipping_cost = 38.0;
             } elseif ($num == 11) {
                 $shipping_cost = 40.0;
             } else {
                 $shipping_cost = 42.0;
             }
         } elseif ($state == 5 || $state == 28) {
             if ($num == 1) {
                 $shipping_cost = 24.0;
             } elseif ($num == 2) {
                 $shipping_cost = 24.75;
             } elseif ($num == 3) {
                 $shipping_cost = 25.75;
             } elseif ($num == 4) {
                 $shipping_cost = 27.75;
             } elseif ($num == 5) {
                 $shipping_cost = 30.25;
             } elseif ($num == 6) {
                 $shipping_cost = 33.5;
             } elseif ($num == 7) {
                 $shipping_cost = 38.0;
             } elseif ($num == 8) {
                 $shipping_cost = 38.5;
             } elseif ($num == 9) {
                 $shipping_cost = 40.0;
             } elseif ($num == 10) {
                 $shipping_cost = 41.75;
             } elseif ($num == 11) {
                 $shipping_cost = 45.5;
             } else {
                 $shipping_cost = 47.75;
             }
         } elseif ($state == 44 or $state == 37 or $state == 3 or $state == 47) {
             if ($num == 1) {
                 $shipping_cost = 24.75;
             } elseif ($num == 2) {
                 $shipping_cost = 25.75;
             } elseif ($num == 3) {
                 $shipping_cost = 27.0;
             } elseif ($num == 4) {
                 $shipping_cost = 30.5;
             } elseif ($num == 5) {
                 $shipping_cost = 34.0;
             } elseif ($num == 6) {
                 $shipping_cost = 36.75;
             } elseif ($num == 7) {
                 $shipping_cost = 40.25;
             } elseif ($num == 8) {
                 $shipping_cost = 42.25;
             } elseif ($num == 9) {
                 $shipping_cost = 45.25;
             } elseif ($num == 10) {
                 $shipping_cost = 47.75;
             } elseif ($num == 11) {
                 $shipping_cost = 50.75;
             } else {
                 $shipping_cost = 53.5;
             }
         } elseif ($state == 12 || $state == 26 || $state == 6 || $state == 31) {
             if ($num == 1) {
                 $shipping_cost = 24.75;
             } elseif ($num == 2) {
                 $shipping_cost = 27.75;
             } elseif ($num == 3) {
                 $shipping_cost = 29.5;
             } elseif ($num == 4) {
                 $shipping_cost = 33.5;
             } elseif ($num == 5) {
                 $shipping_cost = 38.0;
             } elseif ($num == 6) {
                 $shipping_cost = 40.75;
             } elseif ($num == 7) {
                 $shipping_cost = 45.25;
             } elseif ($num == 8) {
                 $shipping_cost = 48.0;
             } elseif ($num == 9) {
                 $shipping_cost = 52.25;
             } elseif ($num == 10) {
                 $shipping_cost = 54.25;
             } elseif ($num == 11) {
                 $shipping_cost = 57.25;
             } else {
                 $shipping_cost = 62.25;
             }
         } elseif ($state == 34 || $state == 41 || $state == 27 || $state == 16 || $state == 36 || $state == 50) {
             if ($num == 1) {
                 $shipping_cost = 25.5;
             } elseif ($num == 2) {
                 $shipping_cost = 30.5;
             } elseif ($num == 3) {
                 $shipping_cost = 36.0;
             } elseif ($num == 4) {
                 $shipping_cost = 40.25;
             } elseif ($num == 5) {
                 $shipping_cost = 47.75;
             } elseif ($num == 6) {
                 $shipping_cost = 51.25;
             } elseif ($num == 7) {
                 $shipping_cost = 56.25;
             } elseif ($num == 8) {
                 $shipping_cost = 60.25;
             } elseif ($num == 9) {
                 $shipping_cost = 65.0;
             } elseif ($num == 10) {
                 $shipping_cost = 69.5;
             } elseif ($num == 11) {
                 $shipping_cost = 74.25;
             } else {
                 $shipping_cost = 78.5;
             }
         } elseif ($state == 23 || $state == 15 || $state == 25 || $state == 4 || $state == 18 || $state == 24 || $state == 49) {
             if ($num == 1) {
                 $shipping_cost = 31.5;
             } elseif ($num == 2) {
                 $shipping_cost = 33.25;
             } elseif ($num == 3) {
                 $shipping_cost = 38.5;
             } elseif ($num == 4) {
                 $shipping_cost = 43.75;
             } elseif ($num == 5) {
                 $shipping_cost = 49.5;
             } elseif ($num == 6) {
                 $shipping_cost = 54.75;
             } elseif ($num == 7) {
                 $shipping_cost = 62.25;
             } elseif ($num == 8) {
                 $shipping_cost = 67.0;
             } elseif ($num == 9) {
                 $shipping_cost = 72.0;
             } elseif ($num == 10) {
                 $shipping_cost = 77.25;
             } elseif ($num == 11) {
                 $shipping_cost = 81.5;
             } else {
                 $shipping_cost = 86.5;
             }
         } elseif ($state == 2 || $state == 11) {
             if ($num == 1) {
                 $shipping_cost = -1;
             } elseif ($num == 2) {
                 $shipping_cost = -1;
             } elseif ($num == 3) {
                 $shipping_cost = -1;
             } elseif ($num == 4) {
                 $shipping_cost = -1;
             } elseif ($num == 5) {
                 $shipping_cost = -1;
             } elseif ($num == 6) {
                 $shipping_cost = -1;
             } elseif ($num == 7) {
                 $shipping_cost = -1;
             } elseif ($num == 8) {
                 $shipping_cost = -1;
             } elseif ($num == 9) {
                 $shipping_cost = -1;
             } elseif ($num == 10) {
                 $shipping_cost = -1;
             } elseif ($num == 11) {
                 $shipping_cost = -1;
             } else {
                 $shipping_cost = -1;
             }
         } else {
             if ($num == 1) {
                 $shipping_cost = 28.25;
             } elseif ($num == 2) {
                 $shipping_cost = 34.25;
             } elseif ($num == 3) {
                 $shipping_cost = 41.0;
             } elseif ($num == 4) {
                 $shipping_cost = 48.25;
             } elseif ($num == 5) {
                 $shipping_cost = 54.0;
             } elseif ($num == 6) {
                 $shipping_cost = 59.0;
             } elseif ($num == 7) {
                 $shipping_cost = 67.0;
             } elseif ($num == 8) {
                 $shipping_cost = 73.75;
             } elseif ($num == 9) {
                 $shipping_cost = 77.5;
             } elseif ($num == 10) {
                 $shipping_cost = 83.25;
             } elseif ($num == 11) {
                 $shipping_cost = 88.5;
             } else {
                 $shipping_cost = 93.0;
             }
         }
     } elseif ($id_carrier == 32) {
         //NO CA - 202
         if ($state == 313) {
             if ($num == 1) {
                 $shipping_cost = 23.75;
             } elseif ($num == 2) {
                 $shipping_cost = 23.75;
             } elseif ($num == 3) {
                 $shipping_cost = 26.0;
             } elseif ($num == 4) {
                 $shipping_cost = 27.5;
             } elseif ($num == 5) {
                 $shipping_cost = 29.25;
             } elseif ($num == 6) {
                 $shipping_cost = 30.75;
             } elseif ($num == 7) {
                 $shipping_cost = 34.75;
             } elseif ($num == 8) {
                 $shipping_cost = 37.5;
             } elseif ($num == 9) {
                 $shipping_cost = 40.0;
             } elseif ($num == 10) {
                 $shipping_cost = 40.75;
             } elseif ($num == 11) {
                 $shipping_cost = 43.25;
             } else {
                 $shipping_cost = 45.5;
             }
         } elseif ($state == 5 || $state == 28) {
             if ($num == 1) {
                 $shipping_cost = 23.75;
             } elseif ($num == 2) {
                 $shipping_cost = 24.25;
             } elseif ($num == 3) {
                 $shipping_cost = 28.0;
             } elseif ($num == 4) {
                 $shipping_cost = 29.25;
             } elseif ($num == 5) {
                 $shipping_cost = 31.75;
             } elseif ($num == 6) {
                 $shipping_cost = 34.75;
             } elseif ($num == 7) {
                 $shipping_cost = 38.75;
             } elseif ($num == 8) {
                 $shipping_cost = 41.25;
             } elseif ($num == 9) {
                 $shipping_cost = 43.75;
             } elseif ($num == 10) {
                 $shipping_cost = 46.25;
             } elseif ($num == 11) {
                 $shipping_cost = 48.25;
             } else {
                 $shipping_cost = 50.5;
             }
         } elseif ($state == 44 or $state == 37 or $state == 3 or $state == 47) {
             if ($num == 1) {
                 $shipping_cost = 23.75;
             } elseif ($num == 2) {
                 $shipping_cost = 25.5;
             } elseif ($num == 3) {
                 $shipping_cost = 30.75;
             } elseif ($num == 4) {
                 $shipping_cost = 33.0;
             } elseif ($num == 5) {
                 $shipping_cost = 36.25;
             } elseif ($num == 6) {
                 $shipping_cost = 40.5;
             } elseif ($num == 7) {
                 $shipping_cost = 44.75;
             } elseif ($num == 8) {
                 $shipping_cost = 46.5;
             } elseif ($num == 9) {
                 $shipping_cost = 50.25;
             } elseif ($num == 10) {
                 $shipping_cost = 52.5;
             } elseif ($num == 11) {
                 $shipping_cost = 55.25;
             } else {
                 $shipping_cost = 59.0;
             }
         } elseif ($state == 12 || $state == 26 || $state == 6 || $state == 31) {
             if ($num == 1) {
                 $shipping_cost = 27.25;
             } elseif ($num == 2) {
                 $shipping_cost = 30.75;
             } elseif ($num == 3) {
                 $shipping_cost = 36.0;
             } elseif ($num == 4) {
                 $shipping_cost = 41.0;
             } elseif ($num == 5) {
                 $shipping_cost = 46.0;
             } elseif ($num == 6) {
                 $shipping_cost = 50.5;
             } elseif ($num == 7) {
                 $shipping_cost = 57.25;
             } elseif ($num == 8) {
                 $shipping_cost = 61.75;
             } elseif ($num == 9) {
                 $shipping_cost = 65.0;
             } elseif ($num == 10) {
                 $shipping_cost = 68.75;
             } elseif ($num == 11) {
                 $shipping_cost = 72.25;
             } else {
                 $shipping_cost = 76.75;
             }
         } elseif ($state == 34 || $state == 41 || $state == 27 || $state == 16 || $state == 36 || $state == 50) {
             if ($num == 1) {
                 $shipping_cost = 29.25;
             } elseif ($num == 2) {
                 $shipping_cost = 38.75;
             } elseif ($num == 3) {
                 $shipping_cost = 46.5;
             } elseif ($num == 4) {
                 $shipping_cost = 54.75;
             } elseif ($num == 5) {
                 $shipping_cost = 62.75;
             } elseif ($num == 6) {
                 $shipping_cost = 69.75;
             } elseif ($num == 7) {
                 $shipping_cost = 77.75;
             } elseif ($num == 8) {
                 $shipping_cost = 84.25;
             } elseif ($num == 9) {
                 $shipping_cost = 90.75;
             } elseif ($num == 10) {
                 $shipping_cost = 96.75;
             } elseif ($num == 11) {
                 $shipping_cost = 105.0;
             } else {
                 $shipping_cost = 111.25;
             }
         } elseif ($state == 23 || $state == 15 || $state == 25 || $state == 4 || $state == 18 || $state == 24 || $state == 49) {
             if ($num == 1) {
                 $shipping_cost = 32.0;
             } elseif ($num == 2) {
                 $shipping_cost = 40.25;
             } elseif ($num == 3) {
                 $shipping_cost = 49.75;
             } elseif ($num == 4) {
                 $shipping_cost = 58.0;
             } elseif ($num == 5) {
                 $shipping_cost = 65.5;
             } elseif ($num == 6) {
                 $shipping_cost = 74.25;
             } elseif ($num == 7) {
                 $shipping_cost = 82.5;
             } elseif ($num == 8) {
                 $shipping_cost = 89.5;
             } elseif ($num == 9) {
                 $shipping_cost = 96.5;
             } elseif ($num == 10) {
                 $shipping_cost = 102.5;
             } elseif ($num == 11) {
                 $shipping_cost = 109.25;
             } else {
                 $shipping_cost = 116.75;
             }
         } elseif ($state == 2 || $state == 11) {
             if ($num == 1) {
                 $shipping_cost = -1;
             } elseif ($num == 2) {
                 $shipping_cost = -1;
             } elseif ($num == 3) {
                 $shipping_cost = -1;
             } elseif ($num == 4) {
                 $shipping_cost = -1;
             } elseif ($num == 5) {
                 $shipping_cost = -1;
             } elseif ($num == 6) {
                 $shipping_cost = -1;
             } elseif ($num == 7) {
                 $shipping_cost = -1;
             } elseif ($num == 8) {
                 $shipping_cost = -1;
             } elseif ($num == 9) {
                 $shipping_cost = -1;
             } elseif ($num == 10) {
                 $shipping_cost = -1;
             } elseif ($num == 11) {
                 $shipping_cost = -1;
             } else {
                 $shipping_cost = -1;
             }
         } else {
             if ($num == 1) {
                 $shipping_cost = 34.75;
             } elseif ($num == 2) {
                 $shipping_cost = 41.0;
             } elseif ($num == 3) {
                 $shipping_cost = 50.25;
             } elseif ($num == 4) {
                 $shipping_cost = 59.75;
             } elseif ($num == 5) {
                 $shipping_cost = 66.5;
             } elseif ($num == 6) {
                 $shipping_cost = 75.25;
             } elseif ($num == 7) {
                 $shipping_cost = 84.5;
             } elseif ($num == 8) {
                 $shipping_cost = 92.25;
             } elseif ($num == 9) {
                 $shipping_cost = 98.5;
             } elseif ($num == 10) {
                 $shipping_cost = 105.5;
             } elseif ($num == 11) {
                 $shipping_cost = 112.0;
             } else {
                 $shipping_cost = 119.25;
             }
         }
     } elseif ($id_carrier == 29) {
         //NO CA - 102
         if ($state == 313) {
             if ($num == 1) {
                 $shipping_cost = 27.25;
             } elseif ($num == 2) {
                 $shipping_cost = 29.0;
             } elseif ($num == 3) {
                 $shipping_cost = 32.75;
             } elseif ($num == 4) {
                 $shipping_cost = 36.25;
             } elseif ($num == 5) {
                 $shipping_cost = 38.75;
             } elseif ($num == 6) {
                 $shipping_cost = 40.75;
             } elseif ($num == 7) {
                 $shipping_cost = 45.25;
             } elseif ($num == 8) {
                 $shipping_cost = 48.25;
             } elseif ($num == 9) {
                 $shipping_cost = 50.5;
             } elseif ($num == 10) {
                 $shipping_cost = 54.75;
             } elseif ($num == 11) {
                 $shipping_cost = 56.25;
             } else {
                 $shipping_cost = 60.5;
             }
         } elseif ($state == 5 || $state == 28) {
             if ($num == 1) {
                 $shipping_cost = 31.75;
             } elseif ($num == 2) {
                 $shipping_cost = 37.5;
             } elseif ($num == 3) {
                 $shipping_cost = 39.5;
             } elseif ($num == 4) {
                 $shipping_cost = 44.25;
             } elseif ($num == 5) {
                 $shipping_cost = 48.0;
             } elseif ($num == 6) {
                 $shipping_cost = 52.75;
             } elseif ($num == 7) {
                 $shipping_cost = 56.75;
             } elseif ($num == 8) {
                 $shipping_cost = 59.5;
             } elseif ($num == 9) {
                 $shipping_cost = 65.0;
             } elseif ($num == 10) {
                 $shipping_cost = 67.5;
             } elseif ($num == 11) {
                 $shipping_cost = 71.25;
             } else {
                 $shipping_cost = 76.5;
             }
         } elseif ($state == 44 or $state == 37 or $state == 3 or $state == 47) {
             if ($num == 1) {
                 $shipping_cost = 38.75;
             } elseif ($num == 2) {
                 $shipping_cost = 47.75;
             } elseif ($num == 3) {
                 $shipping_cost = 57.75;
             } elseif ($num == 4) {
                 $shipping_cost = 64.0;
             } elseif ($num == 5) {
                 $shipping_cost = 71.25;
             } elseif ($num == 6) {
                 $shipping_cost = 80.75;
             } elseif ($num == 7) {
                 $shipping_cost = 85.75;
             } elseif ($num == 8) {
                 $shipping_cost = 92.5;
             } elseif ($num == 9) {
                 $shipping_cost = 100.75;
             } elseif ($num == 10) {
                 $shipping_cost = 105.25;
             } elseif ($num == 11) {
                 $shipping_cost = 111.5;
             } else {
                 $shipping_cost = 117.75;
             }
         } elseif ($state == 12 || $state == 26 || $state == 6 || $state == 31) {
             if ($num == 1) {
                 $shipping_cost = 41.25;
             } elseif ($num == 2) {
                 $shipping_cost = 50.75;
             } elseif ($num == 3) {
                 $shipping_cost = 61.75;
             } elseif ($num == 4) {
                 $shipping_cost = 70.75;
             } elseif ($num == 5) {
                 $shipping_cost = 78.75;
             } elseif ($num == 6) {
                 $shipping_cost = 86.75;
             } elseif ($num == 7) {
                 $shipping_cost = 91.5;
             } elseif ($num == 8) {
                 $shipping_cost = 99.0;
             } elseif ($num == 9) {
                 $shipping_cost = 105.5;
             } elseif ($num == 10) {
                 $shipping_cost = 113.0;
             } elseif ($num == 11) {
                 $shipping_cost = 119.75;
             } else {
                 $shipping_cost = 126.5;
             }
         } elseif ($state == 34 || $state == 41 || $state == 27 || $state == 16 || $state == 36 || $state == 50) {
             if ($num == 1) {
                 $shipping_cost = 46.75;
             } elseif ($num == 2) {
                 $shipping_cost = 53.75;
             } elseif ($num == 3) {
                 $shipping_cost = 67.25;
             } elseif ($num == 4) {
                 $shipping_cost = 77.0;
             } elseif ($num == 5) {
                 $shipping_cost = 83.75;
             } elseif ($num == 6) {
                 $shipping_cost = 93.0;
             } elseif ($num == 7) {
                 $shipping_cost = 100.25;
             } elseif ($num == 8) {
                 $shipping_cost = 103.0;
             } elseif ($num == 9) {
                 $shipping_cost = 112.25;
             } elseif ($num == 10) {
                 $shipping_cost = 120.5;
             } elseif ($num == 11) {
                 $shipping_cost = 126.25;
             } else {
                 $shipping_cost = 132.0;
             }
         } elseif ($state == 23 || $state == 15 || $state == 25 || $state == 4 || $state == 18 || $state == 24 || $state == 49) {
             if ($num == 1) {
                 $shipping_cost = 49.25;
             } elseif ($num == 2) {
                 $shipping_cost = 56.25;
             } elseif ($num == 3) {
                 $shipping_cost = 69.0;
             } elseif ($num == 4) {
                 $shipping_cost = 79.25;
             } elseif ($num == 5) {
                 $shipping_cost = 88.25;
             } elseif ($num == 6) {
                 $shipping_cost = 95.75;
             } elseif ($num == 7) {
                 $shipping_cost = 101.5;
             } elseif ($num == 8) {
                 $shipping_cost = 109.25;
             } elseif ($num == 9) {
                 $shipping_cost = 116.0;
             } elseif ($num == 10) {
                 $shipping_cost = 123.25;
             } elseif ($num == 11) {
                 $shipping_cost = 130.0;
             } else {
                 $shipping_cost = 138.75;
             }
         } elseif ($state == 2 || $state == 11) {
             if ($num == 1) {
                 $shipping_cost = 53.75;
             } elseif ($num == 2) {
                 $shipping_cost = 67.5;
             } elseif ($num == 3) {
                 $shipping_cost = 78.75;
             } elseif ($num == 4) {
                 $shipping_cost = 85.5;
             } elseif ($num == 5) {
                 $shipping_cost = 96.75;
             } elseif ($num == 6) {
                 $shipping_cost = 101.5;
             } elseif ($num == 7) {
                 $shipping_cost = 116.25;
             } elseif ($num == 8) {
                 $shipping_cost = 130.0;
             } elseif ($num == 9) {
                 $shipping_cost = 142.5;
             } elseif ($num == 10) {
                 $shipping_cost = 152.5;
             } elseif ($num == 11) {
                 $shipping_cost = 159.75;
             } else {
                 $shipping_cost = 168.25;
             }
         } else {
             if ($num == 1) {
                 $shipping_cost = 50.75;
             } elseif ($num == 2) {
                 $shipping_cost = 60.5;
             } elseif ($num == 3) {
                 $shipping_cost = 70.5;
             } elseif ($num == 4) {
                 $shipping_cost = 81.0;
             } elseif ($num == 5) {
                 $shipping_cost = 90.25;
             } elseif ($num == 6) {
                 $shipping_cost = 98.5;
             } elseif ($num == 7) {
                 $shipping_cost = 104.5;
             } elseif ($num == 8) {
                 $shipping_cost = 113.0;
             } elseif ($num == 9) {
                 $shipping_cost = 119.25;
             } elseif ($num == 10) {
                 $shipping_cost = 127.0;
             } elseif ($num == 11) {
                 $shipping_cost = 133.75;
             } else {
                 $shipping_cost = 139.75;
             }
         }
     } elseif ($id_carrier == 16) {
         //NO CA
         if ($state == 313) {
             if ($num == 1) {
                 $shipping_cost = 11.0;
             } elseif ($num == 2) {
                 $shipping_cost = 12.0;
             } elseif ($num == 3) {
                 $shipping_cost = 12.75;
             } elseif ($num == 4) {
                 $shipping_cost = 14.75;
             } elseif ($num == 5) {
                 $shipping_cost = 15.75;
             } elseif ($num == 6) {
                 $shipping_cost = 16.0;
             } elseif ($num == 7) {
                 $shipping_cost = 19.0;
             } elseif ($num == 8) {
                 $shipping_cost = 19.25;
             } elseif ($num == 9) {
                 $shipping_cost = 20.0;
             } elseif ($num == 10) {
                 $shipping_cost = 20.75;
             } elseif ($num == 11) {
                 $shipping_cost = 22.0;
             } else {
                 $shipping_cost = 22.25;
             }
         } elseif ($state == 314) {
             if ($num == 1) {
                 $shipping_cost = 11.75;
             } elseif ($num == 2) {
                 $shipping_cost = 12.5;
             } elseif ($num == 3) {
                 $shipping_cost = 13.75;
             } elseif ($num == 4) {
                 $shipping_cost = 14.75;
             } elseif ($num == 5) {
                 $shipping_cost = 16.0;
             } elseif ($num == 6) {
                 $shipping_cost = 16.75;
             } elseif ($num == 7) {
                 $shipping_cost = 20.0;
             } elseif ($num == 8) {
                 $shipping_cost = 20.75;
             } elseif ($num == 9) {
                 $shipping_cost = 22.0;
             } elseif ($num == 10) {
                 $shipping_cost = 22.75;
             } elseif ($num == 11) {
                 $shipping_cost = 24.0;
             } else {
                 $shipping_cost = 24.0;
             }
         } elseif ($state == 315) {
             if ($num == 1) {
                 $shipping_cost = 12.25;
             } elseif ($num == 2) {
                 $shipping_cost = 13.75;
             } elseif ($num == 3) {
                 $shipping_cost = 14.5;
             } elseif ($num == 4) {
                 $shipping_cost = 15.75;
             } elseif ($num == 5) {
                 $shipping_cost = 16.5;
             } elseif ($num == 6) {
                 $shipping_cost = 17.0;
             } elseif ($num == 7) {
                 $shipping_cost = 20.5;
             } elseif ($num == 8) {
                 $shipping_cost = 22.0;
             } elseif ($num == 9) {
                 $shipping_cost = 22.75;
             } elseif ($num == 10) {
                 $shipping_cost = 24.0;
             } elseif ($num == 11) {
                 $shipping_cost = 25.25;
             } else {
                 $shipping_cost = 26.0;
             }
         } elseif ($state == 3 || $state == 28) {
             if ($num == 1) {
                 $shipping_cost = 12.25;
             } elseif ($num == 2) {
                 $shipping_cost = 14.0;
             } elseif ($num == 3) {
                 $shipping_cost = 14.75;
             } elseif ($num == 4) {
                 $shipping_cost = 16.25;
             } elseif ($num == 5) {
                 $shipping_cost = 17.75;
             } elseif ($num == 6) {
                 $shipping_cost = 18.75;
             } elseif ($num == 7) {
                 $shipping_cost = 22.5;
             } elseif ($num == 8) {
                 $shipping_cost = 24.0;
             } elseif ($num == 9) {
                 $shipping_cost = 25.25;
             } elseif ($num == 10) {
                 $shipping_cost = 26.75;
             } elseif ($num == 11) {
                 $shipping_cost = 28.25;
             } else {
                 $shipping_cost = 29.0;
             }
         } else {
             if ($num == 1) {
                 $shipping_cost = -1;
             } elseif ($num == 2) {
                 $shipping_cost = -1;
             } elseif ($num == 3) {
                 $shipping_cost = -1;
             } elseif ($num == 4) {
                 $shipping_cost = -1;
             } elseif ($num == 5) {
                 $shipping_cost = -1;
             } elseif ($num == 6) {
                 $shipping_cost = -1;
             } elseif ($num == 7) {
                 $shipping_cost = -1;
             } elseif ($num == 8) {
                 $shipping_cost = -1;
             } elseif ($num == 9) {
                 $shipping_cost = -1;
             } elseif ($num == 10) {
                 $shipping_cost = -1;
             } elseif ($num == 11) {
                 $shipping_cost = -1;
             } else {
                 $shipping_cost = -1;
             }
         }
     }
     //###############################################################
     $shipping_cost = (double) Tools::ps_round((double) $shipping_cost, 2);
     Cache::store($cache_id, $shipping_cost);
     return $shipping_cost;
 }
Beispiel #25
0
    public static function getPriceStatic($id_product, $usetax = true, $id_product_attribute = null, $decimals = 6, $divisor = null, $only_reduc = false, $usereduc = true, $quantity = 1, $force_associated_tax = false, $id_customer = null, $id_cart = null, $id_address = null, &$specific_price_output = null, $with_ecotax = true, $use_group_reduction = true, Context $context = null, $use_customer_price = true)
    {
        if (!$context) {
            $context = Context::getContext();
        }
        $cur_cart = $context->cart;
        if ($divisor !== null) {
            Tools::displayParameterAsDeprecated('divisor');
        }
        if (!Validate::isBool($usetax) || !Validate::isUnsignedId($id_product)) {
            die(Tools::displayError());
        }
        $id_group = null;
        if ($id_customer) {
            $id_group = Customer::getDefaultGroupId((int) $id_customer);
        }
        if (!$id_group) {
            $id_group = (int) Group::getCurrent()->id;
        }
        if (!is_object($cur_cart) || Validate::isUnsignedInt($id_cart) && $id_cart && $cur_cart->id != $id_cart) {
            /*
             * When a user (e.g., guest, customer, Google...) is on PrestaShop, he has already its cart as the global (see /init.php)
             * When a non-user calls directly this method (e.g., payment module...) is on PrestaShop, he does not have already it BUT knows the cart ID
             * When called from the back office, cart ID can be inexistant
             */
            if (!$id_cart && !isset($context->employee)) {
                die(Tools::displayError());
            }
            $cur_cart = new Cart($id_cart);
            if (!Validate::isLoadedObject($context->cart)) {
                $context->cart = $cur_cart;
            }
        }
        $qty = $quantity;
        if (is_array($quantity)) {
            $quantity = PP::resolveQty($qty[0], $qty[1]);
        }
        $cart_quantity = 0;
        if ((int) $id_cart) {
            $cache_id = 'Product::getPriceStatic_' . (int) $id_product . '-' . (int) $id_cart;
            if (!Cache::isStored($cache_id) || ($cart_quantity = Cache::retrieve($cache_id) != (double) $quantity)) {
                $sql = 'SELECT SUM(' . PP::sqlQty('quantity') . ')
				FROM `' . _DB_PREFIX_ . 'cart_product`
				WHERE `id_product` = ' . (int) $id_product . '
				AND `id_cart` = ' . (int) $id_cart;
                $cart_quantity = (double) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
                Cache::store($cache_id, $cart_quantity);
            }
            $cart_quantity = Cache::retrieve($cache_id);
        }
        $id_currency = (int) Validate::isLoadedObject($context->currency) ? $context->currency->id : Configuration::get('PS_CURRENCY_DEFAULT');
        $id_country = (int) $context->country->id;
        $id_state = 0;
        $zipcode = 0;
        if (!$id_address && Validate::isLoadedObject($cur_cart)) {
            $id_address = $cur_cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
        }
        if ($id_address) {
            $address_infos = Address::getCountryAndState($id_address);
            if ($address_infos['id_country']) {
                $id_country = (int) $address_infos['id_country'];
                $id_state = (int) $address_infos['id_state'];
                $zipcode = $address_infos['postcode'];
            }
        } elseif (isset($context->customer->geoloc_id_country)) {
            $id_country = (int) $context->customer->geoloc_id_country;
            $id_state = (int) $context->customer->id_state;
            $zipcode = $context->customer->postcode;
        }
        if (Tax::excludeTaxeOption()) {
            $usetax = false;
        }
        if ($usetax != false && !empty($address_infos['vat_number']) && $address_infos['id_country'] != Configuration::get('VATNUMBER_COUNTRY') && Configuration::get('VATNUMBER_MANAGEMENT')) {
            $usetax = false;
        }
        if (is_null($id_customer) && Validate::isLoadedObject($context->customer)) {
            $id_customer = $context->customer->id;
        }
        return Product::priceCalculation($context->shop->id, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $qty, $usetax, $decimals, $only_reduc, $usereduc, $with_ecotax, $specific_price_output, $use_group_reduction, $id_customer, $use_customer_price, $id_cart, $cart_quantity);
    }
 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;
             }
             $group_reduction = (100 - Group::getReduction((int) self::$cookie->id_customer)) / 100;
             $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'));
             // 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);
             }
             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, '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' => $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']]['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')));
 }
Beispiel #27
0
 /**
  * Apply tax to the product
  * @param object $order
  * @param array $product
  */
 protected function setProductTax(Order $order, $product)
 {
     $this->ecotax = Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency));
     // Exclude VAT
     if (!Tax::excludeTaxeOption()) {
         $this->setContext((int) $product['id_shop']);
         $this->id_tax_rules_group = (int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $this->context);
         $tax_manager = TaxManagerFactory::getManager($this->vat_address, $this->id_tax_rules_group);
         $this->tax_calculator = $tax_manager->getTaxCalculator();
         $this->tax_computation_method = (int) $this->tax_calculator->computation_method;
     }
     $this->ecotax_tax_rate = 0;
     if (!empty($product['ecotax'])) {
         $this->ecotax_tax_rate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     }
 }
    function displayFormAttributes($obj, $languages, $defaultLanguage)
    {
        global $currentIndex, $cookie;
        $attributeJs = array();
        $attributes = Attribute::getAttributes((int) $cookie->id_lang, true);
        foreach ($attributes as $k => $attribute) {
            $attributeJs[$attribute['id_attribute_group']][$attribute['id_attribute']] = $attribute['name'];
        }
        $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
        $attributes_groups = AttributeGroup::getAttributesGroups((int) $cookie->id_lang);
        $default_country = new Country((int) Configuration::get('PS_COUNTRY_DEFAULT'));
        $images = Image::getImages((int) $cookie->id_lang, $obj->id);
        if ($obj->id) {
            echo '
			<script type="text/javascript">
				$(document).ready(function(){
					$(\'#id_mvt_reason\').change(function(){
						updateMvtStatus($(this).val());
					});
					updateMvtStatus($(this).val());
				});
			</script>
			<table cellpadding="5">
				<tr>
					<td colspan="2"><b>' . $this->l('Add or modify combinations for this product') . '</b> -
					&nbsp;<a href="index.php?tab=AdminCatalog&id_product=' . $obj->id . '&id_category=' . (int) Tools::getValue('id_category') . '&attributegenerator&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (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/appearance.gif" alt="combinations_generator" class="middle" title="' . $this->l('Product combinations generator') . '" />&nbsp;' . $this->l('Product combinations generator') . '</a>
					</td>
				</tr>
			</table>
			<hr style="width:100%;" /><br />
			<table cellpadding="5" style="width:100%">
			<tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" valign="top">' . $this->l('Group:') . '</td>
			  <td style="padding-bottom:5px;"><select name="attribute_group" id="attribute_group" style="width: 200px;" onchange="populate_attrs();">';
            if (isset($attributes_groups)) {
                foreach ($attributes_groups as $k => $attribute_group) {
                    if (isset($attributeJs[$attribute_group['id_attribute_group']])) {
                        echo '
							<option value="' . $attribute_group['id_attribute_group'] . '">
							' . htmlentities(stripslashes($attribute_group['name']), ENT_COMPAT, 'UTF-8') . '&nbsp;&nbsp;</option>';
                    }
                }
            }
            echo '
				</select></td>
		  </tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" valign="top">' . $this->l('Attribute:') . '</td>
			  <td style="padding-bottom:5px;"><select name="attribute" id="attribute" style="width: 200px;">
			  <option value="0">---</option>
			  </select>
			  <script type="text/javascript" language="javascript">populate_attrs();</script>
			  </td>
		  </tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" valign="top">
			  <input style="width: 140px; margin-bottom: 10px;" type="button" value="' . $this->l('Add') . '" class="button" onclick="add_attr();"/><br />
			  <input style="width: 140px;" type="button" value="' . $this->l('Delete') . '" class="button" onclick="del_attr()"/></td>
			  <td align="left">
				  <select id="product_att_list" name="attribute_combinaison_list[]" multiple="multiple" size="4" style="width: 320px;"></select>
				</td>
		  </tr>
		  <tr><td colspan="2"><hr style="width:100%;" /></td></tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Reference:') . '</td>
			  <td style="padding-bottom:5px;">
				<input size="55" type="text" id="attribute_reference" name="attribute_reference" value="" style="width: 130px; margin-right: 44px;" />
				' . $this->l('EAN13:') . '<input size="55" maxlength="13" type="text" id="attribute_ean13" name="attribute_ean13" value="" style="width: 110px; margin-left: 10px; margin-right: 44px;" />
				' . $this->l('UPC:') . '<input size="55" maxlength="12" type="text" id="attribute_upc" name="attribute_upc" value="" 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 style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Supplier Reference:') . '</td>
			  <td style="padding-bottom:5px;">
				<input size="55" type="text" id="attribute_supplier_reference" name="attribute_supplier_reference" value="" style="width: 130px; margin-right: 44px;" />
				' . $this->l('Location:') . '<input size="55" type="text" id="attribute_location" name="attribute_location" value="" 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 colspan="2"><hr style="width:100%;" /></td></tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Wholesale price:') . '</td>
			  <td style="padding-bottom:5px;">' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<input type="text" size="6"  name="attribute_wholesale_price" id="attribute_wholesale_price" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' (' . $this->l('overrides Wholesale price on Information tab') . ')</td>
		  </tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Impact on price:') . '</td>
			  <td colspan="2" style="padding-bottom:5px;">
				<select name="attribute_price_impact" id="attribute_price_impact" style="width: 140px;" onchange="check_impact(); calcImpactPriceTI();">
				  <option value="0">' . $this->l('None') . '</option>
				  <option value="1">' . $this->l('Increase') . '</option>
				  <option value="-1">' . $this->l('Reduction') . '</option>
				</select>
				<span id="span_impact">&nbsp;&nbsp;' . $this->l('of') . '&nbsp;&nbsp;' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '
					<input type="text" size="6" name="attribute_price" id="attribute_price" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\'); calcImpactPriceTI();"/>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '');
            if ($default_country->display_tax_label) {
                echo ' ' . $this->l('(tax excl.)') . '<span ' . (Tax::excludeTaxeOption() ? 'style="display:none"' : '') . '> ' . $this->l('or') . ' ' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '
							<input type="text" size="6" name="attribute_priceTI" id="attribute_priceTI" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\'); calcImpactPriceTE();"/>' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' ' . $this->l('(tax incl.)') . '</span> ' . $this->l('final product price will be set to') . ' ' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<span id="attribute_new_total_price">0.00</span>' . ($currency->format % 2 == 0 ? $currency->sign . ' ' : '');
            }
            echo '
				</span>
			</td>
		  </tr>
		  <tr>
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Impact on weight:') . '</td>
			  <td colspan="2" style="padding-bottom:5px;"><select name="attribute_weight_impact" id="attribute_weight_impact" style="width: 140px;" onchange="check_weight_impact();">
			  <option value="0">' . $this->l('None') . '</option>
			  <option value="1">' . $this->l('Increase') . '</option>
			  <option value="-1">' . $this->l('Reduction') . '</option>
			  </select>
			  <span id="span_weight_impact">&nbsp;&nbsp;' . $this->l('of') . '&nbsp;&nbsp;
				<input type="text" size="6" name="attribute_weight" id="attribute_weight" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" /> ' . Configuration::get('PS_WEIGHT_UNIT') . '</span></td>
		  </tr>
		  <tr id="tr_unit_impact">
			  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Impact on unit price :') . '</td>
			  <td colspan="2" style="padding-bottom:5px;"><select name="attribute_unit_impact" id="attribute_unit_impact" style="width: 140px;" onchange="check_unit_impact();">
			  <option value="0">' . $this->l('None') . '</option>
			  <option value="1">' . $this->l('Increase') . '</option>
			  <option value="-1">' . $this->l('Reduction') . '</option>
			  </select>
			  <span id="span_unit_impact">&nbsp;&nbsp;' . $this->l('of') . '&nbsp;&nbsp;' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '
				<input type="text" size="6" name="attribute_unity" id="attribute_unity" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' / <span id="unity_third">' . $this->getFieldValue($obj, 'unity') . '</span>
			</span></td>
		  </tr>';
            if (Configuration::get('PS_USE_ECOTAX')) {
                echo '
				  <tr>
					  <td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;">' . $this->l('Eco-tax:') . '</td>
					  <td style="padding-bottom:5px;">' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . '<input type="text" size="3" name="attribute_ecotax" id="attribute_ecotax" value="0.00" onKeyUp="if (isArrowKey(event)) return ;this.value = this.value.replace(/,/g, \'.\');" />' . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . ' (' . $this->l('overrides Eco-tax on Information tab') . ')</td>
				  </tr>';
            }
            echo '
		  <tr id="initial_stock_attribute">
				<td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" class="col-left">' . $this->l('Initial stock:') . '</td>
				<td><input type="text" name="attribute_quantity" size="3" maxlength="10" value="0"/></td>
		  </tr>
		  </tr>
			<tr id="stock_mvt_attribute" style="display:none;">
				<td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" 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 type="text" name="attribute_mvt_quantity" size="3" maxlength="10" value="0"/>&nbsp;&nbsp;
					<span style="display:none;" id="mvt_sign"></span>
					<br />
					<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>
			<tr>
			<td style="width:150px;vertical-align:top;text-align:right;padding-right:10px;font-weight:bold;" class="col-left">' . $this->l('Minimum quantity:') . '</td>
				<td style="padding-bottom:5px;">
					<input size="3" maxlength="10" name="attribute_minimal_quantity" id="attribute_minimal_quantity" type="text" value="' . ($this->getFieldValue($obj, 'attribute_minimal_quantity') ? $this->getFieldValue($obj, 'attribute_minimal_quantity') : 1) . '" />
					<p>' . $this->l('The minimum quantity to buy this product (set to 1 to disable this feature)') . '</p>
				</td>
			</tr>
		  <tr style="display:none;" id="attr_qty_stock">
			  <td style="width:150px">' . $this->l('Quantity in stock:') . '</td>
			  <td style="padding-bottom:5px;"><b><span style="display:none;" id="attribute_quantity"></span></b></td>
		  </tr>
		  <tr><td colspan="2"><hr style="width:100%;" /></td></tr>
		  <tr>
			  <td style="width:150px">' . $this->l('Image:') . '</td>
			  <td style="padding-bottom:5px;">
				<ul id="id_image_attr">';
            $i = 0;
            $imageType = ImageType::getByNameNType('small', 'products');
            $imageWidth = (isset($imageType['width']) ? (int) $imageType['width'] : 64) + 25;
            foreach ($images as $image) {
                $imageObj = new Image($image['id_image']);
                echo '<li style="float: left; width: ' . $imageWidth . 'px;"><input type="checkbox" name="id_image_attr[]" value="' . (int) $image['id_image'] . '" id="id_image_attr_' . (int) $image['id_image'] . '" />
				<label for="id_image_attr_' . (int) $image['id_image'] . '" style="float: none;"><img src="' . _THEME_PROD_DIR_ . $imageObj->getExistingImgPath() . '-small.jpg" alt="' . htmlentities(stripslashes($image['legend']), ENT_COMPAT, 'UTF-8') . '" title="' . htmlentities(stripslashes($image['legend']), ENT_COMPAT, 'UTF-8') . '" /></label></li>';
                ++$i;
            }
            echo '</ul>
				<img id="pic" alt="" title="" style="display: none; width: 100px; height: 100px; float: left; border: 1px dashed #BBB; margin-left: 20px;" />
			  </td>
		  </tr>
			<tr>
			  <td style="width:150px">' . $this->l('Default:') . '<br /><br /></td>
			  <td style="padding-bottom:5px;">
				<input type="checkbox" name="attribute_default" id="attribute_default" value="1" />&nbsp;' . $this->l('Make this the default combination for this product') . '<br /><br />
			  </td>
		  </tr>
		  <tr>
			  <td style="width:150px">&nbsp;</td>
			  <td style="padding-bottom:5px;">
				<span style="float: left;"><input type="submit" name="submitProductAttribute" id="submitProductAttribute" value="' . $this->l('Add this combination') . '" class="button" onclick="attr_selectall(); this.form.action += \'&addproduct&tabs=3\';" /> </span>
				<span id="ResetSpan" style="float: left; margin-left: 8px; display: none;">
				  <input type="reset" name="ResetBtn" id="ResetBtn" onclick="init_elems(); getE(\'submitProductAttribute\').value = \'' . $this->l('Add this attributes group', __CLASS__, true) . '\';
				  getE(\'id_product_attribute\').value = 0; $(\'#ResetSpan\').slideToggle();" class="button" value="' . $this->l('Cancel modification') . '" /></span><span class="clear"></span>
			  </td>
		  </tr>
		  <tr><td colspan="2"><hr style="width:100%;" /></td></tr>
		  <tr>
			  <td colspan="2">
					<br />
					<table border="0" cellpadding="0" cellspacing="0" class="table">
						<tr>
							<th>' . $this->l('Attributes') . '</th>
							<th>' . $this->l('Impact') . '</th>
							<th>' . $this->l('Weight') . '</th>
							<th>' . $this->l('Reference') . '</th>
							<th>' . $this->l('EAN13') . '</th>
							<th>' . $this->l('UPC') . '</th>
							<th class="center">' . $this->l('Quantity') . '</th>
							<th class="center">' . $this->l('Actions') . '</th>
						</tr>';
            if ($obj->id) {
                /* Build attributes combinaisons */
                $combinaisons = $obj->getAttributeCombinaisons((int) $cookie->id_lang);
                $groups = array();
                if (is_array($combinaisons)) {
                    $combinationImages = $obj->getCombinationImages((int) $cookie->id_lang);
                    foreach ($combinaisons as $k => $combinaison) {
                        $combArray[$combinaison['id_product_attribute']]['wholesale_price'] = $combinaison['wholesale_price'];
                        $combArray[$combinaison['id_product_attribute']]['price'] = $combinaison['price'];
                        $combArray[$combinaison['id_product_attribute']]['weight'] = $combinaison['weight'];
                        $combArray[$combinaison['id_product_attribute']]['unit_impact'] = $combinaison['unit_price_impact'];
                        $combArray[$combinaison['id_product_attribute']]['reference'] = $combinaison['reference'];
                        $combArray[$combinaison['id_product_attribute']]['supplier_reference'] = $combinaison['supplier_reference'];
                        $combArray[$combinaison['id_product_attribute']]['ean13'] = $combinaison['ean13'];
                        $combArray[$combinaison['id_product_attribute']]['upc'] = $combinaison['upc'];
                        $combArray[$combinaison['id_product_attribute']]['attribute_minimal_quantity'] = $combinaison['minimal_quantity'];
                        $combArray[$combinaison['id_product_attribute']]['location'] = $combinaison['location'];
                        $combArray[$combinaison['id_product_attribute']]['quantity'] = $combinaison['quantity'];
                        $combArray[$combinaison['id_product_attribute']]['id_image'] = isset($combinationImages[$combinaison['id_product_attribute']][0]['id_image']) ? $combinationImages[$combinaison['id_product_attribute']][0]['id_image'] : 0;
                        $combArray[$combinaison['id_product_attribute']]['default_on'] = $combinaison['default_on'];
                        $combArray[$combinaison['id_product_attribute']]['ecotax'] = $combinaison['ecotax'];
                        $combArray[$combinaison['id_product_attribute']]['attributes'][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute']);
                        if ($combinaison['is_color_group']) {
                            $groups[$combinaison['id_attribute_group']] = $combinaison['group_name'];
                        }
                    }
                }
                $irow = 0;
                if (isset($combArray)) {
                    foreach ($combArray as $id_product_attribute => $product_attribute) {
                        $list = '';
                        $jsList = '';
                        /* In order to keep the same attributes order */
                        asort($product_attribute['attributes']);
                        foreach ($product_attribute['attributes'] as $attribute) {
                            $list .= addslashes(htmlspecialchars($attribute[0])) . ' - ' . addslashes(htmlspecialchars($attribute[1])) . ', ';
                            $jsList .= '\'' . addslashes(htmlspecialchars($attribute[0])) . ' : ' . addslashes(htmlspecialchars($attribute[1])) . '\', \'' . $attribute[2] . '\', ';
                        }
                        $list = rtrim($list, ', ');
                        $jsList = rtrim($jsList, ', ');
                        $attrImage = $product_attribute['id_image'] ? new Image($product_attribute['id_image']) : false;
                        echo '
						<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . ($product_attribute['default_on'] ? ' style="background-color:#D1EAEF"' : '') . '>
							<td>' . stripslashes($list) . '</td>
							<td class="right">' . ($currency->format % 2 != 0 ? $currency->sign . ' ' : '') . $product_attribute['price'] . ($currency->format % 2 == 0 ? ' ' . $currency->sign : '') . '</td>
							<td class="right">' . $product_attribute['weight'] . Configuration::get('PS_WEIGHT_UNIT') . '</td>
							<td class="right">' . $product_attribute['reference'] . '</td>
							<td class="right">' . $product_attribute['ean13'] . '</td>
							<td class="right">' . $product_attribute['upc'] . '</td>
							<td class="center">' . $product_attribute['quantity'] . '</td>
							<td class="center">
							<a style="cursor: pointer;">
							<img src="../img/admin/edit.gif" alt="' . $this->l('Modify this combination') . '"
							onclick="javascript:fillCombinaison(\'' . $product_attribute['wholesale_price'] . '\', \'' . $product_attribute['price'] . '\', \'' . $product_attribute['weight'] . '\', \'' . $product_attribute['unit_impact'] . '\', \'' . $product_attribute['reference'] . '\', \'' . $product_attribute['supplier_reference'] . '\', \'' . $product_attribute['ean13'] . '\',
							\'' . $product_attribute['quantity'] . '\', \'' . ($attrImage ? $attrImage->id : 0) . '\', Array(' . $jsList . '), \'' . $id_product_attribute . '\', \'' . $product_attribute['default_on'] . '\', \'' . $product_attribute['ecotax'] . '\', \'' . $product_attribute['location'] . '\', \'' . $product_attribute['upc'] . '\', \'' . $product_attribute['attribute_minimal_quantity'] . '\'); calcImpactPriceTI();" /></a>&nbsp;
							' . (!$product_attribute['default_on'] ? '<a href="' . $currentIndex . '&defaultProductAttribute&id_product_attribute=' . $id_product_attribute . '&id_product=' . $obj->id . '&' . (Tools::isSubmit('id_category') ? 'id_category=' . (int) Tools::getValue('id_category') . '&' : '&') . 'token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '">
							<img src="../img/admin/asterisk.gif" alt="' . $this->l('Make this the default combination') . '" title="' . $this->l('Make this combination the default one') . '"></a>' : '') . '
							<a href="' . $currentIndex . '&deleteProductAttribute&id_product_attribute=' . $id_product_attribute . '&id_product=' . $obj->id . '&' . (Tools::isSubmit('id_category') ? 'id_category=' . (int) Tools::getValue('id_category') . '&' : '&') . 'token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" onclick="return confirm(\'' . $this->l('Are you sure?', __CLASS__, true, false) . '\');">
							<img src="../img/admin/delete.gif" alt="' . $this->l('Delete this combination') . '" /></a></td>
						</tr>';
                    }
                    echo '<tr><td colspan="7" align="center"><a href="' . $currentIndex . '&deleteAllProductAttributes&id_product=' . $obj->id . '&token=' . Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee) . '" onclick="return confirm(\'' . $this->l('Are you sure?', __CLASS__, true, false) . '\');"><img src="../img/admin/delete.gif" alt="' . $this->l('Delete this combination') . '" /> ' . $this->l('Delete all combinations') . '</a></td></tr>';
                } else {
                    echo '<tr><td colspan="7" align="center"><i>' . $this->l('No combination yet') . '.</i></td></tr>';
                }
            }
            echo '
						</table>
						<br />' . $this->l('The row in blue is the default combination.') . '
						<br />
						' . $this->l('A default combination must be designated for each product.') . '
						</td>
						</tr>
					</table>
					<script type="text/javascript">
						var impact = getE(\'attribute_price_impact\');
						var impact2 = getE(\'attribute_weight_impact\');

						var s_attr_group = document.getElementById(\'span_new_group\');
						var s_attr_name = document.getElementById(\'span_new_attr\');
						var s_impact = document.getElementById(\'span_impact\');
						var s_impact2 = document.getElementById(\'span_weight_impact\');

						init_elems();
					</script>
					<hr style="width:100%;" />
					<table cellpadding="5">
						<tr>
							<td class="col-left"><b>' . $this->l('Color picker:') . '</b></td>
							<td style="padding-bottom:5px;">
								<select name="id_color_default">
								<option value="0">' . $this->l('Do not display') . '</option>';
            foreach ($attributes_groups as $k => $attribute_group) {
                if (isset($groups[$attribute_group['id_attribute_group']])) {
                    echo '<option value="' . (int) $attribute_group['id_attribute_group'] . '"
												' . ((int) $attribute_group['id_attribute_group'] == (int) $obj->id_color_default ? 'selected="selected"' : '') . '>' . htmlentities(stripslashes($attribute_group['name']), ENT_COMPAT, 'UTF-8') . '</option>';
                }
            }
            echo '
								</select>
								&nbsp;&nbsp;<input type="submit" value="' . $this->l('OK') . '" name="submitAdd' . $this->table . 'AndStay" class="button" />
								&nbsp;&nbsp;&nbsp;&nbsp;<a href="index.php?tab=AdminAttributesGroups&token=' . Tools::getAdminToken('AdminAttributesGroups' . (int) Tab::getIdFromClassName('AdminAttributesGroups') . (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/asterisk.gif" alt="" /> ' . $this->l('Color attribute management') . '</a>
								<p >' . $this->l('Activate the color choice by selecting a color attribute group.') . '</p>
							</td>
						</tr>
					</table>';
        } else {
            echo '<b>' . $this->l('You must save this product before adding combinations') . '.</b>';
        }
    }
Beispiel #29
0
 public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
 {
     if (!Configuration::get('LEGAL_SHIPTAXMETH')) {
         return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
     }
     if ($this->isVirtualCart()) {
         return 0;
     }
     if (!$default_country) {
         $default_country = Context::getContext()->country;
     }
     if (!is_null($product_list)) {
         foreach ($product_list as $key => $value) {
             if ($value['is_virtual'] == 1) {
                 unset($product_list[$key]);
             }
         }
     }
     $complete_product_list = $this->getProducts();
     if (is_null($product_list)) {
         $products = $complete_product_list;
     } else {
         $products = $product_list;
     }
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
         $address_id = (int) $this->id_address_invoice;
     } elseif (count($product_list)) {
         $prod = current($product_list);
         $address_id = (int) $prod['id_address_delivery'];
     } else {
         $address_id = null;
     }
     if (!Address::addressExists($address_id)) {
         $address_id = null;
     }
     $cache_id = 'getPackageShippingCost_' . (int) $this->id . '_' . (int) $address_id . '_' . (int) $id_carrier . '_' . (int) $use_tax . '_' . (int) $default_country->id;
     if ($products) {
         foreach ($products as $product) {
             $cache_id .= '_' . (int) $product['id_product'] . '_' . (int) $product['id_product_attribute'];
         }
     }
     if (Cache::isStored($cache_id)) {
         return Cache::retrieve($cache_id);
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if (!count($products)) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (!isset($id_zone)) {
         // Get id zone
         if (!$this->isMultiAddressDelivery() && isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             if (!Validate::isLoadedObject($default_country)) {
                 $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
             }
             $id_zone = (int) $default_country->id_zone;
         }
     }
     if ($id_carrier && !$this->isCarrierInRange((int) $id_carrier, (int) $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange((int) Configuration::get('PS_CARRIER_DEFAULT'), (int) $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     $total_package_without_shipping_tax_inc = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list);
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight((int) $id_zone) === false || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice((int) $id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), (int) $id_zone);
                 $total_order = $total_package_without_shipping_tax_inc;
                 $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $total_order, (int) $id_zone, (int) $this->id_currency);
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), (int) $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, (int) $id_zone, (int) $this->id_currency);
             }
             if (!isset($min_shipping_price)) {
                 $min_shipping_price = $shipping;
             }
             if ($shipping <= $min_shipping_price) {
                 $id_carrier = (int) $row['id_carrier'];
                 $min_shipping_price = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     // No valid Carrier or $id_carrier <= 0 ?
     if (!Validate::isLoadedObject($carrier)) {
         Cache::store($cache_id, 0);
         return 0;
     }
     if (!$carrier->active) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         Cache::store($cache_id, 0);
         return 0;
     }
     // Select carrier tax
     if ($use_tax && !Tax::excludeTaxeOption()) {
         $address = Address::initialize((int) $address_id);
         $carrier_tax = $carrier->getTaxesRate($address);
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price && (double) $free_fees_price > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) && $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] && (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         if (!isset($id_zone)) {
             // Get id zone
             if (isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
                 $id_zone = Address::getZoneById((int) $this->id_address_delivery);
             } else {
                 $id_zone = (int) $default_country->id_zone;
             }
         }
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), (int) $id_zone) || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($carrier->id, $total_package_without_shipping_tax_inc, $id_zone, (int) $this->id_currency)) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         if (!$product['is_virtual']) {
             $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
         }
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $module_name = $carrier->external_module_name;
         $module = Module::getInstanceByName($module_name);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 if (method_exists($module, 'getPackageShippingCost')) {
                     $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
                 } else {
                     $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
                 }
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 Cache::store($cache_id, false);
                 return false;
             }
         } else {
             Cache::store($cache_id, false);
             return false;
         }
     }
     $shipping_cost = (double) Tools::ps_round((double) $shipping_cost, 2);
     Cache::store($cache_id, $shipping_cost);
     return $shipping_cost;
 }
Beispiel #30
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];
 }