Example #1
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     if ($oPrediggoResult = $this->launchSearch((int) $this->oPrediggoConfig->search_nb_items)) {
         if (isset($this->context->cookie->id_compare)) {
             $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) $this->context->cookie->id_compare));
         }
         $this->context->smarty->assign(array('page_name' => 'prediggo_search_page', 'sPrediggoQuery' => $this->sQuery, 'aPrediggoProducts' => $this->oPrediggoCall->getProducts($oPrediggoResult, (int) $this->context->cookie->id_lang), 'aDidYouMeanWords' => $oPrediggoResult->getDidYouMeanWords(), 'aSortingOptions' => $oPrediggoResult->getSortingOptions(), 'aCancellableFiltersGroups' => $oPrediggoResult->getCancellableFiltersGroups(), 'aDrillDownGroups' => $oPrediggoResult->getDrillDownGroups(), 'aChangePageLinks' => $oPrediggoResult->getChangePageLinks(), 'oSearchStatistics' => $oPrediggoResult->getSearchStatistics(), 'bSearchandizingActive' => $this->oPrediggoConfig->searchandizing_active, 'aCustomRedirections' => $oPrediggoResult->getCustomRedirections(), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'sImageType' => Tools::version_compare(_PS_VERSION_, '1.5.1', '>=') ? 'home_default' : 'home', 'bRewriteEnabled' => (int) Configuration::get('PS_REWRITING_SETTINGS')));
     }
     parent::initContent();
     $this->setTemplate('search.tpl');
 }
Example #2
0
    public function initContent()
    {
        parent::initContent();
        $customer = $this->context->customer;
        /*
         * Get delivery address and data.
         */
        if ((int) $this->context->cart->id_address_delivery) {
            $shipto_delivery_address = new Address((int) $this->context->cart->id_address_delivery);
            $country_name = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'country_lang
		WHERE id_country = ' . (int) Configuration::get('SHIPTOMYID_DEFAULT_ADDR_COUNTRY') . ' ');
            $state_name = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'state
		WHERE id_state = ' . (int) Configuration::get('SHIPTOMYID_DEFAULT_ADDR_STATE') . ' ');
            $default_delivery_address = array('address1' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_ADDRESS'), 'address2' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_ADDRESS2'), 'city' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_CITY'), 'zip' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_POSTCODE'), 'phone' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_PHONE'), 'alise' => Configuration::get('SHIPTOMYID_DEFAULT_ADDR_ALIAS'), 'country' => $country_name, 'state' => $state_name);
            $this->context->smarty->assign(array('shipto_delivery_address' => $shipto_delivery_address, 'shipto_default_delivery_address' => $default_delivery_address));
        }
        /*
         * Get addresses.
         */
        $customer_addresses = $customer->getAddresses($this->context->language->id, false);
        // On supprime de la liste les addresse shipto
        foreach ($customer_addresses as $key => $address) {
            if (strpos(Tools::strtolower($address['alias']), 'ship2myid') !== false) {
                $customer_addresses[$key]['shipto_addr'] = 1;
            }
        }
        // Getting a list of formated address fields with associated values
        $formated_address_fields_values_list = array();
        foreach ($customer_addresses as $i => $address) {
            if (!Address::isCountryActiveById((int) $address['id_address'])) {
                unset($customer_addresses[$i]);
            }
            $tmp_address = new Address($address['id_address']);
            $formated_address_fields_values_list[$address['id_address']]['ordered_fields'] = AddressFormat::getOrderedAddressFields($address['id_country']);
            $formated_address_fields_values_list[$address['id_address']]['formated_fields_values'] = AddressFormat::getFormattedAddressFieldsValues($tmp_address, $formated_address_fields_values_list[$address['id_address']]['ordered_fields']);
            unset($tmp_address);
        }
        if (key($customer_addresses) != 0) {
            $customer_addresses = array_values($customer_addresses);
        }
        $this->context->smarty->assign(array('addresses' => $customer_addresses, 'formatedAddressFieldsValuesList' => $formated_address_fields_values_list));
        if (class_exists('Tools') && method_exists('Tools', 'version_compare') && Tools::version_compare(_PS_VERSION_, '1.6', '>=') === true) {
            $this->setTemplate('front-16.tpl');
        } else {
            $this->setTemplate('front.tpl');
        }
    }
Example #3
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $this->context->smarty->assign('back_compat', Tools::version_compare(_PS_VERSION_, '1.6'));
     if ($this->context->cart->nbProducts() <= 0) {
         $this->context->smarty->assign('payzen_empty_cart', true);
     } else {
         $this->context->smarty->assign('payzen_empty_cart', false);
         $data = array();
         $logo = '';
         $type = Tools::getValue('payzen_payment_type');
         /* the selected payzen payment type */
         switch ($type) {
             case 'standard':
                 if (Configuration::get('PAYZEN_STD_CARD_DATA_MODE') == 2 || Configuration::get('PAYZEN_STD_CARD_DATA_MODE') == 3) {
                     $data['card_type'] = Tools::getValue('payzen_card_type');
                     if (Configuration::get('PAYZEN_STD_CARD_DATA_MODE') == 3) {
                         $data['card_number'] = Tools::getValue('payzen_card_number');
                         $data['cvv'] = Tools::getValue('payzen_cvv');
                         $data['expiry_month'] = Tools::getValue('payzen_expiry_month');
                         $data['expiry_year'] = Tools::getValue('payzen_expiry_year');
                     }
                 }
                 $logo = 'BannerLogo1.png';
                 break;
             case 'multi':
                 $data['opt'] = Tools::getValue('payzen_opt');
                 $logo = 'BannerLogo2.png';
                 break;
             case 'oney':
                 $logo = 'BannerLogo3.png';
                 break;
             default:
                 // TODO define the default behaviour
                 break;
         }
         $module = new Payzen();
         $params = $module->getFormFields($type, $data);
         $module->logger->logInfo('Data to be sent to payment platform : ' . print_r($params, true));
         $this->context->smarty->assign('payzen_params', $params);
         $this->context->smarty->assign('payzen_url', Configuration::get('PAYZEN_PLATFORM_URL'));
         $this->context->smarty->assign('payzen_logo', $logo);
     }
     $this->setTemplate('redirect.tpl');
 }
Example #4
0
 public function executeSqlFile($sVersion, $sFileName)
 {
     if (Tools::version_compare($sVersion, $this->version, '=')) {
         $sFilePath = $this->module_dir . 'sql' . DIRECTORY_SEPARATOR;
         if (!file_exists($sFilePath . $sFileName)) {
             return false;
         } else {
             if (!($sql = file_get_contents($sFilePath . $sFileName))) {
                 return false;
             }
         }
         $sql = str_replace(array('PREFIX_', 'ENGINE_TYPE'), array(_DB_PREFIX_, _MYSQL_ENGINE_), $sql);
         $sql = preg_split("/;\\s*[\r\n]+/", trim($sql));
         foreach ($sql as $query) {
             if (!Db::getInstance()->execute(trim($query))) {
                 return false;
             }
         }
         return true;
     }
     return false;
 }
