/** * Logs a given customer in. */ public static function login_customer($id_customer) { // Make sure that that the customers exists. $sql = "SELECT * FROM `" . _DB_PREFIX_ . "customer` WHERE `id_customer` = '" . pSQL($id_customer) . "'"; $result = Db::getInstance()->GetRow($sql); // The user account has been found! if (!empty($result['id_customer'])) { // See => CustomerCore::getByEmail $customer = new Customer(); $customer->id = $result['id_customer']; foreach ($result as $key => $value) { if (key_exists($key, $customer)) { $customer->{$key} = $value; } } // See => AuthControllerCore::processSubmitLogin Hook::exec('actionBeforeAuthentication'); $context = Context::getContext(); $context->cookie->id_compare = isset($context->cookie->id_compare) ? $context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $context->cookie->id_customer = (int) $customer->id; $context->cookie->customer_lastname = $customer->lastname; $context->cookie->customer_firstname = $customer->firstname; $context->cookie->logged = 1; $customer->logged = 1; $context->cookie->is_guest = $customer->isGuest(); $context->cookie->passwd = $customer->passwd; $context->cookie->email = $customer->email; // Add customer to the context $context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($context->cookie->id_cart) || Cart::getNbProducts($context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($context->customer->id))) { $context->cart = new Cart($id_cart); } else { $context->cart->id_carrier = 0; $context->cart->setDeliveryOption(null); $context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id); $context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id); } $context->cart->id_customer = (int) $customer->id; $context->cart->secure_key = $customer->secure_key; $context->cart->save(); $context->cookie->id_cart = (int) $context->cart->id; $context->cookie->update(); $context->cart->autosetProductAddress(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($context); CartRule::autoAddToCart($context); // Customer is now logged in. return true; } // Invalid customer specified. return false; }
public function submit() { if ($this->validate()) { Hook::exec('actionAuthenticationBefore'); $customer = new Customer(); $authentication = $customer->getByEmail($this->getValue('email'), $this->getValue('password')); if (isset($authentication->active) && !$authentication->active) { $this->errors[''][] = $this->translator->trans('Your account isn\'t available at this time, please contact us', [], 'Shop.Notifications.Error'); } elseif (!$authentication || !$customer->id || $customer->is_guest) { $this->errors[''][] = $this->translator->trans('Authentication failed.', [], 'Shop.Notifications.Error'); } else { $this->context->updateCustomer($customer); Hook::exec('actionAuthentication', ['customer' => $this->context->customer]); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); } } return !$this->hasErrors(); }
/** * Assign template vars related to page content * @see FrontController::initContent() */ public function initContent() { parent::initContent(); /* id_carrier is not defined in database before choosing a carrier, set it to a default one to match a potential cart _rule */ if (empty($this->context->cart->id_carrier)) { $checked = $this->context->cart->simulateCarrierSelectedOutput(); $checked = (int) Cart::desintifier($checked); $this->context->cart->id_carrier = $checked; $this->context->cart->update(); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); } // SHOPPING CART $this->_assignSummaryInformations(); // WRAPPING AND TOS $this->_assignWrappingAndTOS(); if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) { $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true); } else { $countries = Country::getCountries($this->context->language->id, true); } // If a rule offer free-shipping, force hidding shipping prices $free_shipping = false; foreach ($this->context->cart->getCartRules() as $rule) { if ($rule['free_shipping'] && !$rule['carrier_restriction']) { $free_shipping = true; break; } } $this->context->smarty->assign(array('free_shipping' => $free_shipping, 'isGuest' => isset($this->context->cookie->is_guest) ? $this->context->cookie->is_guest : 0, 'countries' => $countries, 'sl_country' => (int) Tools::getCountry(), 'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'errorCarrier' => Tools::displayError('You must choose a carrier.', false), 'errorTOS' => Tools::displayError('You must accept the Terms of Service.', false), 'isPaymentStep' => isset($_GET['isPaymentStep']) && $_GET['isPaymentStep'], 'genders' => Gender::getGenders(), 'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'), 'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('displayCustomerAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Hook::exec('displayCustomerAccountFormTop'))); $years = Tools::dateYears(); $months = Tools::dateMonths(); $days = Tools::dateDays(); $this->context->smarty->assign(array('years' => $years, 'months' => $months, 'days' => $days)); /* Load guest informations */ if ($this->isLogged && $this->context->cookie->is_guest) { $this->context->smarty->assign('guestInformations', $this->_getGuestInformations()); } // ADDRESS if ($this->isLogged) { $this->_assignAddress(); } // CARRIER $this->_assignCarrier(); // PAYMENT $this->_assignPayment(); Tools::safePostVars(); $newsletter = Configuration::get('PS_CUSTOMER_NWSL') || Module::isInstalled('blocknewsletter') && Module::getInstanceByName('blocknewsletter')->active; $this->context->smarty->assign('newsletter', $newsletter); $this->context->smarty->assign('optin', (bool) Configuration::get('PS_CUSTOMER_OPTIN')); $this->context->smarty->assign('field_required', $this->context->customer->validateFieldsRequiredDatabase()); $this->_processAddressFormat(); $link = new Link(); if (Tools::getValue('deleteFromOrderLine')) { $id_product = Tools::getValue('id_product'); $date_from = Tools::getValue('date_from'); $date_to = Tools::getValue('date_to'); $obj_cart_bk_data = new HotelCartBookingData(); $cart_data_dlt = $obj_cart_bk_data->deleteRoomDataFromOrderLine($this->context->cart->id, $this->context->cart->id_guest, $id_product, $date_from, $date_to); if ($cart_data_dlt) { Tools::redirect($link->getPageLink('order', null, $this->context->language->id)); } } if ((bool) Configuration::get('PS_ADVANCED_PAYMENT_API')) { $this->addJS(_THEME_JS_DIR_ . 'advanced-payment-api.js'); $this->setTemplate(_PS_THEME_DIR_ . 'order-opc-advanced.tpl'); } else { if (Module::isInstalled('hotelreservationsystem')) { require_once _PS_MODULE_DIR_ . 'hotelreservationsystem/define.php'; $obj_cart_bk_data = new HotelCartBookingData(); $obj_htl_bk_dtl = new HotelBookingDetail(); $obj_rm_type = new HotelRoomType(); $htl_rm_types = $this->context->cart->getProducts(); if (!empty($htl_rm_types)) { foreach ($htl_rm_types as $type_key => $type_value) { $product = new Product($type_value['id_product'], false, $this->context->language->id); $cover_image_arr = $product->getCover($type_value['id_product']); if (!empty($cover_image_arr)) { $cover_img = $this->context->link->getImageLink($product->link_rewrite, $product->id . '-' . $cover_image_arr['id_image'], 'small_default'); } else { $cover_img = $this->context->link->getImageLink($product->link_rewrite, $this->context->language->iso_code . "-default", 'small_default'); } $unit_price = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1); if (isset($this->context->customer->id)) { $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->context->cart->id, $this->context->cart->id_guest, $type_value['id_product']); } else { $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->context->cart->id, $this->context->cart->id_guest, $type_value['id_product']); } $rm_dtl = $obj_rm_type->getRoomTypeInfoByIdProduct($type_value['id_product']); $cart_htl_data[$type_key]['id_product'] = $type_value['id_product']; $cart_htl_data[$type_key]['cover_img'] = $cover_img; $cart_htl_data[$type_key]['name'] = $product->name; $cart_htl_data[$type_key]['unit_price'] = $unit_price; $cart_htl_data[$type_key]['adult'] = $rm_dtl['adult']; $cart_htl_data[$type_key]['children'] = $rm_dtl['children']; foreach ($cart_bk_data as $data_k => $data_v) { $date_join = strtotime($data_v['date_from']) . strtotime($data_v['date_to']); if (isset($cart_htl_data[$type_key]['date_diff'][$date_join])) { $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] += 1; $num_days = $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days']; $vart_quant = (int) $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] * $num_days; $amount = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1); $amount *= $vart_quant; $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = $amount; } else { $num_days = $obj_htl_bk_dtl->getNumberOfDays($data_v['date_from'], $data_v['date_to']); $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] = 1; $cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = $data_v['date_from']; $cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = $data_v['date_to']; $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'] = $num_days; $amount = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1); $amount *= $num_days; $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = $amount; $cart_htl_data[$type_key]['date_diff'][$date_join]['link'] = $link->getPageLink('order', null, $this->context->language->id, "id_product=" . $type_value['id_product'] . "&deleteFromOrderLine=1&date_from=" . $data_v['date_from'] . "&date_to=" . $data_v['date_to']); } } } $this->context->smarty->assign('cart_htl_data', $cart_htl_data); } } $this->setTemplate(_PS_THEME_DIR_ . 'order-opc.tpl'); } }
/** * Process login */ protected function processSubmitLogin() { Hook::exec('actionBeforeAuthentication'); $passwd = trim(Tools::getValue('passwd')); $email = trim(Tools::getValue('email')); if (empty($email)) { $this->errors[] = Tools::displayError('E-mail address required'); } elseif (!Validate::isEmail($email)) { $this->errors[] = Tools::displayError('Invalid e-mail address'); } elseif (empty($passwd)) { $this->errors[] = Tools::displayError('Password is required'); } elseif (!Validate::isPasswd($passwd)) { $this->errors[] = Tools::displayError('Invalid password'); } else { $customer = new Customer(); $authentication = $customer->getByEmail(trim($email), trim($passwd)); if (!$authentication || !$customer->id) { $this->errors[] = Tools::displayError('Authentication failed'); } else { $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->logged = 1; $customer->logged = 1; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; // Add customer to the context $this->context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0)) { $this->context->cookie->id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id); } // Update cart address $this->context->cart->id = $this->context->cookie->id_cart; $this->context->cart->setDeliveryOption(null); $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->secure_key = $customer->secure_key; $this->context->cart->update(); $this->context->cart->autosetProductAddress(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (!$this->ajax) { if ($back = Tools::getValue('back')) { Tools::redirect(html_entity_decode($back)); } Tools::redirect('index.php?controller=my-account'); } } } if ($this->ajax) { $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false)); die(Tools::jsonEncode($return)); } else { $this->context->smarty->assign('authentification_error', $this->errors); } }
/** * This process add or update a product in the cart */ protected function processChangeProductInCart() { $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add'; if (Tools::getIsset('group')) { $this->id_product_attribute = (int) Product::getIdProductAttributesByIdAttributes($this->id_product, Tools::getValue('group')); } if ($this->qty == 0) { $this->errors[] = $this->trans('Null quantity.', array(), 'Shop.Notifications.Error'); } elseif (!$this->id_product) { $this->errors[] = $this->trans('Product not found', array(), 'Shop.Notifications.Error'); } $product = new Product($this->id_product, true, $this->context->language->id); if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) { $this->errors[] = $this->trans('This product is no longer available.', array(), 'Shop.Notifications.Error'); return; } $qty_to_check = $this->qty; $cart_products = $this->context->cart->getProducts(); if (is_array($cart_products)) { foreach ($cart_products as $cart_product) { if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute && $cart_product['id_customization'] == $this->customization_id) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) { $qty_to_check = $cart_product['cart_quantity']; if (Tools::getValue('op', 'up') == 'down') { $qty_to_check -= $this->qty; } else { $qty_to_check += $this->qty; } break; } } } // Check product quantity availability if ($this->id_product_attribute) { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = $this->trans('There isn\'t enough product in stock', array(), 'Shop.Notifications.Error'); } } elseif ($product->hasAttributes()) { $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock; $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity); // @todo do something better than a redirect admin !! if (!$this->id_product_attribute) { Tools::redirectAdmin($this->context->link->getProductLink($product)); } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = $this->trans('There isn\'t enough product in stock', array(), 'Shop.Notifications.Error'); } } elseif (!$product->checkQty($qty_to_check)) { $this->errors[] = $this->trans('There isn\'t enough product in stock', array(), 'Shop.Notifications.Error'); } // If no errors, process product addition if (!$this->errors) { // Add cart if no cart found if (!$this->context->cart->id) { if (Context::getContext()->cookie->id_guest) { $guest = new Guest(Context::getContext()->cookie->id_guest); $this->context->cart->mobile_theme = $guest->mobile_theme; } $this->context->cart->add(); if ($this->context->cart->id) { $this->context->cookie->id_cart = (int) $this->context->cart->id; } } // Check customizable fields if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) { $this->errors[] = $this->trans('Please fill in all of the required fields, and then save your customizations.', array(), 'Shop.Notifications.Error'); } if (!$this->errors) { $cart_rules = $this->context->cart->getCartRules(); $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true); $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, Tools::getValue('op', 'up'), $this->id_address_delivery); if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity; $this->errors[] = $this->trans('You must add %d minimum quantity', array($minimal_quantity), 'Shop.Notifications.Error'); } elseif (!$update_quantity) { $this->errors[] = $this->trans('You already have the maximum quantity available for this product.', array(), 'Shop.Notifications.Error'); } } } $removed = CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); }
/** * Delete a product from the cart * * @param integer $id_product Product ID * @param integer $id_product_attribute Attribute ID if needed * @param integer $id_customization Customization id * @return boolean result */ public function deleteProduct($id_product, $id_product_attribute = null, $id_customization = null, $id_address_delivery = 0) { if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } if ((int) $id_customization) { $product_total_quantity = (int) Db::getInstance()->getValue('SELECT `quantity` FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' AND `id_cart` = ' . (int) $this->id . ' AND `id_product_attribute` = ' . (int) $id_product_attribute); $customization_quantity = (int) Db::getInstance()->getValue(' SELECT `quantity` FROM `' . _DB_PREFIX_ . 'customization` WHERE `id_cart` = ' . (int) $this->id . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute . ' ' . ((int) $id_address_delivery ? 'AND `id_address_delivery` = ' . (int) $id_address_delivery : '')); if (!$this->_deleteCustomization((int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery)) { return false; } // refresh cache of self::_products $this->_products = $this->getProducts(true); return $customization_quantity == $product_total_quantity && $this->deleteProduct((int) $id_product, (int) $id_product_attribute, null, (int) $id_address_delivery); } /* Get customization quantity */ $result = Db::getInstance()->getRow(' SELECT SUM(`quantity`) AS \'quantity\' FROM `' . _DB_PREFIX_ . 'customization` WHERE `id_cart` = ' . (int) $this->id . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute); if ($result === false) { return false; } /* If the product still possesses customization it does not have to be deleted */ if (Db::getInstance()->NumRows() && (int) $result['quantity']) { return Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'cart_product` SET `quantity` = ' . (int) $result['quantity'] . ' WHERE `id_cart` = ' . (int) $this->id . ' AND `id_product` = ' . (int) $id_product . ($id_product_attribute != null ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '')); } /* Product deletion */ $result = Db::getInstance()->execute(' DELETE FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' ' . (!is_null($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . ' ' . ((int) $id_address_delivery ? 'AND `id_address_delivery` = ' . (int) $id_address_delivery : '')); if ($result) { $return = $this->update(true); // refresh cache of self::_products $this->_products = $this->getProducts(true); CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); return $return; } return false; }
protected function _assignAddress() { //if guest checkout disabled and flag is_guest in cookies is actived if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED') == 0 && (int) $this->context->customer->is_guest != Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) { $this->context->customer->logout(); Tools::redirect(''); } else { if (!Customer::getAddressesTotalById($this->context->customer->id)) { Tools::redirect('index.php?controller=address&back=' . urlencode('order.php?step=1&multi-shipping=' . (int) Tools::getValue('multi-shipping'))); } } $customer = $this->context->customer; if (Validate::isLoadedObject($customer)) { /* Getting customer addresses */ $customerAddresses = $customer->getAddresses($this->context->language->id); // Getting a list of formated address fields with associated values $formatedAddressFieldsValuesList = array(); foreach ($customerAddresses as $i => $address) { if (!Address::isCountryActiveById((int) $address['id_address'])) { unset($customerAddresses[$i]); } $tmpAddress = new Address($address['id_address']); $formatedAddressFieldsValuesList[$address['id_address']]['ordered_fields'] = AddressFormat::getOrderedAddressFields($address['id_country']); $formatedAddressFieldsValuesList[$address['id_address']]['formated_fields_values'] = AddressFormat::getFormattedAddressFieldsValues($tmpAddress, $formatedAddressFieldsValuesList[$address['id_address']]['ordered_fields']); unset($tmpAddress); } if (key($customerAddresses) != 0) { $customerAddresses = array_values($customerAddresses); } if (!count($customerAddresses)) { $bad_delivery = false; if (($bad_delivery = (bool) (!Address::isCountryActiveById((int) $this->context->cart->id_address_delivery))) || !Address::isCountryActiveById((int) $this->context->cart->id_address_invoice)) { $back_url = $this->context->link->getPageLink('order', true, (int) $this->context->language->id, array('step' => Tools::getValue('step'), 'multi-shipping' => (int) Tools::getValue('multi-shipping'))); $params = array('multi-shipping' => (int) Tools::getValue('multi-shipping'), 'id_address' => $bad_delivery ? (int) $this->context->cart->id_address_delivery : (int) $this->context->cart->id_address_invoice, 'back' => $back_url); Tools::redirect($this->context->link->getPageLink('address', true, (int) $this->context->language->id, $params)); } } $this->context->smarty->assign(array('addresses' => $customerAddresses, 'formatedAddressFieldsValuesList' => $formatedAddressFieldsValuesList)); /* Setting default addresses for cart */ if ((!isset($this->context->cart->id_address_delivery) || empty($this->context->cart->id_address_delivery)) && count($customerAddresses)) { $this->context->cart->id_address_delivery = (int) $customerAddresses[0]['id_address']; $update = 1; } if ((!isset($this->context->cart->id_address_invoice) || empty($this->context->cart->id_address_invoice)) && count($customerAddresses)) { $this->context->cart->id_address_invoice = (int) $customerAddresses[0]['id_address']; $update = 1; } /* Update cart addresses only if needed */ if (isset($update) && $update) { $this->context->cart->update(); // Address has changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); } /* If delivery address is valid in cart, assign it to Smarty */ if (isset($this->context->cart->id_address_delivery)) { $deliveryAddress = new Address((int) $this->context->cart->id_address_delivery); if (Validate::isLoadedObject($deliveryAddress) && $deliveryAddress->id_customer == $customer->id) { $this->context->smarty->assign('delivery', $deliveryAddress); } } /* If invoice address is valid in cart, assign it to Smarty */ if (isset($this->context->cart->id_address_invoice)) { $invoiceAddress = new Address((int) $this->context->cart->id_address_invoice); if (Validate::isLoadedObject($invoiceAddress) && $invoiceAddress->id_customer == $customer->id) { $this->context->smarty->assign('invoice', $invoiceAddress); } } } if ($oldMessage = Message::getMessageByCartId((int) $this->context->cart->id)) { $this->context->smarty->assign('oldMessage', $oldMessage['message']); } }
public function addData($data, $add, $type) { $delivery = array(); $cart = new Cart(); if ($data->{$type}->currency == 'RUR') { $currency_id = Currency::getIdByIsoCode('RUB'); } else { $currency_id = Currency::getIdByIsoCode($data->cart->currency); } $def_currency = Configuration::get('PS_CURRENCY_DEFAULT'); $this->context->cookie->id_currency = $def_currency != $currency_id ? $currency_id : $def_currency; $this->context->cookie->write(); $this->context->currency = new Currency($this->context->cookie->id_currency); $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->add(); $this->context->cookie->id_cart = (int) $cart->id; $this->context->cookie->write(); $buyer = isset($data->{$type}->buyer) ? $data->{$type}->buyer : ''; $b = array(); if ($add) { $delivery = isset($data->{$type}->delivery->address) ? $data->{$type}->delivery->address : new stdClass(); $street = isset($delivery->street) ? ' Улица: ' . $delivery->street : 'Самовывоз'; $subway = isset($delivery->subway) ? ' Метро: ' . $delivery->subway : ''; $block = isset($delivery->block) ? ' Корпус/Строение: ' . $delivery->block : ''; $floor = isset($delivery->floor) ? ' Этаж: ' . $delivery->floor : ''; $house = isset($delivery->house) ? ' Дом: ' . $delivery->house : ''; $address1 = $street . $subway . $block . $floor . $house; $customer = new Customer(Configuration::get('YA_POKUPKI_CUSTOMER')); $address = new Address(); $address->firstname = $customer->firstname; $address->lastname = $customer->lastname; $address->phone_mobile = isset($buyer->phone) ? $buyer->phone : 999999; $address->postcode = isset($delivery->postcode) ? $delivery->postcode : 00; $address->address1 = $address1; $address->city = isset($delivery->city) ? $delivery->city : 'Город'; $address->alias = 'pokupki_' . Tools::substr(md5(time() . _COOKIE_KEY_), 0, 7); $address->id_customer = $customer->id; $address->id_country = Configuration::get('PS_COUNTRY_DEFAULT'); $address->save(); $cart->id_address_invoice = (int) $address->id; $cart->id_address_delivery = (int) $address->id; $cart->update(); $cart->id_customer = (int) $customer->id; $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->write(); $b = array('address' => $address, 'customer' => $customer); } CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); $a = array('cart' => $cart); $dd = array_merge($a, $b); return $dd; }
public function init() { self::$amz_payments = new AmzPayments(); $this->isLogged = (bool) $this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer); parent::init(); /* Disable some cache related bugs on the cart/order */ header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); $this->display_column_left = false; $this->display_column_right = false; // Service initialisieren $this->service = self::$amz_payments->getService(); if (Tools::isSubmit('ajax')) { if (Tools::isSubmit('method')) { switch (Tools::getValue('method')) { case 'redirectAuthentication': case 'setusertoshop': if (Tools::getValue('access_token')) { $this->context->cookie->amz_access_token = AmzPayments::prepareCookieValueForPrestaShopUse(Tools::getValue('access_token')); $this->context->cookie->amz_access_token_set_time = time(); } else { if (Tools::getValue('method') == 'redirectAuthentication') { Tools::redirect('index'); } else { error_log('Error, method not submitted and no token'); die('error'); } } if (Tools::getValue('action') == 'fromCheckout') { $accessTokenValue = AmzPayments::prepareCookieValueForAmazonPaymentsUse(Tools::getValue('access_token')); } else { $accessTokenValue = Tools::getValue('access_token'); } $d = self::$amz_payments->requestTokenInfo($accessTokenValue); if ($d->aud != self::$amz_payments->client_id) { if (Tools::getValue('method') == 'redirectAuthentication') { Tools::redirect('index'); } else { error_log('auth error LPA'); die('error'); } } $d = self::$amz_payments->requestProfile($accessTokenValue); $customer_userid = $d->user_id; $customer_name = $d->name; $customer_email = $d->email; // $postcode = $d->postal_code; if ($customers_local_id = AmazonPaymentsCustomerHelper::findByAmazonCustomerId($customer_userid)) { // Customer already exists - login Hook::exec('actionBeforeAuthentication'); $customer = new Customer(); $authentication = AmazonPaymentsCustomerHelper::getByCustomerID($customers_local_id, true, $customer); if (isset($authentication->active) && !$authentication->active) { $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us'); } elseif (!$authentication || !$customer->id) { $this->errors[] = Tools::displayError('Authentication failed.'); } else { $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->logged = 1; $customer->logged = 1; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; // Add customer to the context $this->context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) { $this->context->cart = new Cart($id_cart); } else { $id_carrier = (int) $this->context->cart->id_carrier; $this->context->cart->id_carrier = 0; $this->context->cart->setDeliveryOption(null); $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id); } $this->context->cart->id_customer = (int) $customer->id; $this->context->cart->secure_key = $customer->secure_key; if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ','); $this->context->cart->setDeliveryOption($delivery_option); } $this->context->cart->save(); $this->context->cookie->id_cart = (int) $this->context->cart->id; $this->context->cookie->write(); $this->context->cart->autosetProductAddress(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) { AmzPayments::switchOrderToCustomer($this->context->customer->id, $this->context->cookie->amz_connect_order, true); } if (Tools::getValue('action') == 'checkout') { $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments'); } elseif (Tools::getValue('action') == 'fromCheckout') { $goto = 'index.php?controller=history'; } elseif ($this->context->cart->nbProducts()) { $goto = 'index.php?controller=order'; } else { if (Configuration::get('PS_SSL_ENABLED')) { $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__; } else { $goto = _PS_BASE_URL_ . __PS_BASE_URI__; } } if (Tools::getValue('method') == 'redirectAuthentication') { Tools::redirect($goto); } else { echo $goto; } } } else { if (AmazonPaymentsCustomerHelper::findByEmailAddress($customer_email)) { $this->context->cookie->amzConnectEmail = $customer_email; $this->context->cookie->amzConnectCustomerId = $customer_userid; $goto = $this->context->link->getModuleLink('amzpayments', 'connect_accounts'); if (Tools::getValue('action') && Tools::getValue('action') == 'checkout') { if (strpos($goto, '?') > 0) { $goto .= '&checkout=1'; } else { $goto .= '?checkout=1'; } } if (Tools::getValue('method') == 'redirectAuthentication') { Tools::redirect($goto); } else { echo $goto; } } else { // Customer does not exist - Create account Hook::exec('actionBeforeSubmitAccount'); $this->create_account = true; $_POST['passwd'] = md5(time() . _COOKIE_KEY_); $firstname = ''; $lastname = ''; $customer_name = preg_replace("/[0-9]/", "", $customer_name); if (strpos(trim($customer_name), ' ') !== false) { list($firstname, $lastname) = explode(' ', trim($customer_name)); } elseif (strpos(trim($customer_name), '-') !== false) { list($firstname, $lastname) = explode('-', trim($customer_name)); } else { $firstname = trim($customer_name); $lastname = 'Placeholder'; } $customer = new Customer(); $customer->email = $customer_email; $lastname_address = $lastname; $firstname_address = $firstname; $_POST['lastname'] = Tools::getValue('customer_lastname', $lastname_address); $_POST['firstname'] = Tools::getValue('customer_firstname', $firstname_address); // $addresses_types = array('address'); $this->errors = array_unique(array_merge($this->errors, $customer->validateController())); // Check the requires fields which are settings in the BO $this->errors = $this->errors + $customer->validateFieldsRequiredDatabase(); if (!count($this->errors)) { $customer->firstname = Tools::ucwords($customer->firstname); $customer->is_guest = 0; $customer->active = 1; if (!count($this->errors)) { if ($customer->add()) { if (!$customer->is_guest) { if (!$this->sendConfirmationMail($customer)) { $this->errors[] = Tools::displayError('The email cannot be sent.'); } } AmazonPaymentsCustomerHelper::saveCustomersAmazonReference($customer, $customer_userid); $this->updateContext($customer); $this->context->cart->update(); Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer)); if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) { AmzPayments::switchOrderToCustomer($customer->id, $this->context->cookie->amz_connect_order, true); } if (Tools::getValue('action') == 'checkout') { $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments'); } elseif (Tools::getValue('action') == 'fromCheckout') { $goto = 'index.php?controller=history'; } elseif ($this->context->cart->nbProducts()) { $goto = 'index.php?controller=order'; } else { if (Configuration::get('PS_SSL_ENABLED')) { $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__; } else { $goto = _PS_BASE_URL_ . __PS_BASE_URI__; } } if (Tools::getValue('method') == 'redirectAuthentication') { Tools::redirect($goto); } else { echo $goto; } } else { $this->errors[] = Tools::displayError('An error occurred while creating your account.'); } } } else { error_log('Error validating customers informations'); die('error'); } } } die; } } } }
/** * @see FrontController::initContent() */ public function initContent() { parent::initContent(); $fb_connect_appid = Configuration::get('FB_CONNECT_APPID'); $fb_connect_appkey = Configuration::get('FB_CONNECT_APPKEY'); $this->login_url = $this->context->link->getModuleLink('fbconnect_psb', 'login', array(), TRUE, $this->context->language->id); require_once _PS_ROOT_DIR_ . '/modules/fbconnect_psb/fb_sdk/facebook.php'; $facebook = new Facebook(array('appId' => $fb_connect_appid, 'secret' => $fb_connect_appkey)); // Get User ID $user = $facebook->getUser(); // We may or may not have this data based on whether the user is logged in. // // If we have a $user id here, it means we know the user is logged into // Facebook, but we don't know if the access token is valid. An access // token is invalid if the user logged out of Facebook. if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $fb_user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { //die('Error: '.$e); error_log($e); $user = null; } } else { // Get new Access tokens Tools::redirect($facebook->getLoginUrl(array('scope' => 'email'))); } // current user state Logged In with FB if ($user) { //get the user email from DB with FB ID $sql = 'SELECT c.`email` FROM `' . _DB_PREFIX_ . 'customer` c LEFT JOIN `' . _DB_PREFIX_ . 'customer_profile_connect` pc ON pc.id_customer = c.id_customer WHERE pc.`facebook_id` = ' . (int) $fb_user_profile['id'] . Shop::addSqlRestriction(Shop::SHARE_CUSTOMER, 'c'); $email = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); if (empty($email)) { Tools::redirect($this->context->link->getModuleLink('fbconnect_psb', 'registration', array(), TRUE, $this->context->language->id)); } else { $customer = new Customer(); $authentication = $customer->getByEmail(trim($email)); if (!$authentication || !$customer->id) { $this->errors[] = Tools::displayError('Error: Authentication failed.'); } else { $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->logged = 1; $customer->logged = 1; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; // Add customer to the context $this->context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) { $this->context->cart = new Cart($id_cart); } else { $this->context->cart->id_carrier = 0; $this->context->cart->setDeliveryOption(null); $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id); } $this->context->cart->id_customer = (int) $customer->id; $this->context->cart->secure_key = $customer->secure_key; $this->context->cart->save(); $this->context->cookie->id_cart = (int) $this->context->cart->id; $this->context->cookie->update(); $this->context->cart->autosetProductAddress(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if ($back = Tools::getValue('back')) { Tools::redirect(html_entity_decode($back)); } else { Tools::redirect('index.php?controller=' . ($this->authRedirection !== false ? url_encode($this->authRedirection) : 'my-account')); } } } $this->context->smarty->assign(array('redirect_uri' => urlencode($this->login_url), 'fb_connect_appid' => $fb_connect_appid, 'fb_connect_error' => $this->errors)); $this->setTemplate('login_fb.tpl'); } else { if (isset($_GET['error']) && isset($_GET['error_code'])) { $msg = 'There was error while trying to get information from Facebook.'; $msg .= '<br>' . $_GET['error'] . ' - ' . $_GET['error_code'] . ' - ' . $_GET['error_description'] . ' - ' . $_GET['error_reason']; $this->errors[] = Tools::displayError($msg); $this->setTemplate('login_fb.tpl'); } else { Tools::redirect($facebook->getLoginUrl(array('scope' => 'email'))); } } }
protected function processForm() { if (Tools::getValue('action') == 'tryConnect') { if (Tools::getValue('email') == $this->context->cookie->amzConnectEmail) { $customer = new Customer(); $authentication = $customer->getByEmail(trim(Tools::getValue('email')), trim(Tools::getValue('passwd'))); if (isset($authentication->active) && !$authentication->active) { $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us'); } elseif (!$authentication || !$customer->id) { $this->errors[] = Tools::displayError('Authentication failed.'); } else { $authentication->save(); AmazonPaymentsCustomerHelper::saveCustomersAmazonReference($authentication, $this->context->cookie->amzConnectCustomerId); $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->logged = 1; $customer->logged = 1; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; // Add customer to the context $this->context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) { $this->context->cart = new Cart($id_cart); } else { $id_carrier = (int) $this->context->cart->id_carrier; $this->context->cart->id_carrier = 0; $this->context->cart->setDeliveryOption(null); $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id); } $this->context->cart->id_customer = (int) $customer->id; $this->context->cart->secure_key = $customer->secure_key; if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ','); $this->context->cart->setDeliveryOption($delivery_option); } $this->context->cart->save(); $this->context->cookie->id_cart = (int) $this->context->cart->id; $this->context->cookie->write(); $this->context->cart->autosetProductAddress(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (Tools::getValue('toCheckout') == '1') { $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments'); } elseif (Tools::getValue('fromCheckout') == '1') { $goto = 'index.php?controller=history'; } elseif ($this->context->cart->nbProducts()) { $goto = 'index.php?controller=order'; } else { if (Configuration::get('PS_SSL_ENABLED')) { $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__; } else { $goto = _PS_BASE_URL_ . __PS_BASE_URI__; } } Tools::redirect($goto); } } } }
private function processLogin($customer) { if (!Validate::isLoadedObject($customer)) { FSLTools::returnError(Tools::displayError('Bad customer object.')); } Hook::exec('actionBeforeAuthentication'); $context = $this->context; $context->cookie->id_compare = isset($context->cookie->id_compare) ? $context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $context->cookie->id_customer = (int) $customer->id; $context->cookie->customer_lastname = $customer->lastname; $context->cookie->customer_firstname = $customer->firstname; $context->cookie->logged = 1; $customer->logged = 1; $context->cookie->is_guest = $customer->isGuest(); $context->cookie->passwd = $customer->passwd; $context->cookie->email = $customer->email; // Add customer to the context $context->customer = $customer; if (isset($context->cart)) { if (Configuration::get('PS_CART_FOLLOWING') && (empty($context->cookie->id_cart) || Cart::getNbProducts($context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($context->customer->id))) { $context->cart = new Cart($id_cart); } else { $id_carrier = (int) $context->cart->id_carrier; $context->cart->id_carrier = 0; $context->cart->setDeliveryOption(null); $context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id); $context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id); } $context->cart->id_customer = (int) $customer->id; $context->cart->secure_key = $customer->secure_key; if (isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $delivery_option = array($context->cart->id_address_delivery => $id_carrier . ','); $context->cart->setDeliveryOption($delivery_option); } $context->cart->save(); $context->cookie->id_cart = (int) $context->cart->id; $context->cart->autosetProductAddress(); } $context->cookie->write(); Hook::exec('actionAuthentication'); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($context); CartRule::autoAddToCart($context); }
protected function _processCarrier() { $this->context->cart->recyclable = (int) Tools::getValue('recyclable'); $this->context->cart->gift = (int) Tools::getValue('gift'); if ((int) Tools::getValue('gift')) { if (!Validate::isMessage(Tools::getValue('gift_message'))) { $this->errors[] = Tools::displayError('Invalid gift message.'); } else { $this->context->cart->gift_message = strip_tags(Tools::getValue('gift_message')); } } if (isset($this->context->customer->id) && $this->context->customer->id) { $address = new Address((int) $this->context->cart->id_address_delivery); if (!Address::getZoneById($address->id)) { $this->errors[] = Tools::displayError('No zone matches your address.'); } } else { Country::getIdZone((int) Configuration::get('PS_COUNTRY_DEFAULT')); } if (Tools::getIsset('delivery_option')) { if ($this->validateDeliveryOption(Tools::getValue('delivery_option'))) { $this->context->cart->setDeliveryOption(Tools::getValue('delivery_option')); } } elseif (Tools::getIsset('id_carrier')) { $delivery_option_list = $this->context->cart->getDeliveryOptionList(); if (count($delivery_option_list) == 1) { reset($delivery_option_list); $key = Cart::desintifier(Tools::getValue('id_carrier')); foreach ($delivery_option_list as $id_address => $options) { if (isset($options[$key])) { $this->context->cart->id_carrier = (int) Tools::getValue('id_carrier'); $this->context->cart->setDeliveryOption(array($id_address => $key)); if (isset($this->context->cookie->id_country)) { unset($this->context->cookie->id_country); } if (isset($this->context->cookie->id_state)) { unset($this->context->cookie->id_state); } } } } } Hook::exec('actionCarrierProcess', array('cart' => $this->context->cart)); if (!$this->context->cart->update()) { return false; } CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); return true; }
/** * Process login */ protected function processSubmitLogin() { Hook::exec('actionBeforeAuthentication'); $passwd = trim(Tools::getValue('passwd')); $_POST['passwd'] = null; $email = trim(Tools::getValue('email')); if (empty($email)) { $this->errors[] = Tools::displayError('An email address required.'); } elseif (!Validate::isEmail($email)) { $this->errors[] = Tools::displayError('Invalid email address.'); } elseif (empty($passwd)) { $this->errors[] = Tools::displayError('Password is required.'); } elseif (!Validate::isPasswd($passwd)) { $this->errors[] = Tools::displayError('Invalid password.'); } else { $customer = new Customer(); $authentication = $customer->getByEmail(trim($email), trim($passwd)); if (isset($authentication->active) && !$authentication->active) { $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us'); } elseif (!$authentication || !$customer->id) { $this->errors[] = Tools::displayError('Authentication failed.'); } else { $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->logged = 1; $customer->logged = 1; $this->context->cookie->is_guest = $customer->isGuest(); $this->context->cookie->passwd = $customer->passwd; $this->context->cookie->email = $customer->email; // Add customer to the context $this->context->customer = $customer; if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) { $this->context->cart = new Cart($id_cart); } else { $id_carrier = (int) $this->context->cart->id_carrier; $this->context->cart->id_carrier = 0; $this->context->cart->setDeliveryOption(null); $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id); $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id); } $this->context->cart->id_customer = (int) $customer->id; $this->context->cart->secure_key = $customer->secure_key; if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) { $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ','); $this->context->cart->setDeliveryOption($delivery_option); } $this->context->cart->save(); $this->context->cookie->id_cart = (int) $this->context->cart->id; $this->context->cookie->write(); $this->context->cart->autosetProductAddress(); Hook::exec('actionAuthentication', array('customer' => $this->context->customer)); // Login information have changed, so we check if the cart rules still apply CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (!$this->ajax) { $back = Tools::getValue('back', 'my-account'); if ($back == Tools::secureReferrer($back)) { Tools::redirect(html_entity_decode($back)); } Tools::redirect('index.php?controller=' . ($this->authRedirection !== false ? urlencode($this->authRedirection) : $back)); } } } if ($this->ajax) { $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false)); $this->ajaxDie(Tools::jsonEncode($return)); } else { $this->context->smarty->assign('authentification_error', $this->errors); } }
/** * Manage address */ public function processAddress() { $same = Tools::isSubmit('same'); if (!Tools::getValue('id_address_invoice', false) && !$same) { $same = true; } if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery')) || !$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice'))) { $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax')); } else { $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery'); $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice'); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (!$this->context->cart->update()) { $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax')); } if (!$this->context->cart->isMultiAddressDelivery()) { $this->context->cart->setNoMultishipping(); } // If there is only one delivery address, set each delivery address lines with the main delivery address if (Tools::isSubmit('message')) { $this->_updateMessage(Tools::getValue('message')); } // Add checking for all addresses $errors = array(); $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers(false, $errors); if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) { $flag_error_message = false; foreach ($errors as $error) { if ($error == Carrier::SHIPPING_WEIGHT_EXCEPTION && !$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): it is too heavy. Please amend your cart to lower its weight.', !Tools::getValue('ajax'))); $flag_error_message = true; } elseif ($error == Carrier::SHIPPING_PRICE_EXCEPTION && !$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s). Please amend your cart.', !Tools::getValue('ajax'))); $flag_error_message = true; } elseif ($error == Carrier::SHIPPING_SIZE_EXCEPTION && !$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): its size does not fit. Please amend your cart to reduce its size.', !Tools::getValue('ajax'))); $flag_error_message = true; } } if (count($address_without_carriers) > 1 && !$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax'))); } elseif ($this->context->cart->isMultiAddressDelivery() && !$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax'))); } elseif (!$flag_error_message) { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax'))); } } } if ($this->errors) { if (Tools::getValue('ajax')) { $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } $this->step = 1; } if ($this->ajax) { $this->ajaxDie(true); } }
/** * Assign template vars related to page content * @see FrontController::initContent() */ public function initContent() { parent::initContent(); /* id_carrier is not defined in database before choosing a carrier, set it to a default one to match a potential cart _rule */ if (empty($this->context->cart->id_carrier)) { $checked = $this->context->cart->simulateCarrierSelectedOutput(); $checked = (int) Cart::desintifier($checked); $this->context->cart->id_carrier = $checked; $this->context->cart->update(); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); } // SHOPPING CART $this->_assignSummaryInformations(); // WRAPPING AND TOS $this->_assignWrappingAndTOS(); $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT'); if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) { $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true); } else { $countries = Country::getCountries($this->context->language->id, true); } // If a rule offer free-shipping, force hidding shipping prices $free_shipping = false; foreach ($this->context->cart->getCartRules() as $rule) { if ($rule['free_shipping'] && !$rule['carrier_restriction']) { $free_shipping = true; break; } } $this->context->smarty->assign(array('free_shipping' => $free_shipping, 'isGuest' => isset($this->context->cookie->is_guest) ? $this->context->cookie->is_guest : 0, 'countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'errorCarrier' => Tools::displayError('You must choose a carrier.', false), 'errorTOS' => Tools::displayError('You must accept the Terms of Service.', false), 'isPaymentStep' => (bool) (isset($_GET['isPaymentStep']) && $_GET['isPaymentStep']), 'genders' => Gender::getGenders(), 'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'), 'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('displayCustomerAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Hook::exec('displayCustomerAccountFormTop'))); $years = Tools::dateYears(); $months = Tools::dateMonths(); $days = Tools::dateDays(); $this->context->smarty->assign(array('years' => $years, 'months' => $months, 'days' => $days)); /* Load guest informations */ if ($this->isLogged && $this->context->cookie->is_guest) { $this->context->smarty->assign('guestInformations', $this->_getGuestInformations()); } // ADDRESS if ($this->isLogged) { $this->_assignAddress(); } // CARRIER $this->_assignCarrier(); // PAYMENT $this->_assignPayment(); Tools::safePostVars(); $blocknewsletter = Module::getInstanceByName('blocknewsletter'); $this->context->smarty->assign('newsletter', (bool) ($blocknewsletter && $blocknewsletter->active)); $this->_processAddressFormat(); $this->setTemplate(_PS_THEME_DIR_ . 'order-opc.tpl'); }
/** * This process add or update a product in the cart */ protected function processChangeProductInCart() { $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add'; if ($this->qty == 0) { $this->errors[] = Tools::displayError('Null quantity.', !Tools::getValue('ajax')); } elseif (!$this->id_product) { $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax')); } $product = new Product($this->id_product, true, $this->context->language->id); if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) { $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax')); return; } $qty_to_check = $this->qty; $cart_products = $this->context->cart->getProducts(); $operator = Tools::getValue('op', 'up'); if (is_array($cart_products)) { foreach ($cart_products as $cart_product) { if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) { $qty_to_check = $cart_product['cart_quantity']; if ($operator == 'down') { $qty_to_check -= $this->qty; } elseif ($operator == 'up') { $qty_to_check += $this->qty; } elseif ($operator == 'update') { $qty_to_check = $this->qty; if ($this->qty < $cart_product['cart_quantity']) { $this->qty = $cart_product['cart_quantity'] - $this->qty; $operator = 'down'; } else { $this->qty = $this->qty - $cart_product['cart_quantity']; $operator = 'up'; } } break; } } } // Check product quantity availability if ($this->id_product_attribute) { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } elseif ($product->hasAttributes()) { $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock; $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity); // @todo do something better than a redirect admin !! if (!$this->id_product_attribute) { Tools::redirectAdmin($this->context->link->getProductLink($product)); } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } elseif (!$product->checkQty($qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } // If no errors, process product addition if (!$this->errors && ($mode == 'add' || $mode == 'update')) { // Add cart if no cart found if (!$this->context->cart->id) { if (Context::getContext()->cookie->id_guest) { $guest = new Guest(Context::getContext()->cookie->id_guest); $this->context->cart->mobile_theme = $guest->mobile_theme; } $this->context->cart->add(); if ($this->context->cart->id) { $this->context->cookie->id_cart = (int) $this->context->cart->id; } } // Check customizable fields if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) { $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax')); } if (!$this->errors) { $cart_rules = $this->context->cart->getCartRules(); $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, $operator, $this->id_address_delivery); if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity; $this->errors[] = sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity); } elseif (!$update_quantity) { $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax')); } elseif ((int) Tools::getValue('allow_refresh')) { // If the cart rules has changed, we need to refresh the whole cart $cart_rules2 = $this->context->cart->getCartRules(); if (count($cart_rules2) != count($cart_rules)) { $this->ajax_refresh = true; } else { $rule_list = array(); foreach ($cart_rules2 as $rule) { $rule_list[] = $rule['id_cart_rule']; } foreach ($cart_rules as $rule) { if (!in_array($rule['id_cart_rule'], $rule_list)) { $this->ajax_refresh = true; break; } } } } } } $removed = CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); if (count($removed) && (int) Tools::getValue('allow_refresh')) { $this->ajax_refresh = true; } }
$address->id_country = Country::getByIso(Configuration::get('QUI_COUNTRY')); } $address->firstname = Tools::getValue('firstname'); $address->lastname = ' '; $address->phone_mobile = Tools::getValue('phone'); $address->other = 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Время: ' . Tools::getValue('time'); $address->address1 = ' '; $address->city = ' '; $address->alias = 'quickorder_' . substr(md5(time() . _COOKIE_KEY_), 0, 7); $address->id_customer = $customer->id; $address->save(); $cart->id_address_invoice = (int) $address->id; $cart->id_address_delivery = (int) $address->id; $id_address = (int) $address->id; $cart->update(); CartRule::autoRemoveFromCart($context); CartRule::autoAddToCart($context); if (!$context->cart->isMultiAddressDelivery()) { $context->cart->setNoMultishipping(); } } else { $message = new Message(); $message->id_cart = $cart->id; $message->message = 'Имя:' . ' ' . Tools::getValue('firstname') . "\r\n" . 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Телефон:' . ' ' . Tools::getValue('phone') . "\r\n" . 'Время: ' . Tools::getValue('time'); $message->private = true; $message->add(); } if (Configuration::get('QUI_CARRIER')) { $cart->id_carrier = Configuration::get('QUI_CARRIER'); } if (Configuration::get('QUI_PAYMENT')) {
public function validateGlobalCartDiscounts(&$errors, $reportErrors = false) { global $cart, $cookie; if (_PS_VERSION_ < '1.5') { // code taken from CartController preProcess() $discounts = $cart->getDiscounts(); foreach ($discounts as $discount) { $discountObj = new Discount((int) $discount['id_discount'], (int) $cookie->id_lang); if ($error = $cart->checkDiscountValidity($discountObj, $discounts, $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $cart->getProducts())) { $cart->deleteDiscount((int) $discount['id_discount']); $cart->update(); // reportErrors added to accomodate the initial checkDiscountValidity() in the beginning of CartController preProcess() if ($reportErrors) { $errors[] = CartAPI_Handlers_Helpers::removeHtmlTags($error); return false; } } } } else { // code taken from CartController processChangeProductInCart() $more_errors = CartRule::autoRemoveFromCart(); if (count($more_errors) && $reportErrors) { $errors = array_merge($errors, $more_errors); return false; } } return true; }
/** * Remove discounts on cart * * @deprecated 1.5.3.0 */ protected function processRemoveDiscounts() { Tools::displayAsDeprecated(); $this->errors = array_merge($this->errors, CartRule::autoRemoveFromCart()); }
public function init() { if (!$this->isOpcModuleActive()) { return parent::init(); } if (Tools::getIsset('id_carrier') && strpos(Tools::getValue('id_carrier'), ",") > 0) { $_POST['id_carrier'] = Cart::intifier(Tools::getValue('id_carrier')); } $this->opc_templates_path = _PS_MODULE_DIR_ . 'onepagecheckout/views/templates/front'; $this->origInit(); $this->_assignOpcSettings(); if ($this->opc_config != null && $this->opc_config['goods_return_cms'] > 0) { $cms = new CMS((int) $this->opc_config['goods_return_cms'], (int) $this->context->language->id); $link_goods_return = $this->context->link->getCMSLink($cms, $cms->link_rewrite, true); if (!strpos($link_goods_return, '?')) { $link_goods_return .= '?content_only=1'; } else { $link_goods_return .= '&content_only=1'; } $this->context->smarty->assign("link_goods_return", $link_goods_return); } $this->_setInfoBlockContent(); $this->_setExtraDivPaymentBlock(); if ($this->nbProducts) { $this->context->smarty->assign('virtual_cart', false); } $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1); $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1); $this->context->smarty->assign('order_process_type', Configuration::get('PS_ORDER_PROCESS_TYPE')); $this->context->smarty->assign('one_phone_at_least', (int) Configuration::get('PS_ONE_PHONE_AT_LEAST')); $this->inv_first_on = isset($this->opc_config) && isset($this->opc_config["invoice_first"]) && $this->opc_config["invoice_first"] == "1"; $this->default_ps_carriers = isset($this->opc_config) && isset($this->opc_config["default_ps_carriers"]) && $this->opc_config["default_ps_carriers"] == "1"; if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) { $this->isLogged = (bool) ($this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer)); } if ($this->context->cart->nbProducts()) { if (Tools::isSubmit('ajax')) { if (Tools::isSubmit('method')) { switch (Tools::getValue('method')) { case 'updateMessage': if (Tools::isSubmit('message')) { $txtMessage = urldecode(Tools::getValue('message')); $this->_updateMessage($txtMessage); if (count($this->errors)) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } die(true); } break; case 'updateCarrierAndGetPayments': if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message')) { $this->_assignWrappingAndTOS(); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if ($this->_processCarrier()) { $carriers = $this->context->cart->simulateCarriersOutput(); $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail()); Cart::addExtraCarriers($return); die(Tools::jsonEncode($return)); } else { $this->errors[] = Tools::displayError('Error occurred while updating cart.'); } if (count($this->errors)) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } exit; } break; case 'updateTOSStatusAndGetPayments': if (Tools::isSubmit('checked')) { $this->context->cookie->checkedTOS = (int) Tools::getValue('checked'); die(Tools::jsonEncode(array())); } break; case 'updatePaymentsOnly': die(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => self::_getPaymentMethods()))); break; case 'getCarrierList': $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart()); $result = $this->_getCarrierList(); $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()), $this->getFormatedSummaryDetail()); die(Tools::jsonEncode($result)); break; case 'editCustomer': if (!$this->isLogged) { exit; } if (Tools::getValue('years')) { $this->context->customer->birthday = (int) Tools::getValue('years') . '-' . (int) Tools::getValue('months') . '-' . (int) Tools::getValue('days'); } if (trim(Tools::getValue('customer_lastname')) == "") { $_POST['customer_lastname'] = $this->inv_first_on ? Tools::getValue('lastname_invoice') : Tools::getValue('lastname'); } if (trim(Tools::getValue('customer_firstname')) == "") { $_POST['customer_firstname'] = $this->inv_first_on ? Tools::getValue('firstname_invoice') : Tools::getValue('firstname'); } $this->errors = $this->context->customer->validateController(); $this->context->customer->newsletter = (int) Tools::isSubmit('newsletter'); $this->context->customer->optin = (int) Tools::isSubmit('optin'); $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_customer' => (int) $this->context->customer->id, 'token' => Tools::getToken(false)); if (!count($this->errors)) { $return['isSaved'] = (bool) $this->context->customer->update(); } else { $return['isSaved'] = false; } die(Tools::jsonEncode($return)); break; case 'getAddressBlockAndCarriersAndPayments': if ($this->context->customer->isLogged()) { if (!Customer::getAddressesTotalById($this->context->customer->id)) { die(Tools::jsonEncode(array('no_address' => 1))); } if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) { include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php'; $blockUserInfo = new BlockUserInfo(); } $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart()); $customer = $this->context->customer; $customer_info = array("id" => $customer->id, "email" => $customer->email, "id_gender" => $customer->id_gender, "birthday" => $customer->birthday, "newsletter" => $customer->newsletter, "optin" => $customer->optin, "is_guest" => $customer->is_guest); $this->_processAddressFormat(); $this->_assignAddress(); $address_delivery = $this->context->smarty->tpl_vars['delivery']->value; $address_invoice = $this->context->smarty->tpl_vars['invoice']->value; if (Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && !class_exists("VatNumber", false)) { include_once _PS_MODULE_DIR_ . '/vatnumber/vatnumber.php'; } if (isset($address_delivery) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_delivery->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_delivery->id_country) { $allow_eu_vat_delivery = 1; } else { $allow_eu_vat_delivery = 0; } if (isset($address_invoice) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_invoice->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_invoice->id_country) { $allow_eu_vat_invoice = 1; } else { $allow_eu_vat_invoice = 0; } $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) { $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE'); $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100); } else { $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false); $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice(); } $return = array_merge(array('customer_info' => $customer_info, 'allow_eu_vat_delivery' => $allow_eu_vat_delivery, 'allow_eu_vat_invoice' => $allow_eu_vat_invoice, 'customer_addresses' => $this->context->smarty->tpl_vars['addresses']->value, 'block_user_info' => isset($blockUserInfo) ? method_exists($blockUserInfo, 'hookTop') ? $blockUserInfo->hookTop(array()) : $blockUserInfo->hookDisplayTop(array()) : '', 'carrier_data' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail()); die(Tools::jsonEncode($return)); } die(Tools::displayError("Customer is not logged in, while he should be. Check please AuthController and cookies.")); break; case 'makeFreeOrder': if (($id_order = $this->_checkFreeOrder()) && $id_order) { $order = new Order((int) $id_order); $email = $this->context->customer->email; if ($this->context->customer->is_guest) { $this->context->customer->logout(); } // If guest we clear the cookie for security reason die('freeorder:' . $order->reference . ':' . $email); } exit; break; case 'updateAddressesSelected': $id_address_delivery = (int) Tools::getValue('id_address_delivery'); $id_address_invoice = (int) Tools::getValue('id_address_invoice'); $address_delivery = new Address((int) Tools::getValue('id_address_delivery')); $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice')); if (Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && !class_exists("VatNumber", false)) { include_once _PS_MODULE_DIR_ . '/vatnumber/vatnumber.php'; } if (isset($address_delivery) && Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_delivery->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_delivery->id_country) { $allow_eu_vat_delivery = 1; } else { $allow_eu_vat_delivery = 0; } if (isset($address_invoice) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_invoice->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_invoice->id_country) { $allow_eu_vat_invoice = 1; } else { $allow_eu_vat_invoice = 0; } $address_delivery = new Address((int) Tools::getValue('id_address_delivery')); $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart()); $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice')); if ($address_delivery->id_customer && $address_delivery->id_customer != $this->context->customer->id || $address_invoice->id_customer && $address_invoice->id_customer != $this->context->customer->id) { $this->errors = "not_your_address"; } if (!Address::isCountryActiveById((int) Tools::getValue('id_address_delivery'))) { $this->errors[] = Tools::displayError('This address is not in a valid area.'); } elseif (!Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) { $this->errors[] = Tools::displayError('This address is invalid.'); } else { $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery'); $this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice'); if (!$this->context->cart->update()) { $this->errors[] = Tools::displayError('An error occurred while updating your cart.'); } CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); $this->context->cart->setNoMultishipping(); // As the cart is no multishipping, set each delivery address lines with the main delivery address if (!count($this->errors)) { $result = $this->_getCarrierList(); $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) { $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE'); $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100); } else { $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false); $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice(); } $result = array_merge($result, array('allow_eu_vat_delivery' => $allow_eu_vat_delivery, 'allow_eu_vat_invoice' => $allow_eu_vat_invoice, 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList()), $this->getFormatedSummaryDetail()); die(Tools::jsonEncode($result)); } } if (count($this->errors)) { die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors))); } break; case 'multishipping': $this->_assignSummaryInformations(); $this->context->smarty->assign('product_list', $this->context->cart->getProducts()); if ($this->context->customer->id) { $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id)); } else { $this->context->smarty->assign('address_list', array()); } $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl'); $this->display(); die; break; case 'cartReload': $this->_assignSummaryInformations(); if ($this->context->customer->id) { $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id)); } else { $this->context->smarty->assign('address_list', array()); } $this->context->smarty->assign('opc', true); $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl'); $this->display(); die; break; case 'noMultiAddressDelivery': $this->context->cart->setNoMultishipping(); die; break; case 'emailCheck': if (Tools::isSubmit('cust_email')) { $customer_email = Tools::getValue('cust_email'); $is_registered = Validate::isEmail($customer_email) ? Customer::customerExists($customer_email) : 0; $return = array('is_registered' => $is_registered); die(Tools::jsonEncode($return)); } break; case 'zipCheck': if (Tools::isSubmit('id_country')) { $id_country = Tools::getValue('id_country'); if ($id_country > 0) { $errors = array(); $country = new Country($id_country); $zip_code_format = $country->zip_code_format; if ($country->need_zip_code) { if ($postcode = Tools::getValue('postcode') and $zip_code_format) { $zip_regexp = '/^' . $zip_code_format . '$/ui'; $zip_regexp = str_replace(' ', '( |)', $zip_regexp); $zip_regexp = str_replace('-', '(-|)', $zip_regexp); $zip_regexp = str_replace('N', '[0-9]', $zip_regexp); $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp); $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp); if (!preg_match($zip_regexp, $postcode)) { $errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format))); } } elseif ($zip_code_format) { $errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is required.'); } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) { $errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format))); } } } //if($id_country>0) $return = array('is_ok' => empty($errors), 'errors' => $errors); die(Tools::jsonEncode($return)); } break; default: throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"'); } } else { throw new PrestaShopException('Method is not defined'); } } } elseif (Tools::isSubmit('ajax')) { throw new PrestaShopException('Method is not defined'); } }
protected function processChangeProductInCart() { $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add'; if (!$this->id_product) { $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax')); } $product = new Product($this->id_product, true, $this->context->language->id); if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) { $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax')); return; } $qty_factor = 1; $ext_qty_factor = 1; $ext_prop_quantities = null; $id_cart_product = 0; $qty_behavior = 0; $icp = (int) Tools::getValue('icp'); $properties = $product->productProperties(); if ($icp && $this->context->cart->id) { $cart_products = $this->context->cart->getProducts(); if (count($cart_products)) { foreach ($cart_products as $cart_product) { if ($icp == (int) $cart_product['id_cart_product']) { $id_cart_product = $icp; if ($mode == 'add') { if (Tools::getValue('qty') != 'default') { $qty_factor = (int) Tools::getValue('qty'); } $_POST['qty'] = (double) $cart_product['cart_quantity_fractional'] > 0 ? (double) $cart_product['cart_quantity_fractional'] : ($product->qtyStep() > 0 ? $product->qtyStep() : 1); } elseif ($mode == 'update') { $qty_behavior = PP::qtyBehavior($product, $cart_product['cart_quantity']); } break; } } } } else { if ($properties['pp_ext'] == 1 && in_array($properties['pp_ext_policy'], array(0, 2))) { $ext_prop_quantities = array(); $ext_prop_qty_ratio = array(); if ($properties['pp_ext_policy'] == 2) { $prop = $product->productProp(); if ($this->id_product_attribute) { $id_product_attribute = $this->id_product_attribute; } else { if ($product->hasAttributes()) { $id_product_attribute = Product::getDefaultAttribute($product->id); } else { $id_product_attribute = 0; } } } $positions = count($properties['pp_ext_prop']); for ($position = 1; $position <= $positions; $position++) { $pp_ext_prop = $properties['pp_ext_prop'][$position]; if ($properties['pp_ext_policy'] == 2) { $q = PP::productProp($prop, $id_product_attribute, $position, 'quantity'); if ($q === false) { $q = (double) $pp_ext_prop['default_quantity']; } if ($q <= 0) { $q = 1; } } else { $q = PP::resolveInputQty(Tools::getValue('pp_ext_prop_quantity_' . $position, 'default'), $properties['pp_qty_policy'], $pp_ext_prop['qty_step'], $pp_ext_prop['default_quantity'] > 0 ? $pp_ext_prop['default_quantity'] : 1); } $ext_prop_quantities[$position] = $q; $ext_prop_qty_ratio[$position] = $properties['pp_ext_prop'][$position]['qty_ratio']; if ($q <= 0) { $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax')); } $min_qty = (double) $pp_ext_prop['minimum_quantity']; if ($min_qty > 0 && $q < $min_qty) { $this->errors[] = Tools::displayError(sprintf('Please specify at least %s for %s', (string) PP::formatQty($min_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax')); } $max_qty = (double) $pp_ext_prop['maximum_quantity']; if ($max_qty > 0 && $q > $max_qty) { $this->errors[] = Tools::displayError(sprintf('Please specify no more than %s for %s', (string) PP::formatQty($max_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax')); } } if (!$this->errors) { $ext_qty_factor = $properties['pp_ext_method'] == 1 ? 1 : 0; $positions = count($ext_prop_quantities); for ($position = 1; $position <= $positions; $position++) { $value = $ext_prop_quantities[$position]; $qty_ratio = $ext_prop_qty_ratio[$position]; if ($properties['pp_ext_method'] == 1) { $ext_qty_factor *= $qty_ratio > 0 ? $value / $qty_ratio : $value; } elseif ($properties['pp_ext_method'] == 2) { $ext_qty_factor += $qty_ratio > 0 ? $value / $qty_ratio : $value; } } } } } if (!$this->errors) { if ($this->id_product_attribute) { $default_quantity = $product->attributeDefaultQty($this->id_product_attribute); $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity); if ($this->qty == 0) { $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax')); } else { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } } else { if ($product->hasAttributes()) { $min_quantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock; $this->id_product_attribute = Product::getDefaultAttribute($product->id, $min_quantity); if (!$this->id_product_attribute) { Tools::redirectAdmin($this->context->link->getProductLink($product)); } else { $default_quantity = $product->attributeDefaultQty($this->id_product_attribute); $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity); if ($this->qty == 0) { $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax')); } else { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } } } else { $default_quantity = $product->defaultQty(); $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity); if ($this->qty == 0) { $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax')); } else { if (!$product->checkQty($ext_qty_factor * $this->qty)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } } } } if (!$this->errors && ($mode == 'add' || $mode == 'update' && $qty_behavior)) { if ($mode == 'add' && !$this->context->cart->id) { if (Context::getContext()->cookie->id_guest) { $guest = new Guest(Context::getContext()->cookie->id_guest); $this->context->cart->mobile_theme = $guest->mobile_theme; } $this->context->cart->add(); if ($this->context->cart->id) { $this->context->cookie->id_cart = (int) $this->context->cart->id; } } if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) { $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax')); } if (!$this->errors) { $cart_rules = $this->context->cart->getCartRules(); $update_quantity = $this->context->cart->updateQty($id_cart_product ? $mode == 'add' ? $qty_factor : $this->qty : ($ext_prop_quantities !== null ? $ext_qty_factor : $this->qty), $this->id_product, $this->id_product_attribute, $this->customization_id, $mode == 'update' ? 'update' : Tools::getValue('op', 'up'), $this->id_address_delivery, null, true, $id_cart_product, $ext_prop_quantities, $this->qty); if ($update_quantity < 0) { $minimal_quantity = $this->id_product_attribute ? $product->attributeMinQty($this->id_product_attribute) : $product->minQty(); $this->errors[] = Tools::displayError(sprintf('You must add %s minimum quantity', $minimal_quantity), !Tools::getValue('ajax')); } elseif (!$update_quantity) { $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax')); } elseif ((int) Tools::getValue('allow_refresh')) { $cart_rules2 = $this->context->cart->getCartRules(); if (count($cart_rules2) != count($cart_rules)) { $this->ajax_refresh = true; } else { $rule_list = array(); foreach ($cart_rules2 as $rule) { $rule_list[] = $rule['id_cart_rule']; } foreach ($cart_rules as $rule) { if (!in_array($rule['id_cart_rule'], $rule_list)) { $this->ajax_refresh = true; break; } } } } } } $removed = CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); if (count($removed) && (int) Tools::getValue('allow_refresh')) { $this->ajax_refresh = true; } }
public function init() { ParentOrderController::init(); if ($this->nbProducts) { $this->context->smarty->assign('virtual_cart', $this->context->cart->isVirtualCart()); } $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1); $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1); if ($this->context->cart->nbProducts()) { if (Tools::isSubmit('ajax')) { if (Tools::isSubmit('method')) { switch (Tools::getValue('method')) { case 'getCartSummary': if ($this->_legal && ($tpl = $this->_legal->getThemeOverride('order-summary'))) { $summary = $this->context->cart->getSummaryDetails(); $this->context->smarty->assign($summary); $this->context->smarty->assign('HOOK_SHOPPING_CART', Hook::exec('displayShoppingCartFooter', $summary)); die(Tools::jsonEncode(array('summary' => $this->context->smarty->fetch($tpl)))); } break; case 'updateMessage': if (Tools::isSubmit('message')) { $txt_message = urldecode(Tools::getValue('message')); $this->_updateMessage($txt_message); if (count($this->errors)) { $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } $this->ajaxDie(true); } break; case 'updateCarrierAndGetPayments': if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message')) { $this->_assignWrappingAndTOS(); if ($this->_processCarrier()) { $carriers = $this->context->cart->simulateCarriersOutput(); $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail()); Cart::addExtraCarriers($return); $this->ajaxDie(Tools::jsonEncode($return)); } else { $this->errors[] = Tools::displayError('An error occurred while updating the cart.'); } if (count($this->errors)) { $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } exit; } break; case 'updateTOSStatusAndGetPayments': if (Tools::isSubmit('checked')) { $this->context->cookie->checkedTOS = (int) Tools::getValue('checked'); $this->ajaxDie(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()))); } break; case 'getCarrierList': $this->ajaxDie(Tools::jsonEncode($this->_getCarrierList())); break; case 'editCustomer': if (!$this->isLogged || !$this->context->customer->is_guest) { exit; } if (Validate::isEmail($email = Tools::getValue('email')) && !empty($email)) { if (Customer::customerExists($email)) { $this->errors[] = Tools::displayError('An account using this email address has already been registered.', false); } } if (Tools::getValue('years')) { $this->context->customer->birthday = (int) Tools::getValue('years') . '-' . (int) Tools::getValue('months') . '-' . (int) Tools::getValue('days'); } $_POST['lastname'] = $_POST['customer_lastname']; $_POST['firstname'] = $_POST['customer_firstname']; $this->errors = array_merge($this->errors, $this->context->customer->validateController()); $this->context->customer->newsletter = (int) Tools::isSubmit('newsletter'); $this->context->customer->optin = (int) Tools::isSubmit('optin'); $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_customer' => (int) $this->context->customer->id, 'token' => Tools::getToken(false)); if (!count($this->errors)) { $return['isSaved'] = (bool) $this->context->customer->update(); } else { $return['isSaved'] = false; } $this->ajaxDie(Tools::jsonEncode($return)); break; case 'getAddressBlockAndCarriersAndPayments': if ($this->context->customer->isLogged()) { // check if customer have addresses if (!Customer::getAddressesTotalById($this->context->customer->id)) { $this->ajaxDie(Tools::jsonEncode(array('no_address' => 1))); } if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) { include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php'; $block_user_info = new BlockUserInfo(); } $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart()); $this->_processAddressFormat(); $this->_assignAddress(); if (!($formated_address_fields_values_list = $this->context->smarty->getTemplateVars('formatedAddressFieldsValuesList'))) { $formated_address_fields_values_list = array(); } // Wrapping fees $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false); $wrapping_fees_tax_inc = $this->context->cart->getGiftWrappingPrice(); $return = array_merge(array('order_opc_adress' => $this->context->smarty->fetch(_PS_THEME_DIR_ . 'order-address.tpl'), 'block_user_info' => isset($block_user_info) ? $block_user_info->hookDisplayTop(array()) : '', 'formatedAddressFieldsValuesList' => $formated_address_fields_values_list, 'carrier_data' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail()); $this->ajaxDie(Tools::jsonEncode($return)); } die(Tools::displayError()); break; case 'makeFreeOrder': /* Bypass payment step if total is 0 */ if (($id_order = $this->_checkFreeOrder()) && $id_order) { $order = new Order((int) $id_order); $email = $this->context->customer->email; if ($this->context->customer->is_guest) { $this->context->customer->logout(); } // If guest we clear the cookie for security reason $this->ajaxDie('freeorder:' . $order->reference . ':' . $email); } exit; break; case 'updateAddressesSelected': if ($this->context->customer->isLogged(true)) { $address_delivery = new Address((int) Tools::getValue('id_address_delivery')); $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart()); $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice')); if ($address_delivery->id_customer != $this->context->customer->id || $address_invoice->id_customer != $this->context->customer->id) { $this->errors[] = Tools::displayError('This address is not yours.'); } elseif (!Address::isCountryActiveById((int) Tools::getValue('id_address_delivery'))) { $this->errors[] = Tools::displayError('This address is not in a valid area.'); } elseif (!Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) { $this->errors[] = Tools::displayError('This address is invalid.'); } else { $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery'); $this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice'); if (!$this->context->cart->update()) { $this->errors[] = Tools::displayError('An error occurred while updating your cart.'); } $infos = Address::getCountryAndState((int) $this->context->cart->id_address_delivery); if (isset($infos['id_country']) && $infos['id_country']) { $country = new Country((int) $infos['id_country']); $this->context->country = $country; } // Address has changed, so we check if the cart rules still apply $cart_rules = $this->context->cart->getCartRules(); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if ((int) Tools::getValue('allow_refresh')) { // If the cart rules has changed, we need to refresh the whole cart $cart_rules2 = $this->context->cart->getCartRules(); if (count($cart_rules2) != count($cart_rules)) { $this->ajax_refresh = true; } else { $rule_list = array(); foreach ($cart_rules2 as $rule) { $rule_list[] = $rule['id_cart_rule']; } foreach ($cart_rules as $rule) { if (!in_array($rule['id_cart_rule'], $rule_list)) { $this->ajax_refresh = true; break; } } } } if (!$this->context->cart->isMultiAddressDelivery()) { $this->context->cart->setNoMultishipping(); } // As the cart is no multishipping, set each delivery address lines with the main delivery address if (!count($this->errors)) { $result = $this->_getCarrierList(); // Wrapping fees $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false); $wrapping_fees_tax_inc = $this->context->cart->getGiftWrappingPrice(); $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList(), 'refresh' => (bool) $this->ajax_refresh), $this->getFormatedSummaryDetail()); $this->ajaxDie(Tools::jsonEncode($result)); } } if (count($this->errors)) { $this->ajaxDie(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors))); } } die(Tools::displayError()); break; case 'multishipping': $this->_assignSummaryInformations(); $this->context->smarty->assign('product_list', $this->context->cart->getProducts()); if ($this->context->customer->id) { $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id)); } else { $this->context->smarty->assign('address_list', array()); } $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl'); $this->display(); $this->ajaxDie(); break; case 'cartReload': $this->_assignSummaryInformations(); if ($this->context->customer->id) { $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id)); } else { $this->context->smarty->assign('address_list', array()); } $this->context->smarty->assign('opc', true); $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl'); $this->display(); $this->ajaxDie(); break; case 'noMultiAddressDelivery': $this->context->cart->setNoMultishipping(); $this->ajaxDie(); break; default: throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"'); } } else { throw new PrestaShopException('Method is not defined'); } } } elseif (Tools::isSubmit('ajax')) { $this->errors[] = Tools::displayError('There is no product in your cart.'); $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } }
/** * Manage address */ public function processAddress() { $same = Tools::isSubmit('same'); if (!Tools::getValue('id_address_invoice', false) && !$same) { $same = true; } if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery')) || !$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice'))) { $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax')); } else { $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery'); $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice'); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (!$this->context->cart->update()) { $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax')); } if (!$this->context->cart->isMultiAddressDelivery()) { $this->context->cart->setNoMultishipping(); } // If there is only one delivery address, set each delivery address lines with the main delivery address if (Tools::isSubmit('message')) { $this->_updateMessage(Tools::getValue('message')); } // Add checking for all addresses $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers(); if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) { if (count($address_without_carriers) > 1) { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax'))); } elseif ($this->context->cart->isMultiAddressDelivery()) { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax'))); } else { $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax'))); } } } if ($this->errors) { if (Tools::getValue('ajax')) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } $this->step = 1; } if ($this->ajax) { die(true); } }
public function deleteProduct($id_product, $id_product_attribute = null, $id_customization = null, $id_address_delivery = 0, $id_cart_product = 0) { if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } /* if ((int)$id_customization) { $product_total_quantity = (int)Db::getInstance()->getValue( 'SELECT `quantity` FROM `'._DB_PREFIX_.'cart_product` WHERE `id_product` = '.(int)$id_product.' AND `id_cart` = '.(int)$this->id.' AND `id_product_attribute` = '.(int)$id_product_attribute); $customization_quantity = (int)Db::getInstance()->getValue(' SELECT `quantity` FROM `'._DB_PREFIX_.'customization` WHERE `id_cart` = '.(int)$this->id.' AND `id_product` = '.(int)$id_product.' AND `id_product_attribute` = '.(int)$id_product_attribute.' '.((int)$id_address_delivery ? 'AND `id_address_delivery` = '.(int)$id_address_delivery : '')); if (!$this->_deleteCustomization((int)$id_customization, (int)$id_product, (int)$id_product_attribute, (int)$id_address_delivery)) return false; $this->_products = $this->getProducts(true); return ($customization_quantity == $product_total_quantity && $this->deleteProduct((int)$id_product, (int)$id_product_attribute, null, (int)$id_address_delivery)); } $result = Db::getInstance()->getRow(' SELECT SUM(`quantity`) AS \'quantity\' FROM `'._DB_PREFIX_.'customization` WHERE `id_cart` = '.(int)$this->id.' AND `id_product` = '.(int)$id_product.' AND `id_product_attribute` = '.(int)$id_product_attribute); if ($result === false) return false; if (Db::getInstance()->NumRows() && (int)$result['quantity']) return Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'cart_product` SET `quantity` = '.(int)$result['quantity'].' WHERE `id_cart` = '.(int)$this->id.' AND `id_product` = '.(int)$id_product. ($id_product_attribute != null ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '') ); */ if (($id_cart_product = PP::resolveIcp($id_cart_product)) <= 0) { return false; } $sql_icp = PP::sqlIcp($id_cart_product); $id_customization = (int) Db::getInstance()->getValue(' SELECT `id_customization` FROM `' . _DB_PREFIX_ . 'customization` WHERE `id_cart_product` = ' . (int) $id_cart_product); if ((int) $id_customization && !$this->_deleteCustomization((int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery)) { return false; } $result = Db::getInstance()->execute(' DELETE FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_product` = ' . (int) $id_product . ' ' . (!is_null($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . ' ' . ((int) $id_address_delivery ? 'AND `id_address_delivery` = ' . (int) $id_address_delivery : '') . $sql_icp); if (PP::multidimensionalEnabled()) { Db::getInstance()->execute(' DELETE FROM `' . _DB_PREFIX_ . 'pp_product_ext` WHERE `id_cart_product` = ' . (int) $id_cart_product); } if ($result) { $return = $this->update(); $this->_products = $this->getProducts(true); CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); return $return; } return false; }