public function addQuickLink() { if (!isset($this->className) || empty($this->className)) { return false; } $this->validateRules(); if (count($this->errors) <= 0) { $this->object = new $this->className(); $this->copyFromPost($this->object, $this->table); $exists = Db::getInstance()->getValue('SELECT id_quick_access FROM ' . _DB_PREFIX_ . 'quick_access WHERE link = "' . pSQL($this->object->link) . '"'); if ($exists) { return true; } $this->beforeAdd($this->object); if (method_exists($this->object, 'add') && !$this->object->add()) { $this->errors[] = Tools::displayError('An error occurred while creating an object.') . ' <b>' . $this->table . ' (' . Db::getInstance()->getMsgError() . ')</b>'; } elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect) { PrestaShopLogger::addLog(sprintf($this->l('%s addition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $this->object->id, true, (int) $this->context->employee->id); $this->afterAdd($this->object); } } $this->errors = array_unique($this->errors); if (!empty($this->errors)) { $this->errors['has_errors'] = true; $this->ajaxDie(Tools::jsonEncode($this->errors)); return false; } return $this->getQuickAccessesList(); }
/** * add a log item to the database and send a mail if configured for this $severity * * @param string $message the log message * @param int $severity * @param int $error_code * @param string $object_type * @param int $object_id * @param bool $allow_duplicate if set to true, can log several time the same information (not recommended) * @return bool true if succeed */ public static function addLog($message, $severity = 1, $error_code = null, $object_type = null, $object_id = null, $allow_duplicate = false, $id_employee = null) { $log = new PrestaShopLogger(); $log->severity = (int) $severity; $log->error_code = (int) $error_code; $log->message = pSQL($message); $log->date_add = date('Y-m-d H:i:s'); $log->date_upd = date('Y-m-d H:i:s'); if ($id_employee === null && isset(Context::getContext()->employee) && Validate::isLoadedObject(Context::getContext()->employee)) { $id_employee = Context::getContext()->employee->id; } if ($id_employee !== null) { $log->id_employee = (int) $id_employee; } if (!empty($object_type) && !empty($object_id)) { $log->object_type = pSQL($object_type); $log->object_id = (int) $object_id; } if ($object_type != 'Swift_Message') { PrestaShopLogger::sendByMail($log); } if ($allow_duplicate || !$log->_isPresent()) { $res = $log->add(); if ($res) { self::$is_present[$log->getHash()] = isset(self::$is_present[$log->getHash()]) ? self::$is_present[$log->getHash()] + 1 : 1; return true; } } return false; }
/** * @see FrontController::postProcess() */ public function postProcess() { // Log requests from Privat API side in Debug mode. if (Configuration::get('PRIVAT24_DEBUG_MODE')) { $logger = new FileLogger(); $logger->setFilename(_PS_ROOT_DIR_ . '/log/' . $this->module->name . '_' . date('Ymd_His') . '_response.log'); $logger->logError($_POST); } $payment = array(); parse_str(Tools::getValue('payment'), $payment); $hash = sha1(md5(Tools::getValue('payment') . $this->module->merchant_password)); if ($payment && $hash === Tools::getValue('signature')) { if ($payment['state'] == 'ok') { $state = Configuration::get('PRIVAT24_WAITINGPAYMENT_OS'); $cart_id = (int) $payment['order']; $order = new Order(Order::getOrderByCartId($cart_id)); if (!Validate::isLoadedObject($order)) { PrestaShopLogger::addLog('Privat24: cannot get order by cart id ' . $cart_id, 3); die; } if ($order->getCurrentState() != $state) { PrestaShopLogger::addLog(sprintf('Privat24: order id %s current state %s !== expected state %s', $order->id, $order->getCurrentState(), $state), 3); die; } // Check paid currency and paid amount. $id_currency = Currency::getIdByIsoCode($payment['ccy']); if (!$id_currency) { PrestaShopLogger::addLog(sprintf('Privat24: order id %s cannot get currency id by iso code: %s', $order->id, $payment['ccy']), 3); die; } if ($order->id_currency != $id_currency) { PrestaShopLogger::addLog(sprintf('Privat 24: order id %s, order currency id %s does not match with %s', $order->id, $order->id_currency, $id_currency), 3); die; } if ((double) $order->total_paid != (double) $payment['amt']) { PrestaShopLogger::addLog(sprintf('Privat 24: order id %s order total paid %s does not match %s', $order->id, $order->total_paid, $payment['amt']), 3); die; } $order_history = new OrderHistory(); $order_history->id_order = $order->id; $order_history->changeIdOrderState(_PS_OS_PAYMENT_, $order->id); $order_history->addWithemail(); $this->setPaymentTransaction($order, $payment); $this->module->paymentNotify($order, $payment); PrestaShopLogger::addLog(sprintf('Privat24 payment accepted: order id: %s, amount: %s, ref: %s', $order->id, $payment['amt'], $payment['ref']), 1); } else { PrestaShopLogger::addLog(sprintf('Privat24 payment failed: state: %s, order: %s, ref: %s', $payment['state'], $payment['order'], $payment['ref']), 3, null, null, null, true); } } else { PrestaShopLogger::addLog('Privat24: Payment callback bad signature.', 3, null, null, null, true); } die; }
/** * Displays message about occured technical error. * * @param Exception $ex Error cause. */ protected function displayTechnicalError(Exception $ex) { PrestaShopLogger::addLog((string) $ex, 50); $this->context->smarty->assign('error_message', $this->module->l('Technical error occured')); if ($this->context->customer->is_guest) { $this->context->smarty->assign(array('reference_order' => $this->module->currentOrderReference, 'email' => $this->context->customer->email)); /* If guest we clear the cookie for security reason */ $this->context->customer->mylogout(); } $this->setTemplate('payment_error.tpl'); parent::display(); }
public function displayAjax() { if (Configuration::get('MERCADOPAGO_LOG') == 'true') { PrestaShopLogger::addLog('Debug Mode :: displayAjax - topic = ' . Tools::getValue('topic'), MP::INFO, 0); PrestaShopLogger::addLog('Debug Mode :: displayAjax - id = ' . Tools::getValue('id'), MP::INFO, 0); PrestaShopLogger::addLog('Debug Mode :: displayAjax - checkout = ' . Tools::getValue('checkout'), MP::INFO, 0); } if (Tools::getValue('topic') && Tools::getValue('id')) { $mercadopago = new MercadoPago(); $mercadopago->listenIPN(Tools::getValue('checkout'), Tools::getValue('topic'), Tools::getValue('id')); } }
public function processUpdate() { $existing_offer = $this->object; $this->checkOffer(); if (!empty($this->errors)) { $this->display = 'edit'; return false; } $id = (int) Tools::getValue('id_' . $this->table); /* Update an existing offer */ if (isset($id) && !empty($id)) { /** @var Product $object */ $object = new $this->className((int) $id); $this->object = $object; if (Validate::isLoadedObject($object)) { $this->copyFromPost($object, $this->table); $object->indexed = 0; if ($object->update()) { PrestaShopLogger::addLog(sprintf($this->l('%s modification', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $this->object->id, true, (int) $this->context->employee->id); if (in_array(Shop::getContext(), array(Shop::CONTEXT_SHOP, Shop::CONTEXT_ALL))) { if ($this->isTabSubmitted('Products')) { $this->updateProducts($object); $this->updateCustomPrices($object); } if ($this->isTabSubmitted('Shops')) { $this->updateShops($object); $this->updateCustomPrices($object); } if ($this->isTabSubmitted('Images')) { $this->processImageLegends(); } } if (empty($this->errors)) { $page = (int) Tools::getValue('page'); // Save and stay on same form if ($this->display == 'edit') { $this->confirmations[] = $this->l('Update successful'); $this->redirect_after = self::$currentIndex . '&id_offer=' . (int) $this->object->id . '&updateoffer&conf=4&key_tab=' . Tools::safeOutput(Tools::getValue('key_tab')) . ($page > 1 ? '&page=' . (int) $page : '') . '&token=' . $this->token; } else { // Default behavior (save and back) $this->redirect_after = self::$currentIndex . '&conf=4' . ($page > 1 ? '&submitFilteroffer=' . (int) $page : '') . '&token=' . $this->token; } } else { $this->display = 'edit'; } } else { $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')'; } } else { $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Tools::displayError('The object cannot be loaded. ') . ')'; } return $object; } }
public function catchUrls() { if (Tools::getValue('ajax') && (bool) Tools::getValue('ajax') == true) { return; } // Setup $uri_var = $this->formatLink($_SERVER['REQUEST_URI']); $id_shop = Shop::getContextShopID(); $db = Db::getInstance(); $redir = array(); $cache_enabled = (bool) Configuration::get('MGRT_URLCACHE'); $cache_name = 'MR1_' . $id_shop . '_' . Tools::str2url($uri_var); $cache_file = $this->cache_folder . md5($cache_name); // Better checking this before if ($cache_enabled === true && is_writable(_PS_CACHE_DIR_) && file_exists($this->cache_folder)) { $time_cache = (int) Configuration::get('MGRT_CACHETIME'); if (file_exists($cache_file) && filemtime($cache_file) > time() - $time_cache * 60) { $datas = Tools::file_get_contents($cache_file); $redir = unserialize($datas); return $this->makeRedirection($redir); } } $sql_redir = $db->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'redirect r, ' . _DB_PREFIX_ . 'redirect_shop rs WHERE rs.id_redirect = r.id_redirect AND r.old = "' . pSQL($uri_var) . '" AND rs.id_shop = ' . (int) $id_shop . ' AND r.active = 1 AND r.regex = 0 ORDER BY date_upd DESC'); if (empty($sql_redir)) { $sql_regex = $db->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'redirect r, ' . _DB_PREFIX_ . 'redirect_shop rs WHERE rs.id_redirect = r.id_redirect AND rs.id_shop = ' . (int) $id_shop . ' AND r.active = 1 AND r.regex = 1 ORDER BY date_upd DESC'); $before = '/\\'; $after = '/i'; if (!empty($sql_regex)) { foreach ($sql_regex as $value) { $test = preg_match($before . $value['old'] . $after, $uri_var); if ((bool) $test === true) { $redir['new'] = preg_replace($before . $value['old'] . $after, $value['new'], $uri_var); $redir['type'] = $value['type']; break; } } } } else { // Match $redir = $sql_redir; } if ($cache_enabled === true && is_writable(_PS_CACHE_DIR_) && file_exists($this->cache_folder)) { try { file_put_contents($cache_file, serialize($redir), LOCK_EX); } catch (Exception $e) { PrestaShopLogger::addLog('Redirect Cache folder not writable, please check your modules folder permissions.'); } } $this->makeRedirection($redir); }
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true); } if (!isset($this->context)) { $this->context = Context::getContext(); } $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); // The tax cart is loaded before the customer so re-cache the tax calculation method $this->context->cart->setTaxCalculationMethod(); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); ShopUrl::resetMainDomainCache(); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $context_country = $this->context->country; } $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id); if (!Validate::isLoadedObject($order_status)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t load Order status'); } if (!$this->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) { if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) { foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } } } $order_list = array(); $order_detail_list = array(); do { $reference = Order::generateReference(); } while (Order::getByReference($reference)->count()); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) { foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) { foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } } } // Make sure CartRule caches are empty CartRule::cleanCache(); $cart_rules = $this->context->cart->getCartRules(); foreach ($cart_rules as $cart_rule) { if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) { if ($error = $rule->checkValidity($this->context, true, true)) { $this->context->cart->removeCartRule((int) $rule->id); if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) { if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } else { $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code; $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name)); PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id); } } } } foreach ($package_list as $id_address => $packageByAddress) { foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); if (!$this->context->country->active) { throw new PrestaShopException('The delivery address country is not active.'); } } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int) $carrier->id; $id_carrier = (int) $carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_address_delivery = (int) $id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int) $this->context->cart->id_lang; $order->id_cart = (int) $this->context->cart->id; $order->reference = $reference; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key); $order->payment = $payment_method; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $this->context->cart->recyclable; $order->gift = (int) $this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) { $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid = $order->total_paid_tax_incl; $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE'); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Creating order $result = $order->add(); if (!$result) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order'); } // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } $order_list[] = $order; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl; $order_carrier->add(); } } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $this->context->country = $context_country; } if (!$this->context->country->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('The order address country is not active.'); } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) { $transaction_id = $extra_vars['transaction_id']; } else { $transaction_id = null; } if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order Payment'); } } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) { $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true); } $msg->message = $message; $msg->id_order = (int) $order->id; $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; $ppropertiessmartprice_hook1 = null; $product_var_tpl_list = array(); foreach ($order->product_list as $product) { PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency)); $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $ppropertiessmartprice_hook2 = ''; $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array()); $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart); $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas); if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { $product_var_tpl['customization'] = array(); foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { if ($product['id_cart_product'] == $customization['id_cart_product']) { $customization_text = ''; if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) { foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) { $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) { $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />'; } $customization_quantity = (int) $product['customization_quantity']; $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total'))); } } } $product_var_tpl_list[] = $product_var_tpl; // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) { $virtual_product &= false; } } // end foreach ($products) PP::smartyPPAssign(); $product_list_txt = ''; $product_list_html = ''; if (count($product_var_tpl_list) > 0) { $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list); $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list); } $cart_rules_list = array(); $total_reduction_value_ti = 0; $total_reduction_value_tex = 0; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) { continue; } // IF // This is not multi-shipping // The value of the voucher is greater than the total of the order // Partial use is allowed // This is an "amount" reduction, not a reduction in % or a gift // THEN // The voucher is cloned with a new value corresponding to the remainder if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2'; if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) { $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code); } // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) { $voucher->reduction_amount -= $order->total_shipping_tax_incl; } } else { $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) { $voucher->reduction_amount -= $order->total_shipping_tax_excl; } } if ($voucher->reduction_amount <= 0) { continue; } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->free_shipping = 0; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference()); Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti; $values['tax_excl'] = $order->total_products - $total_reduction_value_tex; } $total_reduction_value_ti += $values['tax_incl']; $total_reduction_value_tex += $values['tax_excl']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false)); } $cart_rules_list_txt = ''; $cart_rules_list_html = ''; if (count($cart_rules_list) > 0) { $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list); $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list); } // Specify order id for message $old_message = Message::getMessageByCartId((int) $this->context->cart->id); if ($old_message) { $update_message = new Message((int) $old_message['id_message']); $update_message->id_order = (int) $order->id; $update_message->update(); // Add this message in the 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 = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) { $this->errors[] = Tools::displayError('An error occurred while saving message'); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true); } // Hook validate order Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status)); foreach ($this->context->cart->getProducts() as $product) { if ($order_status->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true); $history->addWithemail(); } unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)); if (is_array($extra_vars)) { $data = array_merge($data, $extra_vars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement = array(); $file_attachement['content'] = $pdf->render(false); $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf'; $file_attachement['mime'] = 'application/pdf'; } else { $file_attachement = null; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true); } if (Validate::isEmail($this->context->customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart); die($error); } } // End foreach $order_detail_list // Update Order Details Tax in case cart rules have free shipping foreach ($order->getOrderDetailList() as $detail) { $order_detail = new OrderDetail($detail['id_order_detail']); $order_detail->updateTaxAmount($order); } // Use the last order as currentOrder if (isset($order) && $order->id) { $this->currentOrder = (int) $order->id; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true); } return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id); die($error); } }
public function processDelete() { if (PrestaShopLogger::eraseAllLogs()) { Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminLogs')); } }
public function processUpdate() { $existing_product = $this->object; $this->checkProduct(); if (!empty($this->errors)) { $this->display = 'edit'; return false; } $id = (int) Tools::getValue('id_' . $this->table); /* Update an existing product */ if (isset($id) && !empty($id)) { $object = new $this->className((int) $id); $this->object = $object; if (Validate::isLoadedObject($object)) { $this->_removeTaxFromEcotax(); $product_type_before = $object->getType(); $this->copyFromPost($object, $this->table); $object->indexed = 0; if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) { $object->setFieldsToUpdate((array) Tools::getValue('multishop_check')); } // Duplicate combinations if not associated to shop if ($this->context->shop->getContext() == Shop::CONTEXT_SHOP && !$object->isAssociatedToShop()) { $is_associated_to_shop = false; $combinations = Product::getProductAttributesIds($object->id); if ($combinations) { foreach ($combinations as $id_combination) { $combination = new Combination((int) $id_combination['id_product_attribute']); $default_combination = new Combination((int) $id_combination['id_product_attribute'], null, (int) $this->object->id_shop_default); $def = ObjectModel::getDefinition($default_combination); foreach ($def['fields'] as $field_name => $row) { $combination->{$field_name} = ObjectModel::formatValue($default_combination->{$field_name}, $def['fields'][$field_name]['type']); } $combination->save(); } } } else { $is_associated_to_shop = true; } if ($object->update()) { // If the product doesn't exist in the current shop but exists in another shop if (Shop::getContext() == Shop::CONTEXT_SHOP && !$existing_product->isAssociatedToShop($this->context->shop->id)) { $out_of_stock = StockAvailable::outOfStock($existing_product->id, $existing_product->id_shop_default); $depends_on_stock = StockAvailable::dependsOnStock($existing_product->id, $existing_product->id_shop_default); StockAvailable::setProductOutOfStock((int) $this->object->id, $out_of_stock, $this->context->shop->id); StockAvailable::setProductDependsOnStock((int) $this->object->id, $depends_on_stock, $this->context->shop->id); } PrestaShopLogger::addLog(sprintf($this->l('%s edition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $this->object->id, true, (int) $this->context->employee->id); if (in_array($this->context->shop->getContext(), array(Shop::CONTEXT_SHOP, Shop::CONTEXT_ALL))) { if ($this->isTabSubmitted('Shipping')) { $this->addCarriers(); } if ($this->isTabSubmitted('Associations')) { $this->updateAccessories($object); } if ($this->isTabSubmitted('Suppliers')) { $this->processSuppliers(); } if ($this->isTabSubmitted('Features')) { $this->processFeatures(); } if ($this->isTabSubmitted('Combinations')) { $this->processProductAttribute(); } if ($this->isTabSubmitted('Prices')) { $this->processPriceAddition(); $this->processSpecificPricePriorities(); } if ($this->isTabSubmitted('Customization')) { $this->processCustomizationConfiguration(); } if ($this->isTabSubmitted('Attachments')) { $this->processAttachments(); } $this->updatePackItems($object); // Disallow avanced stock management if the product become a pack if ($product_type_before == Product::PTYPE_SIMPLE && $object->getType() == Product::PTYPE_PACK) { StockAvailable::setProductDependsOnStock((int) $object->id, false); } $this->updateDownloadProduct($object, 1); $this->updateTags(Language::getLanguages(false), $object); if ($this->isProductFieldUpdated('category_box') && !$object->updateCategories(Tools::getValue('categoryBox'))) { $this->errors[] = Tools::displayError('An error occurred while linking the object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('To categories'); } } if ($this->isTabSubmitted('Warehouses')) { $this->processWarehouses(); } if (empty($this->errors)) { if (in_array($object->visibility, array('both', 'search')) && Configuration::get('PS_SEARCH_INDEXATION')) { Search::indexation(false, $object->id); } // Save and preview if (Tools::isSubmit('submitAddProductAndPreview')) { $this->redirect_after = $this->getPreviewUrl($object); } else { // Save and stay on same form if ($this->display == 'edit') { $this->confirmations[] = $this->l('Update successful'); $this->redirect_after = self::$currentIndex . '&id_product=' . (int) $this->object->id . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&updateproduct&conf=4&key_tab=' . Tools::safeOutput(Tools::getValue('key_tab')) . '&token=' . $this->token; } else { // Default behavior (save and back) $this->redirect_after = self::$currentIndex . (Tools::getIsset('id_category') ? '&id_category=' . (int) Tools::getValue('id_category') : '') . '&conf=4&token=' . $this->token; } } } else { $this->display = 'edit'; } } else { if (!$is_associated_to_shop && $combinations) { foreach ($combinations as $id_combination) { $combination = new Combination((int) $id_combination['id_product_attribute']); $combination->delete(); } } $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Db::getInstance()->getMsgError() . ')'; } } else { $this->errors[] = Tools::displayError('An error occurred while updating an object.') . ' <b>' . $this->table . '</b> (' . Tools::displayError('The object cannot be loaded. ') . ')'; } return $object; } }
function smartyTranslate($params, &$smarty) { global $_LANG; if (!isset($params['js'])) { $params['js'] = false; } if (!isset($params['pdf'])) { $params['pdf'] = false; } if (!isset($params['mod'])) { $params['mod'] = false; } if (!isset($params['sprintf'])) { $params['sprintf'] = array(); } if (!isset($params['d'])) { $params['d'] = null; } if (!is_null($params['d'])) { if (isset($params['tags'])) { $backTrace = debug_backtrace(); $errorMessage = sprintf('Unable to translate "%s" in %s. tags() is not supported anymore, please use sprintf().', $params['s'], $backTrace[0]['args'][1]->template_resource); if (_PS_MODE_DEV_) { throw new Exception($errorMessage); } else { PrestaShopLogger::addLog($errorMessage); } } if (!is_array($params['sprintf'])) { $backTrace = debug_backtrace(); $errorMessage = sprintf('Unable to translate "%s" in %s. sprintf() parameter should be an array.', $params['s'], $backTrace[0]['args'][1]->template_resource); if (_PS_MODE_DEV_) { throw new Exception($errorMessage); } else { PrestaShopLogger::addLog($errorMessage); return $params['s']; } } } if (($translation = Context::getContext()->getTranslator()->trans($params['s'], $params['sprintf'], $params['d'])) !== $params['s']) { return $translation; } $string = str_replace('\'', '\\\'', $params['s']); $filename = !isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath(); $basename = basename($filename, '.tpl'); $key = $basename . '_' . md5($string); if (isset($smarty->source) && strpos($smarty->source->filepath, DIRECTORY_SEPARATOR . 'override' . DIRECTORY_SEPARATOR) !== false) { $key = 'override_' . $key; } if ($params['mod']) { return Translate::smartyPostProcessTranslation(Translate::getModuleTranslation($params['mod'], $params['s'], $basename, $params['sprintf'], $params['js']), $params); } elseif ($params['pdf']) { return Translate::smartyPostProcessTranslation(Translate::getPdfTranslation($params['s'], $params['sprintf']), $params); } if ($_LANG != null && isset($_LANG[$key])) { $msg = $_LANG[$key]; } elseif ($_LANG != null && isset($_LANG[Tools::strtolower($key)])) { $msg = $_LANG[Tools::strtolower($key)]; } else { $msg = $params['s']; } if ($msg != $params['s'] && !$params['js']) { $msg = stripslashes($msg); } elseif ($params['js']) { $msg = addslashes($msg); } if ($params['sprintf'] !== null) { $msg = Translate::checkAndReplaceArgs($msg, $params['sprintf']); } return Translate::smartyPostProcessTranslation($params['js'] ? $msg : Tools::safeOutput($msg), $params); }
public function processDelete() { return PrestaShopLogger::eraseAllLogs(); }
/** * Initializes front controller: sets smarty variables, * class properties, redirects depending on context, etc. * * @global bool $useSSL SSL connection flag * @global Cookie $cookie Visitor's cookie * @global Smarty $smarty * @global Cart $cart Visitor's cart * @global string $iso Language ISO * @global Country $defaultCountry Visitor's country object * @global string $protocol_link * @global string $protocol_content * @global Link $link * @global array $css_files * @global array $js_files * @global Currency $currency Visitor's selected currency * * @throws PrestaShopException */ public function init() { /* * Globals are DEPRECATED as of version 1.5.0.1 * Use the Context object to access objects instead. * Example: $this->context->cart */ global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency; if (self::$initialized) { return; } self::$initialized = true; parent::init(); // enable Symfony error handler if debug mode enabled $this->initDebugguer(); // If current URL use SSL, set it true (used a lot for module redirect) if (Tools::usingSecureMode()) { $useSSL = true; } // For compatibility with globals, DEPRECATED as of version 1.5.0.1 $css_files = $this->css_files; $js_files = $this->js_files; $this->sslRedirection(); if ($this->ajax) { $this->display_header = false; $this->display_footer = false; } // If account created with the 2 steps register process, remove 'account_created' from cookie if (isset($this->context->cookie->account_created)) { unset($this->context->cookie->account_created); } ob_start(); // Init cookie language // @TODO This method must be moved into switchLanguage Tools::setCookieLanguage($this->context->cookie); $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://'; $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false; $protocol_content = $useSSL ? 'https://' : 'http://'; $link = new Link($protocol_link, $protocol_content); $this->context->link = $link; if ($id_cart = (int) $this->recoverCart()) { $this->context->cookie->id_cart = (int) $id_cart; } if ($this->auth && !$this->context->customer->isLogged()) { Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : '')); } /* Theme is missing */ if (!is_dir(_PS_THEME_DIR_)) { throw new PrestaShopException(sprintf(Tools::displayError('Current theme unavailable "%s". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\')))); } if (Configuration::get('PS_GEOLOCATION_ENABLED')) { if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) { $this->context->country = $new_default; } } elseif (Configuration::get('PS_DETECT_COUNTRY')) { $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency; $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country; $has_address_type = false; if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) { $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; } if ((!$has_currency || $has_country) && !$has_address_type) { $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ? (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry(); $country = new Country($id_country, (int) $this->context->cookie->id_lang); if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) { $this->context->country = $country; $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id; $this->context->cookie->iso_code_country = strtoupper($country->iso_code); } } } $currency = Tools::setCurrency($this->context->cookie); if (isset($_GET['logout']) || $this->context->customer->logged && Customer::isBanned($this->context->customer->id)) { $this->context->customer->logout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null); } elseif (isset($_GET['mylogout'])) { $this->context->customer->mylogout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null); } /* Cart already exists */ if ((int) $this->context->cookie->id_cart) { if (!isset($cart)) { $cart = new Cart($this->context->cookie->id_cart); } if (Validate::isLoadedObject($cart) && $cart->OrderExists()) { PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true); unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS); $this->context->cookie->check_cgv = false; } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 && !FrontController::isInWhitelistForGeolocation() && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) { /* Delete product of cart, if user can't make an order from his country */ PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true); unset($this->context->cookie->id_cart, $cart); } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) { // update cart values if ($this->context->cookie->id_customer) { $cart->id_customer = (int) $this->context->cookie->id_customer; } $cart->id_lang = (int) $this->context->cookie->id_lang; $cart->id_currency = (int) $currency->id; $cart->update(); } /* Select an address if not set */ if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 || !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) { $to_update = false; if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) { $to_update = true; $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer); } if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) { $to_update = true; $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer); } if ($to_update) { $cart->update(); } } } if (!isset($cart) || !$cart->id) { $cart = new Cart(); $cart->id_lang = (int) $this->context->cookie->id_lang; $cart->id_currency = (int) $this->context->cookie->id_currency; $cart->id_guest = (int) $this->context->cookie->id_guest; $cart->id_shop_group = (int) $this->context->shop->id_shop_group; $cart->id_shop = $this->context->shop->id; if ($this->context->cookie->id_customer) { $cart->id_customer = (int) $this->context->cookie->id_customer; $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer); $cart->id_address_invoice = (int) $cart->id_address_delivery; } else { $cart->id_address_delivery = 0; $cart->id_address_invoice = 0; } // Needed if the merchant want to give a free product to every visitors $this->context->cart = $cart; CartRule::autoAddToCart($this->context); } else { $this->context->cart = $cart; } $this->context->cart->checkAndUpdateAddresses(); $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI']))); // Automatically redirect to the canonical URL if needed if (!empty($this->php_self) && !Tools::getValue('ajax')) { $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id)); } Product::initPricesComputation(); $display_tax_label = $this->context->country->display_tax_label; if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) { $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $country = new Country((int) $infos['id_country']); $this->context->country = $country; if (Validate::isLoadedObject($country)) { $display_tax_label = $country->display_tax_label; } } $languages = Language::getLanguages(true, $this->context->shop->id); $meta_language = array(); foreach ($languages as $lang) { $meta_language[] = $lang['iso_code']; } /* * These shortcuts are DEPRECATED as of version 1.5.0.1 * Use the Context to access objects instead. * Example: $this->context->cart */ self::$cookie = $this->context->cookie; self::$cart = $cart; self::$smarty = $this->context->smarty; self::$link = $link; $defaultCountry = $this->context->country; $this->displayMaintenancePage(); if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) { $this->displayRestrictedCountryPage(); } $this->iso = $iso; $this->context->cart = $cart; $this->context->currency = $currency; }
public function hookActionOrderReturn($params) { try { if ($this->isActive()) { $url = $this->getApiUrl('/prestashop/webhook-order-return', true); $body = Tools::jsonEncode($params); $this->webhook($url, $body); } } catch (Exception $exception) { $orderReturn = $params['orderReturn']; $id_order = $orderReturn->id_order; $message = 'Darwinpricing::hookActionOrderReturn - Cannot send order return details'; PrestaShopLogger::addLog($message, 3, null, 'Order', $id_order); } }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amount_paid Amount really paid by customer (in the default currency) * @param string $payment_method Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = ($shop ? $shop : new Shop($this->context->cart->id_shop)); ShopUrl::resetMainDomainCache(); $id_currency = $currency_special ? (int)$currency_special : (int)$this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') $context_country = $this->context->country; $order_status = new OrderState((int)$id_order_state, (int)$this->context->language->id); if (!Validate::isLoadedObject($order_status)) throw new PrestaShopException('Can\'t load Order status'); if (!$this->active) die(Tools::displayError()); // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) die(Tools::displayError()); // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } $order_list = array(); $order_detail_list = array(); do $reference = Order::generateReference(); while(Order::getByReference($reference)->count()); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int)$this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int)$id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($package_list as $id_address => $packageByAddress) foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int)$carrier->id; $id_carrier = (int)$carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int)$this->context->cart->id_customer; $order->id_address_invoice = (int)$this->context->cart->id_address_invoice; $order->id_address_delivery = (int)$id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int)$this->context->cart->id_lang; $order->id_cart = (int)$this->context->cart->id; $order->reference = $reference; $order->id_shop = (int)$this->context->shop->id; $order->id_shop_group = (int)$this->context->shop->id_shop_group; $order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key)); $order->payment = $payment_method; if (isset($this->name)) $order->module = $this->name; $order->recyclable = $this->context->cart->recyclable; $order->gift = (int)$this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((float)$amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (float)$this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (float)$this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (float)$this->context->cart->getPackageShippingCost((int)$id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $order->total_wrapping_tax_excl = (float)abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (float)abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid_tax_incl = (float)Tools::ps_round((float)$this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid = $order->total_paid_tax_incl; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Creating order $result = $order->add(); if (!$result) throw new PrestaShopException('Can\'t save Order'); // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, 2) != number_format($amount_paid, 2)) $id_order_state = Configuration::get('PS_OS_ERROR'); $order_list[] = $order; // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int)$order->id; $order_carrier->id_carrier = (int)$id_carrier; $order_carrier->weight = (float)$order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (float)$order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (float)$order->total_shipping_tax_incl; $order_carrier->add(); } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') $this->context->country = $context_country; // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) $transaction_id = $extra_vars['transaction_id']; else $transaction_id = null; if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) throw new PrestaShopException('Can\'t save Order Payment'); } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); $cart_rules = $this->context->cart->getCartRules(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) $message .= '<br />'.Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; foreach ($order->product_list as $key => $product) { $price = Product::getPriceStatic((int)$product['id_product'], false, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 6, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? (int)$product['id_product_attribute'] : null), 2, null, false, true, $product['cart_quantity'], false, (int)$order->id_customer, (int)$order->id_cart, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $products_list .= '<tr> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.$product['reference'].' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td> <font size="2" face="Open-sans, sans-serif" color="#555454"> <strong>'.$product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : '').'</strong> </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false).' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.$product['quantity'].' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.Tools::displayPrice($product['quantity'] * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false).' </font> </td> <td width="10"> </td> </tr> </table> </td> </tr>'; $customization_quantity = 0; $customized_datas = Product::getAllCustomizedDatas((int)$order->id_cart); if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { $customization_text = ''; foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) $customization_text .= $text['name'].': '.$text['value'].'<br />'; if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])).'<br />'; $customization_quantity = (int)$product['customization_quantity']; $products_list .= '<tr> <td colspan="2" style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td> <font size="2" face="Open-sans, sans-serif" color="#555454"> <strong>'.$product['name'].(isset($product['attributes']) ? ' - '.$product['attributes'] : '').'</strong><br> '.$customization_text.' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false).' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.$customization_quantity.' </font> </td> <td width="10"> </td> </tr> </table> </td> <td style="border:1px solid #D6D4D4;"> <table class="table"> <tr> <td width="10"> </td> <td align="right"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.Tools::displayPrice($customization_quantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false).' </font> </td> <td width="10"> </td> </tr> </table> </td> </tr>'; } } // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) $virtual_product &= false; } // end foreach ($products) $cart_rules_list = ''; $total_reduction_value_ti = 0; $total_reduction_value_tex = 0; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array( 'tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package) ); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) continue; /* IF ** - This is not multi-shipping ** - The value of the voucher is greater than the total of the order ** - Partial use is allowed ** - This is an "amount" reduction, not a reduction in % or a gift ** THEN ** The voucher is cloned with a new value corresponding to the remainder */ if (count($order_list) == 1 && $values['tax_incl'] > ($order->total_products_wt - $total_reduction_value_ti) && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? substr(md5($order->id.'-'.$order->id_customer.'-'.$cart_rule['obj']->id), 0, 16) : $voucher->code.'-2'; if (preg_match('/\-([0-9]{1,2})\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) $voucher->code = preg_replace('/'.$matches[0].'$/', '-'.(intval($matches[1]) + 1), $voucher->code); // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $values['tax_incl'] - ($order->total_products_wt - $total_reduction_value_ti); // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) $voucher->reduction_amount -= $order->total_shipping_tax_incl; } else { $voucher->reduction_amount = $values['tax_excl'] - ($order->total_products - $total_reduction_value_tex); // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) $voucher->reduction_amount -= $order->total_shipping_tax_excl; } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->free_shipping = 0; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array( '{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference() ); Mail::Send( (int)$order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int)$order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname.' '.$this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int)$order->id_shop ); } $values['tax_incl'] -= $values['tax_incl'] - $order->total_products_wt; $values['tax_excl'] -= $values['tax_excl'] - $order->total_products; } $total_reduction_value_ti += $values['tax_incl']; $total_reduction_value_tex += $values['tax_excl']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list .= '<tr class="conf_body"> <td bgcolor="#f8f8f8" colspan="4" style="border:1px solid #D6D4D4;color:#333;padding:7px 0"> <table class="table" style="width:100%;border-collapse:collapse"> <tr> <td width="10" style="color:#333;padding:0"></td> <td align="right" style="color:#333;padding:0"> <font size="2" face="Open-sans, sans-serif" color="#555454"> <strong>'.Tools::displayError('Voucher name:').' '.$cart_rule['obj']->name.'</strong> </font> </td> <td width="10" style="color:#333;padding:0"></td> </tr> </table> </td> <td bgcolor="#f8f8f8" colspan="4" style="border:1px solid #D6D4D4;color:#333;padding:7px 0"> <table class="table" style="width:100%;border-collapse:collapse"> <tr> <td width="10" style="color:#333;padding:0"></td> <td align="right" style="color:#333;padding:0"> <font size="2" face="Open-sans, sans-serif" color="#555454"> '.($values['tax_incl'] != 0.00 ? '-' : '').Tools::displayPrice($values['tax_incl'], $this->context->currency, false).' </font> </td> <td width="10" style="color:#333;padding:0"></td> </tr> </table> </td> </tr>'; } // Specify order id for message $old_message = Message::getMessageByCartId((int)$this->context->cart->id); if ($old_message) { $update_message = new Message((int)$old_message['id_message']); $update_message->id_order = (int)$order->id; $update_message->update(); // Add this message in the 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 = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) $this->errors[] = Tools::displayError('An error occurred while saving message'); } // Hook validate order Hook::exec('actionValidateOrder', array( 'cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status )); foreach ($this->context->cart->getProducts() as $product) if ($order_status->logable) ProductSale::addProductSale((int)$product['id_product'], (int)$product['cart_quantity']); // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int)$order->id; $new_history->changeIdOrderState((int)$id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int)$order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), $order, true); $history->addWithemail(); } unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array( '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array( 'firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>' )), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array( 'firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>' )), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => ($delivery->phone) ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => ($invoice->phone) ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'),null , 1), '{carrier}' => $virtual_product ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $this->formatProductAndVoucherForEmail($products_list), '{discounts}' => $this->formatProductAndVoucherForEmail($cart_rules_list), '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)); if (is_array($extra_vars)) $data = array_merge($data, $extra_vars); // Join PDF invoice if ((int)Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement_invoice['content'] = $pdf->render(false); $file_attachement_invoice['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf'; $file_attachement_invoice['mime'] = 'application/pdf'; } else $file_attachement_invoice = null; $pdf_info = new PDF($order, 'info', $this->context->smarty); $file_attachement_info['content'] = $pdf_info->render(false); $file_attachement_info['name'] = 'test.pdf'; $file_attachement_info['mime'] = 'application/pdf'; $file_attachement[] = $file_attachement_info; if($file_attachement_invoice) $file_attachement[] = $file_attachement_invoice; if (Validate::isEmail($this->context->customer->email)) Mail::Send( (int)$order->id_lang, 'order_conf', Mail::l('Order confirmation', (int)$order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname.' '.$this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int)$order->id_shop ); } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart)); die($error); } } // End foreach $order_detail_list // Use the last order as currentOrder $this->currentOrder = (int)$order->id; return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id)); die($error); } }
function smartyTranslate($params, &$smarty) { $htmlentities = !isset($params['js']); $pdf = isset($params['pdf']); $addslashes = isset($params['slashes']) || isset($params['js']); $sprintf = isset($params['sprintf']) ? $params['sprintf'] : array(); if (!empty($params['d'])) { if (isset($params['tags'])) { $backTrace = debug_backtrace(); $errorMessage = sprintf('Unable to translate "%s" in %s. tags() is not supported anymore, please use sprintf().', $params['s'], $backTrace[0]['args'][1]->template_resource); if (_PS_MODE_DEV_) { throw new Exception($errorMessage); } else { PrestaShopLogger::addLog($errorMessage); } } if (!is_array($sprintf)) { $backTrace = debug_backtrace(); $errorMessage = sprintf('Unable to translate "%s" in %s. sprintf() parameter should be an array.', $params['s'], $backTrace[0]['args'][1]->template_resource); if (_PS_MODE_DEV_) { throw new Exception($errorMessage); } else { PrestaShopLogger::addLog($errorMessage); return $params['s']; } } return Context::getContext()->getTranslator()->trans($params['s'], $sprintf, $params['d']); } if ($pdf) { return Translate::smartyPostProcessTranslation(Translate::getPdfTranslation($params['s'], $sprintf), $params); } $filename = !isset($smarty->compiler_object) || !is_object($smarty->compiler_object->template) ? $smarty->template_resource : $smarty->compiler_object->template->getTemplateFilepath(); // If the template is part of a module if (!empty($params['mod'])) { return Translate::smartyPostProcessTranslation(Translate::getModuleTranslation($params['mod'], $params['s'], basename($filename, '.tpl'), $sprintf, isset($params['js'])), $params); } // If the tpl is at the root of the template folder if (dirname($filename) == '.') { $class = 'index'; } // If the tpl is used by a Helper if (strpos($filename, 'helpers') === 0) { $class = 'Helper'; } else { // If the tpl is used by a Controller if (!empty(Context::getContext()->override_controller_name_for_translations)) { $class = Context::getContext()->override_controller_name_for_translations; } elseif (isset(Context::getContext()->controller)) { $class_name = get_class(Context::getContext()->controller); $class = substr($class_name, 0, strpos(Tools::strtolower($class_name), 'controller')); } else { // Split by \ and / to get the folder tree for the file $folder_tree = preg_split('#[/\\\\]#', $filename); $key = array_search('controllers', $folder_tree); // If there was a match, construct the class name using the child folder name // Eg. xxx/controllers/customers/xxx => AdminCustomers if ($key !== false) { $class = 'Admin' . Tools::toCamelCase($folder_tree[$key + 1], true); } elseif (isset($folder_tree[0])) { $class = 'Admin' . Tools::toCamelCase($folder_tree[0], true); } } } return Translate::smartyPostProcessTranslation(Translate::getAdminTranslation($params['s'], $class, $addslashes, $htmlentities, $sprintf), $params); }
public function listenIPN($checkout, $topic, $id) { $payment_method_ids = array(); $payment_ids = array(); $payment_statuses = array(); $payment_types = array(); $credit_cards = array(); $transaction_amounts = 0; $cardholders = array(); $external_reference = ''; if (Configuration::get('MERCADOPAGO_LOG') == 'true') { PrestaShopLogger::addLog('MercadoPago :: listenIPN - topic = ' . $topic, MP::INFO, 0); PrestaShopLogger::addLog('MercadoPago :: listenIPN - id = ' . $id, MP::INFO, 0); PrestaShopLogger::addLog('MercadoPago :: listenIPN - checkout = ' . $checkout, MP::INFO, 0); } if ($checkout == "standard" && $topic == 'merchant_order' && $id > 0) { // get merchant order info $result = $this->mercadopago->getMerchantOrder($id); $merchant_order_info = $result['response']; $payments = $merchant_order_info['payments']; $external_reference = $merchant_order_info['external_reference']; foreach ($payments as $payment) { // get payment info $result = $this->mercadopago->getPayment($payment['id']); $payment_info = $result['response']['collection']; // colect payment details $payment_ids[] = $payment_info['id']; $payment_statuses[] = $payment_info['status']; $payment_types[] = $payment_info['payment_type']; $transaction_amounts += $payment_info['transaction_amount']; if ($payment_info['payment_type'] == 'credit_card') { $payment_method_ids[] = isset($payment_info['payment_method_id']) ? $payment_info['payment_method_id'] : ""; $credit_cards[] = isset($payment_info['last_four_digits']) ? '**** **** **** ' . $payment_info['last_four_digits'] : ""; $cardholders[] = $payment_info['cardholder']['name']; } } if ($merchant_order_info['total_amount'] == $transaction_amounts) { $this->updateOrder($payment_ids, $payment_statuses, $payment_method_ids, $payment_types, $credit_cards, $cardholders, $transaction_amounts, $external_reference); } } else { if ($checkout == "custom" && $topic == 'payment' && $id > 0) { $result = $this->mercadopago->getPayment($id); $payment_info = $result['response']['collection']; $external_reference = $payment_info['external_reference']; // colect payment details $payment_ids[] = $payment_info['id']; $payment_statuses[] = $payment_info['status']; $payment_types[] = $payment_info['payment_type']; $transaction_amounts += $payment_info['transaction_amount']; if ($payment_info['payment_type'] == 'credit_card') { $payment_method_ids[] = $payment_info['payment_method_id']; $credit_cards[] = '**** **** **** ' . $payment_info['last_four_digits']; $cardholders[] = $payment_info['cardholder']['name']; } $this->updateOrder($payment_ids, $payment_statuses, $payment_method_ids, $payment_types, $credit_cards, $cardholders, $transaction_amounts, $external_reference); } } }
/** * Initializes front controller: sets smarty variables, * class properties, redirects depending on context, etc. * * @global bool $useSSL SSL connection flag * @global Cookie $cookie Visitor's cookie * @global Smarty $smarty * @global Cart $cart Visitor's cart * @global string $iso Language ISO * @global Country $defaultCountry Visitor's country object * @global string $protocol_link * @global string $protocol_content * @global Link $link * @global array $css_files * @global array $js_files * @global Currency $currency Visitor's selected currency * * @throws PrestaShopException */ public function init() { /** * Globals are DEPRECATED as of version 1.5.0.1 * Use the Context object to access objects instead. * Example: $this->context->cart */ global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency; if (self::$initialized) { return; } self::$initialized = true; parent::init(); // If current URL use SSL, set it true (used a lot for module redirect) if (Tools::usingSecureMode()) { $useSSL = true; } // For compatibility with globals, DEPRECATED as of version 1.5.0.1 $css_files = $this->css_files; $js_files = $this->js_files; $this->sslRedirection(); if ($this->ajax) { $this->display_header = false; $this->display_footer = false; } // If account created with the 2 steps register process, remove 'account_created' from cookie if (isset($this->context->cookie->account_created)) { $this->context->smarty->assign('account_created', 1); unset($this->context->cookie->account_created); } ob_start(); // Init cookie language // @TODO This method must be moved into switchLanguage Tools::setCookieLanguage($this->context->cookie); $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://'; $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false; $protocol_content = $useSSL ? 'https://' : 'http://'; $link = new Link($protocol_link, $protocol_content); $this->context->link = $link; if ($id_cart = (int) $this->recoverCart()) { $this->context->cookie->id_cart = (int) $id_cart; } if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) { Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : '')); } /* Theme is missing */ if (!is_dir(_PS_THEME_DIR_)) { throw new PrestaShopException(sprintf(Tools::displayError('Current theme unavailable "%s". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\')))); } if (Configuration::get('PS_GEOLOCATION_ENABLED')) { if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) { $this->context->country = $new_default; } } elseif (Configuration::get('PS_DETECT_COUNTRY')) { $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency; $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country; $has_address_type = false; if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) { $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; } if ((!$has_currency || $has_country) && !$has_address_type) { $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ? (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry(); $country = new Country($id_country, (int) $this->context->cookie->id_lang); if (validate::isLoadedObject($country) && $this->context->country->id !== $country->id) { $this->context->country = $country; $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id; $this->context->cookie->iso_code_country = strtoupper($country->iso_code); } } } $currency = Tools::setCurrency($this->context->cookie); if (isset($_GET['logout']) || $this->context->customer->logged && Customer::isBanned($this->context->customer->id)) { $this->context->customer->logout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null); } elseif (isset($_GET['mylogout'])) { $this->context->customer->mylogout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null); } /* Cart already exists */ if ((int) $this->context->cookie->id_cart) { if (!isset($cart)) { $cart = new Cart($this->context->cookie->id_cart); } if (Validate::isLoadedObject($cart) && $cart->OrderExists()) { PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true); unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS); $this->context->cookie->check_cgv = false; } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 && !FrontController::isInWhitelistForGeolocation() && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) { PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true); unset($this->context->cookie->id_cart, $cart); } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) { if ($this->context->cookie->id_customer) { $cart->id_customer = (int) $this->context->cookie->id_customer; } $cart->id_lang = (int) $this->context->cookie->id_lang; $cart->id_currency = (int) $currency->id; $cart->update(); } /* Select an address if not set */ if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 || !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) { $to_update = false; if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) { $to_update = true; $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer); } if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) { $to_update = true; $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer); } if ($to_update) { $cart->update(); } } } if (!isset($cart) || !$cart->id) { $cart = new Cart(); $cart->id_lang = (int) $this->context->cookie->id_lang; $cart->id_currency = (int) $this->context->cookie->id_currency; $cart->id_guest = (int) $this->context->cookie->id_guest; $cart->id_shop_group = (int) $this->context->shop->id_shop_group; $cart->id_shop = $this->context->shop->id; if ($this->context->cookie->id_customer) { $cart->id_customer = (int) $this->context->cookie->id_customer; $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer); $cart->id_address_invoice = (int) $cart->id_address_delivery; } else { $cart->id_address_delivery = 0; $cart->id_address_invoice = 0; } // Needed if the merchant want to give a free product to every visitors $this->context->cart = $cart; CartRule::autoAddToCart($this->context); } else { $this->context->cart = $cart; } /* get page name to display it in body id */ // Are we in a payment module $module_name = ''; if (Validate::isModuleName(Tools::getValue('module'))) { $module_name = Tools::getValue('module'); } if (!empty($this->page_name)) { $page_name = $this->page_name; } elseif (!empty($this->php_self)) { $page_name = $this->php_self; } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) { $page_name = 'module-payment-submit'; } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) { $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]); } else { $page_name = Dispatcher::getInstance()->getController(); $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name; } $this->context->smarty->assign(Meta::getMetaTags($this->context->language->id, $page_name)); $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI']))); /* Breadcrumb */ $navigation_pipe = Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>'; $this->context->smarty->assign('navigationPipe', $navigation_pipe); // Automatically redirect to the canonical URL if needed if (!empty($this->php_self) && !Tools::getValue('ajax')) { $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id)); } Product::initPricesComputation(); $display_tax_label = $this->context->country->display_tax_label; if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) { $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $country = new Country((int) $infos['id_country']); $this->context->country = $country; if (Validate::isLoadedObject($country)) { $display_tax_label = $country->display_tax_label; } } $languages = Language::getLanguages(true, $this->context->shop->id); $meta_language = array(); foreach ($languages as $lang) { $meta_language[] = $lang['iso_code']; } $compared_products = array(); if (Configuration::get('PS_COMPARATOR_MAX_ITEM') && isset($this->context->cookie->id_compare)) { $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare); } $this->context->smarty->assign(array('mobile_device' => $this->context->getMobileDevice(), 'link' => $link, 'cart' => $cart, 'currency' => $currency, 'currencyRate' => (double) $currency->getConversationRate(), 'cookie' => $this->context->cookie, 'page_name' => $page_name, 'hide_left_column' => !$this->display_column_left, 'hide_right_column' => !$this->display_column_right, 'base_dir' => _PS_BASE_URL_ . __PS_BASE_URI__, 'base_dir_ssl' => $protocol_link . Tools::getShopDomainSsl() . __PS_BASE_URI__, 'force_ssl' => Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE'), 'content_dir' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__, 'base_uri' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__ . (!Configuration::get('PS_REWRITING_SETTINGS') ? 'index.php' : ''), 'tpl_dir' => _PS_THEME_DIR_, 'tpl_uri' => _THEME_DIR_, 'modules_dir' => _MODULE_DIR_, 'mail_dir' => _MAIL_DIR_, 'lang_iso' => $this->context->language->iso_code, 'lang_id' => (int) $this->context->language->id, 'language_code' => $this->context->language->language_code ? $this->context->language->language_code : $this->context->language->iso_code, 'come_from' => Tools::getHttpHost(true, true) . Tools::htmlentitiesUTF8(str_replace(array('\'', '\\'), '', urldecode($_SERVER['REQUEST_URI']))), 'cart_qties' => (int) $cart->nbProducts(), 'currencies' => Currency::getCurrencies(), 'languages' => $languages, 'meta_language' => implode(',', $meta_language), 'priceDisplay' => Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer), 'is_logged' => (bool) $this->context->customer->isLogged(), 'is_guest' => (bool) $this->context->customer->isGuest(), 'add_prod_display' => (int) Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'shop_name' => Configuration::get('PS_SHOP_NAME'), 'roundMode' => (int) Configuration::get('PS_PRICE_ROUND_MODE'), 'use_taxes' => (int) Configuration::get('PS_TAX'), 'show_taxes' => (int) (Configuration::get('PS_TAX_DISPLAY') == 1 && (int) Configuration::get('PS_TAX')), 'display_tax_label' => (bool) $display_tax_label, 'vat_management' => (int) Configuration::get('VATNUMBER_MANAGEMENT'), 'opc' => (bool) Configuration::get('PS_ORDER_PROCESS_TYPE'), 'PS_CATALOG_MODE' => (bool) Configuration::get('PS_CATALOG_MODE') || Group::isFeatureActive() && !(bool) Group::getCurrent()->show_prices, 'b2b_enable' => (bool) Configuration::get('PS_B2B_ENABLE'), 'request' => $link->getPaginationLink(false, false, false, true), 'PS_STOCK_MANAGEMENT' => Configuration::get('PS_STOCK_MANAGEMENT'), 'quick_view' => (bool) Configuration::get('PS_QUICK_VIEW'), 'shop_phone' => Configuration::get('PS_SHOP_PHONE'), 'compared_products' => is_array($compared_products) ? $compared_products : array(), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'currencySign' => $currency->sign, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank)); // Add the tpl files directory for mobile if ($this->useMobileTheme()) { $this->context->smarty->assign(array('tpl_mobile_uri' => _PS_THEME_MOBILE_DIR_)); } // Deprecated $this->context->smarty->assign(array('id_currency_cookie' => (int) $currency->id, 'logged' => $this->context->customer->isLogged(), 'customerName' => $this->context->customer->logged ? $this->context->cookie->customer_firstname . ' ' . $this->context->cookie->customer_lastname : false)); $assign_array = array('img_ps_dir' => _PS_IMG_, 'img_cat_dir' => _THEME_CAT_DIR_, 'img_lang_dir' => _THEME_LANG_DIR_, 'img_prod_dir' => _THEME_PROD_DIR_, 'img_manu_dir' => _THEME_MANU_DIR_, 'img_sup_dir' => _THEME_SUP_DIR_, 'img_ship_dir' => _THEME_SHIP_DIR_, 'img_store_dir' => _THEME_STORE_DIR_, 'img_col_dir' => _THEME_COL_DIR_, 'img_dir' => _THEME_IMG_DIR_, 'css_dir' => _THEME_CSS_DIR_, 'js_dir' => _THEME_JS_DIR_, 'pic_dir' => _THEME_PROD_PIC_DIR_); // Add the images directory for mobile if ($this->useMobileTheme()) { $assign_array['img_mobile_dir'] = _THEME_MOBILE_IMG_DIR_; } // Add the CSS directory for mobile if ($this->useMobileTheme()) { $assign_array['css_mobile_dir'] = _THEME_MOBILE_CSS_DIR_; } foreach ($assign_array as $assign_key => $assign_value) { if (substr($assign_value, 0, 1) == '/' || $protocol_content == 'https://') { $this->context->smarty->assign($assign_key, $protocol_content . Tools::getMediaServer($assign_value) . $assign_value); } else { $this->context->smarty->assign($assign_key, $assign_value); } } /** * These shortcuts are DEPRECATED as of version 1.5.0.1 * Use the Context to access objects instead. * Example: $this->context->cart */ self::$cookie = $this->context->cookie; self::$cart = $cart; self::$smarty = $this->context->smarty; self::$link = $link; $defaultCountry = $this->context->country; $this->displayMaintenancePage(); if ($this->restrictedCountry) { $this->displayRestrictedCountryPage(); } if (Tools::isSubmit('live_edit') && !$this->checkLiveEditAccess()) { Tools::redirect('index.php?controller=404'); } $this->iso = $iso; $this->context->cart = $cart; $this->context->currency = $currency; }
public function processDelete() { if (Validate::isLoadedObject($object = $this->loadObject())) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject)) { $this->errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { if (!count($this->errors)) { if ($object->delete()) { $object->deleteProducts(); PrestaShopLogger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $object->id, true, (int) $this->context->employee->id); $this->redirect_after = self::$currentIndex . '&conf=1&token=' . $this->token . $category_url; } else { $this->errors[] = Tools::displayError('An error occurred during deletion.'); } } } } else { $this->errors[] = Tools::displayError('An error occurred while deleting the object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } }
public function initContent() { parent::initContent(); if (Tools::getIsset('collection_id') && Tools::getValue('collection_id') != 'null') { // payment variables $payment_statuses = array(); $payment_ids = array(); $payment_types = array(); $payment_method_ids = array(); $card_holder_names = array(); $four_digits_arr = array(); $statement_descriptors = array(); $status_details = array(); $transaction_amounts = 0; $collection_ids = split(',', Tools::getValue('collection_id')); $mercadopago = $this->module; $mercadopago_sdk = $mercadopago->mercadopago; foreach ($collection_ids as $collection_id) { $result = $mercadopago_sdk->getPayment($collection_id); $payment_info = $result['response']['collection']; $id_cart = $payment_info['external_reference']; $cart = new Cart($id_cart); $payment_statuses[] = $payment_info['status']; $payment_ids[] = $payment_info['id']; $payment_types[] = $payment_info['payment_type']; $payment_method_ids[] = $payment_info['payment_method_id']; $transaction_amounts += $payment_info['transaction_amount']; if ($payment_info['payment_type'] == 'credit_card') { $card_holder_names[] = $payment_info['cardholder']['name']; $four_digits_arr[] = '**** **** **** ' . $payment_info['last_four_digits']; $statement_descriptors[] = $payment_info['statement_descriptor']; $status_details[] = $payment_info['status_detail']; } } if (Validate::isLoadedObject($cart)) { $total = (double) number_format($payment_info['transaction_amount'], 2, '.', ''); $extra_vars = array('{bankwire_owner}' => $mercadopago->textshowemail, '{bankwire_details}' => '', '{bankwire_address}' => ''); $order_status = null; $payment_status = $payment_info['status']; switch ($payment_status) { case 'in_process': $order_status = 'MERCADOPAGO_STATUS_0'; break; case 'approved': $order_status = 'MERCADOPAGO_STATUS_1'; break; case 'pending': $order_status = 'MERCADOPAGO_STATUS_7'; break; } $order_id = Order::getOrderByCartId($cart->id); if ($order_status != null) { if (!$order_id) { $mercadopago->validateOrder($cart->id, Configuration::get($order_status), $total, $mercadopago->displayName, null, $extra_vars, $cart->id_currency, false, $cart->secure_key); } $order_id = !$order_id ? Order::getOrderByCartId($cart->id) : $order_id; $order = new Order($order_id); $uri = __PS_BASE_URI__ . 'order-confirmation.php?id_cart=' . $order->id_cart . '&id_module=' . $mercadopago->id . '&id_order=' . $order->id . '&key=' . $order->secure_key; $order_payments = $order->getOrderPayments(); $order_payments[0]->transaction_id = Tools::getValue('collection_id'); $uri .= '&payment_status=' . $payment_statuses[0]; $uri .= '&payment_id=' . join(" / ", $payment_ids); $uri .= '&payment_type=' . join(" / ", $payment_types); $uri .= '&payment_method_id=' . join(" / ", $payment_method_ids); $uri .= '&amount=' . $transaction_amounts; if ($payment_info['payment_type'] == 'credit_card') { $uri .= '&card_holder_name=' . join(" / ", $card_holder_names); $uri .= '&four_digits=' . join(" / ", $four_digits_arr); $uri .= '&statement_descriptor=' . $statement_descriptors[0]; $uri .= '&status_detail=' . $status_details[0]; $order_payments[0]->card_number = join(" / ", $four_digits_arr); $order_payments[0]->card_brand = join(" / ", $payment_method_ids); $order_payments[0]->card_holder = join(" / ", $card_holder_names); } $order_payments[0]->save(); Tools::redirectLink($uri); } } } else { PrestaShopLogger::addLog("MercadoPagoStandardReturnModuleFrontController::initContent = " . 'External reference is not set. Order placement has failed.', MP::ERROR, 0); } }
public static function log($level, $msg = '') { if (!$msg) { list($level, $msg) = array('debug', $level); } if ($level == 'debug' && !self::DEBUG_MODE) { return; } elseif ($level == 'debug' && self::DEBUG_MODE) { self::logToFile($level, $msg); } try { if (class_exists('PrestaShopLogger')) { PrestaShopLogger::addLog('pilipay:' . $level . ': ' . $msg, 1, 0, 'pilipay', Configuration::get(self::PILIPAY_MERCHANT_NO)); } elseif (class_exists('Logger')) { $msg = strtr($msg, array('{' => '{', '}' => '}', '<' => '<', '>' => '>')); Logger::addLog('pilipay:' . $level . ': ' . $msg, 1, 0, 'pilipay', Configuration::get(self::PILIPAY_MERCHANT_NO)); } } catch (Exception $e) { if (self::DEBUG_MODE) { trigger_error(get_class($e) . ': ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString(), E_USER_WARNING); } } }
/** * Send Email * * @param int $id_lang Language ID of the email (to translate the template) * @param string $template Template: the name of template not be a var but a string ! * @param string $subject Subject of the email * @param string $template_vars Template variables for the email * @param string $to To email * @param string $to_name To name * @param string $from From email * @param string $from_name To email * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files * @param bool $mode_smtp SMTP mode (deprecated) * @param string $template_path Template path * @param bool $die Die after error * @param string $bcc Bcc recipient * @return bool|int Whether sending was successful. If not at all, false, otherwise amount of recipients succeeded. */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null, $reply_to = null) { if (!$id_shop) { $id_shop = Context::getContext()->shop->id; } $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_TYPE'), null, null, $id_shop); // Returns immediatly if emails are deactivated if ($configuration['PS_MAIL_METHOD'] == 3) { return true; } $theme_path = _PS_THEME_DIR_; // Get the path of theme by id_shop if exist if (is_numeric($id_shop) && $id_shop) { $shop = new Shop((int) $id_shop); $theme_name = $shop->getTheme(); if (_THEME_NAME_ != $theme_name) { $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/'; } } if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION']) || Tools::strtolower($configuration['PS_MAIL_SMTP_ENCRYPTION']) === 'off') { $configuration['PS_MAIL_SMTP_ENCRYPTION'] = false; } if (!isset($configuration['PS_MAIL_SMTP_PORT'])) { $configuration['PS_MAIL_SMTP_PORT'] = 'default'; } // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail if (!isset($from) || !Validate::isEmail($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!Validate::isEmail($from)) { $from = null; } // $from_name is not that important, no need to die if it is not valid if (!isset($from_name) || !Validate::isMailName($from_name)) { $from_name = $configuration['PS_SHOP_NAME']; } if (!Validate::isMailName($from_name)) { $from_name = null; } // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem if (!is_array($to) && !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } // if bcc is not null, make sure it's a vaild e-mail if (!is_null($bcc) && !is_array($bcc) && !Validate::isEmail($bcc)) { Tools::dieOrLog(Tools::displayError('Error: parameter "bcc" is corrupted'), $die); $bcc = null; } if (!is_array($template_vars)) { $template_vars = array(); } // Do not crash for this error, that may be a complicated customer name if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) { $to_name = null; } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die); return false; } /* Construct multiple recipients list if needed */ $message = Swift_Message::newInstance(); if (is_array($to) && isset($to)) { foreach ($to as $key => $addr) { $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die); return false; } if (is_array($to_name) && $to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) { $to_name = $to_name[$key]; } $to_name = $to_name == null || $to_name == $addr ? '' : self::mimeEncode($to_name); $message->addTo($addr, $to_name); } $to_plugin = $to[0]; } else { /* Simple recipient, one address */ $to_plugin = $to; $to_name = $to_name == null || $to_name == $to ? '' : self::mimeEncode($to_name); $message->addTo($to, $to_name); } if (isset($bcc)) { $message->addBcc($bcc); } try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $connection = Swift_SmtpTransport::newInstance($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'])->setUsername($configuration['PS_MAIL_USER'])->setPassword($configuration['PS_MAIL_PASSWD']); } else { $connection = Swift_MailTransport::newInstance(); } if (!$connection) { return false; } $swift = Swift_Mailer::newInstance($connection); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $iso_template = $iso . '/' . $template; $module_name = false; $override_mail = false; // get templatePath if (preg_match('#' . $shop->physical_uri . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) { $module_name = $res[1]; } if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $iso_template . '.html'))) { $template_path = $theme_path . 'modules/' . $module_name . '/mails/'; } elseif (file_exists($theme_path . 'mails/' . $iso_template . '.txt') || file_exists($theme_path . 'mails/' . $iso_template . '.html')) { $template_path = $theme_path . 'mails/'; $override_mail = true; } if (!file_exists($template_path . $iso_template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.txt', $die); return false; } elseif (!file_exists($template_path . $iso_template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $iso_template . '.html', $die); return false; } $template_html = ''; $template_txt = ''; Hook::exec('actionEmailAddBeforeContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true); $template_html .= Tools::file_get_contents($template_path . $iso_template . '.html'); $template_txt .= strip_tags(html_entity_decode(Tools::file_get_contents($template_path . $iso_template . '.txt'), null, 'utf-8')); Hook::exec('actionEmailAddAfterContent', array('template' => $template, 'template_html' => &$template_html, 'template_txt' => &$template_txt, 'id_lang' => (int) $id_lang), null, true); if ($override_mail && file_exists($template_path . $iso . '/lang.php')) { include_once $template_path . $iso . '/lang.php'; } elseif ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) { include_once $theme_path . 'mails/' . $iso . '/lang.php'; } elseif (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) { include_once _PS_MAIL_DIR_ . $iso . '/lang.php'; } else { Tools::dieOrLog(Tools::displayError('Error - The language file is missing for:') . ' ' . $iso, $die); return false; } /* Create mail and attach differents parts */ $subject = '[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject; $message->setSubject($subject); $message->setCharset('utf-8'); /* Set Message-ID - getmypid() is blocked on some hosting */ $message->setId(Mail::generateId()); if (!($reply_to && Validate::isEmail($reply_to))) { $reply_to = $from; } if (isset($reply_to) && $reply_to) { $message->setReplyTo($reply_to); } $template_vars = array_map(array('Tools', 'htmlentitiesDecodeUTF8'), $template_vars); $template_vars = array_map(array('Tools', 'stripslashes'), $template_vars); if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop); } else { if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop); } else { $template_vars['{shop_logo}'] = ''; } } ShopUrl::cacheMainDomainForShop((int) $id_shop); /* don't attach the logo as */ if (isset($logo)) { $template_vars['{shop_logo}'] = $message->embed(Swift_Image::fromPath($logo)); } if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop)); $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id, null, false, $id_shop); $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop)); // Get extra template_vars $extra_template_vars = array(); Hook::exec('actionGetExtraMailTemplateVars', array('template' => $template, 'template_vars' => $template_vars, 'extra_template_vars' => &$extra_template_vars, 'id_lang' => (int) $id_lang), null, true); $template_vars = array_merge($template_vars, $extra_template_vars); $swift->registerPlugin(new Swift_Plugins_DecoratorPlugin(array($to_plugin => $template_vars))); if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) { $message->addPart($template_txt, 'text/plain', 'utf-8'); } if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) { $message->addPart($template_html, 'text/html', 'utf-8'); } if ($file_attachment && !empty($file_attachment)) { // Multiple attachments? if (!is_array(current($file_attachment))) { $file_attachment = array($file_attachment); } foreach ($file_attachment as $attachment) { if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) { $message->attach(Swift_Attachment::newInstance()->setFilename($attachment['name'])->setContentType($attachment['mime'])->setBody($attachment['content'])); } } } /* Send mail */ $message->setFrom(array($from => $from_name)); $send = $swift->send($message); ShopUrl::resetMainDomainCache(); if ($send && Configuration::get('PS_LOG_EMAILS')) { $mail = new Mail(); $mail->template = Tools::substr($template, 0, 62); $mail->subject = Tools::substr($subject, 0, 254); $mail->id_lang = (int) $id_lang; $recipients_to = $message->getTo(); $recipients_cc = $message->getCc(); $recipients_bcc = $message->getBcc(); if (!is_array($recipients_to)) { $recipients_to = array(); } if (!is_array($recipients_cc)) { $recipients_cc = array(); } if (!is_array($recipients_bcc)) { $recipients_bcc = array(); } foreach (array_merge($recipients_to, $recipients_cc, $recipients_bcc) as $email => $recipient_name) { /** @var Swift_Address $recipient */ $mail->id = null; $mail->recipient = Tools::substr($email, 0, 126); $mail->add(); } } return $send; } catch (Swift_SwiftException $e) { PrestaShopLogger::addLog('Swift Error: ' . $e->getMessage(), 3, null, 'Swift_Message'); return false; } }
public function importByGroups($offset = false, $limit = false, &$results = null, $validateOnly = false, $moreStep = 0) { // Check if the CSV file exist if (Tools::getValue('csv')) { $shop_is_feature_active = Shop::isFeatureActive(); // If i am a superadmin, i can truncate table (ONLY IF OFFSET == 0 or false and NOT FOR VALIDATION MODE!) if (!$offset && !$moreStep && !$validateOnly && ($shop_is_feature_active && $this->context->employee->isSuperAdmin() || !$shop_is_feature_active) && Tools::getValue('truncate')) { $this->truncateTables((int) Tools::getValue('entity')); } $import_type = false; $doneCount = 0; // Sometime, import will use registers to memorize data across all elements to import (for trees, or else). // Since import is splitted in multiple ajax calls, we must keep these data across all steps of the full import. $crossStepsVariables = array(); if ($crossStepsVars = Tools::getValue('crossStepsVars')) { $crossStepsVars = json_decode($crossStepsVars, true); if (sizeof($crossStepsVars) > 0) { $crossStepsVariables = $crossStepsVars; } } Db::getInstance()->disableCache(); switch ((int) Tools::getValue('entity')) { case $this->entities[$import_type = $this->l('Categories')]: $doneCount += $this->categoryImport($offset, $limit, $crossStepsVariables, $validateOnly); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Products')]: if (!defined('PS_MASS_PRODUCT_CREATION')) { define('PS_MASS_PRODUCT_CREATION', true); } $moreStepLabels = array($this->l('Linking Accessories...')); $doneCount += $this->productImport($offset, $limit, $crossStepsVariables, $validateOnly, $moreStep); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Customers')]: $doneCount += $this->customerImport($offset, $limit, $validateOnly); break; case $this->entities[$import_type = $this->l('Addresses')]: $doneCount += $this->addressImport($offset, $limit, $validateOnly); break; case $this->entities[$import_type = $this->l('Combinations')]: $doneCount += $this->attributeImport($offset, $limit, $crossStepsVariables, $validateOnly); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Brands')]: $doneCount += $this->manufacturerImport($offset, $limit, $validateOnly); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Suppliers')]: $doneCount += $this->supplierImport($offset, $limit, $validateOnly); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Alias')]: $doneCount += $this->aliasImport($offset, $limit, $validateOnly); break; case $this->entities[$import_type = $this->l('Store contacts')]: $doneCount += $this->storeContactImport($offset, $limit, $validateOnly); $this->clearSmartyCache(); break; } // @since 1.5.0 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { switch ((int) Tools::getValue('entity')) { case $this->entities[$import_type = $this->l('Supply Orders')]: if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $doneCount += $this->supplyOrdersImport($offset, $limit, $validateOnly); } break; case $this->entities[$import_type = $this->l('Supply Order Details')]: if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $doneCount += $this->supplyOrdersDetailsImport($offset, $limit, $crossStepsVariables, $validateOnly); } break; } } if ($results !== null) { $results['isFinished'] = $doneCount < $limit; $results['doneCount'] = $offset + $doneCount; if ($offset === 0) { // compute total count only once, because it takes time $handle = $this->openCsvFile(0); if ($handle) { $count = 0; while (fgetcsv($handle, MAX_LINE_SIZE, $this->separator)) { $count++; } $results['totalCount'] = $count; } $this->closeCsvFile($handle); } if (!$results['isFinished'] || !$validateOnly && $moreStep < count($moreStepLabels)) { // Since we'll have to POST this array from ajax for the next call, we should care about it size. $nextPostSize = mb_strlen(json_encode($crossStepsVariables)); $results['crossStepsVariables'] = $crossStepsVariables; $results['nextPostSize'] = $nextPostSize + 1024 * 64; // 64KB more for the rest of the POST query. $results['postSizeLimit'] = Tools::getMaxUploadSize(); } if ($results['isFinished'] && !$validateOnly && $moreStep < count($moreStepLabels)) { $results['oneMoreStep'] = $moreStep + 1; $results['moreStepLabel'] = $moreStepLabels[$moreStep]; } } if ($import_type !== false) { $log_message = sprintf($this->l('%s import', 'AdminTab', false, false), $import_type); if ($offset !== false && $limit !== false) { $log_message .= ' ' . sprintf($this->l('(from %s to %s)', 'AdminTab', false, false), $offset, $limit); } if (Tools::getValue('truncate')) { $log_message .= ' ' . $this->l('with truncate', 'AdminTab', false, false); } PrestaShopLogger::addLog($log_message, 1, null, $import_type, null, true, (int) $this->context->employee->id); } Db::getInstance()->enableCache(); } else { $this->errors[] = $this->l('To proceed, please upload a file first.'); } }
private function logHistoryFail($orderId, $transactionId, $statusId, $e) { $message = "Erro ao registrar histórico da atualizão da Transação: " . $transactionId . ', Pedido: ' . $orderId . ', Status: ' . $this->getStatus($statusId); if (!empty($e->getErrors()->erro->descricao)) { $message .= '. Menssagem do Erro: ' . $e->getErrors()->erro->descricao; } PrestaShopLogger::addLog($message, 3); }
/** * Delete multiple items * * @return boolean true if succcess */ protected function processBulkDelete() { if (is_array($this->boxes) && !empty($this->boxes)) { $object = new $this->className(); if (isset($object->noZeroObject)) { $objects_count = count(call_user_func(array($this->className, $object->noZeroObject))); // Check if all object will be deleted if ($objects_count <= 1 || count($this->boxes) == $objects_count) { $this->errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } } else { $result = true; foreach ($this->boxes as $id) { $to_delete = new $this->className($id); $delete_ok = true; if ($this->deleted) { $to_delete->deleted = 1; if (!$to_delete->update()) { $result = false; $delete_ok = false; } } else { if (!$to_delete->delete()) { $result = false; $delete_ok = false; } } if ($delete_ok) { PrestaShopLogger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int) $to_delete->id, true, (int) $this->context->employee->id); } else { $this->errors[] = sprintf(Tools::displayError('Can\'t delete #%d'), $id); } } if ($result) { $this->redirect_after = self::$currentIndex . '&conf=2&token=' . $this->token; } $this->errors[] = Tools::displayError('An error occurred while deleting this selection.'); } } else { $this->errors[] = Tools::displayError('You must select at least one element to delete.'); } if (isset($result)) { return $result; } else { return false; } }
private static function exec($method, $uri, $data, $content_type) { $connect = self::getConnect($uri, $method, $content_type); if ($data) { self::setData($connect, $data, $content_type); } $api_result = curl_exec($connect); $api_http_code = curl_getinfo($connect, CURLINFO_HTTP_CODE); $response = array('status' => $api_http_code, 'response' => Tools::jsonDecode($api_result, true)); if (Configuration::get('MERCADOPAGO_LOG') == 'true') { PrestaShopLogger::addLog('MercadoPago.exec :: data = ' . Tools::jsonEncode($data), MP::INFO, 0, null, null, true); PrestaShopLogger::addLog('MercadoPago.exec :: response = ' . $api_result, MP::INFO, $response['status'], null, null, true); } if ($response['status'] == 0) { $error = 'Can not call the API, status code 0.'; throw new Exception($error); } else { if ($response['status'] > 202) { PrestaShopLogger::addLog("MercadoPago::exec = " . $response['response']['message'], MP::ERROR, $response['status']); } } curl_close($connect); return $response; }
public function processLogin() { /* Check fields validity */ $passwd = trim(Tools::getValue('passwd')); $email = trim(Tools::getValue('email')); if (empty($email)) { $this->errors[] = Tools::displayError('Email is empty.'); } elseif (!Validate::isEmail($email)) { $this->errors[] = Tools::displayError('Invalid email address.'); } if (empty($passwd)) { $this->errors[] = Tools::displayError('The password field is blank.'); } elseif (!Validate::isPasswd($passwd)) { $this->errors[] = Tools::displayError('Invalid password.'); } if (!count($this->errors)) { // Find employee $this->context->employee = new Employee(); $is_employee_loaded = $this->context->employee->getByEmail($email, $passwd); $employee_associated_shop = $this->context->employee->getAssociatedShops(); if (!$is_employee_loaded) { $this->errors[] = Tools::displayError('The Employee does not exist, or the password provided is incorrect.'); $this->context->employee->logout(); } elseif (empty($employee_associated_shop) && !$this->context->employee->isSuperAdmin()) { $this->errors[] = Tools::displayError('This employee does not manage the shop anymore (Either the shop has been deleted or permissions have been revoked).'); $this->context->employee->logout(); } else { PrestaShopLogger::addLog(sprintf($this->l('Back Office connection from %s', 'AdminTab', false, false), Tools::getRemoteAddr()), 1, null, '', 0, true, (int) $this->context->employee->id); $this->context->employee->remote_addr = (int) ip2long(Tools::getRemoteAddr()); // Update cookie $cookie = Context::getContext()->cookie; $cookie->id_employee = $this->context->employee->id; $cookie->email = $this->context->employee->email; $cookie->profile = $this->context->employee->id_profile; $cookie->passwd = $this->context->employee->passwd; $cookie->remote_addr = $this->context->employee->remote_addr; if (!Tools::getValue('stay_logged_in')) { $cookie->last_activity = time(); } $cookie->write(); // If there is a valid controller name submitted, redirect to it if (isset($_POST['redirect']) && Validate::isControllerName($_POST['redirect'])) { $url = $this->context->link->getAdminLink($_POST['redirect']); } else { $tab = new Tab((int) $this->context->employee->default_tab); $url = $this->context->link->getAdminLink($tab->class_name); } if (Tools::isSubmit('ajax')) { die(Tools::jsonEncode(array('hasErrors' => false, 'redirect' => $url))); } else { $this->redirect_after = $url; } } } if (Tools::isSubmit('ajax')) { die(Tools::jsonEncode(array('hasErrors' => true, 'errors' => $this->errors))); } }
public function sendCampaign() { // get abandoned cart : $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86000, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t\t\tWHERE a.date_add > (NOW() - INTERVAL 60 DAY) ORDER BY a.id_cart DESC \n\t\t) AS toto WHERE id_order='Abandoned cart'"; $currency = Context::getContext()->currency->sign; $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT')); $abandoned_carts = Db::getInstance()->ExecuteS($sql); // get all available campaigns $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1'; $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns); if (!$allCampaigns || empty($allCampaigns)) { die('NO CAMPAIGN'); } // loop on all abandoned carts foreach ($abandoned_carts as $abncart) { if (Cart::getNbProducts((int) $abncart['id_cart']) > 0) { $emailsSent = 0; // loop on all available campaigns foreach ($allCampaigns as $camp) { if (DEBUG_SAC) { echo 'IdCustomer : ' . $abncart['id_customer'] . ' - IdCart : ' . $abncart['id_cart'] . '<br/>'; } $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']); if ($cartIsOnCampaign) { if (DEBUG_SAC) { echo 'Cart on campaign</br>'; } $id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $customer = new Customer($abncart['id_customer']); $cart = new Cart($abncart['id_cart']); $products = $cart->getProducts(); $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{campaign_name}' => $camp['name'], '{track_url}' => $this->getBaseURL() . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'], '{track_request}' => '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer']); $campM = new Campaign($camp['id_campaign']); if ($campM->voucher_amount && $campM->voucher_day && $campM->voucher_amount_type) { $campM->clean_old_reduction($campM->voucher_prefix); $customerVoucher = $campM->registerDiscount($customer->id, $campM->voucher_amount, $campM->voucher_day, $campM->voucher_amount_type, $campM->voucher_prefix); $tpl_vars['{coupon_name}'] = $customerVoucher->name; $tpl_vars['{coupon_code}'] = $customerVoucher->code; $tpl_vars['{coupon_value}'] = $camp['voucher_amount_type'] == 'percent' ? $customerVoucher->reduction_percent . '%' : Tools::displayprice($customerVoucher->reduction_amount); $tpl_vars['{coupon_valid_to}'] = date('d/m/Y', strtotime($customerVoucher->date_to)); } if (!empty($products)) { $cart_content = $campM->getCartContentHeader(); } else { $cart_content = ''; } foreach ($products as $prod) { $p = new Product($prod['id_product'], true, $id_lang); $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false); $total_no_tax = $prod['cart_quantity'] * $price_no_tax; $images = Image::getImages((int) $id_lang, (int) $p->id); $link = new Link(); $cart_content .= '<tr> <td align="center" ><img src="' . Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td> <td align="center" ><a href="' . $link->getProductLink($p) . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'] . '"/>' . $p->name . '</a></td> <td align="center" >' . Tools::displayprice($price_no_tax) . '</td> <td align="center" >' . $prod['cart_quantity'] . '</td> <td align="center" >' . Tools::displayprice($total_no_tax) . '</td> </tr>'; } $cart_content .= '</table>'; $tpl_vars['{cart_content}'] = $cart_content; $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/'; // send email to customer : $mailUser = Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id); // if mail user is successfully sent : if ($mailUser) { $history = new CampaignHistory(); $history->id_campaign = (int) $camp['id_campaign']; $history->id_customer = $abncart['id_customer']; $history->id_cart = $abncart['id_cart']; $history->id_cart_rule = isset($customerVoucher->id) ? $customerVoucher->id : 0; $history->click = 0; $history->converted = 0; $history->date_update = date('Y-m-d H:i:s', time()); $history->save(); // Email to admin : Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id); ++$emailsSent; } else { PrestaShopLogger::addLog('Error when sending user email (tpl:' . $campM->getFileName() . ',customer:' . $customer->email . ', campagne : ' . $camp['name'], 3); } } } // log emailing results : if ($emailsSent > 0) { PrestaShopLogger::addLog($emailsSent . ' emails sent for ' . $camp['name'] . ' campaign', 1); } } } }
/** * Display error and dies or silently log the error. * * @param string $msg * @param bool $die * * @return bool success of logging */ public static function dieOrLog($msg, $die = true) { if ($die || defined('_PS_MODE_DEV_') && _PS_MODE_DEV_) { die($msg); } return PrestaShopLogger::addLog($msg); }
public function postProcess() { /* PrestaShop demo mode */ if (_PS_MODE_DEMO_) { $this->errors[] = Tools::displayError('This functionality has been disabled.'); return; } if (Tools::isSubmit('import')) { // Check if the CSV file exist if (Tools::getValue('csv')) { // If i am a superadmin, i can truncate table if ((Shop::isFeatureActive() && $this->context->employee->isSuperAdmin() || !Shop::isFeatureActive()) && Tools::getValue('truncate')) { $this->truncateTables((int) Tools::getValue('entity')); } $import_type = false; switch ((int) Tools::getValue('entity')) { case $this->entities[$import_type = $this->l('Categories')]: $this->categoryImport(); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Products')]: $this->productImport(); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Customers')]: $this->customerImport(); break; case $this->entities[$import_type = $this->l('Addresses')]: $this->addressImport(); break; case $this->entities[$import_type = $this->l('Combinations')]: $this->attributeImport(); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Manufacturers')]: $this->manufacturerImport(); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Suppliers')]: $this->supplierImport(); $this->clearSmartyCache(); break; case $this->entities[$import_type = $this->l('Alias')]: $this->aliasImport(); break; } // @since 1.5.0 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { switch ((int) Tools::getValue('entity')) { case $this->entities[$import_type = $this->l('Supply Orders')]: if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->supplyOrdersImport(); } break; case $this->entities[$import_type = $this->l('Supply Order Details')]: if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->supplyOrdersDetailsImport(); } break; } } if ($import_type !== false) { $log_message = sprintf($this->l('%s import', 'AdminTab', false, false), $import_type); if (Tools::getValue('truncate')) { $log_message .= ' ' . $this->l('with truncate', 'AdminTab', false, false); } PrestaShopLogger::addLog($log_message, 1, null, $import_type, null, true, (int) $this->context->employee->id); } } else { $this->errors[] = $this->l('You must upload a file in order to proceed to the next step'); } } elseif ($filename = Tools::getValue('csvfilename')) { $filename = urldecode($filename); $file = AdminImportController::getPath(basename($filename)); if (realpath(dirname($file)) != realpath(AdminImportController::getPath())) { exit; } if (!empty($filename)) { $b_name = basename($filename); if (Tools::getValue('delete') && file_exists($file)) { @unlink($file); } elseif (file_exists($file)) { $b_name = explode('.', $b_name); $b_name = strtolower($b_name[count($b_name) - 1]); $mime_types = array('csv' => 'text/csv'); if (isset($mime_types[$b_name])) { $mime_type = $mime_types[$b_name]; } else { $mime_type = 'application/octet-stream'; } if (ob_get_level() && ob_get_length() > 0) { ob_end_clean(); } header('Content-Transfer-Encoding: binary'); header('Content-Type: ' . $mime_type); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename="' . $filename . '"'); $fp = fopen($file, 'rb'); while (is_resource($fp) && !feof($fp)) { echo fgets($fp, 16384); } exit; } } } return parent::postProcess(); }