Example #5
0
 function psmIntegrateCopy($source, $target, array &$errors, $start_signature, $end_signature)
 {
     if (!($copy_file = !file_exists($target))) {
         $source_ver = psmFindSignature(Tools::file_get_contents($source), $start_signature, $end_signature);
         $target_ver = psmFindSignature(Tools::file_get_contents($target), $start_signature, $end_signature);
         $copy_file = Tools::version_compare($source_ver, $target_ver, '>');
     }
     if ($copy_file) {
         if (!file_exists(dirname($target))) {
             mkdir(dirname($target), 0777, true);
         }
         Tools::copy($source, $target);
         if (file_exists($target)) {
             chmod($target, 0664);
             Tools::deleteFile(_PS_ROOT_DIR_ . '/' . PrestaShopAutoload::INDEX_FILE);
         } else {
             $errors[] = 'Cannot create file "' . $target . '". Please check write permissions.';
             return false;
         }
     }
     return true;
 }
 function psmHelperIntegrateFile($target, $modules)
 {
     $version = '';
     $origin = '';
     $files = array();
     foreach ($modules as $module) {
         $file = _PS_MODULE_DIR_ . $module . '/' . $target;
         if (file_exists($file)) {
             $content = Tools::file_get_contents($file);
             $ver = ($start = strpos($content, 'PSM_VERSION[')) !== false && ($end = strpos($content, ']', $start)) !== false ? Tools::substr($content, $start + 12, $end - $start - 12) : false;
             if ($ver && Tools::version_compare($ver, $version, '>')) {
                 $version = $ver;
                 $origin = $file;
             }
             $files[$file] = $ver;
         }
     }
     foreach ($files as $file => $ver) {
         if (Tools::version_compare($version, $ver, '>') && $origin != $file) {
             Tools::copy($origin, $file);
         }
     }
 }
