/**
  * Assign template vars if displaying one manufacturer
  */
 protected function assignOne()
 {
     $this->manufacturer->description = Tools::nl2br(trim($this->manufacturer->description));
     $nbProducts = $this->manufacturer->getProducts($this->manufacturer->id, null, null, null, $this->orderBy, $this->orderWay, true);
     $this->pagination((int) $nbProducts);
     $this->context->smarty->assign(array('nb_products' => $nbProducts, 'products' => $this->manufacturer->getProducts($this->manufacturer->id, $this->context->language->id, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay), 'path' => $this->manufacturer->active ? Tools::safeOutput($this->manufacturer->name) : '', 'manufacturer' => $this->manufacturer, 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
 }
Example #2
0
 /**
  * Assign template vars if displaying one supplier
  */
 protected function assignOne()
 {
     $this->supplier->description = Tools::nl2br(trim($this->supplier->description));
     $nbProducts = $this->supplier->getProducts($this->supplier->id, null, null, null, $this->orderBy, $this->orderWay, true);
     $this->pagination((int) $nbProducts);
     $products = $this->supplier->getProducts($this->supplier->id, $this->context->cookie->id_lang, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
     $this->addColorsToProductList($products);
     $this->context->smarty->assign(array('nb_products' => $nbProducts, 'products' => $products, 'path' => $this->supplier->active ? Tools::safeOutput($this->supplier->name) : '', 'supplier' => $this->supplier, 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'body_classes' => array($this->php_self . '-' . $this->supplier->id, $this->php_self . '-' . $this->supplier->link_rewrite)));
 }
Example #3
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart = $this->context->cart;
     if (!$this->module->checkCurrency($cart)) {
         Tools::redirect('index.php?controller=order');
     }
     $this->context->smarty->assign(array('nbProducts' => $cart->nbProducts(), 'cust_currency' => $cart->id_currency, 'currencies' => $this->module->getCurrency((int) $cart->id_currency), 'total' => $cart->getOrderTotal(true, Cart::BOTH), 'isoCode' => $this->context->language->iso_code, 'chequeName' => $this->module->chequeName, 'chequeAddress' => Tools::nl2br($this->module->address), 'this_path' => $this->module->getPathUri(), 'this_path_cheque' => $this->module->getPathUri(), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/'));
     $this->setTemplate('payment_execution.tpl');
 }
 function postProcess()
 {
     // we retrieve the potential currencies to make sure the selected currency exists in this shop
     $currencies = TotCompatibility::getCurrenciesByIdShop($this->ebay_profile->id_shop);
     $currencies_ids = array_map(array($this, 'getCurrencyId'), $currencies);
     if ($this->ebay_profile->setConfiguration('EBAY_PAYPAL_EMAIL', pSQL(Tools::getValue('ebay_paypal_email'))) && $this->ebay_profile->setConfiguration('EBAY_SHOP', pSQL(Tools::getValue('ebay_shop'))) && $this->ebay_profile->setConfiguration('EBAY_SHOP_POSTALCODE', pSQL(Tools::getValue('ebay_shop_postalcode'))) && $this->ebay_profile->setConfiguration('EBAY_SHOP_COUNTRY', pSQL(Tools::getValue('ebay_shop_country'))) && $this->ebay_profile->setConfiguration('EBAY_LISTING_DURATION', Tools::getValue('listingdurations')) && $this->ebay_profile->setConfiguration('EBAY_AUTOMATICALLY_RELIST', Tools::getValue('automaticallyrelist')) && $this->ebay_profile->setReturnsPolicyConfiguration(pSQL(Tools::getValue('returnswithin')), pSQL(Tools::getValue('returnswhopays')), version_compare(_PS_VERSION_, '1.5', '>') ? Tools::nl2br(Tools::getValue('ebay_returns_description')) : nl2br2(Tools::getValue('ebay_returns_description')), pSQL(Tools::getValue('ebay_returns_accepted_option'))) && $this->ebay->setConfiguration('EBAY_ACTIVATE_MAILS', Tools::getValue('activate_mails') ? 1 : 0) && in_array((int) Tools::getValue('currency'), $currencies_ids) && $this->ebay_profile->setConfiguration('EBAY_CURRENCY', (int) Tools::getValue('currency')) && $this->ebay_profile->setConfiguration('EBAY_SEND_TRACKING_CODE', (int) Tools::getValue('send_tracking_code')) && $this->ebay_profile->setConfiguration('EBAY_SHIPPED_ORDER_STATE', (int) Tools::getValue('shipped_order_state')) && $this->ebay_profile->setConfiguration('EBAY_IMMEDIATE_PAYMENT', (int) Tools::getValue('immediate_payment'))) {
         return $this->ebay->displayConfirmation($this->ebay->l('Settings updated'));
     } else {
         return $this->ebay->displayError($this->ebay->l('Settings failed'));
     }
 }
Example #5
0
 public function processData()
 {
     if (Module::isInstalled('agilemultipleshop') && Shop::$id_shop_owner > 0) {
         if (!Validate::isLoadedObject($this->seller)) {
             $this->errors[] = Tools::displayError('Seller does not exist');
         } elseif (!$this->seller->active) {
             self::$smarty->assign('seller', $this->seller);
         } else {
             $rewrited_url = self::$link->getAgileSellerLink((int) $this->seller->id, $this->getSellerLinkRwrite());
             $this->seller_info->description = _PS_VERSION_ > '1.5' ? Tools::nl2br($this->seller_info->description) : nl2br2($this->seller_info->description);
             self::$smarty->assign('seller', $this->seller);
             self::$smarty->assign('seller_info', $this->seller_info);
             $sellermodule = new AgileMultipleSeller();
             $conf = Configuration::getMultiple($sellermodule->getCustomFields());
             $custom_labels = $sellermodule->getCustomLabels();
             self::$smarty->assign('conf', $conf);
             self::$smarty->assign('custom_labels', $custom_labels);
             $nbProducts = $this->getProducts(NULL, NULL, NULL, $this->orderBy, $this->orderWay, true);
             $this->pagination((int) $nbProducts);
             self::$smarty->assign('nb_products', (int) $nbProducts);
             $seller_products = $this->getProducts((int) self::$cookie->id_lang, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
             AgileHelper::AssignProductImgs($seller_products);
             $si_1531_later = version_compare(_PS_VERSION_, '1.5.3.1', ">=");
             $HOOK_SELLER_RATINGS = '';
             if (Module::isInstalled('agilesellerratings')) {
                 require_once _PS_ROOT_DIR_ . "/modules/agilesellerratings/agilesellerratings.php";
                 $rmodule = new AgileSellerRatings();
                 $HOOK_SELLER_RATINGS = $rmodule->getAverageRating($this->id_seller, AgileSellerRatings::RATING_TYPE_SELLER);
             }
             self::$smarty->assign(array('products' => (isset($seller_products) and $seller_products) ? $seller_products : NULL, 'id_seller' => (int) $this->seller->id, 'path' => $this->seller_info->company, 'agilesellerproducts_tpl' => _PS_ROOT_DIR_ . "/modules/agilesellerproducts/", 'agilemultipleshop_tpl' => _PS_ROOT_DIR_ . "/modules/agilemultipleshop/", 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('category') : 'category'), 'mediumSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('medium') : 'medium'), 'thumbSceneSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('thumb_scene') : 'thumb_scene'), 'homeSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('home') : 'home'), 'HOOK_SELLER_RATINGS' => $HOOK_SELLER_RATINGS, 'page_name' => 'agileseller'));
             $ver = (int) str_replace(".", "", _PS_VERSION_);
             if ($ver <= 1430) {
             } else {
                 if ($ver <= 1451) {
                     if (isset(self::$cookie->id_customer)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getCustomerCompareProducts((int) self::$cookie->id_customer));
                     } elseif (isset(self::$cookie->id_guest)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getGuestCompareProducts((int) self::$cookie->id_guest));
                     }
                 } else {
                     if (isset(self::$cookie->id_compare)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) self::$cookie->id_compare));
                     }
                 }
             }
         }
         self::$smarty->assign(array('allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers()));
     }
 }
Example #6
0
 public function hookProductTabContent($params)
 {
     $manufacturer_id = (int) $params['product']->id_manufacturer;
     if (isset($manufacturer_id)) {
         $cache_id = 'manufacturertab|tabcontent|' . $manufacturer_id;
         if (!$this->isCached('manufacturertab.tpl', $this->getCacheId($cache_id))) {
             $manufacturer = new Manufacturer($manufacturer_id, $this->context->language->id);
             $manufacturer->description = Tools::nl2br(trim($manufacturer->description));
             if (!empty($manufacturer->description) && isset($manufacturer->description)) {
                 $this->context->smarty->assign(array('tabContent' => $manufacturer->description));
             }
         }
         return $this->display(__FILE__, 'manufacturertab.tpl', $this->getCacheId($cache_id));
     } else {
         return;
     }
 }
 protected function assignOne()
 {
     $this->manufacturer->description = Tools::nl2br(trim($this->manufacturer->description));
     $nbProducts = $this->manufacturer->getProducts($this->manufacturer->id, null, null, null, $this->orderBy, $this->orderWay, true);
     $this->pagination((int) $nbProducts);
     $products = $this->manufacturer->getProducts($this->manufacturer->id, $this->context->language->id, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
     $this->addColorsToProductList($products);
     if (method_exists('Product', 'getProductsImgs')) {
         $image_array = array();
         for ($i = 0; $i < $nbProducts; $i++) {
             if (isset($products[$i]['id_product'])) {
                 $image_array[$products[$i]['id_product']] = Product::getProductsImgs($products[$i]['id_product']);
             }
         }
         $this->context->smarty->assign('productimg', (isset($image_array) and $image_array) ? $image_array : NULL);
     }
     $this->context->smarty->assign(array('nb_products' => $nbProducts, 'products' => $products, 'path' => $this->manufacturer->active ? Tools::safeOutput($this->manufacturer->name) : '', 'manufacturer' => $this->manufacturer, 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'body_classes' => array($this->php_self . '-' . $this->manufacturer->id, $this->php_self . '-' . $this->manufacturer->link_rewrite)));
 }
Example #8
0
 protected function assignOne()
 {
     if (Configuration::get('PS_DISPLAY_SUPPLIERS')) {
         $this->supplier->description = Tools::nl2br(trim($this->supplier->description));
         $nbProducts = $this->supplier->getProducts($this->supplier->id, null, null, null, $this->orderBy, $this->orderWay, true);
         $this->pagination((int) $nbProducts);
         $products = $this->supplier->getProducts($this->supplier->id, $this->context->cookie->id_lang, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
         $this->addColorsToProductList($products);
         /************************* /Images Array ******************************/
         if (method_exists('Product', 'getProductsImgs')) {
             $image_array = array();
             for ($i = 0; $i < $nbProducts; $i++) {
                 if (isset($products[$i]['id_product'])) {
                     $image_array[$products[$i]['id_product']] = Product::getProductsImgs($products[$i]['id_product']);
                 }
             }
             $this->context->smarty->assign('productimg', (isset($image_array) and $image_array) ? $image_array : NULL);
         }
         /************************* /Images Array ******************************/
         $this->context->smarty->assign(array('nb_products' => $nbProducts, 'products' => $products, 'path' => $this->supplier->active ? Tools::safeOutput($this->supplier->name) : '', 'supplier' => $this->supplier, 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'body_classes' => array($this->php_self . '-' . $this->supplier->id, $this->php_self . '-' . $this->supplier->link_rewrite)));
     } else {
         Tools::redirect('index.php?controller=404');
     }
 }
    function content_5598cf567cf804_96413460($_smarty_tpl)
    {
        ?>
{
"products": [
<?php 
        if ($_smarty_tpl->tpl_vars['products']->value) {
            $_smarty_tpl->tpl_vars['product'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['product']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['products']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            $_smarty_tpl->tpl_vars['product']->total = $_smarty_tpl->_count($_from);
            $_smarty_tpl->tpl_vars['product']->iteration = 0;
            foreach ($_from as $_smarty_tpl->tpl_vars['product']->key => $_smarty_tpl->tpl_vars['product']->value) {
                $_smarty_tpl->tpl_vars['product']->_loop = true;
                $_smarty_tpl->tpl_vars['product']->iteration++;
                $_smarty_tpl->tpl_vars['product']->last = $_smarty_tpl->tpl_vars['product']->iteration === $_smarty_tpl->tpl_vars['product']->total;
                $_smarty_tpl->tpl_vars['smarty']->value['foreach']['products']['last'] = $_smarty_tpl->tpl_vars['product']->last;
                $_smarty_tpl->tpl_vars['productId'] = new Smarty_variable($_smarty_tpl->tpl_vars['product']->value['id_product'], null, 0);
                $_smarty_tpl->tpl_vars['productAttributeId'] = new Smarty_variable($_smarty_tpl->tpl_vars['product']->value['id_product_attribute'], null, 0);
                ?>
	{
		"id": <?php 
                echo intval($_smarty_tpl->tpl_vars['product']->value['id_product']);
                ?>
,
		"link": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['link']->value->getProductLink($_smarty_tpl->tpl_vars['product']->value['id_product'], $_smarty_tpl->tpl_vars['product']->value['link_rewrite'], $_smarty_tpl->tpl_vars['product']->value['category'], null, null, $_smarty_tpl->tpl_vars['product']->value['id_shop'], $_smarty_tpl->tpl_vars['product']->value['id_product_attribute']));
                ?>
,
		"quantity": <?php 
                echo intval($_smarty_tpl->tpl_vars['product']->value['cart_quantity']);
                ?>
,
		"image": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['link']->value->getImageLink($_smarty_tpl->tpl_vars['product']->value['link_rewrite'], $_smarty_tpl->tpl_vars['product']->value['id_image'], 'home_default'));
                ?>
,
		"image_cart": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['link']->value->getImageLink($_smarty_tpl->tpl_vars['product']->value['link_rewrite'], $_smarty_tpl->tpl_vars['product']->value['id_image'], 'cart_default'));
                ?>
,
		"priceByLine": <?php 
                if ($_smarty_tpl->tpl_vars['priceDisplay']->value == @constant('PS_TAX_EXC')) {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayWtPrice'][0][0]->displayWtPrice(array('p' => $_smarty_tpl->tpl_vars['product']->value['total']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                } else {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayWtPrice'][0][0]->displayWtPrice(array('p' => $_smarty_tpl->tpl_vars['product']->value['total_wt']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                }
                ?>
,
		"name": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(html_entity_decode(trim($_smarty_tpl->tpl_vars['product']->value['name']), 2, 'UTF-8'));
                ?>
,
		"price": <?php 
                if ($_smarty_tpl->tpl_vars['priceDisplay']->value == @constant('PS_TAX_EXC')) {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayWtPrice'][0][0]->displayWtPrice(array('p' => $_smarty_tpl->tpl_vars['product']->value['total']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                } else {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayWtPrice'][0][0]->displayWtPrice(array('p' => $_smarty_tpl->tpl_vars['product']->value['total_wt']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                }
                ?>
,
		"price_float": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(floatval($_smarty_tpl->tpl_vars['product']->value['total']));
                ?>
,
		"idCombination": <?php 
                if (isset($_smarty_tpl->tpl_vars['product']->value['attributes_small'])) {
                    echo intval($_smarty_tpl->tpl_vars['productAttributeId']->value);
                } else {
                    ?>
0<?php 
                }
                ?>
,
		"idAddressDelivery": <?php 
                if (isset($_smarty_tpl->tpl_vars['product']->value['id_address_delivery'])) {
                    echo intval($_smarty_tpl->tpl_vars['product']->value['id_address_delivery']);
                } else {
                    ?>
0<?php 
                }
                ?>
,
		"is_gift": <?php 
                if (isset($_smarty_tpl->tpl_vars['product']->value['is_gift']) && $_smarty_tpl->tpl_vars['product']->value['is_gift']) {
                    ?>
true<?php 
                } else {
                    ?>
false<?php 
                }
                ?>
,
<?php 
                if (isset($_smarty_tpl->tpl_vars['product']->value['attributes_small'])) {
                    ?>
		"hasAttributes": true,
		"attributes": <?php 
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['product']->value['attributes_small']);
                    ?>
,
<?php 
                } else {
                    ?>
		"hasAttributes": false,
<?php 
                }
                ?>
		"hasCustomizedDatas": <?php 
                if (isset($_smarty_tpl->tpl_vars['customizedDatas']->value[$_smarty_tpl->tpl_vars['productId']->value][$_smarty_tpl->tpl_vars['productAttributeId']->value])) {
                    ?>
true<?php 
                } else {
                    ?>
false<?php 
                }
                ?>
,
		"customizedDatas": [
		<?php 
                if (isset($_smarty_tpl->tpl_vars['customizedDatas']->value[$_smarty_tpl->tpl_vars['productId']->value][$_smarty_tpl->tpl_vars['productAttributeId']->value][$_smarty_tpl->tpl_vars['product']->value['id_address_delivery']])) {
                    ?>
		<?php 
                    $_smarty_tpl->tpl_vars['customization'] = new Smarty_Variable();
                    $_smarty_tpl->tpl_vars['customization']->_loop = false;
                    $_smarty_tpl->tpl_vars['id_customization'] = new Smarty_Variable();
                    $_from = $_smarty_tpl->tpl_vars['customizedDatas']->value[$_smarty_tpl->tpl_vars['productId']->value][$_smarty_tpl->tpl_vars['productAttributeId']->value][$_smarty_tpl->tpl_vars['product']->value['id_address_delivery']];
                    if (!is_array($_from) && !is_object($_from)) {
                        settype($_from, 'array');
                    }
                    $_smarty_tpl->tpl_vars['customization']->total = $_smarty_tpl->_count($_from);
                    $_smarty_tpl->tpl_vars['customization']->iteration = 0;
                    foreach ($_from as $_smarty_tpl->tpl_vars['customization']->key => $_smarty_tpl->tpl_vars['customization']->value) {
                        $_smarty_tpl->tpl_vars['customization']->_loop = true;
                        $_smarty_tpl->tpl_vars['id_customization']->value = $_smarty_tpl->tpl_vars['customization']->key;
                        $_smarty_tpl->tpl_vars['customization']->iteration++;
                        $_smarty_tpl->tpl_vars['customization']->last = $_smarty_tpl->tpl_vars['customization']->iteration === $_smarty_tpl->tpl_vars['customization']->total;
                        $_smarty_tpl->tpl_vars['smarty']->value['foreach']['customizedDatas']['last'] = $_smarty_tpl->tpl_vars['customization']->last;
                        ?>
{

			"customizationId": <?php 
                        echo intval($_smarty_tpl->tpl_vars['id_customization']->value);
                        ?>
,
			"quantity": <?php 
                        echo intval($_smarty_tpl->tpl_vars['customization']->value['quantity']);
                        ?>
,
			"datas": [
				<?php 
                        $_smarty_tpl->tpl_vars['datas'] = new Smarty_Variable();
                        $_smarty_tpl->tpl_vars['datas']->_loop = false;
                        $_smarty_tpl->tpl_vars['type'] = new Smarty_Variable();
                        $_from = $_smarty_tpl->tpl_vars['customization']->value['datas'];
                        if (!is_array($_from) && !is_object($_from)) {
                            settype($_from, 'array');
                        }
                        $_smarty_tpl->tpl_vars['datas']->total = $_smarty_tpl->_count($_from);
                        $_smarty_tpl->tpl_vars['datas']->iteration = 0;
                        foreach ($_from as $_smarty_tpl->tpl_vars['datas']->key => $_smarty_tpl->tpl_vars['datas']->value) {
                            $_smarty_tpl->tpl_vars['datas']->_loop = true;
                            $_smarty_tpl->tpl_vars['type']->value = $_smarty_tpl->tpl_vars['datas']->key;
                            $_smarty_tpl->tpl_vars['datas']->iteration++;
                            $_smarty_tpl->tpl_vars['datas']->last = $_smarty_tpl->tpl_vars['datas']->iteration === $_smarty_tpl->tpl_vars['datas']->total;
                            $_smarty_tpl->tpl_vars['smarty']->value['foreach']['customization']['last'] = $_smarty_tpl->tpl_vars['datas']->last;
                            ?>
				{
					"type":	<?php 
                            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['type']->value);
                            ?>
,
					"datas": [
					<?php 
                            $_smarty_tpl->tpl_vars['data'] = new Smarty_Variable();
                            $_smarty_tpl->tpl_vars['data']->_loop = false;
                            $_smarty_tpl->tpl_vars['index'] = new Smarty_Variable();
                            $_from = $_smarty_tpl->tpl_vars['datas']->value;
                            if (!is_array($_from) && !is_object($_from)) {
                                settype($_from, 'array');
                            }
                            $_smarty_tpl->tpl_vars['data']->total = $_smarty_tpl->_count($_from);
                            $_smarty_tpl->tpl_vars['data']->iteration = 0;
                            foreach ($_from as $_smarty_tpl->tpl_vars['data']->key => $_smarty_tpl->tpl_vars['data']->value) {
                                $_smarty_tpl->tpl_vars['data']->_loop = true;
                                $_smarty_tpl->tpl_vars['index']->value = $_smarty_tpl->tpl_vars['data']->key;
                                $_smarty_tpl->tpl_vars['data']->iteration++;
                                $_smarty_tpl->tpl_vars['data']->last = $_smarty_tpl->tpl_vars['data']->iteration === $_smarty_tpl->tpl_vars['data']->total;
                                $_smarty_tpl->tpl_vars['smarty']->value['foreach']['datas']['last'] = $_smarty_tpl->tpl_vars['data']->last;
                                ?>
						{
						"index": <?php 
                                echo intval($_smarty_tpl->tpl_vars['index']->value);
                                ?>
,
						"value": <?php 
                                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(Tools::nl2br($_smarty_tpl->tpl_vars['data']->value['value']));
                                ?>
,
						"truncatedValue": <?php 
                                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(Tools::nl2br($_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['truncate'][0][0]->smarty_modifier_truncate($_smarty_tpl->tpl_vars['data']->value['value'], 28, '...')));
                                ?>

						}<?php 
                                if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['datas']['last']) {
                                    ?>
,<?php 
                                }
                                ?>
					<?php 
                            }
                            ?>
]
				}<?php 
                            if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['customization']['last']) {
                                ?>
,<?php 
                            }
                            ?>
				<?php 
                        }
                        ?>
			]
		}<?php 
                        if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['customizedDatas']['last']) {
                            ?>
,<?php 
                        }
                        ?>
		<?php 
                    }
                    ?>
		<?php 
                }
                ?>
		]
	}<?php 
                if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['products']['last']) {
                    ?>
,<?php 
                }
            }
        }
        ?>
],
"discounts": [
<?php 
        if ($_smarty_tpl->tpl_vars['discounts']->value) {
            $_smarty_tpl->tpl_vars['discount'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['discount']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['discounts']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            $_smarty_tpl->tpl_vars['discount']->total = $_smarty_tpl->_count($_from);
            $_smarty_tpl->tpl_vars['discount']->iteration = 0;
            foreach ($_from as $_smarty_tpl->tpl_vars['discount']->key => $_smarty_tpl->tpl_vars['discount']->value) {
                $_smarty_tpl->tpl_vars['discount']->_loop = true;
                $_smarty_tpl->tpl_vars['discount']->iteration++;
                $_smarty_tpl->tpl_vars['discount']->last = $_smarty_tpl->tpl_vars['discount']->iteration === $_smarty_tpl->tpl_vars['discount']->total;
                $_smarty_tpl->tpl_vars['smarty']->value['foreach']['discounts']['last'] = $_smarty_tpl->tpl_vars['discount']->last;
                ?>
	{
		"id": <?php 
                echo intval($_smarty_tpl->tpl_vars['discount']->value['id_discount']);
                ?>
,
		"name": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['truncate'][0][0]->smarty_modifier_truncate(trim($_smarty_tpl->tpl_vars['discount']->value['name']), 18, '...'));
                ?>
,
		"description": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['discount']->value['description']);
                ?>
,
		"nameDescription": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['truncate'][0][0]->smarty_modifier_truncate(trim($_smarty_tpl->tpl_vars['discount']->value['name'] . ' : ' . $_smarty_tpl->tpl_vars['discount']->value['description']), 18, '...'));
                ?>
,
		"code": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['discount']->value['code']);
                ?>
,
		"link": <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['link']->value->getPageLink((string) $_smarty_tpl->tpl_vars['order_process']->value, true, null, "deleteDiscount=" . (string) $_smarty_tpl->tpl_vars['discount']->value['id_discount']));
                ?>
