Example #1
0
	/**
	 * Attaches a product download asset to the price object
	 * 
	 * @since 1.1
	 *
	 * @return boolean
	 **/
	function attach_download ($id) {
		if (!$id) return false;

		$Download = new ProductDownload($id);
		$Download->parent = $this->id;
		$Download->save();

		do_action('attach_product_download',$id,$this->id);

		return true;
	}
 public function hasProductDownload($cart)
 {
     foreach ($cart->getProducts() as $product) {
         $pd = ProductDownload::getIdFromIdProduct((int) $product['id_product']);
         if ($pd and Validate::isUnsignedInt($pd)) {
             return true;
         }
     }
     return false;
 }
Example #3
0
 public function hookPayment($params)
 {
     if (!$this->active) {
         return;
     }
     global $smarty;
     // Check if cart has product download
     foreach ($params['cart']->getProducts() as $product) {
         $pd = ProductDownload::getIdFromIdProduct((int) $product['id_product']);
         if ($pd and Validate::isUnsignedInt($pd)) {
             return false;
         }
     }
     $smarty->assign(array('this_path' => $this->_path, 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     return $this->display(__FILE__, 'payment.tpl');
 }
Example #4
0
 public function hookPayment($params)
 {
     if (!$this->active) {
         return;
     }
     global $smarty;
     // Check if cart has product download
     foreach ($params['cart']->getProducts() as $product) {
         $pd = ProductDownload::getIdFromIdProduct(intval($product['id_product']));
         if ($pd and Validate::isUnsignedInt($pd)) {
             return false;
         }
     }
     $smarty->assign(array('this_path' => $this->_path, 'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     return $this->display(__FILE__, 'payment.tpl');
 }
Example #5
0
 public function initFormInformations($product)
 {
     if (!$this->default_form_language) {
         $this->getLanguages();
     }
     $data = $this->createTemplate($this->tpl_form);
     $currency = $this->context->currency;
     $data->assign('languages', $this->_languages);
     $data->assign('default_form_language', $this->default_form_language);
     $data->assign('currency', $currency);
     $this->object = $product;
     //$this->display = 'edit';
     $data->assign('product_name_redirected', Product::getProductName((int) $product->id_product_redirected, null, (int) $this->context->language->id));
     /*
      * Form for adding a virtual product like software, mp3, etc...
      */
     $product_download = new ProductDownload();
     if ($id_product_download = $product_download->getIdFromIdProduct($this->getFieldValue($product, 'id'))) {
         $product_download = new ProductDownload($id_product_download);
     }
     $product->{'productDownload'} = $product_download;
     $cache_default_attribute = (int) $this->getFieldValue($product, 'cache_default_attribute');
     $product_props = array();
     // global informations
     array_push($product_props, 'reference', 'ean13', 'upc', 'available_for_order', 'show_price', 'online_only', 'id_manufacturer');
     // specific / detailled information
     array_push($product_props, 'width', 'height', 'weight', 'active', 'is_virtual', 'cache_default_attribute', 'uploadable_files', 'text_fields');
     // prices
     array_push($product_props, 'price', 'wholesale_price', 'id_tax_rules_group', 'unit_price_ratio', 'on_sale', 'unity', 'minimum_quantity', 'additional_shipping_cost', 'available_now', 'available_later', 'available_date');
     if (Configuration::get('PS_USE_ECOTAX')) {
         array_push($product_props, 'ecotax');
     }
     foreach ($product_props as $prop) {
         $product->{$prop} = $this->getFieldValue($product, $prop);
     }
     $product->name['class'] = 'updateCurrentText';
     if (!$product->id || Configuration::get('PS_FORCE_FRIENDLY_PRODUCT')) {
         $product->name['class'] .= ' copy2friendlyUrl';
     }
     $images = Image::getImages($this->context->language->id, $product->id);
     if (is_array($images)) {
         foreach ($images as $k => $image) {
             $images[$k]['src'] = $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], $product->id . '-' . $image['id_image'], 'small_default');
         }
         $data->assign('images', $images);
     }
     $data->assign('imagesTypes', ImageType::getImagesTypes('products'));
     $product->tags = Tag::getProductTags($product->id);
     $data->assign('product_type', (int) Tools::getValue('type_product', $product->getType()));
     $data->assign('is_in_pack', (int) Pack::isPacked($product->id));
     $check_product_association_ajax = false;
     if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL) {
         $check_product_association_ajax = true;
     }
     // TinyMCE
     $iso_tiny_mce = $this->context->language->iso_code;
     $iso_tiny_mce = file_exists(_PS_ROOT_DIR_ . '/js/tiny_mce/langs/' . $iso_tiny_mce . '.js') ? $iso_tiny_mce : 'en';
     $data->assign('ad', dirname($_SERVER['PHP_SELF']));
     $data->assign('iso_tiny_mce', $iso_tiny_mce);
     $data->assign('check_product_association_ajax', $check_product_association_ajax);
     $data->assign('id_lang', $this->context->language->id);
     $data->assign('product', $product);
     $data->assign('token', $this->token);
     $data->assign('currency', $currency);
     $data->assign($this->tpl_form_vars);
     $data->assign('link', $this->context->link);
     $data->assign('PS_PRODUCT_SHORT_DESC_LIMIT', Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT') ? Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT') : 400);
     $this->tpl_form_vars['product'] = $product;
     $this->tpl_form_vars['custom_form'] = $data->fetch();
 }
Example #6
0
 public function delete()
 {
     if (!GroupReduction::deleteProductReduction($this->id)) {
         return false;
     }
     Hook::deleteProduct($this);
     if (!parent::delete() or !$this->deleteCategories(true) or !$this->deleteImages() or !$this->deleteProductAttributes() or !$this->deleteProductFeatures() or !$this->deleteTags() or !$this->deleteCartProducts() or !$this->deleteAttributesImpacts() or !$this->deleteAttachments() or !$this->deleteCustomization() or !SpecificPrice::deleteByProductId((int) $this->id) or !$this->deletePack() or !$this->deleteProductSale() or !$this->deleteSceneProducts() or !$this->deleteSearchIndexes() or !$this->deleteAccessories() or !$this->deleteFromAccessories()) {
         return false;
     }
     if ($id = ProductDownload::getIdFromIdProduct($this->id)) {
         if ($productDownload = new ProductDownload($id) and !$productDownload->delete(true)) {
             return false;
         }
     }
     return true;
 }