Example #7
0
 /**
  * Load the available list of upgrade of a specified module
  * with an associated version
  *
  * @static
  * @param $module_name
  * @param $module_version
  * @param $registered_version
  * @return bool to know directly if any files have been found
  */
 protected static function loadUpgradeVersionList($module_name, $module_version, $registered_version)
 {
     $list = array();
     $upgrade_path = _PS_MODULE_DIR_ . $module_name . '/upgrade/';
     // Check if folder exist and it could be read
     if (file_exists($upgrade_path) && ($files = scandir($upgrade_path))) {
         // Read each file name
         foreach ($files as $file) {
             if (!in_array($file, array('.', '..', '.svn', 'index.php'))) {
                 $tab = explode('-', $file);
                 $file_version = basename($tab[1], '.php');
                 // Compare version, if minor than actual, we need to upgrade the module
                 if (count($tab) == 2 && (Tools::version_compare($file_version, $module_version, '<=') && Tools::version_compare($file_version, $registered_version, '>'))) {
                     $list[] = array('file' => $upgrade_path . $file, 'version' => $file_version, 'upgrade_function' => 'upgrade_module_' . str_replace('.', '_', $file_version));
                 }
             }
         }
     }
     // No files upgrade, then upgrade succeed
     if (count($list) == 0) {
         self::$modules_cache[$module_name]['upgrade']['success'] = true;
         Module::upgradeModuleVersion($module_name, $module_version);
     }
     usort($list, 'ps_module_version_sort');
     // Set the list to module cache
     self::$modules_cache[$module_name]['upgrade']['upgrade_file_left'] = $list;
     self::$modules_cache[$module_name]['upgrade']['available_upgrade'] = count($list);
     return (bool) count($list);
 }
 /**
  * Validate an order in database
  * Function called from a payment module
  *
  * @param integer $id_cart Value
  * @param integer $id_order_state Value
  * @param float $amount_paid Amount really paid by customer (in the default currency)
  * @param string $payment_method Payment method (eg. 'Credit card')
  * @param string $message Message to attach to order
  */
 public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
 {
     $this->context->cart = new Cart($id_cart);
     $this->context->customer = new Customer($this->context->cart->id_customer);
     $this->context->language = new Language($this->context->cart->id_lang);
     $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
     $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
     $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
         $context_country = $this->context->country;
     }
     $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
     if (!Validate::isLoadedObject($order_status)) {
         throw new PrestaShopException('Can\'t load Order state status');
     }
     if (!$this->active) {
         // TODO: remove the use of die()
         die(Tools::displayError());
     }
     // Does order already exists ?
     if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
         if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
             // TODO: remove the use of die();
             die(Tools::displayError());
         }
         // For each package, generate an order
         $delivery_option_list = $this->context->cart->getDeliveryOptionList();
         $package_list = $this->context->cart->getPackageList();
         $cart_delivery_option = $this->context->cart->getDeliveryOption();
         // If some delivery options are not defined, or not valid, use the first valid option
         foreach ($delivery_option_list as $id_address => $package) {
             if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
                 foreach ($package as $key => $val) {
                     $cart_delivery_option[$id_address] = $key;
                     break;
                 }
             }
         }
         $order_list = array();
         $order_detail_list = array();
         $order_creation_failed = false;
         $this->currentOrderReference = $reference = Order::generateReference();
         $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
         if ($this->context->cart->orderExists()) {
             $error = Tools::displayError('An order has already been placed using this cart.');
             Logger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id));
             // TODO: remove die();
             die($error);
         }
         foreach ($cart_delivery_option as $id_address => $key_carriers) {
             foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
                 foreach ($data['package_list'] as $id_package) {
                     $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
                 }
             }
         }
         // Make sure CarRule caches are empty
         CartRule::cleanCache();
         foreach ($package_list as $id_address => $packageByAddress) {
             foreach ($packageByAddress as $id_package => $package) {
                 $order = new Order();
                 $order->product_list = $package['product_list'];
                 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                     $address = new Address($id_address);
                     $this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
                 }
                 $carrier = null;
                 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
                     $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
                     $order->id_carrier = (int) $carrier->id;
                     $id_carrier = (int) $carrier->id;
                 } else {
                     $order->id_carrier = 0;
                     $id_carrier = 0;
                 }
                 $order->id_customer = (int) $this->context->cart->id_customer;
                 $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
                 $order->id_address_delivery = (int) $id_address;
                 $order->id_currency = $this->context->currency->id;
                 $order->id_lang = (int) $this->context->cart->id_lang;
                 $order->id_cart = (int) $this->context->cart->id;
                 $order->reference = $reference;
                 $order->id_shop = (int) $this->context->shop->id;
                 $order->id_shop_group = (int) $this->context->shop->id_shop_group;
                 $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key);
                 $order->payment = $payment_method;
                 if (isset($this->name)) {
                     $order->module = $this->name;
                 }
                 $order->recyclable = $this->context->cart->recyclable;
                 $order->gift = (int) $this->context->cart->gift;
                 $order->gift_message = $this->context->cart->gift_message;
                 $order->conversion_rate = $this->context->currency->conversion_rate;
                 $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid;
                 $order->total_paid_real = 0;
                 $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts = $order->total_discounts_tax_incl;
                 /*//////////////////////////////////////////////////////////
                   ////////////////// CÁLCULO DEL RECARGO /////////////////////
                   //////////////////////////////////////////////////////////*/
                 $fee = $this->getPrice($this->context->cart);
                 /*//////////////////////////////////////////////////////////
                   ///////////////// FIN CÁLCULO DEL RECARGO //////////////////
                   //////////////////////////////////////////////////////////*/
                 $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list) + $fee;
                 $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list) + $fee;
                 $order->total_shipping = $order->total_shipping_tax_incl;
                 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
                     $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
                 }
                 $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping = $order->total_wrapping_tax_incl;
                 /*/////////////////////////////////////////////////////////*/
                 $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier) + $fee, 2);
                 $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier) + $fee, 2);
                 $order->total_paid = $order->total_paid_tax_incl;
                 $order->invoice_date = '0000-00-00 00:00:00';
                 $order->delivery_date = '0000-00-00 00:00:00';
                 // Creating order
                 $result = $order->add();
                 if (!$result) {
                     throw new PrestaShopException('Can\'t save Order');
                 }
                 // Amount paid by customer is not the right one -> Status = payment error
                 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
                 // if ($order->total_paid != $order->total_paid_real)
                 // We use number_format in order to compare two string
                 /////////////////////////////////////////////////// REVISADO ///////////////////////////////////////////////////
                 if ($order_status->logable && number_format($cart_total_paid + $fee, 2) != number_format($amount_paid + $fee, 2) && ($order_status->logable && number_format($cart_total_paid + $fee, 2) != number_format($amount_paid, 2))) {
                     $id_order_state = Configuration::get('PS_OS_ERROR');
                 }
                 /////////////////////////////////////////////////// REVISADO ///////////////////////////////////////////////////
                 $order_list[] = $order;
                 // Insert new Order detail list using cart for the current order
                 $order_detail = new OrderDetail(null, null, $this->context);
                 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
                 $order_detail_list[] = $order_detail;
                 // Adding an entry in order_carrier table
                 if (!is_null($carrier)) {
                     $order_carrier = new OrderCarrier();
                     $order_carrier->id_order = (int) $order->id;
                     $order_carrier->id_carrier = (int) $id_carrier;
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl;
                     $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl;
                     $order_carrier->add();
                 }
             }
         }
         // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
             $this->context->country = $context_country;
         }
         // Register Payment only if the order status validate the order
         if ($order_status->logable) {
             // $order is the last order loop in the foreach
             // The method addOrderPayment of the class Order make a create a paymentOrder
             //     linked to the order reference and not to the order id
             if (!$order->addOrderPayment($amount_paid)) {
                 throw new PrestaShopException('Can\'t save Order Payment');
             }
         }
         // Next !
         $only_one_gift = false;
         $cart_rule_used = array();
         $products = $this->context->cart->getProducts();
         $cart_rules = $this->context->cart->getCartRules();
         // Make sure CarRule caches are empty
         CartRule::cleanCache();
         foreach ($order_detail_list as $key => $order_detail) {
             $order = $order_list[$key];
             if (!$order_creation_failed & isset($order->id)) {
                 if (!$secure_key) {
                     $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
                 }
                 // Optional message to attach to this order
                 if (!empty($message)) {
                     $msg = new Message();
                     $message = strip_tags($message, '<br>');
                     if (Validate::isCleanHtml($message)) {
                         $msg->message = $message;
                         $msg->id_order = intval($order->id);
                         $msg->private = 1;
                         $msg->add();
                     }
                 }
                 // Insert new Order detail list using cart for the current order
                 //$orderDetail = new OrderDetail(null, null, $this->context);
                 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
                 // Construct order detail table for the email
                 $products_list = '';
                 $virtual_product = true;
                 foreach ($products as $key => $product) {
                     $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $customization_quantity = 0;
                     if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                         $customization_text = '';
                         foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                             if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                 foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                     $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
                                 }
                             }
                             if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                 $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
                             }
                             $customization_text .= '---<br />';
                         }
                         $customization_text = rtrim($customization_text, '---<br />');
                         $customization_quantity = (int) $product['customizationQuantityTotal'];
                         $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
                             <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
                             <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . Tools::displayError('Customized') . (!empty($customization_text) ? ' - ' . $customization_text : '') . '</strong></td>
                             <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td>
                             <td style="padding: 0.6em 0.4em; text-align: center;">' . $customization_quantity . '</td>
                             <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customization_quantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td>
                         </tr>';
                     }
                     if (!$customization_quantity || (int) $product['cart_quantity'] > $customization_quantity) {
                         $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
                             <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
                             <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td>
                             <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td>
                             <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customization_quantity) . '</td>
                             <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customization_quantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td></tr>';
                     }
                     // Check if is not a virtual product for the displaying of shipping
                     if (!$product['is_virtual']) {
                         // TODO: do not makes any sense for me to use a bitwise operator with a bolean value
                         $virtual_product = false;
                     }
                 }
                 // end foreach ($products)
                 $cart_rules_list = '';
                 foreach ($cart_rules as $cart_rule) {
                     $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
                     $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL, $package));
                     // If the reduction is not applicable to this order, then continue with the next one
                     if (!$values['tax_excl']) {
                         continue;
                     }
                     $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values);
                     /* IF
                      ** - This is not multi-shipping
                      ** - The value of the voucher is greater than the total of the order
                      ** - Partial use is allowed
                      ** - This is an "amount" reduction, not a reduction in % or a gift
                      ** THEN
                      ** The voucher is cloned with a new value corresponding to the remainder
                      */
                     if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
                         // Create a new voucher from the original
                         $voucher = new CartRule($cart_rule['obj']->id);
                         // We need to instantiate the CartRule without lang parameter to allow saving it
                         unset($voucher->id);
                         // Set a new voucher code
                         $voucher->code = empty($voucher->code) ? substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
                         if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
                             $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (intval($matches[1]) + 1), $voucher->code);
                         }
                         // Set the new voucher value
                         if ($voucher->reduction_tax) {
                             $voucher->reduction_amount = $values['tax_incl'] - $order->total_products_wt;
                         } else {
                             $voucher->reduction_amount = $values['tax_excl'] - $order->total_products;
                         }
                         $voucher->id_customer = $order->id_customer;
                         $voucher->quantity = 1;
                         if ($voucher->add()) {
                             // If the voucher has conditions, they are now copied to the new voucher
                             CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
                             $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference());
                             Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                         }
                     }
                     if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
                         $cart_rule_used[] = $cart_rule['obj']->id;
                         // Create a new instance of Cart Rule without id_lang, in order to update its quantity
                         $cart_rule_to_update = new CartRule($cart_rule['obj']->id);
                         $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
                         $cart_rule_to_update->update();
                     }
                     $voucher_error = Tools::displayError('Voucher name:') . ' ' . $cart_rule['obj']->name;
                     $tax_prefix = $values['tax_incl'] != 0.0 ? '-' : '';
                     $price_with_tax = Tools::displayPrice($values['tax_incl'], $this->context->currency, false);
                     $cart_rules_list .= "<tr style=\"background-color:#EBECEE;\"><td colspan=\"4\" style=\"padding:0.6em 0.4em;text-align:right\">{$voucher_error}</td><td style=\"padding:0.6em 0.4em;text-align:right\">{$tax_prefix}{$price_with_tax}</td></tr>";
                 }
                 // Specify order id for message
                 $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
                 if ($old_message) {
                     $message = new Message((int) $old_message['id_message']);
                     $message->id_order = (int) $order->id;
                     $message->update();
                     // Add this message in the customer thread
                     $customer_thread = new CustomerThread();
                     $customer_thread->id_contact = 0;
                     $customer_thread->id_customer = (int) $order->id_customer;
                     $customer_thread->id_shop = (int) $this->context->shop->id;
                     $customer_thread->id_order = (int) $order->id;
                     $customer_thread->id_lang = (int) $this->context->language->id;
                     $customer_thread->email = $this->context->customer->email;
                     $customer_thread->status = 'open';
                     $customer_thread->token = Tools::passwdGen(12);
                     $customer_thread->add();
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = 0;
                     $customer_message->message = htmlentities($message->message, ENT_COMPAT, 'UTF-8');
                     $customer_message->private = 0;
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving message');
                     }
                 }
                 // Hook validate order
                 Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                 foreach ($this->context->cart->getProducts() as $product) {
                     if ($order_status->logable) {
                         ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                     }
                 }
                 if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                     $history = new OrderHistory();
                     $history->id_order = (int) $order->id;
                     $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id);
                     $history->addWithemail();
                 }
                 // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                 // So you migth have two order states
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 if (Tools::version_compare(_PS_VERSION_, '1.5.2')) {
                     $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id, true);
                 } else {
                     $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                 }
                 $new_history->addWithemail(true, $extra_vars);
                 unset($order_detail);
                 // Order is reloaded because the status just changed
                 $order = new Order($order->id);
                 // Send an e-mail to customer (one order = one email)
                 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                     $invoice = new Address($order->id_address_invoice);
                     $delivery = new Address($order->id_address_delivery);
                     $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                     $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                     $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $virtual_product ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $this->formatProductAndVoucherForEmail($products_list), '{discounts}' => $this->formatProductAndVoucherForEmail($cart_rules_list), '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_paid_tax_incl - $order->total_paid_tax_excl, $this->context->currency, false));
                     if (is_array($extra_vars)) {
                         $data = array_merge($data, $extra_vars);
                     }
                     // Join PDF invoice
                     if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                         $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                         $file_attachement['content'] = $pdf->render(false);
                         $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf';
                         $file_attachement['mime'] = 'application/pdf';
                     } else {
                         $file_attachement = null;
                     }
                     if (Validate::isEmail($this->context->customer->email)) {
                         Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                     }
                 }
                 // updates stock in shops
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                     $product_list = $order->getProducts();
                     foreach ($product_list as $product) {
                         // if the available quantities depends on the physical stock
                         if (StockAvailable::dependsOnStock($product['product_id'])) {
                             // synchronizes
                             StockAvailable::synchronize($product['product_id'], $order->id_shop);
                         }
                     }
                 }
             } else {
                 $error = Tools::displayError('Order creation failed');
                 Logger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart));
                 // TODO: remove use of die()
                 die($error);
             }
         }
         // End foreach $order_detail_list
         // Use the last order as currentOrder
         $this->currentOrder = (int) $order->id;
         return true;
     } else {
         $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
         Logger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id));
         // TODO:: remove the use of die();
         die($error);
     }
 }