,
		"price": <?php 
                if ($_smarty_tpl->tpl_vars['priceDisplay']->value == 1) {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['convertPrice'][0][0]->convertPrice(array('price' => $_smarty_tpl->tpl_vars['discount']->value['value_tax_exc']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                } else {
                    ob_start();
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['convertPrice'][0][0]->convertPrice(array('price' => $_smarty_tpl->tpl_vars['discount']->value['value_real']), $_smarty_tpl);
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
                }
                ?>
,
		"price_float": <?php 
                if ($_smarty_tpl->tpl_vars['priceDisplay']->value == 1) {
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['discount']->value['value_tax_exc']);
                } else {
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['discount']->value['value_real']);
                }
                ?>
	}
	<?php 
                if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['discounts']['last']) {
                    ?>
,<?php 
                }
            }
        }
        ?>
],
"shippingCost": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['shipping_cost']->value);
        ?>
,
"shippingCostFloat": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['shipping_cost_float']->value);
        ?>
,
<?php 
        if (isset($_smarty_tpl->tpl_vars['tax_cost']->value)) {
            ?>
"taxCost": <?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['tax_cost']->value);
            ?>
,
<?php 
        }
        ?>
"wrappingCost": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['wrapping_cost']->value);
        ?>
,
"nbTotalProducts": <?php 
        echo intval($_smarty_tpl->tpl_vars['nb_total_products']->value);
        ?>