Example #7
0
 /**
  * @param $params
  * @return bool
  */
 public function hookPayment($params)
 {
     if (!$this->active) {
         return;
     }
     global $smarty;
     // Check if cart has product download
     $i = 0;
     $products = $params['cart']->getProducts();
     $total = count($products);
     foreach ($products as $key => $product) {
         $pd = ProductDownload::getIdFromIdProduct((int) $product['id_product']);
         if ($pd and Validate::isUnsignedInt($pd)) {
             $i++;
         }
     }
     if ($i && $total == $i) {
         return false;
     }
     $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
     $cod_fee = $cart_total_paid <= Configuration::get('COD_MINIMUM_AMOUNT') ? (double) Configuration::get('COD_FEE') : 0;
     $smarty->assign(array('this_path' => $this->_path, 'this_path_cod' => $this->_path, 'this_cod_fee' => $cod_fee, 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     return $this->display(__FILE__, 'payment.tpl');
 }
Example #8
0
 public function containsVirtualProducts()
 {
     /*
      * EU-Legal
      * is at least one virtual product in cart?
      */
     if (!ProductDownload::isFeatureActive()) {
         return false;
     }
     if (!isset(self::$_isPartlyVirtualCart[$this->id])) {
         $products = $this->getProducts();
         if (!count($products)) {
             return false;
         }
         $is_partly_virtual = 0;
         foreach ($products as $product) {
             if ($product['is_virtual']) {
                 $is_partly_virtual = 1;
             }
         }
         self::$_isPartlyVirtualCart[$this->id] = (int) $is_partly_virtual;
     }
     return self::$_isPartlyVirtualCart[$this->id];
 }
    function displayFormInformations($obj, $currency)
    {
        parent::displayForm(false);
        global $currentIndex, $cookie, $link;
        $default_country = new Country((int) Configuration::get('PS_COUNTRY_DEFAULT'));
        $iso = Language::getIsoById((int) $cookie->id_lang);
        $has_attribute = false;
        $qty_state = 'readonly';
        $qty = Attribute::getAttributeQty($this->getFieldValue($obj, 'id_product'));
        if ($qty === false) {
            if (Validate::isLoadedObject($obj)) {
                $qty = $this->getFieldValue($obj, 'quantity');
            } else {
                $qty = 1;
            }
            $qty_state = '';
        } else {
            $has_attribute = true;
        }
        $cover = Product::getCover($obj->id);
        $this->_applyTaxToEcotax($obj);
        echo '
		<div class="tab-page" id="step1">
			<h4 class="tab">1. ' . $this->l('Info.') . '</h4>
			<script type="text/javascript">
				$(document).ready(function() {
					updateCurrentText();
					updateFriendlyURL();
					$.ajax({
						url: "' . dirname($currentIndex) . '/ajax.php",
						cache: false,
						dataType: "json",
						data: "ajaxProductManufacturers=1",
						success: function(j) {
							var options = $("select#id_manufacturer").html();
							if (j)
							for (var i = 0; i < j.length; i++)
								options += \'<option value="\' + j[i].optionValue + \'">\' + j[i].optionDisplay + \'</option>\';
							$("select#id_manufacturer").html(options);
						},
						error: function(XMLHttpRequest, textStatus, errorThrown)
						{
							alert(\'Manufacturer ajax error: \'+textStatus);
						}

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

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

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

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

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

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

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

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

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

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

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

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

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

							<link rel="stylesheet" type="text/css" href="' . __PS_BASE_URI__ . 'css/jquery.autocomplete.css" />
							<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/jquery/jquery.autocomplete.js"></script>
							<div id="ajax_choose_product" style="padding:6px; padding-top:2px; width:600px;">
								<p class="clear">' . $this->l('Begin typing the first letters of the product name, then select the product from the drop-down list:') . '</p>
								<input type="text" value="" id="product_autocomplete_input" />
								<img onclick="$(this).prev().search();" style="cursor: pointer;" src="../img/admin/add.gif" alt="' . $this->l('Add an accessory') . '" title="' . $this->l('Add an accessory') . '" />
							</div>
							<script type="text/javascript">
								urlToCall = null;
								/* function autocomplete */
								$(function() {
									$(\'#product_autocomplete_input\')
										.autocomplete(\'ajax_products_list.php\', {
											minChars: 1,
											autoFill: true,
											max:20,
											matchContains: true,
											mustMatch:true,
											scroll:false,
											cacheLength:0,
											formatItem: function(item) {
												return item[1]+\' - \'+item[0];
											}
										}).result(addAccessory);
									$(\'#product_autocomplete_input\').setOptions({
										extraParams: {excludeIds : getAccessorieIds()}
									});
								});
							</script>
						</td>
					</tr>
					<tr><td colspan="2" style="padding-bottom:10px;"><hr style="width:100%;" /></td></tr>
					<tr>
						<td colspan="2" style="text-align:center;">
							<input type="submit" value="' . $this->l('Save') . '" name="submitAdd' . $this->table . '" class="button" />
							&nbsp;<input type="submit" value="' . $this->l('Save and stay') . '" name="submitAdd' . $this->table . 'AndStay" class="button" /></td>
					</tr>
				</table>
			<br />
			</div>';
        // TinyMCE
        global $cookie;
        $iso = Language::getIsoById((int) $cookie->id_lang);
        $isoTinyMCE = file_exists(_PS_ROOT_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
        $ad = dirname($_SERVER["PHP_SELF"]);
        echo '
			<script type="text/javascript">
			var iso = \'' . $isoTinyMCE . '\' ;
			var pathCSS = \'' . _THEME_CSS_DIR_ . '\' ;
			var ad = \'' . $ad . '\' ;
			</script>
			<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/tiny_mce/tiny_mce.js"></script>
			<script type="text/javascript" src="' . __PS_BASE_URI__ . 'js/tinymce.inc.js"></script>
			<script type="text/javascript">
					toggleVirtualProduct(getE(\'is_virtual_good\'));
					unitPriceWithTax(\'unit\');
			</script>';
        $categoryBox = Tools::getValue('categoryBox', array());
    }
Example #10
0
 public function init()
 {
     if (isset($this->context->employee) && $this->context->employee->isLoggedBack() && Tools::getValue('file')) {
         // Admin can directly access to file
         $filename = Tools::getValue('file');
         if (!Validate::isSha1($filename)) {
             die(Tools::displayError());
         }
         $file = _PS_DOWNLOAD_DIR_ . strval(preg_replace('/\\.{2,}/', '.', $filename));
         $filename = ProductDownload::getFilenameFromFilename(Tools::getValue('file'));
         if (empty($filename)) {
             $newFileName = Tools::getValue('filename');
             if (!empty($newFileName)) {
                 $filename = Tools::getValue('filename');
             } else {
                 $filename = 'file';
             }
         }
         if (!file_exists($file)) {
             Tools::redirect('index.php');
         }
     } else {
         if (!($key = Tools::getValue('key'))) {
             $this->displayCustomError('Invalid key.');
         }
         Tools::setCookieLanguage();
         if (!$this->context->customer->isLogged() && !Tools::getValue('secure_key') && !Tools::getValue('id_order')) {
             Tools::redirect('index.php?controller=authentication&back=get-file.php&key=' . $key);
         } else {
             if (!$this->context->customer->isLogged() && Tools::getValue('secure_key') && Tools::getValue('id_order')) {
                 $order = new Order((int) Tools::getValue('id_order'));
                 if (!Validate::isLoadedObject($order)) {
                     $this->displayCustomError('Invalid key.');
                 }
                 if ($order->secure_key != Tools::getValue('secure_key')) {
                     $this->displayCustomError('Invalid key.');
                 }
             }
         }
         /* Key format: <sha1-filename>-<hashOrder> */
         $tmp = explode('-', $key);
         if (count($tmp) != 2) {
             $this->displayCustomError('Invalid key.');
         }
         $filename = $tmp[0];
         $hash = $tmp[1];
         if (!($info = OrderDetail::getDownloadFromHash($hash))) {
             $this->displayCustomError('This product does not exist in our store.');
         }
         /* Product no more present in catalog */
         if (!isset($info['id_product_download']) || empty($info['id_product_download'])) {
             $this->displayCustomError('This product has been deleted.');
         }
         if (!file_exists(_PS_DOWNLOAD_DIR_ . $filename)) {
             $this->displayCustomError('This file no longer exists.');
         }
         if (isset($info['product_quantity_refunded']) && isset($info['product_quantity_return']) && ($info['product_quantity_refunded'] > 0 || $info['product_quantity_return'] > 0)) {
             $this->displayCustomError('This product has been refunded.');
         }
         $now = time();
         $product_deadline = strtotime($info['download_deadline']);
         if ($now > $product_deadline && $info['download_deadline'] != '0000-00-00 00:00:00') {
             $this->displayCustomError('The product deadline is in the past.');
         }
         $customer_deadline = strtotime($info['date_expiration']);
         if ($now > $customer_deadline && $info['date_expiration'] != '0000-00-00 00:00:00') {
             $this->displayCustomError('Expiration date has passed, you cannot download this product');
         }
         if ($info['download_nb'] >= $info['nb_downloadable'] && $info['nb_downloadable']) {
             $this->displayCustomError('You have reached the maximum number of allowed downloads.');
         }
         /* Access is authorized -> increment download value for the customer */
         OrderDetail::incrementDownload($info['id_order_detail']);
         $file = _PS_DOWNLOAD_DIR_ . $info['filename'];
         $filename = $info['display_filename'];
     }
     /* Detect mime content type */
     $mimeType = false;
     if (function_exists('finfo_open')) {
         $finfo = @finfo_open(FILEINFO_MIME);
         $mimeType = @finfo_file($finfo, $file);
         @finfo_close($finfo);
     } else {
         if (function_exists('mime_content_type')) {
             $mimeType = @mime_content_type($file);
         } else {
             if (function_exists('exec')) {
                 $mimeType = trim(@exec('file -b --mime-type ' . escapeshellarg($file)));
                 if (!$mimeType) {
                     $mimeType = trim(@exec('file --mime ' . escapeshellarg($file)));
                 }
                 if (!$mimeType) {
                     $mimeType = trim(@exec('file -bi ' . escapeshellarg($file)));
                 }
             }
         }
     }
     if (empty($mimeType)) {
         $bName = basename($filename);
         $bName = explode('.', $bName);
         $bName = strtolower($bName[count($bName) - 1]);
         $mimeTypes = array('ez' => 'application/andrew-inset', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'doc' => 'application/msword', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'bcpio' => 'application/x-bcpio', 'vcd' => 'application/x-cdlink', 'pgn' => 'application/x-chess-pgn', 'cpio' => 'application/x-cpio', 'csh' => 'application/x-csh', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'spl' => 'application/x-futuresplash', 'gtar' => 'application/x-gtar', 'hdf' => 'application/x-hdf', 'js' => 'application/x-javascript', 'skp' => 'application/x-koan', 'skd' => 'application/x-koan', 'skt' => 'application/x-koan', 'skm' => 'application/x-koan', 'latex' => 'application/x-latex', 'nc' => 'application/x-netcdf', 'cdf' => 'application/x-netcdf', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texinfo' => 'application/x-texinfo', 'texi' => 'application/x-texinfo', 't' => 'application/x-troff', 'tr' => 'application/x-troff', 'roff' => 'application/x-troff', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'ms' => 'application/x-troff-ms', 'ustar' => 'application/x-ustar', 'src' => 'application/x-wais-source', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => 'application/zip', 'au' => 'audio/basic', 'snd' => 'audio/basic', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'kar' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'm3u' => 'audio/x-mpegurl', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'pdb' => 'chemical/x-pdb', 'xyz' => 'chemical/x-xyz', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'ief' => 'image/ief', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tif', 'djvu' => 'image/vnd.djvu', 'djv' => 'image/vnd.djvu', 'wbmp' => 'image/vnd.wap.wbmp', 'ras' => 'image/x-cmu-raster', 'pnm' => 'image/x-portable-anymap', 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'ppm' => 'image/x-portable-pixmap', 'rgb' => 'image/x-rgb', 'xbm' => 'image/x-xbitmap', 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-windowdump', 'igs' => 'model/iges', 'iges' => 'model/iges', 'msh' => 'model/mesh', 'mesh' => 'model/mesh', 'silo' => 'model/mesh', 'wrl' => 'model/vrml', 'vrml' => 'model/vrml', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'asc' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'sgml' => 'text/sgml', 'sgm' => 'text/sgml', 'tsv' => 'text/tab-seperated-values', 'wml' => 'text/vnd.wap.wml', 'wmls' => 'text/vnd.wap.wmlscript', 'etx' => 'text/x-setext', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'mxu' => 'video/vnd.mpegurl', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'ice' => 'x-conference-xcooltalk');
         if (isset($mimeTypes[$bName])) {
             $mimeType = $mimeTypes[$bName];
         } else {
             $mimeType = 'application/octet-stream';
         }
     }
     /* Set headers for download */
     header('Content-Transfer-Encoding: binary');
     header('Content-Type: ' . $mimeType);
     header('Content-Length: ' . filesize($file));
     header('Content-Disposition: attachment; filename="' . $filename . '"');
     ob_end_flush();
     $fp = fopen($file, 'rb');
     while (!feof($fp)) {
         echo fgets($fp, 16384);
     }
     exit;
 }
 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;
     }
 }
Example #12
0
global $errors;
// Modules might throw errors into postProcess
if (!isset($errors)) {
    $errors = array();
}
if (!($id_product = intval(Tools::getValue('id_product'))) or !Validate::isUnsignedId($id_product)) {
    $errors[] = Tools::displayError('product not found');
} else {
    $product = new Product($id_product, true, intval($cookie->id_lang));
    if (!Validate::isLoadedObject($product) or !$product->active) {
        header('HTTP/1.1 404 page not found');
        $errors[] = Tools::displayError('product is no longer available');
    } elseif (!$product->checkAccess(intval($cookie->id_customer))) {
        $errors[] = Tools::displayError('you do not have access to this product');
    } else {
        $smarty->assign('virtual', ProductDownload::getIdFromIdProduct(intval($product->id)));
        /* rewrited url set */
        $rewrited_url = $link->getProductLink($product->id, $product->link_rewrite);
        /* Product pictures management */
        require_once 'images.inc.php';
        $smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
        if (Tools::isSubmit('submitCustomizedDatas')) {
            pictureUpload($product, $cart);
            textRecord($product, $cart);
            formTargetFormat();
        } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct(intval($product->id), intval(Tools::getValue('deletePicture')))) {
            $errors[] = Tools::displayError('An error occured while deleting the selected picture');
        }
        $files = $cookie->getFamily('pictures_' . intval($product->id));
        $textFields = $cookie->getFamily('textFields_' . intval($product->id));
        $smarty->assign(array('pictures' => $files, 'textFields' => $textFields));
 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')));
 }
Example #14
0
/**
 * shopp_rmv_product_download
 *
 * Remove a product download asset
 *
 * @api
 * @since 1.2
 *
 * @param int $download the product asset id
 * @return bool true on success, false on failure
 **/
function shopp_rmv_product_download($download)
{
    if (empty($download)) {
        shopp_debug(__FUNCTION__ . ' failed: download parameter required.');
        return false;
    }
    $File = new ProductDownload($download);
    if (empty($File->id)) {
        shopp_debug(__FUNCTION__ . " failed: No such product download with id {$download}.");
        return false;
    }
    return $File->delete();
}
Example #15
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     if (!$this->errors) {
         $webservice_exi = new SoapClient('http://www2.promoshop.com.mx/ws_store/service.asmx?WSDL');
         $parameter = array("ItemNumber" => $this->product->item_number, "key" => EXIMAGEN_KEY);
         $inventory = $webservice_exi->GetInventory($parameter);
         if (isset($inventory->GetInventoryResult->InventoryData->SKU)) {
             $inventory = $inventory->GetInventoryResult;
         } else {
             $inventory = $inventory->GetInventoryResult->InventoryData;
         }
         $quote_table = "";
         $decoration_list = '';
         $decoration = json_decode($this->product->decoration_details);
         if (!isset($decoration->areasimp->ItemNumber)) {
             $decoration = $decoration->areasimp;
         }
         foreach ($decoration as $deco) {
             $decoration_list .= $deco->TecnicaFull . ', ';
         }
         $decoration_list = substr($decoration_list, 0, -2);
         if ($this->product->quick_quote != '') {
             $quote = json_decode($this->product->quick_quote);
             //var_dump($this->product->quick_quote);
             foreach ($quote->PricesArray->Prices as $price) {
                 $quote_table .= "<tr><td>" . $price->Piezas;
                 $precio = explode('.', $price->Precio);
                 $precio_imp = explode('.', $price->PrecioImp);
                 if (intval($price->Piezas) < 10) {
                     $quote_table .= " Muestra";
                 } else {
                     $quote_table .= " Piezas";
                 }
                 $quote_table .= "</td>";
                 $quote_table .= "<td>\$" . $precio[0] . "." . substr($precio[1], 0, 2) . "</td>";
                 $quote_table .= "<td>\$" . $precio_imp[0] . "." . substr($precio_imp[1], 0, 2) . "</td></tr>";
             }
         }
         $link = new Link();
         $productUrl = $link->getProductLink($this->product);
         $margin = Configuration::get('PROFIT_MARGIN');
         $price_type = Configuration::get('PRODUCT_DYNAMIC_PRICE');
         if (isset($margin) && $price_type == 1) {
             $margin = floatval($margin) / 100;
             $margin = 1 - $margin;
             $this->product->base_price = $this->product->base_price / $margin;
         }
         if (Pack::isPack((int) $this->product->id) && !Pack::isInStock((int) $this->product->id)) {
             $this->product->quantity = 0;
         }
         $this->product->description = $this->transformDescriptionWithImg($this->product->description);
         // Assign to the template the id of the virtual product. "0" if the product is not downloadable.
         $this->context->smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
         $this->context->smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
         if (Tools::isSubmit('submitCustomizedDatas')) {
             // If cart has not been saved, we need to do it so that customization fields can have an id_cart
             // We check that the cookie exists first to avoid ghost carts
             if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
                 $this->context->cart->add();
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
             $this->pictureUpload();
             $this->textRecord();
             $this->formTargetFormat();
         } else {
             if (Tools::getIsset('deletePicture') && !$this->context->cart->deleteCustomizationToProduct($this->product->id, Tools::getValue('deletePicture'))) {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture.');
             }
         }
         $pictures = array();
         $text_fields = array();
         if ($this->product->customizable) {
             $files = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_FILE, true);
             foreach ($files as $file) {
                 $pictures['pictures_' . $this->product->id . '_' . $file['index']] = $file['value'];
             }
             $texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
             foreach ($texts as $text_field) {
                 $text_fields['textFields_' . $this->product->id . '_' . $text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
             }
         }
         $this->context->smarty->assign(array('pictures' => $pictures, 'textFields' => $text_fields));
         $this->product->customization_required = false;
         $customizationFields = $this->product->customizable ? $this->product->getCustomizationFields($this->context->language->id) : false;
         if (is_array($customizationFields)) {
             foreach ($customizationFields as $customizationField) {
                 if ($this->product->customization_required = $customizationField['required']) {
                     break;
                 }
             }
         }
         // Assign template vars related to the category + execute hooks related to the category
         $this->assignCategory();
         // Assign template vars related to the price and tax
         $this->assignPriceAndTax();
         // Assign template vars related to the images
         $this->assignImages();
         // Assign attribute groups to the template
         $this->assignAttributesGroups();
         // Assign attributes combinations to the template
         $this->assignAttributesCombinations();
         // Pack management
         $pack_items = $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, $this->context->language->id, true) : array();
         $this->context->smarty->assign('packItems', $pack_items);
         $this->context->smarty->assign('packs', Pack::getPacksTable($this->product->id, $this->context->language->id, true, 1));
         if (isset($this->category->id) && $this->category->id) {
             $return_link = Tools::safeOutput($this->context->link->getCategoryLink($this->category));
         } else {
             $return_link = 'javascript: history.back();';
         }
         $this->context->smarty->assign(array('stock_management' => Configuration::get('PS_STOCK_MANAGEMENT'), 'customizationFields' => $customizationFields, 'accessories' => $this->product->getAccessories($this->context->language->id), 'return_link' => $return_link, 'product' => $this->product, 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, $this->context->language->id), 'token' => Tools::getToken(false), 'features' => $this->product->getFrontFeatures($this->context->language->id), 'attachments' => $this->product->cache_has_attachments ? $this->product->getAttachments($this->context->language->id) : array(), 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'HOOK_EXTRA_LEFT' => Hook::exec('displayLeftColumnProduct'), 'HOOK_EXTRA_RIGHT' => Hook::exec('displayRightColumnProduct'), 'HOOK_PRODUCT_OOS' => Hook::exec('actionProductOutOfStock', array('product' => $this->product)), 'HOOK_PRODUCT_ACTIONS' => Hook::exec('displayProductButtons', array('product' => $this->product)), 'HOOK_PRODUCT_TAB' => Hook::exec('displayProductTab', array('product' => $this->product)), 'HOOK_PRODUCT_TAB_CONTENT' => Hook::exec('displayProductTabContent', array('product' => $this->product)), 'HOOK_PRODUCT_CONTENT' => Hook::exec('displayProductContent', array('product' => $this->product)), 'HOOK_PRODUCT_FILE_CONTENT' => Hook::exec('productFileContent', array('product' => $this->product)), 'HOOK_PRODUCT_FILE' => Hook::exec('productFile', array('product' => $this->product)), 'HOOK_CUSTOM_QUOTE' => Hook::exec('displayProductcustomquote', array('product' => $this->product, 'customizationFields' => $customizationFields)), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'currencySign' => $this->context->currency->sign, 'currencyRate' => $this->context->currency->conversion_rate, 'currencyFormat' => $this->context->currency->format, 'currencyBlank' => $this->context->currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'), 'ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'quote_table_detail' => $quote_table, 'inventory' => $inventory, 'decoration_list' => $decoration_list, 'product_url' => $productUrl, 'body_classes' => array($this->php_self . '-' . $this->product->id, $this->php_self . '-' . $this->product->link_rewrite, 'category-' . (isset($this->category) ? $this->category->id : ''), 'category-' . (isset($this->category) ? $this->category->getFieldByLang('link_rewrite') : '')), 'display_discount_price' => Configuration::get('PS_DISPLAY_DISCOUNT_PRICE')));
     }
     $this->setTemplate(_PS_THEME_DIR_ . 'product.tpl');
 }
Example #16
0
 /**
  * Check if cart contains only virtual products
  * @return boolean true if is a virtual cart or false
  *
  */
 public function isVirtualCart()
 {
     if (!intval(self::getNbProducts($this->id))) {
         return false;
     }
     $allVirtual = true;
     foreach ($this->getProducts() as $product) {
         $allVirtual &= ProductDownload::getIdFromIdProduct(intval($product['id_product'])) ? true : false;
     }
     return $allVirtual;
 }
 public function generate($to_file = true)
 {
     $link = new Link();
     include_once 'YMarket.class.php';
     //Язык по умолчанию
     $id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
     //Валюта по умолчанию
     $curr_def = new Currency(intval(Configuration::get('PS_CURRENCY_DEFAULT')));
     //создаем новый магазин
     $market = new YMarket($this->_settings['y_sn'], $this->_settings['y_fn'], 'http://' . Tools::getHttpHost(false, true), $this->_settings['y_ldc']);
     //Валюты
     if ($this->_settings['y_cu']) {
         $currencies = Currency::getCurrencies();
         foreach ($currencies as $currency) {
             $market->add(new yCurrency($currency['iso_code'], floatval($currency['conversion_rate'])));
         }
         unset($currencies);
     } else {
         $market->add(new yCurrency($curr_def->iso_code, floatval($curr_def->conversion_rate)));
     }
     //Категории
     $categories = Category::getCategories($id_lang, false, false);
     foreach ($categories as $category) {
         $catdesc = $category['meta_title'] ? $category['meta_title'] : $category['name'];
         $market->add(new yCategory($category['id_category'], $catdesc, $category['id_parent']));
     }
     unset($categories);
     //Продукты
     $products = self::getProducts($id_lang);
     while ($product = Db::getInstance()->nextRow($products)) {
         $tmp = new yOffer($product['id_product'], $product['name'], Product::getPriceStatic($product['id_product'], $usetax = true, NULL, $decimals = 2, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = true));
         $tmp->id = $product['id_product'];
         $tmp->type = '';
         $tmp->sales_notes = $this->_settings['y_sl'];
         $tmp->url = $link->getProductLink((int) $product['id_product'], $product['link_rewrite']);
         //Картинка
         if ($cover = self::getCover($product['id_product'])) {
             $tmp->picture = $link->getImageLink($product['link_rewrite'], $cover);
         }
         $tmp->currencyId = $curr_def->iso_code;
         $tmp->categoryId = $product['id_category_default'];
         //$tmp->vendorCode = $product['reference'];
         $tmp->description = $product['description'];
         if ($this->_settings['y_dl']) {
             $tmp->delivery = 'true';
         } else {
             $tmp->delivery = 'false';
         }
         switch ($this->_settings['y_av']) {
             case 1:
                 $tmp->available = $product['quantity'] == 0 ? 'false' : 'true';
                 break;
             case 3:
                 $tmp->available = 'false';
                 break;
             default:
                 $tmp->available = 'true';
         }
         //$tmp->barcode = $product['ean13'];
         if (ProductDownload::getIdFromIdProduct($product['id_product'])) {
             $tmp->downloadable = 'true';
         }
         if (!($this->_settings['y_av'] == 2 and $product['quantity'] == 0)) {
             $market->add($tmp);
         }
     }
     if ($to_file) {
         $fp = fopen(dirname(__FILE__) . '/../../upload/yml.xml' . ($this->_settings['y_gz'] ? '.gz' : ''), 'w');
         fwrite($fp, $market->generate(false, $this->_settings['y_gz']));
         fclose($fp);
     } else {
         $market->generate(true, $this->_settings['y_gz']);
     }
 }
Example #18
0
 /**
  * Get order products
  *
  * @return array Products with price, quantity (with taxe and without)
  */
 public function getProducts($products = false, $selectedProducts = false, $selectedQty = false)
 {
     if (!$products) {
         $products = $this->getProductsDetail();
     }
     $order = new Order($this->id_order);
     $customized_datas = Product::getAllCustomizedDatas($order->id_cart);
     $resultArray = array();
     foreach ($products as $row) {
         // Change qty if selected
         if ($selectedQty) {
             $row['product_quantity'] = 0;
             foreach ($selectedProducts as $key => $id_product) {
                 if ($row['id_order_detail'] == $id_product) {
                     $row['product_quantity'] = (int) $selectedQty[$key];
                 }
             }
             if (!$row['product_quantity']) {
                 continue;
             }
         }
         $this->setProductImageInformations($row);
         $this->setProductCurrentStock($row);
         $this->setProductCustomizedDatas($row, $customized_datas);
         // Add information for virtual product
         if ($row['download_hash'] && !empty($row['download_hash'])) {
             $row['filename'] = ProductDownload::getFilenameFromIdProduct((int) $row['product_id']);
             // Get the display filename
             $row['display_filename'] = ProductDownload::getFilenameFromFilename($row['filename']);
         }
         $row['id_address_delivery'] = $order->id_address_delivery;
         /* Stock product */
         $resultArray[(int) $row['id_order_detail']] = $row;
     }
     if ($customized_datas) {
         Product::addCustomizationPrice($resultArray, $customized_datas);
     }
     return $resultArray;
 }
Example #19
0
     public function hookPayment($params){
        global $smarty;
        $smarty->assign('payment',$this->l(_iMODULE_FIRST_TITLE_IBON_));    
	$smarty->assign(array('this_path' => $this->_path));
        
        foreach ($params['cart']->getProducts() AS $product)
        {
                $pd = ProductDownload::getIdFromIdProduct((int)($product['id_product']));
                if ($pd AND Validate::isUnsignedInt($pd))
                        return false;
        }
	return $this->display(__FILE__, 'greenworld.tpl');
        

     }
Example #20
0
 /**
  * Check if cart contains only virtual products
  *
  * @return boolean true if is a virtual cart or false
  */
 public function isVirtualCart($strict = false)
 {
     if (!ProductDownload::isFeatureActive()) {
         return false;
     }
     if (!isset(self::$_isVirtualCart[$this->id])) {
         $products = $this->getProducts();
         if (!count($products)) {
             return false;
         }
         $is_virtual = 1;
         foreach ($products as $product) {
             if (empty($product['is_virtual'])) {
                 $is_virtual = 0;
             }
         }
         self::$_isVirtualCart[$this->id] = (int) $is_virtual;
     }
     return self::$_isVirtualCart[$this->id];
 }
Example #21
0
 /**
  * Check if order contains (only) virtual products
  *
  * @param boolean $strict If false return true if there are at least one product virtual
  * @return boolean true if is a virtual order or false
  *
  */
 public function isVirtual($strict = true)
 {
     $products = $this->getProducts();
     if (count($products) < 1) {
         return false;
     }
     $virtual = true;
     foreach ($products as $product) {
         $pd = ProductDownload::getIdFromIdProduct((int) $product['product_id']);
         if ($pd && Validate::isUnsignedInt($pd) && $product['download_hash']) {
             if ($strict === false) {
                 return true;
             }
         } else {
             $virtual &= false;
         }
     }
     return $virtual;
 }
Example #22
0
 /**
  * Get order products
  *
  * @return array Products with price, quantity (with taxe and without)
  */
 public function getProducts($products = false, $selected_products = false, $selected_qty = false)
 {
     if (!$products) {
         $products = $this->getProductsDetail();
     }
     $order = new Order($this->id_order);
     $customized_datas = Product::getAllCustomizedDatas($order->id_cart);
     $result_array = array();
     foreach ($products as $row) {
         // Change qty if selected
         if ($selected_qty) {
             $row['product_quantity'] = 0;
             foreach ($selected_products as $key => $id_product) {
                 if ($row['id_order_detail'] == $id_product) {
                     $row['product_quantity'] = (int) $selected_qty[$key];
                 }
             }
             if (!$row['product_quantity']) {
                 continue;
             }
         }
         $this->setProductImageInformations($row);
         $this->setProductCurrentStock($row);
         $this->setProductCustomizedDatas($row, $customized_datas);
         // Add information for virtual product
         if ($row['download_hash'] && !empty($row['download_hash'])) {
             $row['filename'] = ProductDownload::getFilenameFromIdProduct((int) $row['product_id']);
             // Get the display filename
             $row['display_filename'] = ProductDownload::getFilenameFromFilename($row['filename']);
         }
         $row['id_address_delivery'] = $order->id_address_delivery;
         /* Ecotax */
         $round_mode = $order->round_mode;
         $row['ecotax_tax_excl'] = $row['ecotax'];
         // alias for coherence
         $row['ecotax_tax_incl'] = $row['ecotax'] * (100 + $row['ecotax_tax_rate']) / 100;
         $row['ecotax_tax'] = $row['ecotax_tax_incl'] - $row['ecotax_tax_excl'];
         if ($round_mode == Order::ROUND_ITEM) {
             $row['ecotax_tax_incl'] = Tools::ps_round($row['ecotax_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_, $round_mode);
         }
         $row['total_ecotax_tax_excl'] = $row['ecotax_tax_excl'] * $row['product_quantity'];
         $row['total_ecotax_tax_incl'] = $row['ecotax_tax_incl'] * $row['product_quantity'];
         $row['total_ecotax_tax'] = $row['total_ecotax_tax_incl'] - $row['total_ecotax_tax_excl'];
         foreach (array('ecotax_tax_excl', 'ecotax_tax_incl', 'ecotax_tax', 'total_ecotax_tax_excl', 'total_ecotax_tax_incl', 'total_ecotax_tax') as $ecotax_field) {
             $row[$ecotax_field] = Tools::ps_round($row[$ecotax_field], _PS_PRICE_COMPUTE_PRECISION_, $round_mode);
         }
         // Aliases
         $row['unit_price_tax_excl_including_ecotax'] = $row['unit_price_tax_excl'];
         $row['unit_price_tax_incl_including_ecotax'] = $row['unit_price_tax_incl'];
         $row['total_price_tax_excl_including_ecotax'] = $row['total_price_tax_excl'];
         $row['total_price_tax_incl_including_ecotax'] = $row['total_price_tax_incl'];
         /* Stock product */
         $result_array[(int) $row['id_order_detail']] = $row;
     }
     if ($customized_datas) {
         Product::addCustomizationPrice($result_array, $customized_datas);
     }
     return $result_array;
 }
Example #23
0
    /**
     * Return the id_product_download from an id_product
     *
     * @param int $id_product Product the id
     * @return int Product the id for this virtual product
     */
    public static function getIdFromIdProduct($id_product)
    {
        if (!ProductDownload::isFeatureActive()) {
            return false;
        }
        if (array_key_exists((int) $id_product, self::$_productIds)) {
            return self::$_productIds[$id_product];
        }
        self::$_productIds[$id_product] = (int) Db::getInstance()->getValue('
		SELECT `id_product_download`
		FROM `' . _DB_PREFIX_ . 'product_download`
		WHERE `id_product` = ' . (int) $id_product . '
		AND `active` = 1
		ORDER BY `id_product_download` DESC');
        return self::$_productIds[$id_product];
    }
Example #24
0
    public static function duplicateDownload($id_product_old, $id_product_new)
    {
        $sql = 'SELECT `display_filename`, `filename`, `date_add`, `date_expiration`, `nb_days_accessible`, `nb_downloadable`, `active`, `is_shareable`
				FROM `' . _DB_PREFIX_ . 'product_download`
				WHERE `id_product` = ' . (int) $id_product_old;
        $results = Db::getInstance()->executeS($sql);
        if (!$results) {
            return true;
        }
        $data = array();
        foreach ($results as $row) {
            $new_filename = ProductDownload::getNewFilename();
            copy(_PS_DOWNLOAD_DIR_ . $row['filename'], _PS_DOWNLOAD_DIR_ . $new_filename);
            $data[] = array('id_product' => (int) $id_product_new, 'display_filename' => pSQL($row['display_filename']), 'filename' => pSQL($new_filename), 'date_expiration' => pSQL($row['date_expiration']), 'nb_days_accessible' => (int) $row['nb_days_accessible'], 'nb_downloadable' => (int) $row['nb_downloadable'], 'active' => (int) $row['active'], 'is_shareable' => (int) $row['is_shareable'], 'date_add' => date('Y-m-d H:i:s'));
        }
        return Db::getInstance()->insert('product_download', $data);
    }
Example #25
0
 protected function setVirtualProductInformation($product)
 {
     // Add some informations for virtual products
     $this->download_deadline = '0000-00-00 00:00:00';
     $this->download_hash = null;
     if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
         $product_download = new ProductDownload((int) $id_product_download);
         $this->download_deadline = $product_download->getDeadLine();
         $this->download_hash = $product_download->getHash();
         unset($product_download);
     }
 }
Example #26
0
    /**
     * Sets the new state of the given order
     *
     * @param int $new_order_state
     * @param int/object $id_order
     * @param bool $use_existing_payment
     */
    public function changeIdOrderState($new_order_state, $id_order, $use_existing_payment = false)
    {
        if (!$new_order_state || !$id_order) {
            return;
        }
        if (!is_object($id_order) && is_numeric($id_order)) {
            $order = new Order((int) $id_order);
        } elseif (is_object($id_order)) {
            $order = $id_order;
        } else {
            return;
        }
        ShopUrl::cacheMainDomainForShop($order->id_shop);
        $new_os = new OrderState((int) $new_order_state, $order->id_lang);
        $old_os = $order->getCurrentOrderState();
        $is_validated = $this->isValidated();
        // executes hook
        if (in_array($new_os->id, array(Configuration::get('PS_OS_PAYMENT'), Configuration::get('PS_OS_WS_PAYMENT')))) {
            Hook::exec('actionPaymentConfirmation', array('id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        }
        // executes hook
        Hook::exec('actionOrderStatusUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        if (Validate::isLoadedObject($order) && $new_os instanceof OrderState) {
            // An email is sent the first time a virtual item is validated
            $virtual_products = $order->getVirtualProducts();
            if ($virtual_products && (!$old_os || !$old_os->logable) && $new_os && $new_os->logable) {
                $context = Context::getContext();
                $assign = array();
                foreach ($virtual_products as $key => $virtual_product) {
                    $id_product_download = ProductDownload::getIdFromIdProduct($virtual_product['product_id']);
                    $product_download = new ProductDownload($id_product_download);
                    // If this virtual item has an associated file, we'll provide the link to download the file in the email
                    if ($product_download->display_filename != '') {
                        $assign[$key]['name'] = $product_download->display_filename;
                        $dl_link = $product_download->getTextLink(false, $virtual_product['download_hash']) . '&id_order=' . (int) $order->id . '&secure_key=' . $order->secure_key;
                        $assign[$key]['link'] = $dl_link;
                        if (isset($virtual_product['download_deadline']) && $virtual_product['download_deadline'] != '0000-00-00 00:00:00') {
                            $assign[$key]['deadline'] = Tools::displayDate($virtual_product['download_deadline']);
                        }
                        if ($product_download->nb_downloadable != 0) {
                            $assign[$key]['downloadable'] = (int) $product_download->nb_downloadable;
                        }
                    }
                }
                $customer = new Customer((int) $order->id_customer);
                $links = '<ul>';
                foreach ($assign as $product) {
                    $links .= '<li>';
                    $links .= '<a href="' . $product['link'] . '">' . Tools::htmlentitiesUTF8($product['name']) . '</a>';
                    if (isset($product['deadline'])) {
                        $links .= '&nbsp;' . Tools::htmlentitiesUTF8(Tools::displayError('expires on', false)) . '&nbsp;' . $product['deadline'];
                    }
                    if (isset($product['downloadable'])) {
                        $links .= '&nbsp;' . Tools::htmlentitiesUTF8(sprintf(Tools::displayError('downloadable %d time(s)', false), (int) $product['downloadable']));
                    }
                    $links .= '</li>';
                }
                $links .= '</ul>';
                $data = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{nbProducts}' => count($virtual_products), '{virtualProducts}' => $links);
                // If there's at least one downloadable file
                if (!empty($assign)) {
                    Mail::Send((int) $order->id_lang, 'download_product', Mail::l('Virtual product to download', $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                }
            }
            // @since 1.5.0 : gets the stock manager
            $manager = null;
            if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                $manager = StockManagerFactory::getManager();
            }
            $errorOrCanceledStatuses = array(Configuration::get('PS_OS_ERROR'), Configuration::get('PS_OS_CANCELED'));
            // foreach products of the order
            if (Validate::isLoadedObject($old_os)) {
                foreach ($order->getProductsDetail() as $product) {
                    // if becoming logable => adds sale
                    if ($new_os->logable && !$old_os->logable) {
                        ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
                        // @since 1.5.0 - Stock Management
                        if (!Pack::isPack($product['product_id']) && in_array($old_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'], (int) $order->id_shop)) {
                            StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int) $product['product_quantity'], $order->id_shop);
                        }
                    } elseif (!$new_os->logable && $old_os->logable) {
                        ProductSale::removeProductSale($product['product_id'], $product['product_quantity']);
                        // @since 1.5.0 - Stock Management
                        if (!Pack::isPack($product['product_id']) && in_array($new_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'])) {
                            StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                        }
                    } elseif (!$new_os->logable && !$old_os->logable && in_array($new_os->id, $errorOrCanceledStatuses) && !in_array($old_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'])) {
                        StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                    }
                    // @since 1.5.0 : if the order is being shipped and this products uses the advanced stock management :
                    // decrements the physical stock using $id_warehouse
                    if ($new_os->shipped == 1 && $old_os->shipped == 0 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                        // gets the warehouse
                        $warehouse = new Warehouse($product['id_warehouse']);
                        // decrements the stock (if it's a pack, the StockManager does what is needed)
                        $manager->removeProduct($product['product_id'], $product['product_attribute_id'], $warehouse, $product['product_quantity'], Configuration::get('PS_STOCK_CUSTOMER_ORDER_REASON'), true, (int) $order->id);
                    } elseif ($new_os->shipped == 0 && $old_os->shipped == 1 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                        // if the product is a pack, we restock every products in the pack using the last negative stock mvts
                        if (Pack::isPack($product['product_id'])) {
                            $pack_products = Pack::getItems($product['product_id'], Configuration::get('PS_LANG_DEFAULT', null, null, $order->id_shop));
                            foreach ($pack_products as $pack_product) {
                                if ($pack_product->advanced_stock_management == 1) {
                                    $mvts = StockMvt::getNegativeStockMvts($order->id, $pack_product->id, 0, $pack_product->pack_quantity * $product['product_quantity']);
                                    foreach ($mvts as $mvt) {
                                        $manager->addProduct($pack_product->id, 0, new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                                    }
                                    if (!StockAvailable::dependsOnStock($product['id_product'])) {
                                        StockAvailable::updateQuantity($pack_product->id, 0, (int) $pack_product->pack_quantity * $product['product_quantity'], $order->id_shop);
                                    }
                                }
                            }
                        } else {
                            $mvts = StockMvt::getNegativeStockMvts($order->id, $product['product_id'], $product['product_attribute_id'], $product['product_quantity']);
                            foreach ($mvts as $mvt) {
                                $manager->addProduct($product['product_id'], $product['product_attribute_id'], new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                            }
                        }
                    }
                }
            }
        }
        $this->id_order_state = (int) $new_order_state;
        // changes invoice number of order ?
        if (!Validate::isLoadedObject($new_os) || !Validate::isLoadedObject($order)) {
            die(Tools::displayError('Invalid new order state'));
        }
        // the order is valid if and only if the invoice is available and the order is not cancelled
        $order->current_state = $this->id_order_state;
        $order->valid = $new_os->logable;
        $order->update();
        if ($new_os->invoice && !$order->invoice_number) {
            $order->setInvoice($use_existing_payment);
        }
        // set orders as paid
        if ($new_os->paid == 1) {
            $invoices = $order->getInvoicesCollection();
            if ($order->total_paid != 0) {
                $payment_method = Module::getInstanceByName($order->module);
            }
            foreach ($invoices as $invoice) {
                $rest_paid = $invoice->getRestPaid();
                if ($rest_paid > 0) {
                    $payment = new OrderPayment();
                    $payment->order_reference = $order->reference;
                    $payment->id_currency = $order->id_currency;
                    $payment->amount = $rest_paid;
                    if ($order->total_paid != 0) {
                        $payment->payment_method = $payment_method->displayName;
                    } else {
                        $payment->payment_method = null;
                    }
                    // Update total_paid_real value for backward compatibility reasons
                    if ($payment->id_currency == $order->id_currency) {
                        $order->total_paid_real += $payment->amount;
                    } else {
                        $order->total_paid_real += Tools::ps_round(Tools::convertPrice($payment->amount, $payment->id_currency, false), 2);
                    }
                    $order->save();
                    $payment->conversion_rate = 1;
                    $payment->save();
                    Db::getInstance()->execute('
					INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment`
					VALUES(' . (int) $invoice->id . ', ' . (int) $payment->id . ', ' . (int) $order->id . ')');
                }
            }
        }
        // updates delivery date even if it was already set by another state change
        if ($new_os->delivery) {
            $order->setDelivery();
        }
        // executes hook
        Hook::exec('actionOrderStatusPostUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        ShopUrl::resetMainDomainCache();
    }
    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>
		';
    }
Example #28
0
<?php

define('PS_ADMIN_DIR', getcwd());
include PS_ADMIN_DIR . '/../config/config.inc.php';
if (!class_exists('Cookie')) {
    exit;
}
$cookie = new Cookie('psAdmin', substr($_SERVER['SCRIPT_NAME'], strlen(__PS_BASE_URI__), -10));
if (!$cookie->isLoggedBack()) {
    die;
}
if (isset($_FILES['virtual_product_file']) and is_uploaded_file($_FILES['virtual_product_file']['tmp_name']) and (isset($_FILES['virtual_product_file']['error']) and !$_FILES['virtual_product_file']['error']) or !empty($_FILES['virtual_product_file']['tmp_name']) and $_FILES['virtual_product_file']['tmp_name'] != 'none') {
    $filename = $_FILES['virtual_product_file']['name'];
    $file = $_FILES['virtual_product_file']['tmp_name'];
    $newfilename = ProductDownload::getNewFilename();
    if (!copy($file, _PS_DOWNLOAD_DIR_ . $newfilename)) {
        header('HTTP/1.1 500 Error');
        echo '<return result="error" msg="no rights" filename="' . $filename . '" />';
    }
    @unlink($file);
    header('HTTP/1.1 200 OK');
    echo '<return result="success" msg="' . $newfilename . '" filename="' . $filename . '" />';
} else {
    header('HTTP/1.1 500 Error');
    echo '<return result="error" msg="big error" filename="' . ProductDownload::getNewFilename() . '" />';
}
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     if (!$this->errors) {
         // Assign to the template the id of the virtual product. "0" if the product is not downloadable.
         $this->context->smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
         // If the product is not active, it's the admin preview mode
         if (!$this->product->active) {
             $this->context->smarty->assign('adminActionDisplay', true);
         }
         // Product pictures management
         require_once 'images.inc.php';
         $this->context->smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
         if (Tools::isSubmit('submitCustomizedDatas')) {
             // If cart has not been saved, we need to do it so that customization fields can have an id_cart
             // We check that the cookie exists first to avoid ghost carts
             if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
                 $this->context->cart->add();
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
             $this->pictureUpload();
             $this->textRecord();
             $this->formTargetFormat();
         } else {
             if (Tools::getIsset('deletePicture') && !$this->context->cart->deleteCustomizationToProduct($this->product->id, Tools::getValue('deletePicture'))) {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture');
             }
         }
         $files = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_FILE, true);
         $pictures = array();
         foreach ($files as $file) {
             $pictures['pictures_' . $this->product->id . '_' . $file['index']] = $file['value'];
         }
         $texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
         $text_fields = array();
         foreach ($texts as $text_field) {
             $text_fields['textFields_' . $this->product->id . '_' . $text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
         }
         $this->context->smarty->assign(array('pictures' => $pictures, 'textFields' => $text_fields));
         // Assign template vars related to the category + execute hooks related to the category
         $this->assignCategory();
         // Assign template vars related to the price and tax
         $this->assignPriceAndTax();
         // Assign template vars related to the images
         $this->assignImages();
         // Assign attribute groups to the template
         $this->assignAttributesGroups();
         // Assign attributes combinations to the template
         $this->assignAttributesCombinations();
         // Pack management
         $pack_items = $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, $this->context->language->id, true) : array();
         $this->context->smarty->assign('packItems', $pack_items);
         $this->context->smarty->assign('packs', Pack::getPacksTable($this->product->id, $this->context->language->id, true, 1));
         if (isset($this->category->id) && $this->category->id) {
             $return_link = Tools::safeOutput($this->context->link->getCategoryLink($this->category));
         } else {
             $return_link = 'javascript: history.back();';
         }
         $this->context->smarty->assign(array('stock_management' => Configuration::get('PS_STOCK_MANAGEMENT'), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields($this->context->language->id) : false, 'accessories' => $this->product->getAccessories($this->context->language->id), 'return_link' => $return_link, 'product' => $this->product, 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, $this->context->language->id), 'token' => Tools::getToken(false), 'features' => $this->product->getFrontFeatures($this->context->language->id), 'attachments' => $this->product->cache_has_attachments ? $this->product->getAttachments($this->context->language->id) : array(), 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'HOOK_EXTRA_LEFT' => Hook::exec('displayLeftColumnProduct'), 'HOOK_EXTRA_RIGHT' => Hook::exec('displayRightColumnProduct'), 'HOOK_PRODUCT_OOS' => Hook::exec('actionProductOutOfStock', array('product' => $this->product)), 'HOOK_PRODUCT_ACTIONS' => Hook::exec('displayProductButtons'), 'HOOK_PRODUCT_TAB' => Hook::exec('displayProductTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Hook::exec('displayProductTabContent'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'currencySign' => $this->context->currency->sign, 'currencyRate' => $this->context->currency->conversion_rate, 'currencyFormat' => $this->context->currency->format, 'currencyBlank' => $this->context->currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'), 'ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK')));
     }
     $this->context->smarty->assign('errors', $this->errors);
     $this->setTemplate(_PS_THEME_DIR_ . 'product.tpl');
 }
Example #30
0
    protected function productImportOne($info, $default_language_id, $id_lang, $force_ids, $regenerate, $shop_is_feature_active, $shop_ids, $match_ref, &$accessories, $validateOnly = false)
    {
        if ($force_ids && isset($info['id']) && (int) $info['id']) {
            $product = new Product((int) $info['id']);
        } elseif ($match_ref && array_key_exists('reference', $info)) {
            $datas = Db::getInstance()->getRow('
					SELECT p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($info['reference']) . '"
				', false);
            if (isset($datas['id_product']) && $datas['id_product']) {
                $product = new Product((int) $datas['id_product']);
            } else {
                $product = new Product();
            }
        } elseif (array_key_exists('id', $info) && (int) $info['id'] && Product::existsInDatabase((int) $info['id'], 'product')) {
            $product = new Product((int) $info['id']);
        } else {
            $product = new Product();
        }
        $update_advanced_stock_management_value = false;
        if (isset($product->id) && $product->id && Product::existsInDatabase((int) $product->id, 'product')) {
            $product->loadStockData();
            $update_advanced_stock_management_value = true;
            $category_data = Product::getProductCategories((int) $product->id);
            if (is_array($category_data)) {
                foreach ($category_data as $tmp) {
                    if (!isset($product->category) || !$product->category || is_array($product->category)) {
                        $product->category[] = $tmp;
                    }
                }
            }
        }
        AdminImportController::setEntityDefaultValues($product);
        AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
        if (!$shop_is_feature_active) {
            $product->shop = (int) Configuration::get('PS_SHOP_DEFAULT');
        } elseif (!isset($product->shop) || empty($product->shop)) {
            $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
        }
        if (!$shop_is_feature_active) {
            $product->id_shop_default = (int) Configuration::get('PS_SHOP_DEFAULT');
        } else {
            $product->id_shop_default = (int) Context::getContext()->shop->id;
        }
        // link product to shops
        $product->id_shop_list = array();
        foreach (explode($this->multiple_value_separator, $product->shop) as $shop) {
            if (!empty($shop) && !is_numeric($shop)) {
                $product->id_shop_list[] = Shop::getIdByName($shop);
            } elseif (!empty($shop)) {
                $product->id_shop_list[] = $shop;
            }
        }
        if ((int) $product->id_tax_rules_group != 0) {
            if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) {
                $address = $this->context->shop->getAddress();
                $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group);
                $product_tax_calculator = $tax_manager->getTaxCalculator();
                $product->tax_rate = $product_tax_calculator->getTotalRate();
            } else {
                $this->addProductWarning('id_tax_rules_group', $product->id_tax_rules_group, $this->trans('Unknown tax rule group ID. You need to create a group with this ID first.', array(), 'Admin.Parameters.Notification'));
            }
        }
        if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int) $product->manufacturer)) {
            $product->id_manufacturer = (int) $product->manufacturer;
        } elseif (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) {
            if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) {
                $product->id_manufacturer = (int) $manufacturer;
            } else {
                $manufacturer = new Manufacturer();
                $manufacturer->name = $product->manufacturer;
                $manufacturer->active = true;
                if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $manufacturer->add()) {
                    $product->id_manufacturer = (int) $manufacturer->id;
                    $manufacturer->associateTo($product->id_shop_list);
                } else {
                    if (!$validateOnly) {
                        $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $manufacturer->name, isset($manufacturer->id) && !empty($manufacturer->id) ? $manufacturer->id : 'null');
                    }
                    if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
        }
        if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int) $product->supplier)) {
            $product->id_supplier = (int) $product->supplier;
        } elseif (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) {
            if ($supplier = Supplier::getIdByName($product->supplier)) {
                $product->id_supplier = (int) $supplier;
            } else {
                $supplier = new Supplier();
                $supplier->name = $product->supplier;
                $supplier->active = true;
                if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $supplier->add()) {
                    $product->id_supplier = (int) $supplier->id;
                    $supplier->associateTo($product->id_shop_list);
                } else {
                    if (!$validateOnly) {
                        $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $supplier->name, isset($supplier->id) && !empty($supplier->id) ? $supplier->id : 'null');
                    }
                    if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                        $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                    }
                }
            }
        }
        if (isset($product->price_tex) && !isset($product->price_tin)) {
            $product->price = $product->price_tex;
        } elseif (isset($product->price_tin) && !isset($product->price_tex)) {
            $product->price = $product->price_tin;
            // If a tax is already included in price, withdraw it from price
            if ($product->tax_rate) {
                $product->price = (double) number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', '');
            }
        } elseif (isset($product->price_tin) && isset($product->price_tex)) {
            $product->price = $product->price_tex;
        }
        if (!Configuration::get('PS_USE_ECOTAX')) {
            $product->ecotax = 0;
        }
        if (isset($product->category) && is_array($product->category) && count($product->category)) {
            $product->id_category = array();
            // Reset default values array
            foreach ($product->category as $value) {
                if (is_numeric($value)) {
                    if (Category::categoryExists((int) $value)) {
                        $product->id_category[] = (int) $value;
                    } else {
                        $category_to_create = new Category();
                        $category_to_create->id = (int) $value;
                        $category_to_create->name = AdminImportController::createMultiLangField($value);
                        $category_to_create->active = 1;
                        $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY');
                        // Default parent is home for unknown category to create
                        $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]);
                        $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
                        if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && !$validateOnly && $category_to_create->add()) {
                            $product->id_category[] = (int) $category_to_create->id;
                        } else {
                            if (!$validateOnly) {
                                $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), $category_to_create->name[$default_language_id], isset($category_to_create->id) && !empty($category_to_create->id) ? $category_to_create->id : 'null');
                            }
                            if ($field_error !== true || isset($lang_field_error) && $lang_field_error !== true) {
                                $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
                            }
                        }
                    }
                } elseif (!$validateOnly && is_string($value) && !empty($value)) {
                    $category = Category::searchByPath($default_language_id, trim($value), $this, 'productImportCreateCat');
                    if ($category['id_category']) {
                        $product->id_category[] = (int) $category['id_category'];
                    } else {
                        $this->errors[] = sprintf($this->trans('%1$s cannot be saved', array(), 'Admin.Parameters.Notification'), trim($value));
                    }
                }
            }
            $product->id_category = array_values(array_unique($product->id_category));
            // Will update default category if category column is not ignored AND if there is categories that are set in the import file row.
            if (isset($product->id_category[0])) {
                $product->id_category_default = (int) $product->id_category[0];
            } else {
                $defaultProductShop = new Shop($product->id_shop_default);
                $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id;
            }
        }
        // Will update default category if there is none set here. Home if no category at all.
        if (!isset($product->id_category_default) || !$product->id_category_default) {
            // this if will avoid ereasing default category if category column is not present in the CSV file (or ignored)
            if (isset($product->id_category[0])) {
                $product->id_category_default = (int) $product->id_category[0];
            } else {
                $defaultProductShop = new Shop($product->id_shop_default);
                $product->id_category_default = Category::getRootCategory(null, Validate::isLoadedObject($defaultProductShop) ? $defaultProductShop : null)->id;
            }
        }
        $link_rewrite = is_array($product->link_rewrite) && isset($product->link_rewrite[$id_lang]) ? trim($product->link_rewrite[$id_lang]) : '';
        $valid_link = Validate::isLinkRewrite($link_rewrite);
        if (isset($product->link_rewrite[$id_lang]) && empty($product->link_rewrite[$id_lang]) || !$valid_link) {
            $link_rewrite = Tools::link_rewrite($product->name[$id_lang]);
            if ($link_rewrite == '') {
                $link_rewrite = 'friendly-url-autogeneration-failed';
            }
        }
        if (!$valid_link) {
            $this->informations[] = sprintf($this->trans('Rewrite link for %1$s (ID %2$s): re-written as %3$s.', array(), 'Admin.Parameters.Notification'), $product->name[$id_lang], isset($info['id']) && !empty($info['id']) ? $info['id'] : 'null', $link_rewrite);
        }
        if (!$valid_link || !($match_ref || $force_ids) || !(is_array($product->link_rewrite) && count($product->link_rewrite) && !empty($product->link_rewrite[$id_lang]))) {
            $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite);
        }
        // replace the value of separator by coma
        if ($this->multiple_value_separator != ',') {
            if (is_array($product->meta_keywords)) {
                foreach ($product->meta_keywords as &$meta_keyword) {
                    if (!empty($meta_keyword)) {
                        $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword);
                    }
                }
            }
        }
        // Convert comma into dot for all floating values
        foreach (Product::$definition['fields'] as $key => $array) {
            if ($array['type'] == Product::TYPE_FLOAT) {
                $product->{$key} = str_replace(',', '.', $product->{$key});
            }
        }
        // Indexation is already 0 if it's a new product, but not if it's an update
        $product->indexed = 0;
        $productExistsInDatabase = false;
        if ($product->id && Product::existsInDatabase((int) $product->id, 'product')) {
            $productExistsInDatabase = true;
        }
        if ($match_ref && $product->reference && $product->existsRefInDatabase($product->reference) || $productExistsInDatabase) {
            $product->date_upd = date('Y-m-d H:i:s');
        }
        $res = false;
        $field_error = $product->validateFields(UNFRIENDLY_ERROR, true);
        $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true);
        if ($field_error === true && $lang_field_error === true) {
            // check quantity
            if ($product->quantity == null) {
                $product->quantity = 0;
            }
            // If match ref is specified && ref product && ref product already in base, trying to update
            if ($match_ref && $product->reference && $product->existsRefInDatabase($product->reference)) {
                $datas = Db::getInstance()->getRow('
					SELECT product_shop.`date_add`, p.`id_product`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`reference` = "' . pSQL($product->reference) . '"
				', false);
                $product->id = (int) $datas['id_product'];
                $product->date_add = pSQL($datas['date_add']);
                $res = $validateOnly || $product->update();
            } elseif ($productExistsInDatabase) {
                $datas = Db::getInstance()->getRow('
					SELECT product_shop.`date_add`
					FROM `' . _DB_PREFIX_ . 'product` p
					' . Shop::addSqlAssociation('product', 'p') . '
					WHERE p.`id_product` = ' . (int) $product->id, false);
                $product->date_add = pSQL($datas['date_add']);
                $res = $validateOnly || $product->update();
            }
            // If no id_product or update failed
            $product->force_id = (bool) $force_ids;
            if (!$res) {
                if (isset($product->date_add) && $product->date_add != '') {
                    $res = $validateOnly || $product->add(false);
                } else {
                    $res = $validateOnly || $product->add();
                }
            }
            if (!$validateOnly) {
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    StockAvailable::setProductOutOfStock((int) $product->id, 1);
                } else {
                    StockAvailable::setProductOutOfStock((int) $product->id, (int) $product->out_of_stock);
                }
                if ($product_download_id = ProductDownload::getIdFromIdProduct((int) $product->id)) {
                    $product_download = new ProductDownload($product_download_id);
                    $product_download->delete(true);
                }
                if ($product->getType() == Product::PTYPE_VIRTUAL) {
                    $product_download = new ProductDownload();
                    $product_download->filename = ProductDownload::getNewFilename();
                    Tools::copy($info['file_url'], _PS_DOWNLOAD_DIR_ . $product_download->filename);
                    $product_download->id_product = (int) $product->id;
                    $product_download->nb_downloadable = (int) $info['nb_downloadable'];
                    $product_download->date_expiration = $info['date_expiration'];
                    $product_download->nb_days_accessible = (int) $info['nb_days_accessible'];
                    $product_download->display_filename = basename($info['file_url']);
                    $product_download->add();
                }
            }
        }
        $shops = array();
        $product_shop = explode($this->multiple_value_separator, $product->shop);
        foreach ($product_shop as $shop) {
            if (empty($shop)) {
                continue;
            }
            $shop = trim($shop);
            if (!empty($shop) && !is_numeric($shop)) {
                $shop = Shop::getIdByName($shop);
            }
            if (in_array($shop, $shop_ids)) {
                $shops[] = $shop;
            } else {
                $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid'));
            }
        }
        if (empty($shops)) {
            $shops = Shop::getContextListShopID();
        }
        // If both failed, mysql error
        if (!$res) {
            $this->errors[] = sprintf($this->trans('%1$s (ID: %2$s) cannot be saved', array(), 'Admin.Parameters.Notification'), isset($info['name']) && !empty($info['name']) ? Tools::safeOutput($info['name']) : 'No Name', isset($info['id']) && !empty($info['id']) ? Tools::safeOutput($info['id']) : 'No ID');
            $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . Db::getInstance()->getMsgError();
        } else {
            // Product supplier
            if (!$validateOnly && isset($product->id) && $product->id && isset($product->id_supplier) && property_exists($product, 'supplier_reference')) {
                $id_product_supplier = (int) ProductSupplier::getIdByProductAndSupplier((int) $product->id, 0, (int) $product->id_supplier);
                if ($id_product_supplier) {
                    $product_supplier = new ProductSupplier($id_product_supplier);
                } else {
                    $product_supplier = new ProductSupplier();
                }
                $product_supplier->id_product = (int) $product->id;
                $product_supplier->id_product_attribute = 0;
                $product_supplier->id_supplier = (int) $product->id_supplier;
                $product_supplier->product_supplier_price_te = $product->wholesale_price;
                $product_supplier->product_supplier_reference = $product->supplier_reference;
                $product_supplier->save();
            }
            // SpecificPrice (only the basic reduction feature is supported by the import)
            if (!$shop_is_feature_active) {
                $info['shop'] = 1;
            } elseif (!isset($info['shop']) || empty($info['shop'])) {
                $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
            }
            // Get shops for each attributes
            $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
            $id_shop_list = array();
            foreach ($info['shop'] as $shop) {
                if (!empty($shop) && !is_numeric($shop)) {
                    $id_shop_list[] = (int) Shop::getIdByName($shop);
                } elseif (!empty($shop)) {
                    $id_shop_list[] = $shop;
                }
            }
            if (isset($info['reduction_price']) && $info['reduction_price'] > 0 || isset($info['reduction_percent']) && $info['reduction_percent'] > 0) {
                foreach ($id_shop_list as $id_shop) {
                    $specific_price = SpecificPrice::getSpecificPrice($product->id, $id_shop, 0, 0, 0, 1, 0, 0, 0, 0);
                    if (is_array($specific_price) && isset($specific_price['id_specific_price'])) {
                        $specific_price = new SpecificPrice((int) $specific_price['id_specific_price']);
                    } else {
                        $specific_price = new SpecificPrice();
                    }
                    $specific_price->id_product = (int) $product->id;
                    $specific_price->id_specific_price_rule = 0;
                    $specific_price->id_shop = $id_shop;
                    $specific_price->id_currency = 0;
                    $specific_price->id_country = 0;
                    $specific_price->id_group = 0;
                    $specific_price->price = -1;
                    $specific_price->id_customer = 0;
                    $specific_price->from_quantity = 1;
                    $specific_price->reduction = isset($info['reduction_price']) && $info['reduction_price'] ? $info['reduction_price'] : $info['reduction_percent'] / 100;
                    $specific_price->reduction_type = isset($info['reduction_price']) && $info['reduction_price'] ? 'amount' : 'percentage';
                    $specific_price->from = isset($info['reduction_from']) && Validate::isDate($info['reduction_from']) ? $info['reduction_from'] : '0000-00-00 00:00:00';
                    $specific_price->to = isset($info['reduction_to']) && Validate::isDate($info['reduction_to']) ? $info['reduction_to'] : '0000-00-00 00:00:00';
                    if (!$validateOnly && !$specific_price->save()) {
                        $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid'));
                    }
                }
            }
            if (!$validateOnly && isset($product->tags) && !empty($product->tags)) {
                if (isset($product->id) && $product->id) {
                    $tags = Tag::getProductTags($product->id);
                    if (is_array($tags) && count($tags)) {
                        if (!empty($product->tags)) {
                            $product->tags = explode($this->multiple_value_separator, $product->tags);
                        }
                        if (is_array($product->tags) && count($product->tags)) {
                            foreach ($product->tags as $key => $tag) {
                                if (!empty($tag)) {
                                    $product->tags[$key] = trim($tag);
                                }
                            }
                            $tags[$id_lang] = $product->tags;
                            $product->tags = $tags;
                        }
                    }
                }
                // Delete tags for this id product, for no duplicating error
                Tag::deleteTagsForProduct($product->id);
                if (!is_array($product->tags) && !empty($product->tags)) {
                    $product->tags = AdminImportController::createMultiLangField($product->tags);
                    foreach ($product->tags as $key => $tags) {
                        $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator);
                        if (!$is_tag_added) {
                            $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid'));
                            break;
                        }
                    }
                } else {
                    foreach ($product->tags as $key => $tags) {
                        $str = '';
                        foreach ($tags as $one_tag) {
                            $str .= $one_tag . $this->multiple_value_separator;
                        }
                        $str = rtrim($str, $this->multiple_value_separator);
                        $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator);
                        if (!$is_tag_added) {
                            $this->addProductWarning(Tools::safeOutput($info['name']), (int) $product->id, 'Invalid tag(s) (' . $str . ')');
                            break;
                        }
                    }
                }
            }
            //delete existing images if "delete_existing_images" is set to 1
            if (!$validateOnly && isset($product->delete_existing_images)) {
                if ((bool) $product->delete_existing_images) {
                    $product->deleteImages();
                }
            }
            if (!$validateOnly && isset($product->image) && is_array($product->image) && count($product->image)) {
                $product_has_images = (bool) Image::getImages($this->context->language->id, (int) $product->id);
                foreach ($product->image as $key => $url) {
                    $url = trim($url);
                    $error = false;
                    if (!empty($url)) {
                        $url = str_replace(' ', '%20', $url);
                        $image = new Image();
                        $image->id_product = (int) $product->id;
                        $image->position = Image::getHighestPosition($product->id) + 1;
                        $image->cover = !$key && !$product_has_images ? true : false;
                        $alt = $product->image_alt[$key];
                        if (strlen($alt) > 0) {
                            $image->legend = self::createMultiLangField($alt);
                        }
                        // file_exists doesn't work with HTTP protocol
                        if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) {
                            // associate image to selected shops
                            $image->associateTo($shops);
                            if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !$regenerate)) {
                                $image->delete();
                                $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url);
                            }
                        } else {
                            $error = true;
                        }
                    } else {
                        $error = true;
                    }
                    if ($error) {
                        $this->warnings[] = sprintf($this->trans('Product #%1$d: the picture (%2$s) cannot be saved.', array(), 'Admin.Parameters.Notification'), $image->id_product, $url);
                    }
                }
            }
            if (!$validateOnly && isset($product->id_category) && is_array($product->id_category)) {
                $product->updateCategories(array_map('intval', $product->id_category));
            }
            $product->checkDefaultAttributes();
            if (!$validateOnly && !$product->cache_default_attribute) {
                Product::updateDefaultAttribute($product->id);
            }
            // Features import
            $features = get_object_vars($product);
            if (!$validateOnly && isset($features['features']) && !empty($features['features'])) {
                foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) {
                    if (empty($single_feature)) {
                        continue;
                    }
                    $tab_feature = explode(':', $single_feature);
                    $feature_name = isset($tab_feature[0]) ? trim($tab_feature[0]) : '';
                    $feature_value = isset($tab_feature[1]) ? trim($tab_feature[1]) : '';
                    $position = isset($tab_feature[2]) ? (int) $tab_feature[2] - 1 : false;
                    $custom = isset($tab_feature[3]) ? (int) $tab_feature[3] : false;
                    if (!empty($feature_name) && !empty($feature_value)) {
                        $id_feature = (int) Feature::addFeatureImport($feature_name, $position);
                        $id_product = null;
                        if ($force_ids || $match_ref) {
                            $id_product = (int) $product->id;
                        }
                        $id_feature_value = (int) FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
                        Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value);
                    }
                }
            }
            // clean feature positions to avoid conflict
            Feature::cleanPositions();
            // set advanced stock managment
            if (!$validateOnly && isset($product->advanced_stock_management)) {
                if ($product->advanced_stock_management != 1 && $product->advanced_stock_management != 0) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif ($update_advanced_stock_management_value) {
                    $product->setAdvancedStockManagement($product->advanced_stock_management);
                }
                // automaticly disable depends on stock, if a_s_m set to disabled
                if (StockAvailable::dependsOnStock($product->id) == 1 && $product->advanced_stock_management == 0) {
                    StockAvailable::setProductDependsOnStock($product->id, 0);
                }
            }
            // Check if warehouse exists
            if (isset($product->warehouse) && $product->warehouse) {
                if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse not set on product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif (!$validateOnly) {
                    if (Warehouse::exists($product->warehouse)) {
                        // Get already associated warehouses
                        $associated_warehouses_collection = WarehouseProductLocation::getCollection($product->id);
                        // Delete any entry in warehouse for this product
                        foreach ($associated_warehouses_collection as $awc) {
                            $awc->delete();
                        }
                        $warehouse_location_entity = new WarehouseProductLocation();
                        $warehouse_location_entity->id_product = $product->id;
                        $warehouse_location_entity->id_product_attribute = 0;
                        $warehouse_location_entity->id_warehouse = $product->warehouse;
                        if (WarehouseProductLocation::getProductLocation($product->id, 0, $product->warehouse) !== false) {
                            $warehouse_location_entity->update();
                        } else {
                            $warehouse_location_entity->save();
                        }
                        StockAvailable::synchronize($product->id);
                    } else {
                        $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                    }
                }
            }
            // stock available
            if (isset($product->depends_on_stock)) {
                if ($product->depends_on_stock != 0 && $product->depends_on_stock != 1) {
                    $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif ((!$product->advanced_stock_management || $product->advanced_stock_management == 0) && $product->depends_on_stock == 1) {
                    $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language_id]);
                } elseif (!$validateOnly) {
                    StockAvailable::setProductDependsOnStock($product->id, $product->depends_on_stock);
                }
                // This code allows us to set qty and disable depends on stock
                if (!$validateOnly && isset($product->quantity) && (int) $product->quantity) {
                    // if depends on stock and quantity, add quantity to stock
                    if ($product->depends_on_stock == 1) {
                        $stock_manager = StockManagerFactory::getManager();
                        $price = str_replace(',', '.', $product->wholesale_price);
                        if ($price == 0) {
                            $price = 1.0E-6;
                        }
                        $price = round(floatval($price), 6);
                        $warehouse = new Warehouse($product->warehouse);
                        if ($stock_manager->addProduct((int) $product->id, 0, $warehouse, (int) $product->quantity, 1, $price, true)) {
                            StockAvailable::synchronize((int) $product->id);
                        }
                    } else {
                        if ($shop_is_feature_active) {
                            foreach ($shops as $shop) {
                                StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                            }
                        } else {
                            StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                        }
                    }
                }
            } elseif (!$validateOnly) {
                // if not depends_on_stock set, use normal qty
                if ($shop_is_feature_active) {
                    foreach ($shops as $shop) {
                        StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $shop);
                    }
                } else {
                    StockAvailable::setQuantity((int) $product->id, 0, (int) $product->quantity, (int) $this->context->shop->id);
                }
            }
            // Accessories linkage
            if (isset($product->accessories) && !$validateOnly && is_array($product->accessories) && count($product->accessories)) {
                $accessories[$product->id] = $product->accessories;
            }
        }
    }