Example #9
0
 private function _processPaymentReturn()
 {
     /** @var PayzenResponse $payzenResponse */
     $payzenResponse = new PayzenResponse($_REQUEST, Configuration::get('PAYZEN_MODE'), Configuration::get('PAYZEN_KEY_TEST'), Configuration::get('PAYZEN_KEY_PROD'));
     $cartId = $this->currentCart->id;
     // Check the authenticity of the request
     if (!$payzenResponse->isAuthentified()) {
         $this->module->logger->logError("Cart #{$cartId} : authentication error ! Redirect to home page.");
         Tools::redirectLink('index.php');
     }
     // Search order in db
     $orderId = Order::getOrderByCartId($cartId);
     if ($orderId == false) {
         // order has not been processed yet
         if ($payzenResponse->isAcceptedPayment()) {
             $this->module->logger->logWarning("Payment for cart #{$cartId} has been processed by client return ! This means the check URL did not work.");
             $newState = $this->module->isOneyPendingPayment($payzenResponse) ? Configuration::get('PAYZEN_OS_ONEY_PENDING') : Configuration::get('PS_OS_PAYMENT');
             $this->module->logger->logInfo("Payment accepted for cart #{$cartId}. New order status is {$newState}.");
             $order = $this->module->saveOrder($this->currentCart, $newState, $payzenResponse);
             // redirect to success page
             $this->_redirectSuccess($order, $this->module->id, $payzenResponse, true);
         } else {
             // payment KO
             if (Configuration::get('PAYZEN_FAILURE_MANAGEMENT') == Payzen::ON_FAILURE_SAVE || $this->module->isOney($payzenResponse)) {
                 // save on failure option is selected or oney payment : save order and go to history page
                 $newState = $payzenResponse->isCancelledPayment() ? Configuration::get('PS_OS_CANCELED') : Configuration::get('PS_OS_ERROR');
                 $this->module->logger->logWarning("Payment for order #{$cartId} has been processed by client return ! This means the check URL did not work.");
                 $msg = $this->module->isOney($payzenResponse) ? 'FacilyPay Oney payment' : 'Save on failure option is selected';
                 $this->module->logger->logInfo("{$msg} : save failed order for cart #{$cartId}. New order status is {$newState}.");
                 $this->module->saveOrder($this->currentCart, $newState, $payzenResponse);
                 $this->module->logger->logInfo("Redirect to history page, cart ID : #{$cartId}.");
                 Tools::redirect('index.php?controller=history');
             } else {
                 // option 2 choosen : get back to checkout process and show message
                 $this->module->logger->logInfo("Payment failed, redirect to order checkout page, cart ID : #{$cartId}.");
                 $controller = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc' : 'order' . (Tools::version_compare(_PS_VERSION_, '1.5.1', '>=') ? '&step=3' : '');
                 Tools::redirect('index.php?controller=' . $controller . '&payzen_pay_error=yes');
             }
         }
     } else {
         // order already registered
         $this->module->logger->logInfo("Order already registered for cart #{$cartId}.");
         $order = new Order((int) $orderId);
         $oldState = $order->getCurrentState();
         switch ($oldState) {
             case Configuration::get('PS_OS_ERROR'):
             case Configuration::get('PS_OS_CANCELED'):
                 $this->module->logger->logInfo("Save on failure option is selected or FacilyPay Oney payment. Order for cart #{$cartId} is in a failed status.");
                 if ($payzenResponse->isAcceptedPayment()) {
                     // order saved with failed status while payment is successful
                     $this->module->logger->logError("Payment success received from platform while order is in a failed status for cart #{$cartId}.");
                 } else {
                     // just display a failure confirmation message
                     $this->module->logger->logInfo("Payment failure confirmed for cart #{$cartId}.");
                 }
                 $this->module->logger->logInfo("Redirect to history page. Cart ID : #{$cartId}.");
                 Tools::redirect('index.php?controller=history');
                 break;
             case Configuration::get('PAYZEN_OS_ONEY_PENDING'):
             case $oldState == Configuration::get('PS_OS_OUTOFSTOCK') && $this->module->isOney($payzenResponse):
                 $this->module->logger->logInfo("Order for cart #{$cartId} is saved but waiting FacilyPay Oney confirmation. Update order status according to payment result.");
                 if ($payzenResponse->isPendingPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("FacilyPay Oney pending status confirmed for cart #{$cartId}. Just redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     // order is pending Oney confirmation, payment is not pending : error case
                     $this->module->logger->logError("Order saved with FacilyPay Oney pending status while payment not pending, cart ID : #{$cartId}.");
                     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cartId . '&id_module=' . $this->module->id . '&id_order=' . $order->id . '&key=' . $order->secure_key . '&error=yes');
                 }
                 break;
             case Configuration::get('PS_OS_PAYMENT'):
             case Configuration::get('PAYZEN_OS_PAYMENT_OUTOFSTOCK'):
             case $oldState == Configuration::get('PS_OS_OUTOFSTOCK') && !$this->module->isOney($payzenResponse):
             default:
                 if ($payzenResponse->isAcceptedPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("Payment success confirmed for cart #{$cartId}. Just redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     // order saved with success status while payment failed
                     $this->module->logger->logError("Order saved with success status while payment failed, cart ID : #{$cartId}.");
                     Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cartId . '&id_module=' . $this->module->id . '&id_order=' . $order->id . '&key=' . $order->secure_key . '&error=yes');
                 }
                 break;
             default:
                 // order saved with unmanaged status, redirect client according to payment result
                 $this->module->logger->logInfo("Order saved with unmanaged status for cart #{$cartId}, redirect client according to payment result.");
                 if ($payzenResponse->isAcceptedPayment()) {
                     // redirect to success page
                     $this->module->logger->logInfo("Payment success for cart #{$cartId}. Redirect to success page.");
                     $this->_redirectSuccess($order, $this->module->id, $payzenResponse);
                 } else {
                     $this->module->logger->logInfo("Payment failure for cart #{$cartId}. Redirect to history page.");
                     Tools::redirect('index.php?controller=history');
                 }
                 break;
         }
     }
 }