,
"total": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['total']->value);
        ?>
,
"productTotal": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['product_total']->value);
        ?>
,
"freeShipping": <?php 
        ob_start();
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayWtPrice'][0][0]->displayWtPrice(array('p' => $_smarty_tpl->tpl_vars['free_shipping']->value), $_smarty_tpl);
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode(ob_get_clean());
        ?>
,
"freeShippingFloat": <?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['free_shipping']->value);
        ?>
,
<?php 
        if (isset($_smarty_tpl->tpl_vars['errors']->value) && $_smarty_tpl->tpl_vars['errors']->value) {
            ?>
"hasError" : true,
"errors" : [
<?php 
            $_smarty_tpl->tpl_vars['error'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['error']->_loop = false;
            $_smarty_tpl->tpl_vars['k'] = new Smarty_Variable();
            $_from = $_smarty_tpl->tpl_vars['errors']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            $_smarty_tpl->tpl_vars['error']->total = $_smarty_tpl->_count($_from);
            $_smarty_tpl->tpl_vars['error']->iteration = 0;
            foreach ($_from as $_smarty_tpl->tpl_vars['error']->key => $_smarty_tpl->tpl_vars['error']->value) {
                $_smarty_tpl->tpl_vars['error']->_loop = true;
                $_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['error']->key;
                $_smarty_tpl->tpl_vars['error']->iteration++;
                $_smarty_tpl->tpl_vars['error']->last = $_smarty_tpl->tpl_vars['error']->iteration === $_smarty_tpl->tpl_vars['error']->total;
                $_smarty_tpl->tpl_vars['smarty']->value['foreach']['errors']['last'] = $_smarty_tpl->tpl_vars['error']->last;
                ?>
	<?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['json_encode'][0][0]->jsonEncode($_smarty_tpl->tpl_vars['error']->value);
                ?>

	<?php 
                if (!$_smarty_tpl->getVariable('smarty')->value['foreach']['errors']['last']) {
                    ?>
,<?php 
                }
            }
            ?>
]
<?php 
        } else {
            ?>
"hasError" : false
<?php 
        }
        ?>
}<?php 
    }
Example #10
0
 public function processExport($text_delimiter = '"')
 {
     // clean buffer
     if (ob_get_level() && ob_get_length() > 0) {
         ob_clean();
     }
     $this->getList($this->context->language->id, null, null, 0, false);
     if (!count($this->_list)) {
         return;
     }
     header('Content-type: text/csv');
     header('Content-Type: application/force-download; charset=UTF-8');
     header('Cache-Control: no-store, no-cache');
     header('Content-disposition: attachment; filename="' . $this->table . '_' . date('Y-m-d_His') . '.csv"');
     $headers = array();
     foreach ($this->fields_list as $key => $datas) {
         if ($datas['title'] == 'PDF') {
             unset($this->fields_list[$key]);
         } else {
             $headers[] = Tools::htmlentitiesDecodeUTF8($datas['title']);
         }
     }
     $content = array();
     foreach ($this->_list as $i => $row) {
         $content[$i] = array();
         $path_to_image = false;
         foreach ($this->fields_list as $key => $params) {
             $field_value = isset($row[$key]) ? Tools::htmlentitiesDecodeUTF8(Tools::nl2br($row[$key])) : '';
             if ($key == 'image') {
                 if ($params['image'] != 'p' || Configuration::get('PS_LEGACY_IMAGES')) {
                     $path_to_image = Tools::getShopDomain(true) . _PS_IMG_ . $params['image'] . '/' . $row['id_' . $this->table] . (isset($row['id_image']) ? '-' . (int) $row['id_image'] : '') . '.' . $this->imageType;
                 } else {
                     $path_to_image = Tools::getShopDomain(true) . _PS_IMG_ . $params['image'] . '/' . Image::getImgFolderStatic($row['id_image']) . (int) $row['id_image'] . '.' . $this->imageType;
                 }
                 if ($path_to_image) {
                     $field_value = $path_to_image;
                 }
             }
             if (isset($params['callback'])) {
                 $callback_obj = isset($params['callback_object']) ? $params['callback_object'] : $this->context->controller;
                 if (!preg_match('/<([a-z]+)([^<]+)*(?:>(.*)<\\/\\1>|\\s+\\/>)/ism', call_user_func_array(array($callback_obj, $params['callback']), array($field_value, $row)))) {
                     $field_value = call_user_func_array(array($callback_obj, $params['callback']), array($field_value, $row));
                 }
             }
             $content[$i][] = $field_value;
         }
     }
     $this->context->smarty->assign(array('export_precontent' => "", 'export_headers' => $headers, 'export_content' => $content, 'text_delimiter' => $text_delimiter));
     $this->layout = 'layout-export.tpl';
 }
Example #11
0
    /**
     * Start forms process
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        if (Tools::isSubmit('submitMessage')) {
            $fileAttachment = null;
            if (isset($_FILES['fileUpload']['name']) && !empty($_FILES['fileUpload']['name']) && !empty($_FILES['fileUpload']['tmp_name'])) {
                $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
                $filename = uniqid() . substr($_FILES['fileUpload']['name'], -5);
                $fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']);
                $fileAttachment['name'] = $_FILES['fileUpload']['name'];
                $fileAttachment['mime'] = $_FILES['fileUpload']['type'];
            }
            $message = Tools::getValue('message');
            // Html entities is not usefull, iscleanHtml check there is no bad html tags.
            if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid e-mail address');
            } else {
                if (!$message) {
                    $this->errors[] = Tools::displayError('Message cannot be blank');
                } else {
                    if (!Validate::isCleanHtml($message)) {
                        $this->errors[] = Tools::displayError('Invalid message');
                    } else {
                        if (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
                            $this->errors[] = Tools::displayError('Please select a subject from the list.');
                        } else {
                            if (!empty($_FILES['fileUpload']['name']) && $_FILES['fileUpload']['error'] != 0) {
                                $this->errors[] = Tools::displayError('An error occurred during the file upload');
                            } else {
                                if (!empty($_FILES['fileUpload']['name']) && !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) && !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)) {
                                    $this->errors[] = Tools::displayError('Bad file extension');
                                } else {
                                    $customer = $this->context->customer;
                                    if (!$customer->id) {
                                        $customer->getByEmail($from);
                                    }
                                    $contact = new Contact($id_contact, $this->context->language->id);
                                    if (!(($id_customer_thread = (int) Tools::getValue('id_customer_thread')) && (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') || ($id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, (int) Tools::getValue('id_order'))))) {
                                        $fields = Db::getInstance()->executeS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) Tools::getValue('id_order') . ')');
                                        $score = 0;
                                        foreach ($fields as $key => $row) {
                                            $tmp = 0;
                                            if ((int) $row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) {
                                                continue;
                                            }
                                            if ($row['id_order'] != 0 && Tools::getValue('id_order') != $row['id_order']) {
                                                continue;
                                            }
                                            if ($row['email'] == $from) {
                                                $tmp += 4;
                                            }
                                            if ($row['id_contact'] == $id_contact) {
                                                $tmp++;
                                            }
                                            if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) {
                                                $tmp += 2;
                                            }
                                            if ($tmp >= 5 && $tmp >= $score) {
                                                $score = $tmp;
                                                $id_customer_thread = $row['id_customer_thread'];
                                            }
                                        }
                                    }
                                    $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
					WHERE cc.id_customer_thread = ' . (int) $id_customer_thread . ' AND cc.id_shop = ' . (int) $this->context->shop->id . '
					ORDER BY cm.date_add DESC');
                                    if ($old_message == $message) {
                                        $this->context->smarty->assign('alreadySent', 1);
                                        $contact->email = '';
                                        $contact->customer_service = 0;
                                    }
                                    if (!empty($contact->email)) {
                                        $id_order = (int) Tools::getValue('id_order', 0);
                                        $order = new Order($id_order);
                                        $mail_var_list = array('{email}' => $from, '{message}' => Tools::nl2br(stripslashes($message)), '{id_order}' => $id_order, '{order_name}' => $order->getUniqReference(), '{attached_file}' => isset($_FILES['fileUpload'], $_FILES['fileUpload']['name']) ? $_FILES['fileUpload']['name'] : '');
                                        if (Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form'), $mail_var_list, $contact->email, $contact->name, $from, $customer->id ? $customer->firstname . ' ' . $customer->lastname : '', $fileAttachment) && Mail::Send($this->context->language->id, 'contact_form', Mail::l('Your message has been correctly sent'), $mail_var_list, $from)) {
                                            $this->context->smarty->assign('confirmation', 1);
                                        } else {
                                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                        }
                                    }
                                    if ($contact->customer_service) {
                                        if ((int) $id_customer_thread) {
                                            $ct = new CustomerThread($id_customer_thread);
                                            $ct->status = 'open';
                                            $ct->id_lang = (int) $this->context->language->id;
                                            $ct->id_contact = (int) $id_contact;
                                            if ($id_order = (int) Tools::getValue('id_order')) {
                                                $ct->id_order = $id_order;
                                            }
                                            if ($id_product = (int) Tools::getValue('id_product')) {
                                                $ct->id_product = $id_product;
                                            }
                                            $ct->update();
                                        } else {
                                            $ct = new CustomerThread();
                                            if (isset($customer->id)) {
                                                $ct->id_customer = (int) $customer->id;
                                            }
                                            $ct->id_shop = (int) $this->context->shop->id;
                                            if ($id_order = (int) Tools::getValue('id_order')) {
                                                $ct->id_order = $id_order;
                                            }
                                            if ($id_product = (int) Tools::getValue('id_product')) {
                                                $ct->id_product = $id_product;
                                            }
                                            $ct->id_contact = (int) $id_contact;
                                            $ct->id_lang = (int) $this->context->language->id;
                                            $ct->email = $from;
                                            $ct->status = 'open';
                                            $ct->token = Tools::passwdGen(12);
                                            $ct->add();
                                        }
                                        if ($ct->id) {
                                            $cm = new CustomerMessage();
                                            $cm->id_customer_thread = $ct->id;
                                            $cm->message = Tools::htmlentitiesUTF8($message);
                                            if (isset($filename) && rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_ . '../upload/' . $filename)) {
                                                $cm->file_name = $filename;
                                            }
                                            $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                                            $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                                            if ($cm->add()) {
                                                if (empty($contact->email)) {
                                                    $var_list = array('{order_name}' => '-', '{attached_file}' => '-', '{message}' => stripslashes($message));
                                                    if ($ct->id_order) {
                                                        $order = new Order($ct->id_order);
                                                        $var_list['{order_name}'] = $order->reference;
                                                    }
                                                    if (isset($filename)) {
                                                        $var_list['{attached_file}'] = $_FILES['fileUpload']['name'];
                                                    }
                                                    Mail::Send($this->context->language->id, 'contact_form', Mail::l('Your message has been correctly sent'), $var_list, $from);
                                                }
                                                $this->context->smarty->assign('confirmation', 1);
                                            } else {
                                                $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                            }
                                        } else {
                                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                                        }
                                    }
                                    if (count($this->errors) > 1) {
                                        array_unique($this->errors);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
Example #12
0
 /**
  * Assign template vars if displaying one supplier
  */
 protected function assignOne()
 {
     if (Configuration::get('PS_DISPLAY_SUPPLIERS')) {
         $this->supplier->description = Tools::nl2br(trim($this->supplier->description));
         $this->pagination((int) $nbProducts);
         //$products = $this->supplier->getProducts($this->supplier->id, $this->context->cookie->id_lang, (int)$this->p, (int)$this->n, $this->orderBy, $this->orderWay);
         //$this->addColorsToProductList($products);
         $products = array();
         $a_categories = $this->supplier->getCategories();
         $this->context->smarty->assign(array('products' => $products, 'categories' => $a_categories, 'path' => $this->supplier->active ? Tools::safeOutput($this->supplier->name) : '', 'supplier' => $this->supplier, 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'body_classes' => array($this->php_self . '-' . $this->supplier->id, $this->php_self . '-' . $this->supplier->link_rewrite)));
     } else {
         Tools::redirect('index.php?controller=404');
     }
 }