Example #10
0
 private function checkVersionCompatibility($file, $rel_path, $pp_file)
 {
     $integration_version = PSM::integrationVersion($this->module);
     $result = array();
     $result[self::VERSION_CHECK_INDEX] = false;
     $version = $this->getVersion($file);
     if ($version === false) {
         $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('File is missing: %s'), PSM::normalizePath($rel_path, 'relative'));
     } else {
         $details = $this->notWritableWarning($file);
         if ($version[self::VERSION_INDEX] === false) {
             $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('File not compatible: %s (missing version signature)') . $details, PSM::normalizePath($rel_path, 'relative'));
         } else {
             $pp_version = $this->getVersion($pp_file);
             if (Tools::version_compare($integration_version, $version[self::VERSION_INDEX], '=')) {
                 $result[self::VERSION_CHECK_INDEX] = true;
                 $result[self::VERSION_CHECK_DESC_INDEX] = '';
                 if ($pp_version[self::VERSION_REQUIRED_INDEX] !== false) {
                     if ($version[self::VERSION_REQUIRED_INDEX] !== false) {
                         if (Tools::version_compare($version[self::VERSION_REQUIRED_INDEX], $pp_version[self::VERSION_REQUIRED_INDEX], '<')) {
                             $result[self::VERSION_CHECK_INDEX] = false;
                             $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('Compatibility warning for file: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]), str_replace('#', '-R', $version[self::VERSION_REQUIRED_INDEX]));
                         }
                     } else {
                         $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('Compatibility warning for file: %s (expected version %s, no version information found)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]));
                     }
                 }
             } else {
                 if ($pp_version[self::VERSION_REQUIRED_INDEX] !== false) {
                     if (Tools::version_compare($version[self::VERSION_INDEX], $pp_version[self::VERSION_REQUIRED_INDEX], '>=')) {
                         $result[self::VERSION_CHECK_INDEX] = true;
                         $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('Compatibility warning for file: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]), $version[self::VERSION_INDEX]);
                     } else {
                         if ($version[self::VERSION_REQUIRED_INDEX] !== false) {
                             if (Tools::version_compare($version[self::VERSION_REQUIRED_INDEX], $pp_version[self::VERSION_REQUIRED_INDEX], '<')) {
                                 $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('Compatibility warning for file: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]), str_replace('#', '-R', $version[self::VERSION_REQUIRED_INDEX]));
                             } else {
                                 $result[self::VERSION_CHECK_INDEX] = true;
                                 if (Tools::version_compare($version[self::VERSION_REQUIRED_INDEX], $pp_version[self::VERSION_REQUIRED_INDEX], '>')) {
                                     $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('Compatibility warning for file: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]), str_replace('#', '-R', $version[self::VERSION_REQUIRED_INDEX]));
                                 } else {
                                     $result[self::VERSION_CHECK_DESC_INDEX] = '';
                                 }
                             }
                         } else {
                             $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('File not compatible: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), str_replace('#', '-R', $pp_version[self::VERSION_REQUIRED_INDEX]), $version[self::VERSION_INDEX]);
                         }
                     }
                 } else {
                     $result[self::VERSION_CHECK_DESC_INDEX] = sprintf($this->module->l('File not compatible: %s (expected version %s, found version %s)') . $details, PSM::normalizePath($rel_path, 'relative'), $integration_version, $version[self::VERSION_INDEX]);
                 }
             }
         }
     }
     return $result;
 }
Example #11
0
 /**
  * Generate form fields to post to the payment gateway.
  */
 public function getFormFields($type = 'standard', $data = array())
 {
     /* @var $cust Customer */
     /* @var $cart Cart */
     $cust = $this->context->customer;
     $cart = $this->context->cart;
     /* @var $billingCountry Address */
     $billingAddress = new Address($cart->id_address_invoice);
     $billingCountry = new Country($billingAddress->id_country);
     /* @var $deliveryAddress Address */
     $deliveryAddress = new Address($cart->id_address_delivery);
     // TODO to remove when So Colissimo fix cart delivery address id
     $colissimoAddress = $this->_getColissimoShippingAddress($cart, $deliveryAddress, $cust->id);
     if (is_a($colissimoAddress, 'Address')) {
         $deliveryAddress = $colissimoAddress;
     }
     $deliveryCountry = new Country($deliveryAddress->id_country);
     /* @var $api PayzenApi */
     $api = $this->getLoadedApi();
     /* detect default language */
     $language = strtolower(Language::getIsoById(intval($this->context->language->id)));
     if (!$api->isSupportedLanguage($language)) {
         $language = Configuration::get('PAYZEN_DEFAULT_LANGUAGE');
     }
     /* detect store currency */
     $cartCurrency = new Currency(intval($cart->id_currency));
     $currency = $api->findCurrencyByAlphaCode($cartCurrency->iso_code);
     /* Amount */
     $amount = $cart->getOrderTotal();
     $api->set('amount', $currency->convertAmountToInteger($amount));
     $api->set('currency', $currency->num);
     $api->set('cust_email', $cust->email);
     $api->set('cust_id', $cust->id);
     $custTitle = new Gender((int) $cust->id_gender);
     $api->set('cust_title', $custTitle->name[Context::getContext()->language->id]);
     $api->set('cust_first_name', $billingAddress->firstname);
     $api->set('cust_last_name', $billingAddress->lastname);
     $api->set('cust_address', $billingAddress->address1 . ' ' . $billingAddress->address2);
     $api->set('cust_zip', $billingAddress->postcode);
     $api->set('cust_city', $billingAddress->city);
     $api->set('cust_phone', $billingAddress->phone);
     $api->set('cust_country', $billingCountry->iso_code);
     if ($billingAddress->id_state) {
         $state = new State((int) $billingAddress->id_state);
         $api->set('cust_state', $state->iso_code);
     }
     $title = '';
     $this->logger->logInfo("Form data generation for cart #{$cart->id} with {$type} payment.");
     switch ($type) {
         case 'standard':
             // single payment card data
             if (key_exists('card_type', $data) && $data['card_type']) {
                 // override payemnt_cards var
                 $api->set('payment_cards', $data['card_type']);
             }
             if (key_exists('card_number', $data) && $data['card_number']) {
                 $api->set('card_number', $data['card_number']);
                 $api->set('cvv', $data['cvv']);
                 $api->set('expiry_year', $data['expiry_year']);
                 $api->set('expiry_month', $data['expiry_month']);
                 // override action_mode to do a silent payment
                 $api->set('action_mode', 'SILENT');
             }
             $title = Configuration::get('PAYZEN_STD_TITLE', $this->context->language->id);
             if (!$title) {
                 $title = $this->l('Payment by bank card');
             }
             break;
         case 'multi':
             // multiple payment options
             $multiOptions = $this->_getAvailableMultiPaymentOptions();
             $option = $multiOptions[$data['opt']];
             $configFirst = $option['first'];
             $first = $configFirst != '' ? $currency->convertAmountToInteger($configFirst / 100 * $amount) : null;
             $api->setMultiPayment(null, $first, $option['count'], $option['period']);
             // override cb contract
             $api->set('contracts', $option['contract'] ? 'CB=' . $option['contract'] : null);
             $title = Configuration::get('PAYZEN_MULTI_TITLE', $this->context->language->id);
             if (!$title) {
                 $title = $this->l('Payment by bank card in several times');
             }
             $title .= ' (' . $option['count'] . ' x)';
             break;
         case 'oney':
             // Oney payment
             // override with Oney payment cards
             $api->set('payment_cards', 'ONEY_SANDBOX;ONEY');
             $products = $cart->getProducts(true);
             if (Configuration::get('PAYZEN_ONEY_CAT_MODE') == '1') {
                 $category = Configuration::get('PAYZEN_ONEY_COM_CAT');
             } else {
                 $oneyCategories = @unserialize(Configuration::get('PAYZEN_ONEY_PROD_CAT'));
             }
             foreach ($products as $product) {
                 if (!isset($category)) {
                     // build query to get product default category
                     $sql = 'SELECT `id_category_default` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'];
                     $dbCategory = Db::getInstance()->getValue($sql);
                     $category = $oneyCategories[$dbCategory];
                 }
                 $api->addProductRequestField($product['name'], $currency->convertAmountToInteger($product['total_wt']), $product['cart_quantity'], $product['id_product'], $category);
             }
             // Oney delivery options defined in admin panel
             $oneyOptions = @unserialize(Configuration::get('PAYZEN_ONEY_SHIP_OPTIONS'));
             // retrieve carrier ID from cart
             if (isset($cart->id_carrier) && $cart->id_carrier > 0) {
                 $carrierId = $cart->id_carrier;
             } else {
                 $deliveryOptionList = $cart->getDeliveryOptionList();
                 $deliveryOption = $cart->getDeliveryOption();
                 $carrierKey = $deliveryOption[$deliveryAddress->id];
                 foreach ($deliveryOptionList[$deliveryAddress->id][$carrierKey]['carrier_list'] as $id => $data) {
                     $carrierId = $id;
                     break;
                 }
             }
             $shopNameRegexNotAllowed = "#[^A-Z0-9ÁÀÂÄÉÈÊËÍÌÎÏÓÒÔÖÚÙÛÜÇ /'-]#ui";
             if ($cart->isVirtualCart() || !isset($carrierId) || !is_array($oneyOptions) || empty($oneyOptions)) {
                 // No shipping options
                 $api->set('ship_to_type', 'ETICKET');
                 $api->set('ship_to_speed', 'EXPRESS');
                 $shop = Shop::getShop($cart->id_shop);
                 $api->set('ship_to_delivery_company_name', preg_replace($shopNameRegexNotAllowed, ' ', $shop['name']));
             } elseif (Configuration::get('TNT_CARRIER_' . self::TNT_RELAY_POINT_PREFIX . '_ID') == $carrierId) {
                 $api->set('ship_to_type', 'RELAY_POINT');
                 $api->set('ship_to_speed', 'EXPRESS');
                 if ($row = Db::getInstance()->getRow("SELECT * FROM `" . _DB_PREFIX_ . "tnt_carrier_drop_off`\r\n\t\t\t\t\t\t\t\tWHERE `id_cart` = '" . $cart->id . "'")) {
                     $tntRelayAddress = $row['name'] . ' ' . $row['address'] . ' ' . $row['zipcode'] . ' ' . $row['city'];
                     $api->set('ship_to_delivery_company_name', preg_replace($shop_name_regex, ' ', $tntRelayAddress));
                     $api->set('ship_to_last_name', preg_replace($shop_name_regex, ' ', $row['name']));
                     $api->set('ship_to_street', preg_replace($shop_name_regex, ' ', $row['address']));
                     $api->set('ship_to_zip', $row['zipcode']);
                     $api->set('ship_to_city', preg_replace($shop_name_regex, ' ', $row['city']));
                     $api->set('ship_to_country', 'FR');
                 }
             } else {
                 $deliveryType = $oneyOptions[$carrierId]['delivery_type'];
                 $api->set('ship_to_type', $deliveryType);
                 $companyName = $oneyOptions[$carrierId]['carrier_label'];
                 if ($deliveryType === 'RECLAIM_IN_SHOP') {
                     $companyName .= ' ' . $oneyOptions[$carrierId]['address'];
                 }
                 $api->set('ship_to_delivery_company_name', $companyName);
                 $api->set('ship_to_speed', $oneyOptions[$carrierId]['delivery_speed']);
             }
             $api->set('cust_status', 'PRIVATE');
             // Prestashop don't manage customer type
             $api->set('ship_to_status', $deliveryAddress->company != '' ? 'COMPANY' : 'PRIVATE');
             $api->set('insurance_amount', '');
             // not available in Prestashop by default
             $api->set('tax_amount', $currency->convertAmountToInteger($cart->getOrderTotal() - $cart->getOrderTotal(false)));
             $api->set('shipping_amount', $currency->convertAmountToInteger($cart->getTotalShippingCost()));
             $title = Configuration::get('PAYZEN_ONEY_TITLE', $this->context->language->id);
             if (!$title) {
                 $title = $this->l('Payment with FacilyPay Oney');
             }
     }
     if ($api->get('ship_to_type') == null || $api->get('ship_to_type') == 'PACKAGE_DELIVERY_COMPANY') {
         $api->set('ship_to_first_name', $deliveryAddress->firstname);
         $api->set('ship_to_last_name', $deliveryAddress->lastname);
         $api->set('ship_to_street', $deliveryAddress->address1);
         $api->set('ship_to_street2', $deliveryAddress->address2);
         $api->set('ship_to_zip', $deliveryAddress->postcode);
         $api->set('ship_to_city', $deliveryAddress->city);
         $api->set('ship_to_phone_num', $deliveryAddress->phone);
         $api->set('ship_to_country', $deliveryCountry->iso_code);
         if ($deliveryAddress->id_state) {
             $state = new State((int) $deliveryAddress->id_state);
             $api->set('ship_to_state', $state->iso_code);
         }
     }
     $api->set('order_info', $title);
     // activate 3ds ?
     $threedsMpi = null;
     if (Configuration::get('PAYZEN_3DS_MIN_AMOUNT') != '' && $amount < Configuration::get('PAYZEN_3DS_MIN_AMOUNT')) {
         $threedsMpi = '2';
     }
     $api->set('threeds_mpi', $threedsMpi);
     $api->set('language', $language);
     $api->set('order_id', $cart->id);
     $api->set('url_return', $this->context->link->getModuleLink($this->name, 'submit', array(), true));
     // patch to avoid signature error with HTML minifier introduced since Prestashop 1.6.0.3
     if (Configuration::get('PS_HTML_THEME_COMPRESSION') && Tools::version_compare(_PS_VERSION_, '1.6.0.3', '>=')) {
         foreach ($api->getRequestFields() as $field) {
             $value = preg_replace('/\\s+/m', ' ', $field->getValue());
             $api->set($field->getName(), $value);
         }
     }
     // prepare data for PayZen payment form
     return $api->getRequestFieldsArray();
 }
 /**
  * Function used to render the list to display for this controller
  */
 public function renderList()
 {
     if (!($this->fields_list && is_array($this->fields_list))) {
         return false;
     }
     $this->getList($this->context->language->id);
     $helper = new HelperList();
     // Empty list is ok
     if (!is_array($this->_list)) {
         $this->displayWarning($this->l('Bad SQL query', 'Helper') . '<br />' . htmlspecialchars($this->_list_error));
         return false;
     }
     $this->setHelperDisplay($helper);
     $helper->tpl_vars = $this->tpl_list_vars;
     $helper->tpl_delete_link_vars = $this->tpl_delete_link_vars;
     $helper->show_toolbar = false;
     // For compatibility reasons, we have to check standard actions in class attributes
     foreach ($this->actions_available as $action) {
         if (!in_array($action, $this->actions) && isset($this->{$action}) && $this->{$action}) {
             $this->actions[] = $action;
         }
     }
     if (Tools::version_compare(_PS_VERSION_, '1.5.2', '>')) {
         $helper->is_cms = $this->is_cms;
     }
     $helper->force_show_bulk_actions = true;
     $list = $helper->generateList($this->_list, $this->fields_list);
     return $list;
 }
    public function hookDisplayHeader()
    {
        if (!$this->isAvailable()) {
            return;
        }
        if (empty($this->context->controller->php_self) || $this->context->controller->php_self != 'order') {
            return;
        }
        $current_step = (int) Tools::getValue('step', 0);
        // Clean des anciennes adresses Shiptomyid du panier en cours //
        if (in_array($current_step, array(0, 1)) && !Tools::getIsset('ajax')) {
            $ids_address = Db::getInstance()->ExecuteS('SELECT a.id_address FROM ' . _DB_PREFIX_ . 'address a
				WHERE a.id_address NOT IN 
				(SELECT DISTINCT o.id_address_delivery FROM ' . _DB_PREFIX_ . 'orders o WHERE id_customer = ' . (int) $this->context->customer->id . ')
				AND a.id_customer = ' . (int) $this->context->customer->id . ' AND a.alias LIKE "SHIP2MYID%"
			');
            if ($ids_address) {
                foreach ($ids_address as $id_address) {
                    Db::getInstance()->execute('DELETE FROM ' . _DB_PREFIX_ . 'address WHERE id_address = ' . (int) $id_address['id_address']);
                }
            }
            $this->context->cart->id_address_delivery = 0;
            $this->context->cart->update();
        }
        if ($current_step != 1) {
            return;
        }
        $youtube_link = Configuration::get('SHIPTOMYID_VIDEO_LINK');
        if (isset($this->context->ship2myid->marketplace) && is_array($this->context->ship2myid->marketplace)) {
            $marketplace_details = $this->context->ship2myid->marketplace;
        } else {
            $this->context->ship2myid->marketplace = $marketplace_details = $this->api->getMarketplaceDetails();
        }
        if (isset($marketplace_details['Marketplace']['marketplace_name']) && !empty($marketplace_details['Marketplace']['marketplace_name'])) {
            $marketplace_name = $marketplace_details['Marketplace']['marketplace_name'];
        }
        if (isset($marketplace_details['Marketplace']['marketplace_image']) && !empty($marketplace_details['Marketplace']['marketplace_image'])) {
            $marketplace_image = $marketplace_details['Marketplace']['marketplace_image'];
        }
        $match = array();
        if (preg_match('/(.+www\\.youtube\\.com)\\/watch\\?v=([_0-9a-zA-Z]+)/', $youtube_link, $match)) {
            $youtube_link = $match[1] . '/embed/' . $match[2];
        }
        if (class_exists('Tools') && method_exists('Tools', 'version_compare') && Tools::version_compare(_PS_VERSION_, '1.6', '>=') === true) {
            $button_class = 'button button-small btn btn-default';
        } else {
            $button_class = 'button_large';
        }
        $key = md5($this->context->cart->id . '_' . $this->context->cart->secure_key);
        // Chargement de la popup Shiptomyid //
        $this->context->controller->addCSS(__PS_BASE_URI__ . 'modules/' . $this->name . '/views/css/shiptomyid-fancybox.css', 'all');
        $this->context->controller->addjqueryPlugin('fancybox');
        $this->context->smarty->assign(array('popup_url' => Configuration::get('SHIPTOMYID_POPUP_URL'), 'video_url' => $youtube_link, 'button_class' => $button_class, 'popup_width' => Configuration::get('SHIPTOMYID_POPUP_WIDTH'), 'popup_height' => Configuration::get('SHIPTOMYID_POPUP_HEIGHT'), 'callback_url' => Tools::getShopDomain(true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/postdata.php?data=' . $this->context->cart->id . '&key=' . $key, 'marketplace_name' => $marketplace_name, 'marketplace_image' => $marketplace_image));
        return $this->display(__FILE__, 'load-popup.tpl');
    }
Example #14
0
 /**
  * Get the recommendations from the blocklayered filters
  *
  * @param array $params list of specific data
  * @return array $aData containing the front office block
  */
 public function getBlockLayeredRecommendations($params)
 {
     if (!$this->oPrediggoConfig->web_site_id_checked) {
         return false;
     }
     $sHookName = 'blocklayered';
     $this->oPrediggoCallController->_setPageName($sHookName);
     $params['filters'] = $this->getSelectedFilters();
     $params['customer'] = $this->context->customer;
     if (!($this->aRecommendations[$sHookName] = $this->oPrediggoCallController->getListOfRecommendations($sHookName, $params))) {
         return false;
     }
     // Display Main Configuration management
     $this->smarty->assign(array('hook_name' => $sHookName, 'page_name' => 'category', 'aRecommendations' => $this->aRecommendations, 'tax_enabled' => (int) Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'sImageType' => Tools::version_compare(_PS_VERSION_, '1.5.1', '>=') ? 'home_default' : 'home'));
     return $this->display(__FILE__, 'list_recommendations.tpl');
 }
Example #15
0
    public static function getCMSBlocksByLocation($location, $id_shop = false)
    {
        $context = Context::getContext();
        $id_shop = $id_shop != false ? $id_shop : $context->shop->id;
        $where_shop = '';
        if (Tools::version_compare(_PS_VERSION_, '1.6.0.12', '>=') == true && $id_shop != false) {
            $where_shop = ' AND ccl.`id_shop` = ' . $id_shop;
        }
        $sql = 'SELECT bc.`id_cms_block`, bcl.`name` block_name, ccl.`name` category_name, bc.`position`, bc.`id_cms_category`, bc.`display_store`
			FROM `' . _DB_PREFIX_ . 'cms_block` bc
			LEFT JOIN `' . _DB_PREFIX_ . 'cms_block_shop` bcs
			ON (bcs.id_cms_block = bc.id_cms_block)
			INNER JOIN `' . _DB_PREFIX_ . 'cms_category_lang` ccl
			ON (bc.`id_cms_category` = ccl.`id_cms_category`)
			INNER JOIN `' . _DB_PREFIX_ . 'cms_block_lang` bcl
			ON (bc.`id_cms_block` = bcl.`id_cms_block`)
			WHERE ccl.`id_lang` = ' . (int) Context::getContext()->language->id . '
			AND bcl.`id_lang` = ' . (int) Context::getContext()->language->id . '
			AND bc.`location` = ' . (int) $location . $where_shop . '
			AND bcs.id_shop = ' . $id_shop . '
			ORDER BY bc.`position`';
        return Db::getInstance()->executeS($sql);
    }
Example #16
0
    protected function getCMSPages($id_cms_category, $id_shop = false, $id_lang = false)
    {
        $id_shop = $id_shop !== false ? (int) $id_shop : (int) Context::getContext()->shop->id;
        $id_lang = $id_lang ? (int) $id_lang : (int) Context::getContext()->language->id;
        $where_shop = '';
        if (Tools::version_compare(_PS_VERSION_, '1.6.0.12', '>=') == true) {
            $where_shop = ' AND cl.`id_shop` = ' . (int) $id_shop;
        }
        $sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
			FROM `' . _DB_PREFIX_ . 'cms` c
			INNER JOIN `' . _DB_PREFIX_ . 'cms_shop` cs
			ON (c.`id_cms` = cs.`id_cms`)
			INNER JOIN `' . _DB_PREFIX_ . 'cms_lang` cl
			ON (c.`id_cms` = cl.`id_cms`)
			WHERE c.`id_cms_category` = ' . (int) $id_cms_category . '
			AND cs.`id_shop` = ' . (int) $id_shop . '
			AND cl.`id_lang` = ' . (int) $id_lang . $where_shop . '
			AND c.`active` = 1
			ORDER BY `position`';
        return Db::getInstance()->executeS($sql);
    }
Example #17
0
 public static function getVersion()
 {
     if (Tools::version_compare(_PS_VERSION_, '1.5.6.2', '>')) {
         return 160;
     } elseif (Tools::version_compare(_PS_VERSION_, '1.5.5', '>')) {
         return 156;
     } else {
         return 150;
     }
 }