Example #13
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, 
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.`wholesale_price`, product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('p.`id_product`, cp.`id_product_attribute`, cp.`date_add` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            //                        $quantityDiscount = SpecificPrice::getQuantityDiscount((int)$row['id_product'], $row['id_shop'],
            //			(int)$cart->id_currency, (int)$this->vat_address->id_country,
            //			(int)$this->customer->id_default_group, (int)$row['cart_quantity'], false, null, null, $null, true, true, $this->context);
            //
            //                        echo '<pre>';
            //                        print_r($quantityDiscount);
            //                        echo '</pre>';
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            if ($this->_taxCalculationMethod == PS_TAX_EXC) {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                // Here taxes are computed only once the quantity has been applied to the product price
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $cart_shop_context);
                $tax_rate = Tax::getProductTaxRate((int) $row['id_product'], (int) $address_id);
                $row['total_wt'] = Tools::ps_round($row['price'] * (double) $row['cart_quantity'] * (1 + (double) $tax_rate / 100), 2);
                $row['total'] = $row['price'] * (int) $row['cart_quantity'];
            } else {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, (int) $row['id_product_attribute'], 2, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, (int) $row['id_product_attribute'], 2, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $cart_shop_context);
                // In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals
                $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
                $row['total_wt'] = $row['price_wt'] * (int) $row['cart_quantity'];
                $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], 2);
                $row['description_short'] = Tools::nl2br($row['description_short']);
            }
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            if (Context::getContext()->language->id != 1) {
                $row['name'] = Tools::rus2translit($row['name']);
            }
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
    public function postProcess()
    {
        if ($id_customer_thread = (int) Tools::getValue('id_customer_thread')) {
            if ($id_contact = (int) Tools::getValue('id_contact')) {
                Db::getInstance()->execute('
					UPDATE ' . _DB_PREFIX_ . 'customer_thread
					SET id_contact = ' . (int) $id_contact . '
					WHERE id_customer_thread = ' . (int) $id_customer_thread);
            }
            if ($id_status = (int) Tools::getValue('setstatus')) {
                $status_array = array(1 => 'open', 2 => 'closed', 3 => 'pending1', 4 => 'pending2');
                Db::getInstance()->execute('
					UPDATE ' . _DB_PREFIX_ . 'customer_thread
					SET status = "' . $status_array[$id_status] . '"
					WHERE id_customer_thread = ' . (int) $id_customer_thread . ' LIMIT 1
				');
            }
            if (isset($_POST['id_employee_forward'])) {
                $messages = Db::getInstance()->getRow('
					SELECT ct.*, cm.*, cl.name subject, CONCAT(e.firstname, \' \', e.lastname) employee_name,
						CONCAT(c.firstname, \' \', c.lastname) customer_name, c.firstname
					FROM ' . _DB_PREFIX_ . 'customer_thread ct
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_message cm
						ON (ct.id_customer_thread = cm.id_customer_thread)
					LEFT JOIN ' . _DB_PREFIX_ . 'contact_lang cl
						ON (cl.id_contact = ct.id_contact AND cl.id_lang = ' . (int) $this->context->language->id . ')
					LEFT OUTER JOIN ' . _DB_PREFIX_ . 'employee e
						ON e.id_employee = cm.id_employee
					LEFT OUTER JOIN ' . _DB_PREFIX_ . 'customer c
						ON (c.email = ct.email)
					WHERE ct.id_customer_thread = ' . (int) Tools::getValue('id_customer_thread') . '
					ORDER BY cm.date_add DESC
				');
                $output = $this->displayMessage($messages, true, (int) Tools::getValue('id_employee_forward'));
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $this->context->employee->id;
                $cm->id_customer_thread = (int) Tools::getValue('id_customer_thread');
                $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                $current_employee = $this->context->employee;
                $id_employee = (int) Tools::getValue('id_employee_forward');
                $employee = new Employee($id_employee);
                $email = Tools::getValue('email');
                $message = Tools::getValue('message_forward');
                if (($error = $cm->validateField('message', $message, null, array(), true)) !== true) {
                    $this->errors[] = $error;
                } elseif ($id_employee && $employee && Validate::isLoadedObject($employee)) {
                    $params = array('{messages}' => stripslashes($output), '{employee}' => $current_employee->firstname . ' ' . $current_employee->lastname, '{comment}' => stripslashes(Tools::nl2br($_POST['message_forward'])), '{firstname}' => $employee->firstname, '{lastname}' => $employee->lastname);
                    if (Mail::Send($this->context->language->id, 'forward_msg', Mail::l('Fwd: Customer message', $this->context->language->id), $params, $employee->email, $employee->firstname . ' ' . $employee->lastname, $current_employee->email, $current_employee->firstname . ' ' . $current_employee->lastname, null, null, _PS_MAIL_DIR_, true)) {
                        $cm->private = 1;
                        $cm->message = $this->l('Message forwarded to') . ' ' . $employee->firstname . ' ' . $employee->lastname . "\n" . $this->l('Comment:') . ' ' . $message;
                        $cm->add();
                    }
                } elseif ($email && Validate::isEmail($email)) {
                    $params = array('{messages}' => Tools::nl2br(stripslashes($output)), '{employee}' => $current_employee->firstname . ' ' . $current_employee->lastname, '{comment}' => stripslashes($_POST['message_forward']));
                    if (Mail::Send($this->context->language->id, 'forward_msg', Mail::l('Fwd: Customer message', $this->context->language->id), $params, $email, null, $current_employee->email, $current_employee->firstname . ' ' . $current_employee->lastname, null, null, _PS_MAIL_DIR_, true)) {
                        $cm->message = $this->l('Message forwarded to') . ' ' . $email . "\n" . $this->l('Comment:') . ' ' . $message;
                        $cm->add();
                    }
                } else {
                    $this->errors[] = '<div class="alert error">' . Tools::displayError('The email address is invalid.') . '</div>';
                }
            }
            if (Tools::isSubmit('submitReply')) {
                $ct = new CustomerThread($id_customer_thread);
                ShopUrl::cacheMainDomainForShop((int) $ct->id_shop);
                $cm = new CustomerMessage();
                $cm->id_employee = (int) $this->context->employee->id;
                $cm->id_customer_thread = $ct->id;
                $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                $cm->message = Tools::getValue('reply_message');
                if (($error = $cm->validateField('message', $cm->message, null, array(), true)) !== true) {
                    $this->errors[] = $error;
                } elseif (isset($_FILES) && !empty($_FILES['joinFile']['name']) && $_FILES['joinFile']['error'] != 0) {
                    $this->errors[] = Tools::displayError('An error occurred during the file upload process.');
                } elseif ($cm->add()) {
                    $file_attachment = null;
                    if (!empty($_FILES['joinFile']['name'])) {
                        $file_attachment['content'] = file_get_contents($_FILES['joinFile']['tmp_name']);
                        $file_attachment['name'] = $_FILES['joinFile']['name'];
                        $file_attachment['mime'] = $_FILES['joinFile']['type'];
                    }
                    $customer = new Customer($ct->id_customer);
                    $params = array('{reply}' => Tools::nl2br(Tools::getValue('reply_message')), '{link}' => Tools::url($this->context->link->getPageLink('contact', true), 'id_customer_thread=' . (int) $ct->id . '&token=' . $ct->token), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname);
                    //#ct == id_customer_thread    #tc == token of thread   <== used in the synchronization imap
                    $contact = new Contact((int) $ct->id_contact, (int) $ct->id_lang);
                    if (Validate::isLoadedObject($contact)) {
                        $from_name = $contact->name;
                        $from_email = $contact->email;
                    } else {
                        $from_name = null;
                        $from_email = null;
                    }
                    if (Mail::Send((int) $ct->id_lang, 'reply_msg', sprintf(Mail::l('An answer to your message is available #ct%1$s #tc%2$s', $ct->id_lang), $ct->id, $ct->token), $params, Tools::getValue('msg_email'), null, $from_email, $from_name, $file_attachment, null, _PS_MAIL_DIR_, true)) {
                        $ct->status = 'closed';
                        $ct->update();
                    }
                    Tools::redirectAdmin(self::$currentIndex . '&id_customer_thread=' . (int) $id_customer_thread . '&viewcustomer_thread&token=' . Tools::getValue('token'));
                } else {
                    $this->errors[] = Tools::displayError('An error occurred. Your message was not sent. Please contact your system administrator.');
                }
            }
        }
        return parent::postProcess();
    }
 /**
  * Sanitize data which will be injected into SQL query
  *
  * @param string $string SQL data which will be injected into SQL query
  * @param boolean $html_ok Does data contain HTML code ? (optional)
  * @return string Sanitized data
  */
 public function escape($string, $html_ok = false)
 {
     if (_PS_MAGIC_QUOTES_GPC_) {
         $string = stripslashes($string);
     }
     if (!is_numeric($string)) {
         $string = $this->_escape($string);
         if (!$html_ok) {
             $string = strip_tags(Tools::nl2br($string));
         }
     }
     return $string;
 }
Example #16
0
    private function _displayConfiguration()
    {
        $this->_html .= '
		<script type="text/javascript">
			$(document).ready(function() {
				$(\'#submitCreateAccount\').unbind(\'click\').click(function() {
					if (!$(\'#terms_and_conditions\').attr(\'checked\'))
					{
						alert(\'' . addslashes($this->l('Please accept the terms of service.')) . '\');
						return false;
					}
				});										
			});
		</script>
		<fieldset><legend>' . $this->l('PrestaShop Security configuration') . '</legend>
			<div id="choose_account">
				<center>
				<form>
					<input type="radio" ' . (!Configuration::get('PS_TRUST_SHOP_ID') ? 'checked="checked"' : '') . ' onclick="$(\'#create_account\').show(); $(\'#module_configuration\').hide();" id="trust_account_on" name="trust_account" value="0"/> <b>' . $this->l('My shop does not have a PrestaShop Security account yet') . '</b>&nbsp;&nbsp;&nbsp;
					<input type="radio" ' . (Configuration::get('PS_TRUST_SHOP_ID') ? 'checked="checked"' : '') . ' onclick="$(\'#create_account\').hide(); $(\'#module_configuration\').show();"  id="trust_account_off" name="trust_account" value="1" /> <b>' . $this->l('I already have an account') . '</b>
				</form>
				</center>
			</div>
			<div class="clear">&nbsp;</div>
			<div id="create_account" ' . (Configuration::get('PS_TRUST_SHOP_ID') ? 'style="display:none;"' : '') . '>
				<form action="' . Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']) . '" method="post" name="prestashop_trust" id="prestashop_trust">
					<label>' . $this->l('Your email') . '</label>
					<div class="margin-form">
						<input type="text" style="width:200px;" name="email" value="' . Tools::safeOutput(Tools::getValue('email')) . '" />
					</div>
					<label>' . $this->l('Shop Url') . '</label>
					<div class="margin-form">
						<input type="text" style="width:400px;" name="shop_url" value="http://www.' . Tools::getHttpHost() . __PS_BASE_URI__ . '"/>
					</div>
					<div class="margin-form">
						<input id="terms_and_conditions" type="checkbox" value="1" /> ' . $this->l('I agree with the terms of PrestaShop Security service and I adhere to them unconditionally.') . '</label>
					</div>
					<div id="terms" class="margin-form">';
        $terms = Tools::file_get_contents($this->_trustUrl . 'terms.php?lang=' . $this->context->language->iso_code);
        $this->_html .= '<div style="height:300px;border:1px solid #E0D0B1;overflow-y:scroll;padding:8px;color:black">' . Tools::nl2br(strip_tags($terms)) . '</div>';
        $this->_html .= '</div>
					<div class="margin-form">
						<input class="button" type="submit" id="submitCreateAccount" name="submitCreateAccount" value="' . $this->l('Create account') . '"/>
					</div>
				</form>
				<div class="clear">&nbsp;</div>
			</div>
			<div id="module_configuration" ' . (!Configuration::get('PS_TRUST_SHOP_ID') ? 'style="display:none"' : '') . '>
			<form action="' . Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']) . '" method="post" name="prestashop_trust" id="prestashop_trust">
				<label>' . $this->l('Shop ID') . '</label>
				<div class="margin-form">
					<input type="text" style="width:150px"  name="shop_id" value="' . Configuration::get('PS_TRUST_SHOP_ID') . '"/>
				</div>
				<label>' . $this->l('Shop KEY') . '</label>
				<div class="margin-form">
					<input type="text" style="width:300px" name="shop_key" value="' . Configuration::get('PS_TRUST_SHOP_KEY') . '"/>
				</div>
				<div class="clear">&nbsp;</div>
				<label>' . $this->l('Shop activity') . '</label>
				<div class="margin-form">
					<select name="shop_activity">';
        foreach ($this->_activities as $k => $activity) {
            $this->_html .= '<option value="' . $k . '" ' . ($k == Configuration::get('PS_SHOP_ACTIVITY') ? 'selected="selected"' : '') . '>' . $activity . '</option>';
        }
        $this->_html .= '</select>
				</div>';
        $carriers = Carrier::getCarriers($this->context->language->id, true);
        $trust_carriers_type = $this->_getPrestaTrustCarriersType();
        $configured_carriers = $this->_getConfiguredCarriers();
        $this->_html .= '
				<label>' . $this->l('Carriers') . '</label>
				<div class="margin-form">
					<table cellspacing="0" cellpadding="0" class="table">
						<thead><tr><th>' . $this->l('Carrier') . '</th><th>' . $this->l('Carrier Type') . '</th></tr></thead><tbody>';
        foreach ($carriers as $carrier) {
            $this->_html .= '<tr><td>' . $carrier['name'] . '</td><td><select name="carrier_' . $carrier['id_carrier'] . '">
			<option value="0">' . $this->l('Choose a carrier type...') . '</option>';
            foreach ($this->_getPrestaTrustCarriersType() as $type => $name) {
                $this->_html .= '<option value="' . $type . '"' . ((isset($configured_carriers[$carrier['id_carrier']]) and $type == $configured_carriers[$carrier['id_carrier']]) ? ' selected="selected"' : '') . '>' . $name . '</option>';
            }
            $this->_html .= '</select></td>';
        }
        $this->_html .= '</tbody></table></margin>
			</div>';
        $modules = PaymentModule::getInstalledPaymentModules();
        $configured_payments = $this->_getConfiguredPayments();
        $this->_html .= '
				<label>' . $this->l('Payments') . '</label>
				<div class="margin-form">
					<table cellspacing="0" cellpadding="0" class="table">
						<thead><tr><th>' . $this->l('Payment Module') . '</th><th>' . $this->l('Payment Type') . '</th></tr></thead><tbody>';
        foreach ($modules as $module) {
            $mod = Module::getInstanceByName($module['name']);
            $this->_html .= '<tr><td>' . $mod->displayName . '</td><td><select name="paymentmodule_' . $mod->id . '">
			<option value="0">' . $this->l('Choose a payment type...') . '</option>';
            foreach ($this->_payment_types as $type => $name) {
                $this->_html .= '<option value="' . $type . '"' . ((isset($configured_payments[$mod->id]) and $type == $configured_payments[$mod->id]) ? ' selected="true"' : '') . '>' . $name . '</option>';
            }
            $this->_html .= '</select></td>';
        }
        $this->_html .= '</tbody></table></margin>
			</div>';
        $this->_html .= '<center><input type="submit" name="submitSettings" value="' . $this->l('Save') . '" class="button" /></center>
		</form>
		</div>
		</fieldset>';
        return $this->_html;
    }
Example #17
0
 public function hookPaymentReturn($params)
 {
     if (!$this->active) {
         return;
     }
     $state = $params['objOrder']->getCurrentState();
     if (in_array($state, array(Configuration::get('PS_OS_BANKWIRE'), Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')))) {
         $this->smarty->assign(array('total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false), 'bankwireDetails' => Tools::nl2br($this->details), 'bankwireAddress' => Tools::nl2br($this->address), 'bankwireOwner' => $this->owner, 'status' => 'ok', 'id_order' => $params['objOrder']->id));
         if (isset($params['objOrder']->reference) && !empty($params['objOrder']->reference)) {
             $this->smarty->assign('reference', $params['objOrder']->reference);
         }
     } else {
         $this->smarty->assign('status', 'failed');
     }
     return $this->display(__FILE__, 'payment_return.tpl');
 }
 public function processData()
 {
     if (Module::isInstalled('agilemultipleshop') && Shop::$id_shop_owner > 0) {
         if (!Validate::isLoadedObject($this->seller)) {
             $this->errors[] = Tools::displayError('Seller does not exist');
         } elseif (!$this->seller->active) {
             self::$smarty->assign('seller', $this->seller);
         } else {
             $rewrited_url = self::$link->getAgileSellerLink((int) $this->seller->id, $this->getSellerLinkRwrite());
             $this->seller_info->description = _PS_VERSION_ > '1.5' ? Tools::nl2br($this->seller_info->description) : nl2br2($this->seller_info->description);
             // Setting language and language level
             $language_level = explode(',', $this->seller_info->language_level);
             $language = explode(',', $this->seller_info->language);
             $language_array = array();
             for ($x = 0; $x < count($language); $x++) {
                 $language_array[] = $language[$x] . ' - ' . $language_level[$x];
             }
             $this->seller_info->language = $language_array;
             self::$smarty->assign('seller', $this->seller);
             self::$smarty->assign('seller_info', $this->seller_info);
             $imgPath = _PS_ROOT_DIR_ . DS . 'img' . DS . 'as' . DS . $this->seller_info->id_sellerinfo;
             $licenseImg = _PS_ROOT_DIR_ . DS . 'img' . DS . 'as' . DS . $this->seller_info->id_sellerinfo . '_license';
             $images = scandir($imgPath);
             unset($images[0]);
             unset($images[1]);
             $images = array_values($images);
             @($licenseDir = scandir($licenseImg));
             $licenseExist = count($licenseDir) > 2 ? 1 : 0;
             $this->seller_info->seller_images = $images;
             $sellermodule = new AgileMultipleSeller();
             $conf = Configuration::getMultiple($sellermodule->getCustomFields());
             $custom_labels = $sellermodule->getCustomLabels();
             self::$smarty->assign('conf', $conf);
             self::$smarty->assign('custom_labels', $custom_labels);
             $nbProducts = $this->getProducts(NULL, NULL, NULL, $this->orderBy, $this->orderWay, true);
             $this->pagination((int) $nbProducts);
             self::$smarty->assign('nb_products', (int) $nbProducts);
             $seller_products = $this->getProducts((int) self::$cookie->id_lang, (int) $this->p, (int) $this->n, $this->orderBy, $this->orderWay);
             AgileHelper::AssignProductImgs($seller_products);
             $si_1531_later = version_compare(_PS_VERSION_, '1.5.3.1', ">=");
             $HOOK_SELLER_RATINGS = '';
             if (Module::isInstalled('agilesellerratings')) {
                 require_once _PS_ROOT_DIR_ . "/modules/agilesellerratings/agilesellerratings.php";
                 $rmodule = new AgileSellerRatings();
                 $HOOK_SELLER_RATINGS = $rmodule->getAverageRating($this->id_seller, AgileSellerRatings::RATING_TYPE_SELLER);
             }
             /*foreach($seller_products as $k => $v) {
             			$country = $v['country'];
             			$flagId = Country::getIdByName(1, $country);
             			$seller_products[$k]['img_exist']	= file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini'. DS . $flagId . '.jpg')? 1 : 0;
             			$seller_products[$k]['img_name']	= $flagId . '.jpg';
             		}*/
             foreach ($seller_products as $key => $value) {
                 $seller_id = $value['id_seller'];
                 $flagIds = self::getFlagsId($seller_id);
                 foreach ($flagIds as $k => $flgId) {
                     $seller_products[$key]['img_exist'][$k] = file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini' . DS . $flgId . '.jpg') ? 1 : 0;
                     $seller_products[$key]['img_name'][$k] = $flgId . '.jpg';
                 }
             }
             // die('<pre>' . print_r($seller_products, true));
             self::$smarty->assign(array('products' => (isset($seller_products) and $seller_products) ? $seller_products : NULL, 'license_exist' => $licenseExist, 'id_seller' => (int) $this->seller->id, 'path' => $this->seller_info->company, 'agilesellerproducts_tpl' => _PS_ROOT_DIR_ . "/modules/agilesellerproducts/", 'agilemultipleshop_tpl' => _PS_ROOT_DIR_ . "/modules/agilemultipleshop/", 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('category') : 'category'), 'mediumSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('medium') : 'medium'), 'thumbSceneSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('thumb_scene') : 'thumb_scene'), 'homeSize' => Image::getSize($si_1531_later ? ImageType::getFormatedName('home') : 'home'), 'HOOK_SELLER_RATINGS' => $HOOK_SELLER_RATINGS, 'page_name' => 'agileseller'));
             $ver = (int) str_replace(".", "", _PS_VERSION_);
             if ($ver <= 1430) {
             } else {
                 if ($ver <= 1451) {
                     if (isset(self::$cookie->id_customer)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getCustomerCompareProducts((int) self::$cookie->id_customer));
                     } elseif (isset(self::$cookie->id_guest)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getGuestCompareProducts((int) self::$cookie->id_guest));
                     }
                 } else {
                     if (isset(self::$cookie->id_compare)) {
                         self::$smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) self::$cookie->id_compare));
                     }
                 }
             }
         }
         self::$smarty->assign(array('allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers()));
     }
 }
    /**
     * Start forms process
     * @see FrontController::postProcess()
     */
    public function postProcess()
    {
        if (Tools::isSubmit('submitMessage')) {
            $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
            $file_attachment = Tools::fileAttachment('fileUpload');
            $message = Tools::getValue('message');
            // Html entities is not usefull, iscleanHtml check there is no bad html tags.
            if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid email address.');
            } elseif (!$message) {
                $this->errors[] = Tools::displayError('The message cannot be blank.');
            } elseif (!Validate::isCleanHtml($message)) {
                $this->errors[] = Tools::displayError('Invalid message');
            } elseif (!($id_contact = (int) Tools::getValue('id_contact')) || !Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))) {
                $this->errors[] = Tools::displayError('Please select a subject from the list provided. ');
            } elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0) {
                $this->errors[] = Tools::displayError('An error occurred during the file-upload process.');
            } elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension)) {
                $this->errors[] = Tools::displayError('Bad file extension');
            } else {
                $customer = $this->context->customer;
                if (!$customer->id) {
                    $customer->getByEmail($from);
                }
                $id_order = (int) $this->getOrder();
                if (!(($id_customer_thread = (int) Tools::getValue('id_customer_thread')) && (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') || ($id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order)))) {
                    $fields = Db::getInstance()->executeS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND cm.id_shop = ' . (int) $this->context->shop->id . ' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) $id_order . ')');
                    $score = 0;
                    foreach ($fields as $key => $row) {
                        $tmp = 0;
                        if ((int) $row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from) {
                            continue;
                        }
                        if ($row['id_order'] != 0 && $id_order != $row['id_order']) {
                            continue;
                        }
                        if ($row['email'] == $from) {
                            $tmp += 4;
                        }
                        if ($row['id_contact'] == $id_contact) {
                            $tmp++;
                        }
                        if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product')) {
                            $tmp += 2;
                        }
                        if ($tmp >= 5 && $tmp >= $score) {
                            $score = $tmp;
                            $id_customer_thread = $row['id_customer_thread'];
                        }
                    }
                }
                $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					LEFT JOIN ' . _DB_PREFIX_ . 'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
					WHERE cc.id_customer_thread = ' . (int) $id_customer_thread . ' AND cc.id_shop = ' . (int) $this->context->shop->id . '
					ORDER BY cm.date_add DESC');
                if ($old_message == $message) {
                    $this->context->smarty->assign('alreadySent', 1);
                    $contact->email = '';
                    $contact->customer_service = 0;
                }
                if ($contact->customer_service) {
                    if ((int) $id_customer_thread) {
                        $ct = new CustomerThread($id_customer_thread);
                        $ct->status = 'open';
                        $ct->id_lang = (int) $this->context->language->id;
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_order = (int) $id_order;
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->update();
                    } else {
                        $ct = new CustomerThread();
                        if (isset($customer->id)) {
                            $ct->id_customer = (int) $customer->id;
                        }
                        $ct->id_shop = (int) $this->context->shop->id;
                        $ct->id_order = (int) $id_order;
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_lang = (int) $this->context->language->id;
                        $ct->email = $from;
                        $ct->status = 'open';
                        $ct->token = Tools::passwdGen(12);
                        $ct->add();
                    }
                    if ($ct->id) {
                        $cm = new CustomerMessage();
                        $cm->id_customer_thread = $ct->id;
                        $cm->message = $message;
                        if (isset($file_attachment['rename']) && !empty($file_attachment['rename']) && rename($file_attachment['tmp_name'], _PS_UPLOAD_DIR_ . basename($file_attachment['rename']))) {
                            $cm->file_name = $file_attachment['rename'];
                            @chmod(_PS_UPLOAD_DIR_ . basename($file_attachment['rename']), 0664);
                        }
                        $cm->ip_address = (int) ip2long(Tools::getRemoteAddr());
                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                        if (!$cm->add()) {
                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                        }
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                    }
                }
                if (!count($this->errors)) {
                    $var_list = array('{order_name}' => '-', '{attached_file}' => '-', '{message}' => Tools::nl2br(stripslashes($message)), '{email}' => $from, '{product_name}' => '');
                    if (isset($file_attachment['name'])) {
                        $var_list['{attached_file}'] = $file_attachment['name'];
                    }
                    $id_product = (int) Tools::getValue('id_product');
                    if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order) {
                        $order = new Order((int) $ct->id_order);
                        $var_list['{order_name}'] = $order->getUniqReference();
                        $var_list['{id_order}'] = (int) $order->id;
                    }
                    if ($id_product) {
                        $product = new Product((int) $id_product);
                        if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id])) {
                            $var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
                        }
                    }
                    if (empty($contact->email)) {
                        Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null, $file_attachment);
                    } else {
                        if (!Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form') . ' [no_sync]', $var_list, $contact->email, $contact->name, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $from) || !Mail::Send($this->context->language->id, 'contact_form', isset($ct) && Validate::isLoadedObject($ct) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent'), $var_list, $from, null, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $contact->email)) {
                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
                        }
                    }
                }
                if (count($this->errors) > 1) {
                    array_unique($this->errors);
                } elseif (!count($this->errors)) {
                    $this->context->smarty->assign('confirmation', 1);
                }
            }
        }
    }
Example #20
0
 public function postProcess()
 {
     if (Tools::isSubmit('submitMessage')) {
         $idOrder = (int) Tools::getValue('id_order');
         $msgText = Tools::getValue('msgText');
         if (!$idOrder || !Validate::isUnsignedId($idOrder)) {
             $this->errors[] = Tools::displayError('The order is no longer valid.');
         } elseif (empty($msgText)) {
             $this->errors[] = Tools::displayError('The message cannot be blank.');
         } elseif (!Validate::isMessage($msgText)) {
             $this->errors[] = Tools::displayError('This message is invalid (HTML is not allowed).');
         }
         if (!count($this->errors)) {
             $order = new Order($idOrder);
             if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id) {
                 //check if a thread already exist
                 $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($this->context->customer->email, $order->id);
                 $id_product = (int) Tools::getValue('id_product');
                 $cm = new CustomerMessage();
                 if (!$id_customer_thread) {
                     $ct = new CustomerThread();
                     $ct->id_contact = 0;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     if ($id_product && $order->orderContainProduct((int) $id_product)) {
                         $ct->id_product = $id_product;
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $this->context->customer->email;
                     $ct->status = 'open';
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     $ct = new CustomerThread((int) $id_customer_thread);
                 }
                 $cm->id_customer_thread = $ct->id;
                 if ($id_product && $order->orderContainProduct((int) $id_product)) {
                     $cm->id_product = $id_product;
                 }
                 $cm->message = $msgText;
                 $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                 $cm->add();
                 if (!Configuration::get('PS_MAIL_EMAIL_MESSAGE')) {
                     $to = strval(Configuration::get('PS_SHOP_EMAIL'));
                 } else {
                     $to = new Contact((int) Configuration::get('PS_MAIL_EMAIL_MESSAGE'));
                     $to = strval($to->email);
                 }
                 $toName = strval(Configuration::get('PS_SHOP_NAME'));
                 $customer = $this->context->customer;
                 $product = new Product($id_product);
                 $product_name = '';
                 if (Validate::isLoadedObject($product) && isset($product->name[(int) $this->context->language->id])) {
                     $product_name = $product->name[(int) $this->context->language->id];
                 }
                 if (Validate::isLoadedObject($customer)) {
                     Mail::Send($this->context->language->id, 'order_customer_comment', Mail::l('Message from a customer'), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => Tools::nl2br($msgText), '{product_name}' => $product_name), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 if (Tools::getValue('ajax') != 'true') {
                     Tools::redirect('index.php?controller=order-detail&id_order=' . (int) $idOrder);
                 }
                 $this->context->smarty->assign('message_confirmation', true);
             } else {
                 $this->errors[] = Tools::displayError('Order not found');
             }
         }
     }
     if (Tools::isSubmit('markAsReceived')) {
         $idOrder = (int) Tools::getValue('id_order');
         $order = new Order($idOrder);
         if (Validate::isLoadedObject($order)) {
             if ($order->getCurrentState() == 15) {
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState(3, $order);
                 // 16: Ready for Production
                 //var_dump($order,$new_history);
                 $myfile = fopen(PS_PRODUCT_IMG_PATH . "/orders/" . $order->reference . ".txt", "w") or die("Unable to open file!");
                 $txt = "Order Confirmed\n Order Reference: " . $order->reference;
                 fwrite($myfile, $txt);
                 fclose($myfile);
                 $new_history->addWithemail(true);
             }
             $this->context->smarty->assign('receipt_confirmation', true);
         } else {
             $this->_errors[] = Tools::displayError('Error: Invalid order number');
         }
     }
 }
Example #21
0
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     if (Tools::isSubmit('submitMessage')) {
         $idOrder = (int) Tools::getValue('id_order');
         $msgText = Tools::getValue('msgText');
         if (!$idOrder || !Validate::isUnsignedId($idOrder)) {
             $this->errors[] = Tools::displayError('The order is no longer valid.');
         } elseif (empty($msgText)) {
             $this->errors[] = Tools::displayError('The message cannot be blank.');
         } elseif (!Validate::isMessage($msgText)) {
             $this->errors[] = Tools::displayError('This message is invalid (HTML is not allowed).');
         }
         if (!count($this->errors)) {
             $order = new Order($idOrder);
             if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id) {
                 //check if a thread already exist
                 $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($this->context->customer->email, $order->id);
                 $cm = new CustomerMessage();
                 if (!$id_customer_thread) {
                     $ct = new CustomerThread();
                     $ct->id_contact = 0;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     if (($id_product = (int) Tools::getValue('id_product')) && $order->orderContainProduct((int) $id_product)) {
                         $ct->id_product = $id_product;
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $this->context->customer->email;
                     $ct->status = 'open';
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     $ct = new CustomerThread((int) $id_customer_thread);
                 }
                 $cm->id_customer_thread = $ct->id;
                 $cm->message = $msgText;
                 $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                 $cm->add();
                 if (!Configuration::get('PS_MAIL_EMAIL_MESSAGE')) {
                     $to = strval(Configuration::get('PS_SHOP_EMAIL'));
                 } else {
                     $to = new Contact((int) Configuration::get('PS_MAIL_EMAIL_MESSAGE'));
                     $to = strval($to->email);
                 }
                 $toName = strval(Configuration::get('PS_SHOP_NAME'));
                 $customer = $this->context->customer;
                 if (Validate::isLoadedObject($customer)) {
                     Mail::Send($this->context->language->id, 'order_customer_comment', Mail::l('Message from a customer'), array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{email}' => $customer->email, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => Tools::nl2br($msgText)), $to, $toName, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 if (Tools::getValue('ajax') != 'true') {
                     Tools::redirect('index.php?controller=order-detail&id_order=' . (int) $idOrder);
                 }
                 $this->context->smarty->assign('message_confirmation', true);
             } else {
                 $this->errors[] = Tools::displayError('Order not found');
             }
         }
     }
 }
 public function postProcess()
 {
     ${${"GLOBALS"}["thtbvco"]} = new Order((int) Tools::getValue("id_order"));
     $difdqhzqxl = "id_order_seller";
     if (!Validate::isLoadedObject(${${"GLOBALS"}["thtbvco"]})) {
         $this->errors[] = Tools::displayError("Order not found or you do not have permission to view this order.");
         return;
     }
     ${"GLOBALS"}["fqitvbmdfl"] = "order";
     ${${"GLOBALS"}["gfrblyem"]} = AgileSellerManager::getObjectOwnerID("order", $order->id);
     ${"GLOBALS"}["bsmpehdujqe"] = "id_customer_seller";
     ${${"GLOBALS"}["taultlaseq"]} = AgileSellerManager::getLinkedSellerID($this->context->customer->id);
     $qjwuyezbnwd = "order";
     if (${$difdqhzqxl} != ${${"GLOBALS"}["taultlaseq"]} || ${${"GLOBALS"}["gfrblyem"]} <= 0 || ${${"GLOBALS"}["bsmpehdujqe"]} <= 0) {
         $this->errors[] = Tools::displayError("You do not have permission to view this order.");
         return;
     }
     if (Tools::isSubmit("submitShippingNumber") && isset(${${"GLOBALS"}["fqitvbmdfl"]})) {
         ${"GLOBALS"}["mllzihk"] = "order_carrier";
         $fdknpwcl = "order_carrier";
         ${$fdknpwcl} = new OrderCarrier(Tools::getValue("id_order_carrier"));
         if (!Validate::isLoadedObject(${${"GLOBALS"}["mllzihk"]})) {
             $this->errors[] = Tools::displayError("The order carrier ID is invalid.");
         } elseif (!Validate::isTrackingNumber(Tools::getValue("tracking_number"))) {
             $this->errors[] = Tools::displayError("The tracking number is incorrect.");
         } else {
             $order->shipping_number = Tools::getValue("tracking_number");
             $order->update();
             $order_carrier->tracking_number = pSQL(Tools::getValue("tracking_number"));
             if ($order_carrier->update()) {
                 $qvvnrvmsp = "templateVars";
                 ${${"GLOBALS"}["cdmray"]} = new Customer((int) $order->id_customer);
                 $ijyvqhqokid = "carrier";
                 ${"GLOBALS"}["mhbtmrqg"] = "templateVars";
                 ${$ijyvqhqokid} = new Carrier((int) $order_carrier->id_carrier, $order->id_lang);
                 if (!Validate::isLoadedObject(${${"GLOBALS"}["cdmray"]})) {
                     throw new PrestaShopException("Can't load Customer object");
                 }
                 if (!Validate::isLoadedObject(${${"GLOBALS"}["tvqrewgc"]})) {
                     throw new PrestaShopException("Can't load Carrier object");
                 }
                 ${${"GLOBALS"}["mhbtmrqg"]} = array("{followup}" => str_replace("@", $order_carrier->tracking_number, $carrier->url), "{firstname}" => $customer->firstname, "{lastname}" => $customer->lastname, "{id_order}" => $order->id, "{shipping_number}" => $order_carrier->tracking_number, "{order_name}" => $order->getUniqReference());
                 if (@Mail::Send((int) $order->id_lang, "in_transit", Mail::l('Package in transit', (int) $order->id_lang), ${$qvvnrvmsp}, $customer->email, $customer->firstname . " " . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                     ${"GLOBALS"}["rwzquyb"] = "order";
                     Hook::exec("actionAdminOrdersTrackingNumberUpdate", array("order" => ${${"GLOBALS"}["rwzquyb"]}, "customer" => ${${"GLOBALS"}["cdmray"]}, "carrier" => ${${"GLOBALS"}["tvqrewgc"]}), null, false, true, false, $order->id_shop);
                 } else {
                     $this->errors[] = Tools::displayError("An error occurred while sending an email to the customer.");
                 }
             } else {
                 $this->errors[] = Tools::displayError("The order carrier cannot be updated.");
             }
         }
     } elseif (Tools::isSubmit("submitState") && isset(${$qjwuyezbnwd})) {
         ${${"GLOBALS"}["bfrxhizen"]} = new OrderState(Tools::getValue("id_order_state"));
         if (!Validate::isLoadedObject(${${"GLOBALS"}["bfrxhizen"]})) {
             $this->errors[] = Tools::displayError("Invalid new order status");
         } else {
             ${${"GLOBALS"}["rxsllerec"]} = $order->getCurrentOrderState();
             if ($current_order_state->id != $order_state->id) {
                 $heccerkhiwt = "history";
                 ${$heccerkhiwt} = new OrderHistory();
                 ${"GLOBALS"}["uynetoegv"] = "templateVars";
                 $vriwvgqg = "templateVars";
                 $history->id_order = $order->id;
                 $history->id_employee = 1;
                 $history->changeIdOrderState($order_state->id, $order->id);
                 ${${"GLOBALS"}["tvqrewgc"]} = new Carrier($order->id_carrier, $order->id_lang);
                 ${$vriwvgqg} = array();
                 if ($history->id_order_state == Configuration::get("PS_OS_SHIPPING") && $order->shipping_number) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{followup}" => str_replace("@", $order->shipping_number, $carrier->url));
                 } elseif ($history->id_order_state == Configuration::get("PS_OS_CHEQUE")) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{cheque_name}" => Configuration::get("CHEQUE_NAME") ? Configuration::get("CHEQUE_NAME") : "", "{cheque_address_html}" => Configuration::get("CHEQUE_ADDRESS") ? nl2br(Configuration::get("CHEQUE_ADDRESS")) : "");
                 } elseif ($history->id_order_state == Configuration::get("PS_OS_BANKWIRE")) {
                     ${${"GLOBALS"}["nkwobosfw"]} = array("{bankwire_owner}" => Configuration::get("BANK_WIRE_OWNER") ? Configuration::get("BANK_WIRE_OWNER") : "", "{bankwire_details}" => Configuration::get("BANK_WIRE_DETAILS") ? nl2br(Configuration::get("BANK_WIRE_DETAILS")) : "", "{bankwire_address}" => Configuration::get("BANK_WIRE_ADDRESS") ? nl2br(Configuration::get("BANK_WIRE_ADDRESS")) : "");
                 }
                 if (!$history->addWithemail(true, ${${"GLOBALS"}["uynetoegv"]})) {
                     $this->errors[] = Tools::displayError("An error occurred while changing the status or was unable to send e-mail to the customer.");
                 }
             } else {
                 $this->errors[] = Tools::displayError("This order is already assigned this status");
             }
         }
         if (empty($this->errors)) {
             self::$smarty->assign("cfmmsg_flag", 1);
         }
     }
     if (Tools::isSubmit("submitMessage")) {
         $ipovlstkh = "idOrder";
         ${${"GLOBALS"}["pfwbejwlah"]} = (int) Tools::getValue("id_order");
         ${${"GLOBALS"}["nioumgdgj"]} = Tools::getValue("msgText");
         ${"GLOBALS"}["tumvnnp"] = "msgText";
         if (!${${"GLOBALS"}["pfwbejwlah"]} || !Validate::isUnsignedId(${$ipovlstkh})) {
             $this->errors[] = Tools::displayError("Order is no longer valid");
         } else {
             if (empty(${${"GLOBALS"}["nioumgdgj"]})) {
                 $this->errors[] = Tools::displayError("Message cannot be blank");
             } else {
                 if (!Validate::isMessage(${${"GLOBALS"}["tumvnnp"]})) {
                     $this->errors[] = Tools::displayError("Message is invalid (HTML is not allowed)");
                 }
             }
         }
         if (!count($this->errors)) {
             $svycwjflohh = "idOrder";
             ${${"GLOBALS"}["thtbvco"]} = new Order(${$svycwjflohh});
             if (Validate::isLoadedObject(${${"GLOBALS"}["thtbvco"]})) {
                 ${"GLOBALS"}["pcdbkuo"] = "cm";
                 ${"GLOBALS"}["qejrcjwlidu"] = "to";
                 ${${"GLOBALS"}["nbpumdloal"]} = new Employee();
                 $iilmenu = "seller";
                 ${$iilmenu} = $emp->getbyEmail($this->context->customer->email);
                 $ucwaikq = "customer";
                 ${$ucwaikq} = new Customer($order->id_customer);
                 ${${"GLOBALS"}["ryhapbx"]} = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                 ${"GLOBALS"}["pnxcso"] = "id_customer_thread";
                 ${${"GLOBALS"}["pcdbkuo"]} = new CustomerMessage();
                 ${"GLOBALS"}["csptele"] = "ct";
                 $pykymotfmtq = "fromName";
                 if (!${${"GLOBALS"}["pnxcso"]}) {
                     ${"GLOBALS"}["azdvluwhw"] = "id_product";
                     ${"GLOBALS"}["fpmtmpmcoy"] = "id_product";
                     $vckfnym = "id_product";
                     ${${"GLOBALS"}["docrub"]} = new CustomerThread();
                     $ct->id_contact = 2;
                     $ct->id_customer = (int) $order->id_customer;
                     $ct->id_shop = (int) $this->context->shop->id;
                     ${$vckfnym} = (int) Tools::getValue("id_product");
                     if (${${"GLOBALS"}["fxogbxc"]} && $order->orderContainProduct(${${"GLOBALS"}["azdvluwhw"]})) {
                         $ct->id_product = ${${"GLOBALS"}["fpmtmpmcoy"]};
                     }
                     $ct->id_order = (int) $order->id;
                     $ct->id_lang = (int) $this->context->language->id;
                     $ct->email = $customer->email;
                     $ct->status = "open";
                     $ct->token = Tools::passwdGen(12);
                     $ct->add();
                 } else {
                     ${${"GLOBALS"}["csptele"]} = new CustomerThread((int) ${${"GLOBALS"}["ryhapbx"]});
                 }
                 $qlkkcochivs = "msgText";
                 $cm->id_customer_thread = $ct->id;
                 $cm->message = ${${"GLOBALS"}["nioumgdgj"]};
                 $cm->ip_address = ip2long($_SERVER["REMOTE_ADDR"]);
                 $cm->id_employee = $seller->id;
                 $cm->add();
                 $mwsicth = "fromName";
                 ${"GLOBALS"}["lhbflpuhi"] = "customer";
                 ${${"GLOBALS"}["oatuem"]} = $customer->email;
                 ${${"GLOBALS"}["xtxkthxeqll"]} = $customer->firstname . " " . $customer->lastname;
                 ${${"GLOBALS"}["sormbzxw"]} = $seller->email;
                 ${$mwsicth} = $seller->firstname . " " . $seller->lastname;
                 if (Validate::isLoadedObject(${${"GLOBALS"}["lhbflpuhi"]})) {
                     Mail::Send($this->context->language->id, "order_merchant_comment", Mail::l('Message from a seller'), array("{lastname}" => $customer->lastname, "{firstname}" => $customer->firstname, "{email}" => $customer->email, "{id_order}" => (int) $order->id, "{order_name}" => $order->getUniqReference(), "{message}" => Tools::nl2br(${$qlkkcochivs})), ${${"GLOBALS"}["qejrcjwlidu"]}, ${${"GLOBALS"}["xtxkthxeqll"]}, ${${"GLOBALS"}["sormbzxw"]}, ${$pykymotfmtq});
                 }
             } else {
                 $this->errors[] = Tools::displayError("Order not found");
             }
         }
     }
 }
Example #23
0
 public function hookPaymentReturn($params)
 {
     if (!$this->active) {
         return;
     }
     $state = $params['objOrder']->getCurrentState();
     if ($state == Configuration::get('PS_OS_CHEQUE') || $state == Configuration::get('PS_OS_OUTOFSTOCK')) {
         $this->smarty->assign(array('total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false), 'chequeName' => $this->chequeName, 'chequeAddress' => Tools::nl2br($this->address), 'status' => 'ok', 'id_order' => $params['objOrder']->id));
         if (isset($params['objOrder']->reference) && !empty($params['objOrder']->reference)) {
             $this->smarty->assign('reference', $params['objOrder']->reference);
         }
     } else {
         $this->smarty->assign('status', 'failed');
     }
     return $this->display(__FILE__, 'payment_return.tpl');
 }
Example #24
0
/**
 * @deprecated
 */
function nl2br2($string)
{
    Tools::displayAsDeprecated();
    return Tools::nl2br($string);
}
Example #25
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $history->changeIdOrderState((int) $order_state->id, $order, $use_existings_payment);
                     $carrier = new Carrier($order->id_carrier, $order->id_lang);
                     $templateVars = array();
                     if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                         $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                             foreach ($order->getProducts() as $product) {
                                 if (StockAvailable::dependsOnStock($product['product_id'])) {
                                     StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
Example #26
0
 private function _postProcessParameters()
 {
     // Saving new configurations
     if ($this->setConfiguration('EBAY_PAYPAL_EMAIL', pSQL(Tools::getValue('ebay_paypal_email'))) && $this->setConfiguration('EBAY_IDENTIFIER', pSQL(Tools::getValue('ebay_identifier'))) && $this->setConfiguration('EBAY_RETURNS_ACCEPTED_OPTION', pSQL(Tools::getValue('ebay_returns_accepted_option'))) && $this->setConfiguration('EBAY_RETURNS_DESCRIPTION', version_compare(_PS_VERSION_, '1.5', '>') ? Tools::nl2br(Tools::getValue('ebay_returns_description')) : nl2br2(Tools::getValue('ebay_returns_description')), true) && $this->setConfiguration('EBAY_SHOP', pSQL(Tools::getValue('ebay_shop'))) && $this->setConfiguration('EBAY_SHOP_POSTALCODE', pSQL(Tools::getValue('ebay_shop_postalcode'))) && $this->setConfiguration('EBAY_LISTING_DURATION', Tools::getValue('listingdurations')) && $this->setConfiguration('EBAY_PICTURE_SIZE_DEFAULT', (int) Tools::getValue('sizedefault')) && $this->setConfiguration('EBAY_PICTURE_SIZE_SMALL', (int) Tools::getValue('sizesmall')) && $this->setConfiguration('EBAY_PICTURE_SIZE_BIG', (int) Tools::getValue('sizebig')) && $this->setConfiguration('EBAY_AUTOMATICALLY_RELIST', Tools::getValue('automaticallyrelist')) && $this->setConfiguration('EBAY_RETURNS_WITHIN', pSQL(Tools::getValue('returnswithin'))) && $this->setConfiguration('EBAY_RETURNS_WHO_PAYS', pSQL(Tools::getValue('returnswhopays')))) {
         $this->html .= $this->displayConfirmation($this->l('Settings updated'));
     } else {
         $this->html .= $this->displayError($this->l('Settings failed'));
     }
 }
Example #27
0
 public function getTemplateVarInfos()
 {
     $cart = $this->context->cart;
     $total = sprintf($this->trans('%1$s (tax incl.)', array(), 'Modules.BankBNI.Shop'), Tools::displayPrice($cart->getOrderTotal(true, Cart::BOTH)));
     $bankbniOwner = $this->owner;
     if (!$bankbniOwner) {
         $bankbniOwner = '___________';
     }
     $bankbniDetails = Tools::nl2br($this->details);
     if (!$bankbniDetails) {
         $bankbniDetails = '___________';
     }
     $bankbniAddress = Tools::nl2br($this->address);
     if (!$bankbniAddress) {
         $bankbniAddress = '___________';
     }
     $bankbniReservationDays = Configuration::get('BANK_BNI_RESERVATION_DAYS');
     if (false === $bankbniReservationDays) {
         $bankbniReservationDays = 7;
     }
     $bankbniCustomText = Tools::nl2br(Configuration::get('BANK_BNI_CUSTOM_TEXT', $this->context->language->id));
     if (false === $bankbniCustomText) {
         $bankbniCustomText = '';
     }
     return array('total' => $total, 'bankbniDetails' => $bankbniDetails, 'bankbniAddress' => $bankbniAddress, 'bankbniOwner' => $bankbniOwner, 'bankbniReservationDays' => (int) $bankbniReservationDays, 'bankbniCustomText' => $bankbniCustomText);
 }
 public function getTemplateVars()
 {
     $cart = $this->context->cart;
     $total = $this->trans('%amount% (tax incl.)', array('%amount%' => Tools::displayPrice($cart->getOrderTotal(true, Cart::BOTH))), 'Modules.CheckPayment.Admin');
     $checkOrder = Configuration::get('CHEQUE_NAME');
     if (!$checkOrder) {
         $checkOrder = '___________';
     }
     $checkAddress = Tools::nl2br(Configuration::get('CHEQUE_ADDRESS'));
     if (!$checkAddress) {
         $checkAddress = '___________';
     }
     return ['checkTotal' => $total, 'checkOrder' => $checkOrder, 'checkAddress' => $checkAddress];
 }
Example #29
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        /* 
         * EU-Legal
         * 1) correct calculation of prices -> Problem with inaccuracy at high number of items 
         * 2) assign standard delivery times to products
         */
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`delivery_now`, pl.`delivery_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, 
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        $sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`');
        // AND 'sp.`id_shop` = cp.`id_shop`
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity,
				IF(product_attribute_shop.wholesale_price > 0,  product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            $address = Address::initialize($address_id, true);
            $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context);
            $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, false, true, $cart_shop_context);
            switch (Configuration::get('PS_ROUND_TYPE')) {
                case Order::ROUND_TOTAL:
                    $row['total'] = $row['price'] * (int) $row['cart_quantity'];
                    $row['total_wt'] = $tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'];
                    break;
                case Order::ROUND_LINE:
                    $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    break;
                case Order::ROUND_ITEM:
                default:
                    $row['total'] = Tools::ps_round($row['price'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']), _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    break;
            }
            $row['price_wt'] = $tax_calculator->addTaxes($row['price']);
            $row['description_short'] = Tools::nl2br($row['description_short']);
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            /* 
             * EU-Legal
             * assign standard delivery times to products
             */
            $row['delivery_now'] = !empty($row['delivery_now']) ? $row['delivery_now'] : Configuration::get('LEGAL_DELIVERY_NOW', $this->id_lang);
            $row['delivery_later'] = !empty($row['delivery_later']) ? $row['delivery_later'] : Configuration::get('LEGAL_DELIVERY_LATER', $this->id_lang);
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
Example #30
0
 /**
  * Sanitize data which will be injected into SQL query
  *
  * @param string $string SQL data which will be injected into SQL query
  * @param bool $html_ok Does data contain HTML code ? (optional)
  * @return string Sanitized data
  */
 public function escape($string, $html_ok = false, $bq_sql = false)
 {
     if (_PS_MAGIC_QUOTES_GPC_) {
         $string = stripslashes($string);
     }
     if (!is_numeric($string)) {
         $string = $this->_escape($string);
         if (!$html_ok) {
             $string = strip_tags(Tools::nl2br($string));
         }
         if ($bq_sql === true) {
             $string = str_replace('`', '\\`', $string);
         }
     }
     return $string;
 }