· 6 years ago · Dec 10, 2019, 11:50 AM
1<?php
2/**
3 * 2007-2018 PrestaShop.
4 *
5 * NOTICE OF LICENSE
6 *
7 * This source file is subject to the Open Software License (OSL 3.0)
8 * that is bundled with this package in the file LICENSE.txt.
9 * It is also available through the world-wide-web at this URL:
10 * https://opensource.org/licenses/OSL-3.0
11 * If you did not receive a copy of the license and are unable to
12 * obtain it through the world-wide-web, please send an email
13 * to license@prestashop.com so we can send you a copy immediately.
14 *
15 * DISCLAIMER
16 *
17 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
18 * versions in the future. If you wish to customize PrestaShop for your
19 * needs please refer to http://www.prestashop.com for more information.
20 *
21 * @author PrestaShop SA <contact@prestashop.com>
22 * @copyright 2007-2018 PrestaShop SA
23 * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
24 * International Registered Trademark & Property of PrestaShop SA
25 */
26use PrestaShop\PrestaShop\Adapter\StockManager;
27
28abstract class PaymentModuleCore extends Module
29{
30 /** @var int Current order's id */
31 public $currentOrder;
32 public $currentOrderReference;
33 public $currencies = true;
34 public $currencies_mode = 'checkbox';
35
36 const DEBUG_MODE = false;
37
38 public function install()
39 {
40 if (!parent::install()) {
41 return false;
42 }
43
44 // Insert currencies availability
45 if ($this->currencies_mode == 'checkbox') {
46 if (!$this->addCheckboxCurrencyRestrictionsForModule()) {
47 return false;
48 }
49 } elseif ($this->currencies_mode == 'radio') {
50 if (!$this->addRadioCurrencyRestrictionsForModule()) {
51 return false;
52 }
53 } else {
54 return $this->trans('No currency mode for payment module', array(), 'Admin.Payment.Notification');
55 }
56
57 // Insert countries availability
58 $return = $this->addCheckboxCountryRestrictionsForModule();
59
60 // Insert carrier availability
61 $return &= $this->addCheckboxCarrierRestrictionsForModule();
62
63 if (!Configuration::get('CONF_' . strtoupper($this->name) . '_FIXED')) {
64 Configuration::updateValue('CONF_' . strtoupper($this->name) . '_FIXED', '0.2');
65 }
66 if (!Configuration::get('CONF_' . strtoupper($this->name) . '_VAR')) {
67 Configuration::updateValue('CONF_' . strtoupper($this->name) . '_VAR', '2');
68 }
69 if (!Configuration::get('CONF_' . strtoupper($this->name) . '_FIXED_FOREIGN')) {
70 Configuration::updateValue('CONF_' . strtoupper($this->name) . '_FIXED_FOREIGN', '0.2');
71 }
72 if (!Configuration::get('CONF_' . strtoupper($this->name) . '_VAR_FOREIGN')) {
73 Configuration::updateValue('CONF_' . strtoupper($this->name) . '_VAR_FOREIGN', '2');
74 }
75
76 return $return;
77 }
78
79 public function uninstall()
80 {
81 if (!Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'module_country` WHERE id_module = ' . (int) $this->id)
82 || !Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'module_currency` WHERE id_module = ' . (int) $this->id)
83 || !Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'module_group` WHERE id_module = ' . (int) $this->id)
84 || !Db::getInstance()->execute('DELETE FROM `' . _DB_PREFIX_ . 'module_carrier` WHERE id_module = ' . (int) $this->id)) {
85 return false;
86 }
87
88 return parent::uninstall();
89 }
90
91 /**
92 * Add checkbox currency restrictions for a new module.
93 *
94 * @param array $shops
95 *
96 * @return bool
97 */
98 public function addCheckboxCurrencyRestrictionsForModule(array $shops = array())
99 {
100 if (!$shops) {
101 $shops = Shop::getShops(true, null, true);
102 }
103
104 foreach ($shops as $s) {
105 if (!Db::getInstance()->execute('
106 INSERT INTO `' . _DB_PREFIX_ . 'module_currency` (`id_module`, `id_shop`, `id_currency`)
107 SELECT ' . (int) $this->id . ', "' . (int) $s . '", `id_currency` FROM `' . _DB_PREFIX_ . 'currency` WHERE deleted = 0')) {
108 return false;
109 }
110 }
111
112 return true;
113 }
114
115 /**
116 * Add radio currency restrictions for a new module.
117 *
118 * @param array $shops
119 *
120 * @return bool
121 */
122 public function addRadioCurrencyRestrictionsForModule(array $shops = array())
123 {
124 if (!$shops) {
125 $shops = Shop::getShops(true, null, true);
126 }
127
128 foreach ($shops as $s) {
129 if (!Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'module_currency` (`id_module`, `id_shop`, `id_currency`)
130 VALUES (' . (int) $this->id . ', "' . (int) $s . '", -2)')) {
131 return false;
132 }
133 }
134
135 return true;
136 }
137
138 /**
139 * Add checkbox country restrictions for a new module.
140 *
141 * @param array $shops
142 *
143 * @return bool
144 */
145 public function addCheckboxCountryRestrictionsForModule(array $shops = array())
146 {
147 $countries = Country::getCountries((int) Context::getContext()->language->id, true); //get only active country
148 $country_ids = array();
149 foreach ($countries as $country) {
150 $country_ids[] = $country['id_country'];
151 }
152
153 return Country::addModuleRestrictions($shops, $countries, array(array('id_module' => (int) $this->id)));
154 }
155
156 /**
157 * Add checkbox carrier restrictions for a new module.
158 *
159 * @param array $shops
160 *
161 * @return bool
162 */
163 public function addCheckboxCarrierRestrictionsForModule(array $shops = array())
164 {
165 if (!$shops) {
166 $shops = Shop::getShops(true, null, true);
167 }
168
169 $carriers = Carrier::getCarriers((int) Context::getContext()->language->id);
170 $carrier_ids = array();
171 foreach ($carriers as $carrier) {
172 $carrier_ids[] = $carrier['id_reference'];
173 }
174
175 foreach ($shops as $s) {
176 foreach ($carrier_ids as $id_carrier) {
177 if (!Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'module_carrier` (`id_module`, `id_shop`, `id_reference`)
178 VALUES (' . (int) $this->id . ', "' . (int) $s . '", ' . (int) $id_carrier . ')')) {
179 return false;
180 }
181 }
182 }
183
184 return true;
185 }
186
187 /**
188 * Validate an order in database
189 * Function called from a payment module.
190 *
191 * @param int $id_cart
192 * @param int $id_order_state
193 * @param float $amount_paid Amount really paid by customer (in the default currency)
194 * @param string $payment_method Payment method (eg. 'Credit card')
195 * @param null $message Message to attach to order
196 * @param array $extra_vars
197 * @param null $currency_special
198 * @param bool $dont_touch_amount
199 * @param bool $secure_key
200 * @param Shop $shop
201 *
202 * @return bool
203 *
204 * @throws PrestaShopException
205 */
206 public function validateOrder(
207 $id_cart,
208 $id_order_state,
209 $amount_paid,
210 $payment_method = 'Unknown',
211 $message = null,
212 $extra_vars = array(),
213 $currency_special = null,
214 $dont_touch_amount = false,
215 $secure_key = false,
216 Shop $shop = null
217 ) {
218 if (self::DEBUG_MODE) {
219 PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true);
220 }
221
222 if (!isset($this->context)) {
223 $this->context = Context::getContext();
224 }
225 $this->context->cart = new Cart((int) $id_cart);
226 $this->context->customer = new Customer((int) $this->context->cart->id_customer);
227 // The tax cart is loaded before the customer so re-cache the tax calculation method
228 $this->context->cart->setTaxCalculationMethod();
229
230 $this->context->language = new Language((int) $this->context->cart->id_lang);
231 $this->context->shop = ($shop ? $shop : new Shop((int) $this->context->cart->id_shop));
232 ShopUrl::resetMainDomainCache();
233 $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
234 $this->context->currency = new Currency((int) $id_currency, null, (int) $this->context->shop->id);
235 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
236 $context_country = $this->context->country;
237 }
238
239 $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
240 if (!Validate::isLoadedObject($order_status)) {
241 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true);
242 throw new PrestaShopException('Can\'t load Order status');
243 }
244
245 if (!$this->active) {
246 PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true);
247 die(Tools::displayError());
248 }
249
250 // Does order already exists ?
251 if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
252 if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
253 PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true);
254 die(Tools::displayError());
255 }
256
257 // For each package, generate an order
258 $delivery_option_list = $this->context->cart->getDeliveryOptionList();
259 $package_list = $this->context->cart->getPackageList();
260 $cart_delivery_option = $this->context->cart->getDeliveryOption();
261
262 // If some delivery options are not defined, or not valid, use the first valid option
263 foreach ($delivery_option_list as $id_address => $package) {
264 if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
265 foreach ($package as $key => $val) {
266 $cart_delivery_option[$id_address] = $key;
267 break;
268 }
269 }
270 }
271
272 $order_list = array();
273 $order_detail_list = array();
274
275 do {
276 $reference = Order::generateReference();
277 } while (Order::getByReference($reference)->count());
278
279 $this->currentOrderReference = $reference;
280
281 $cart_total_paid = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
282
283 foreach ($cart_delivery_option as $id_address => $key_carriers) {
284 foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
285 foreach ($data['package_list'] as $id_package) {
286 // Rewrite the id_warehouse
287 $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
288 $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
289 }
290 }
291 }
292 // Make sure CartRule caches are empty
293 CartRule::cleanCache();
294 $cart_rules = $this->context->cart->getCartRules();
295 foreach ($cart_rules as $cart_rule) {
296 if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
297 if ($error = $rule->checkValidity($this->context, true, true)) {
298 $this->context->cart->removeCartRule((int) $rule->id);
299 if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
300 Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
301 } else {
302 $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code;
303 $error = $this->trans('The cart rule named "%1s" (ID %2s) used in this cart is not valid and has been withdrawn from cart', array($rule_name, (int) $rule->id), 'Admin.Payment.Notification');
304 PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id);
305 }
306 }
307 }
308 }
309
310 foreach ($package_list as $id_address => $packageByAddress) {
311 foreach ($packageByAddress as $id_package => $package) {
312 /** @var Order $order */
313 $order = new Order();
314 $order->product_list = $package['product_list'];
315
316 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
317 $address = new Address((int) $id_address);
318 $this->context->country = new Country((int) $address->id_country, (int) $this->context->cart->id_lang);
319 if (!$this->context->country->active) {
320 throw new PrestaShopException('The delivery address country is not active.');
321 }
322 }
323
324 $carrier = null;
325 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
326 $carrier = new Carrier((int) $package['id_carrier'], (int) $this->context->cart->id_lang);
327 $order->id_carrier = (int) $carrier->id;
328 $id_carrier = (int) $carrier->id;
329 } else {
330 $order->id_carrier = 0;
331 $id_carrier = 0;
332 }
333
334 $order->id_customer = (int) $this->context->cart->id_customer;
335 $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
336 $order->id_address_delivery = (int) $id_address;
337 $order->id_address_contatto = (int) $this->context->cart->id_address_contatto;
338 $order->id_currency = $this->context->currency->id;
339 $order->id_lang = (int) $this->context->cart->id_lang;
340 $order->id_cart = (int) $this->context->cart->id;
341 $order->reference = $reference;
342 $order->id_shop = (int) $this->context->shop->id;
343 $order->id_shop_group = (int) $this->context->shop->id_shop_group;
344
345 $order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key));
346 $order->payment = $payment_method;
347 if (isset($this->name)) {
348 $order->module = $this->name;
349 }
350 $order->recyclable = $this->context->cart->recyclable;
351 $order->gift = (int) $this->context->cart->gift;
352 $order->gift_message = $this->context->cart->gift_message;
353 $order->mobile_theme = $this->context->cart->mobile_theme;
354 $order->conversion_rate = $this->context->currency->conversion_rate;
355 $amount_paid = !$dont_touch_amount ? Tools::ps_round((float) $amount_paid, 2) : $amount_paid;
356 $order->total_paid_real = 0;
357
358 $order->total_products = (float) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
359 $order->total_products_wt = (float) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
360 $order->total_discounts_tax_excl = (float) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
361 $order->total_discounts_tax_incl = (float) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
362 $order->total_discounts = $order->total_discounts_tax_incl;
363
364 $order->total_shipping_tax_excl = (float) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
365 $order->total_shipping_tax_incl = (float) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
366 $order->total_shipping = $order->total_shipping_tax_incl;
367
368 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
369 $order->carrier_tax_rate = $carrier->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
370 }
371
372 $order->total_wrapping_tax_excl = (float) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
373 $order->total_wrapping_tax_incl = (float) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
374 $order->total_wrapping = $order->total_wrapping_tax_incl;
375
376 $order->total_paid_tax_excl = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
377 $order->total_paid_tax_incl = (float) Tools::ps_round((float) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
378 $order->total_paid = $order->total_paid_tax_incl;
379 $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
380 $order->round_type = Configuration::get('PS_ROUND_TYPE');
381
382 $order->invoice_date = '0000-00-00 00:00:00';
383 $order->delivery_date = '0000-00-00 00:00:00';
384
385 if (self::DEBUG_MODE) {
386 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true);
387 }
388
389 // Creating order
390 $result = $order->add();
391
392 if (!$result) {
393 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true);
394 throw new PrestaShopException('Can\'t save Order');
395 }
396
397 // Amount paid by customer is not the right one -> Status = payment error
398 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
399 // if ($order->total_paid != $order->total_paid_real)
400 // We use number_format in order to compare two string
401 if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
402 $id_order_state = Configuration::get('PS_OS_ERROR');
403 }
404
405 $order_list[] = $order;
406
407 if (self::DEBUG_MODE) {
408 PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true);
409 }
410
411 // Insert new Order detail list using cart for the current order
412 $order_detail = new OrderDetail(null, null, $this->context);
413 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
414 $order_detail_list[] = $order_detail;
415
416 if (self::DEBUG_MODE) {
417 PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true);
418 }
419
420 // Adding an entry in order_carrier table
421 if (!is_null($carrier)) {
422 $order_carrier = new OrderCarrier();
423 $order_carrier->id_order = (int) $order->id;
424 $order_carrier->id_carrier = (int) $id_carrier;
425 $order_carrier->weight = (float) $order->getTotalWeight();
426 $order_carrier->shipping_cost_tax_excl = (float) $order->total_shipping_tax_excl;
427 $order_carrier->shipping_cost_tax_incl = (float) $order->total_shipping_tax_incl;
428 $order_carrier->add();
429 }
430 }
431 }
432
433 // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
434 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
435 $this->context->country = $context_country;
436 }
437
438 if (!$this->context->country->active) {
439 PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true);
440 throw new PrestaShopException('The order address country is not active.');
441 }
442
443 if (self::DEBUG_MODE) {
444 PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true);
445 }
446
447 // Register Payment only if the order status validate the order
448 if ($order_status->logable) {
449 // $order is the last order loop in the foreach
450 // The method addOrderPayment of the class Order make a create a paymentOrder
451 // linked to the order reference and not to the order id
452 if (isset($extra_vars['transaction_id'])) {
453 $transaction_id = $extra_vars['transaction_id'];
454 } else {
455 $transaction_id = null;
456 }
457
458 if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
459 PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true);
460 throw new PrestaShopException('Can\'t save Order Payment');
461 }
462 }
463
464 // Next !
465 $only_one_gift = false;
466 $cart_rule_used = array();
467 $products = $this->context->cart->getProducts();
468
469 // Make sure CartRule caches are empty
470 CartRule::cleanCache();
471 foreach ($order_detail_list as $key => $order_detail) {
472 /** @var OrderDetail $order_detail */
473 $order = $order_list[$key];
474 if (isset($order->id)) {
475 if (!$secure_key) {
476 $message .= '<br />' . $this->trans('Warning: the secure key is empty, check your payment account before validation', array(), 'Admin.Payment.Notification');
477 }
478 // Optional message to attach to this order
479 if (isset($message) & !empty($message)) {
480 $msg = new Message();
481 $message = strip_tags($message, '<br>');
482 if (Validate::isCleanHtml($message)) {
483 if (self::DEBUG_MODE) {
484 PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true);
485 }
486 $msg->message = $message;
487 $msg->id_cart = (int) $id_cart;
488 $msg->id_customer = (int) ($order->id_customer);
489 $msg->id_order = (int) $order->id;
490 $msg->private = 1;
491 $msg->add();
492 }
493 }
494
495 // Insert new Order detail list using cart for the current order
496 //$orderDetail = new OrderDetail(null, null, $this->context);
497 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
498
499 // Construct order detail table for the email
500 $products_list = '';
501 $virtual_product = true;
502
503 $product_var_tpl_list = array();
504 foreach ($order->product_list as $product) {
505 $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')}, $specific_price, true, true, null, true, $product['id_customization']);
506 $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')}, $specific_price, true, true, null, true, $product['id_customization']);
507
508 $product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt;
509
510 $product_var_tpl = array(
511 'id_product' => $product['id_product'],
512 'reference' => $product['reference'],
513 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : ''),
514 'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false),
515 'quantity' => $product['quantity'],
516 'customization' => array(),
517 );
518
519 if (isset($product['price']) && $product['price']) {
520 $product_var_tpl['unit_price'] = Tools::displayPrice($product_price, $this->context->currency, false);
521 $product_var_tpl['unit_price_full'] = Tools::displayPrice($product_price, $this->context->currency, false)
522 . ' ' . $product['unity'];
523 } else {
524 $product_var_tpl['unit_price'] = $product_var_tpl['unit_price_full'] = '';
525 }
526
527 $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart, null, true, null, (int) $product['id_customization']);
528 if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
529 $product_var_tpl['customization'] = array();
530 foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
531 $customization_text = '';
532 if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
533 foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
534 $customization_text .= '<strong>' . $text['name'] . '</strong>: ' . $text['value'] . '<br />';
535 }
536 }
537
538 if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
539 $customization_text .= $this->trans('%d image(s)', array(count($customization['datas'][Product::CUSTOMIZE_FILE])), 'Admin.Payment.Notification') . '<br />';
540 }
541
542 $customization_quantity = (int) $customization['quantity'];
543
544 $product_var_tpl['customization'][] = array(
545 'customization_text' => $customization_text,
546 'customization_quantity' => $customization_quantity,
547 'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false),
548 );
549 }
550 }
551
552 $product_var_tpl_list[] = $product_var_tpl;
553 // Check if is not a virutal product for the displaying of shipping
554 if (!$product['is_virtual']) {
555 $virtual_product &= false;
556 }
557 } // end foreach ($products)
558
559 $product_list_txt = '';
560 $product_list_html = '';
561 if (count($product_var_tpl_list) > 0) {
562 $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
563 $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
564 }
565
566 $cart_rules_list = array();
567 $total_reduction_value_ti = 0;
568 $total_reduction_value_tex = 0;
569 foreach ($cart_rules as $cart_rule) {
570 $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
571 $values = array(
572 'tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package),
573 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package),
574 );
575
576 // If the reduction is not applicable to this order, then continue with the next one
577 if (!$values['tax_excl']) {
578 continue;
579 }
580
581 // IF
582 // This is not multi-shipping
583 // The value of the voucher is greater than the total of the order
584 // Partial use is allowed
585 // This is an "amount" reduction, not a reduction in % or a gift
586 // THEN
587 // The voucher is cloned with a new value corresponding to the remainder
588 if (count($order_list) == 1 && $values['tax_incl'] > ($order->total_products_wt - $total_reduction_value_ti) && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
589 // Create a new voucher from the original
590 $voucher = new CartRule((int) $cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it
591 unset($voucher->id);
592
593 // Set a new voucher code
594 $voucher->code = empty($voucher->code) ? substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
595 if (preg_match('/\-([0-9]{1,2})\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
596 $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (intval($matches[1]) + 1), $voucher->code);
597 }
598
599 // Set the new voucher value
600 if ($voucher->reduction_tax) {
601 $voucher->reduction_amount = ($total_reduction_value_ti + $values['tax_incl']) - $order->total_products_wt;
602
603 // Add total shipping amout only if reduction amount > total shipping
604 if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
605 $voucher->reduction_amount -= $order->total_shipping_tax_incl;
606 }
607 } else {
608 $voucher->reduction_amount = ($total_reduction_value_tex + $values['tax_excl']) - $order->total_products;
609
610 // Add total shipping amout only if reduction amount > total shipping
611 if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
612 $voucher->reduction_amount -= $order->total_shipping_tax_excl;
613 }
614 }
615 if ($voucher->reduction_amount <= 0) {
616 continue;
617 }
618
619 if ($this->context->customer->isGuest()) {
620 $voucher->id_customer = 0;
621 } else {
622 $voucher->id_customer = $order->id_customer;
623 }
624
625 $voucher->quantity = 1;
626 $voucher->reduction_currency = $order->id_currency;
627 $voucher->quantity_per_user = 1;
628 if ($voucher->add()) {
629 // If the voucher has conditions, they are now copied to the new voucher
630 CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
631 $orderLanguage = new Language((int) $order->id_lang);
632
633 $params = array(
634 '{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false),
635 '{voucher_num}' => $voucher->code,
636 '{firstname}' => $this->context->customer->firstname,
637 '{lastname}' => $this->context->customer->lastname,
638 '{id_order}' => $order->reference,
639 '{order_name}' => $order->getUniqReference(),
640 );
641 Mail::Send(
642 (int) $order->id_lang,
643 'voucher',
644 Context::getContext()->getTranslator()->trans(
645 'New voucher for your order %s',
646 array($order->reference),
647 'Emails.Subject',
648 $orderLanguage->locale
649 ),
650 $params,
651 $this->context->customer->email,
652 $this->context->customer->firstname . ' ' . $this->context->customer->lastname,
653 null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop
654 );
655 }
656
657 $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
658 $values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
659 if (1 == $voucher->free_shipping) {
660 $values['tax_incl'] += $order->total_shipping_tax_incl;
661 $values['tax_excl'] += $order->total_shipping_tax_excl;
662 }
663 }
664 $total_reduction_value_ti += $values['tax_incl'];
665 $total_reduction_value_tex += $values['tax_excl'];
666
667 $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
668
669 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)) {
670 $cart_rule_used[] = $cart_rule['obj']->id;
671
672 // Create a new instance of Cart Rule without id_lang, in order to update its quantity
673 $cart_rule_to_update = new CartRule((int) $cart_rule['obj']->id);
674 $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
675 $cart_rule_to_update->update();
676 }
677
678 $cart_rules_list[] = array(
679 'voucher_name' => $cart_rule['obj']->name,
680 'voucher_reduction' => ($values['tax_incl'] != 0.00 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false),
681 );
682 }
683
684 $cart_rules_list_txt = '';
685 $cart_rules_list_html = '';
686 if (count($cart_rules_list) > 0) {
687 $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
688 $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
689 }
690
691 // Specify order id for message
692 $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
693 if ($old_message && !$old_message['private']) {
694 $update_message = new Message((int) $old_message['id_message']);
695 $update_message->id_order = (int) $order->id;
696 $update_message->update();
697
698 // Add this message in the customer thread
699 $customer_thread = new CustomerThread();
700 $customer_thread->id_contact = 0;
701 $customer_thread->id_customer = (int) $order->id_customer;
702 $customer_thread->id_shop = (int) $this->context->shop->id;
703 $customer_thread->id_order = (int) $order->id;
704 $customer_thread->id_lang = (int) $this->context->language->id;
705 $customer_thread->email = $this->context->customer->email;
706 $customer_thread->status = 'open';
707 $customer_thread->token = Tools::passwdGen(12);
708 $customer_thread->add();
709
710 $customer_message = new CustomerMessage();
711 $customer_message->id_customer_thread = $customer_thread->id;
712 $customer_message->id_employee = 0;
713 $customer_message->message = $update_message->message;
714 $customer_message->private = 1;
715
716 if (!$customer_message->add()) {
717 $this->errors[] = $this->trans('An error occurred while saving message', array(), 'Admin.Payment.Notification');
718 }
719 }
720
721 if (self::DEBUG_MODE) {
722 PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
723 }
724
725 // Hook validate order
726 Hook::exec('actionValidateOrder', array(
727 'cart' => $this->context->cart,
728 'order' => $order,
729 'customer' => $this->context->customer,
730 'currency' => $this->context->currency,
731 'orderStatus' => $order_status,
732 ));
733
734 foreach ($this->context->cart->getProducts() as $product) {
735 if ($order_status->logable) {
736 ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
737 }
738 }
739
740 if (self::DEBUG_MODE) {
741 PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
742 }
743
744 // Set the order status
745 $new_history = new OrderHistory();
746 $new_history->id_order = (int) $order->id;
747 $new_history->changeIdOrderState((int) $id_order_state, $order, true);
748 $new_history->addWithemail(true, $extra_vars);
749
750 // Switch to back order if needed
751 if (Configuration::get('PS_STOCK_MANAGEMENT') &&
752 ($order_detail->getStockState() ||
753 $order_detail->product_quantity_in_stock < 0)) {
754 $history = new OrderHistory();
755 $history->id_order = (int) $order->id;
756 $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
757 $history->addWithemail();
758 }
759
760 unset($order_detail);
761
762 // Order is reloaded because the status just changed
763 $order = new Order((int) $order->id);
764
765 // Send an e-mail to customer (one order = one email)
766 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
767 $invoice = new Address((int) $order->id_address_invoice);
768 $delivery = new Address((int) $order->id_address_delivery);
769 $contatto = new Address((int) $order->id_address_contatto);
770 $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
771 $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
772 $contatto_state = $contatto->id_state ? new State((int) $contatto->id_state) : false;
773
774 $data = array(
775 '{firstname}' => $this->context->customer->firstname,
776 '{lastname}' => $this->context->customer->lastname,
777 '{email}' => $this->context->customer->email,
778 '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"),
779 '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"),
780 '{contatto_block_txt}' => $this->_getFormatedAddress($contatto, "\n"),
781 '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array(
782 'firstname' => '<span style="font-weight:bold;">%s</span>',
783 'lastname' => '<span style="font-weight:bold;">%s</span>',
784 )),
785 '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array(
786 'firstname' => '<span style="font-weight:bold;">%s</span>',
787 'lastname' => '<span style="font-weight:bold;">%s</span>',
788 )),
789 '{contatto_block_html}' => 'ciao',
790 '{delivery_company}' => $delivery->company,
791 '{delivery_firstname}' => $delivery->firstname,
792 '{delivery_lastname}' => $delivery->lastname,
793 '{delivery_address1}' => $delivery->address1,
794 '{delivery_address2}' => $delivery->address2,
795 '{delivery_city}' => $delivery->city,
796 '{delivery_postal_code}' => $delivery->postcode,
797 '{delivery_country}' => $delivery->country,
798 '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
799 '{delivery_phone}' => ($delivery->phone) ? $delivery->phone : $delivery->phone_mobile,
800 '{delivery_other}' => $delivery->other,
801 '{invoice_company}' => $invoice->company,
802 '{invoice_vat_number}' => $invoice->vat_number,
803 '{invoice_firstname}' => $invoice->firstname,
804 '{invoice_lastname}' => $invoice->lastname,
805 '{invoice_address2}' => $invoice->address2,
806 '{invoice_address1}' => $invoice->address1,
807 '{invoice_city}' => $invoice->city,
808 '{invoice_postal_code}' => $invoice->postcode,
809 '{invoice_country}' => $invoice->country,
810 '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
811 '{invoice_phone}' => ($invoice->phone) ? $invoice->phone : $invoice->phone_mobile,
812 '{invoice_other}' => $invoice->other,
813 '{contatto_company}' => $contatto->company,
814 '{contatto_vat_number}' => $contatto->vat_number,
815 '{contatto_firstname}' => $contatto->firstname,
816 '{contatto_lastname}' => $contatto->lastname,
817 '{contatto_address2}' => $contatto->address2,
818 '{contatto_address1}' => $contatto->address1,
819 '{contatto_city}' => $contatto->city,
820 '{contatto_postal_code}' => $contatto->postcode,
821 '{contatto_country}' => $contatto->country,
822 '{contatto_state}' => $contatto->id_state ? $contatto_state->name : '',
823 '{contatto_phone}' => ($contatto->phone) ? $contatto->phone : $contatto->phone_mobile,
824 '{contatto_other}' => $contatto->other,
825 '{order_name}' => $order->getUniqReference(),
826 '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
827 '{carrier}' => ($virtual_product || !isset($carrier->name)) ? $this->trans('No carrier', array(), 'Admin.Payment.Notification') : $carrier->name,
828 '{payment}' => Tools::substr($order->payment, 0, 255),
829 '{products}' => $product_list_html,
830 '{products_txt}' => $product_list_txt,
831 '{discounts}' => $cart_rules_list_html,
832 '{discounts_txt}' => $cart_rules_list_txt,
833 '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
834 '{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
835 '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
836 '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
837 '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
838 '{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false), );
839
840 if (is_array($extra_vars)) {
841 $data = array_merge($data, $extra_vars);
842 }
843
844 // Join PDF invoice
845 if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
846 $order_invoice_list = $order->getInvoicesCollection();
847 Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $order_invoice_list));
848 $pdf = new PDF($order_invoice_list, PDF::TEMPLATE_INVOICE, $this->context->smarty);
849 $file_attachement['content'] = $pdf->render(false);
850 $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
851 $file_attachement['mime'] = 'application/pdf';
852 } else {
853 $file_attachement = null;
854 }
855
856 if (self::DEBUG_MODE) {
857 PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
858 }
859
860 $orderLanguage = new Language((int) $order->id_lang);
861
862 if (Validate::isEmail($this->context->customer->email)) {
863 Mail::Send(
864 (int) $order->id_lang,
865 'order_conf',
866 Context::getContext()->getTranslator()->trans(
867 'Order confirmation',
868 array(),
869 'Emails.Subject',
870 $orderLanguage->locale
871 ),
872 $data,
873 $this->context->customer->email,
874 $this->context->customer->firstname . ' ' . $this->context->customer->lastname,
875 null,
876 null,
877 $file_attachement,
878 null, _PS_MAIL_DIR_, false, (int) $order->id_shop
879 );
880 }
881 }
882
883 // updates stock in shops
884 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
885 $product_list = $order->getProducts();
886 foreach ($product_list as $product) {
887 // if the available quantities depends on the physical stock
888 if (StockAvailable::dependsOnStock($product['product_id'])) {
889 // synchronizes
890 StockAvailable::synchronize($product['product_id'], $order->id_shop);
891 }
892 }
893 }
894
895 $order->updateOrderDetailTax();
896
897 // sync all stock
898 (new StockManager())->updatePhysicalProductQuantity(
899 (int) $order->id_shop,
900 (int) Configuration::get('PS_OS_ERROR'),
901 (int) Configuration::get('PS_OS_CANCELED'),
902 null,
903 (int) $order->id
904 );
905 } else {
906 $error = $this->trans('Order creation failed', array(), 'Admin.Payment.Notification');
907 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart));
908 die($error);
909 }
910 } // End foreach $order_detail_list
911
912 // Use the last order as currentOrder
913 if (isset($order) && $order->id) {
914 $this->currentOrder = (int) $order->id;
915 }
916
917 if (self::DEBUG_MODE) {
918 PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
919 }
920
921 return true;
922 } else {
923 $error = $this->trans('Cart cannot be loaded or an order has already been placed using this cart', array(), 'Admin.Payment.Notification');
924 PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id));
925 die($error);
926 }
927 }
928
929 /**
930 * @deprecated 1.6.0.7
931 *
932 * @param mixed $content
933 *
934 * @return mixed
935 */
936 public function formatProductAndVoucherForEmail($content)
937 {
938 Tools::displayAsDeprecated('Use $content instead');
939
940 return $content;
941 }
942
943 /**
944 * @param object Address $the_address that needs to be txt formated
945 *
946 * @return string the txt formated address block
947 */
948 protected function _getTxtFormatedAddress($the_address)
949 {
950 $adr_fields = AddressFormat::getOrderedAddressFields($the_address->id_country, false, true);
951 $r_values = array();
952 foreach ($adr_fields as $fields_line) {
953 $tmp_values = array();
954 foreach (explode(' ', $fields_line) as $field_item) {
955 $field_item = trim($field_item);
956 $tmp_values[] = $the_address->{$field_item};
957 }
958 $r_values[] = implode(' ', $tmp_values);
959 }
960
961 $out = implode("\n", $r_values);
962
963 return $out;
964 }
965
966 /**
967 * @param object Address $the_address that needs to be txt formated
968 *
969 * @return string the txt formated address block
970 */
971 protected function _getFormatedAddress(Address $the_address, $line_sep, $fields_style = array())
972 {
973 return AddressFormat::generateAddress($the_address, array('avoid' => array()), $line_sep, ' ', $fields_style);
974 }
975
976 /**
977 * @param int $current_id_currency optional but on 1.5 it will be REQUIRED
978 *
979 * @return Currency
980 */
981 public function getCurrency($current_id_currency = null)
982 {
983 if (!(int) $current_id_currency) {
984 $current_id_currency = Context::getContext()->currency->id;
985 }
986
987 if (!$this->currencies) {
988 return false;
989 }
990 if ($this->currencies_mode == 'checkbox') {
991 $currencies = Currency::getPaymentCurrencies($this->id);
992
993 return $currencies;
994 } elseif ($this->currencies_mode == 'radio') {
995 $currencies = Currency::getPaymentCurrenciesSpecial($this->id);
996 $currency = $currencies['id_currency'];
997 if ($currency == -1) {
998 $id_currency = (int) $current_id_currency;
999 } elseif ($currency == -2) {
1000 $id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
1001 } else {
1002 $id_currency = $currency;
1003 }
1004 }
1005 if (!isset($id_currency) || empty($id_currency)) {
1006 return false;
1007 }
1008 $currency = new Currency((int) $id_currency);
1009
1010 return $currency;
1011 }
1012
1013 /**
1014 * Allows specified payment modules to be used by a specific currency.
1015 *
1016 * @since 1.4.5
1017 *
1018 * @param int $id_currency
1019 * @param array $id_module_list
1020 *
1021 * @return bool
1022 */
1023 public static function addCurrencyPermissions($id_currency, array $id_module_list = array())
1024 {
1025 $values = '';
1026 if (count($id_module_list) == 0) {
1027 // fetch all installed module ids
1028 $modules = PaymentModuleCore::getInstalledPaymentModules();
1029 foreach ($modules as $module) {
1030 $id_module_list[] = $module['id_module'];
1031 }
1032 }
1033
1034 foreach ($id_module_list as $id_module) {
1035 $values .= '(' . (int) $id_module . ',' . (int) $id_currency . '),';
1036 }
1037
1038 if (!empty($values)) {
1039 return Db::getInstance()->execute('
1040 INSERT INTO `' . _DB_PREFIX_ . 'module_currency` (`id_module`, `id_currency`)
1041 VALUES ' . rtrim($values, ','));
1042 }
1043
1044 return true;
1045 }
1046
1047 /**
1048 * List all installed and active payment modules.
1049 *
1050 * @see Module::getPaymentModules() if you need a list of module related to the user context
1051 * @since 1.4.5
1052 *
1053 * @return array module informations
1054 */
1055 public static function getInstalledPaymentModules()
1056 {
1057 $hook_payment = 'Payment';
1058 if (Db::getInstance()->getValue('SELECT `id_hook` FROM `' . _DB_PREFIX_ . 'hook` WHERE `name` = \'paymentOptions\'')) {
1059 $hook_payment = 'paymentOptions';
1060 }
1061
1062 return Db::getInstance()->executeS('
1063 SELECT DISTINCT m.`id_module`, h.`id_hook`, m.`name`, hm.`position`
1064 FROM `' . _DB_PREFIX_ . 'module` m
1065 LEFT JOIN `' . _DB_PREFIX_ . 'hook_module` hm ON hm.`id_module` = m.`id_module`'
1066 . Shop::addSqlRestriction(false, 'hm') . '
1067 LEFT JOIN `' . _DB_PREFIX_ . 'hook` h ON hm.`id_hook` = h.`id_hook`
1068 INNER JOIN `' . _DB_PREFIX_ . 'module_shop` ms ON (m.`id_module` = ms.`id_module` AND ms.id_shop=' . (int) Context::getContext()->shop->id . ')
1069 WHERE h.`name` = \'' . pSQL($hook_payment) . '\'');
1070 }
1071
1072 public static function preCall($module_name)
1073 {
1074 if (!parent::preCall($module_name)) {
1075 return false;
1076 }
1077
1078 if (($module_instance = Module::getInstanceByName($module_name))) {
1079 /** @var PaymentModule $module_instance */
1080 if (!$module_instance->currencies || ($module_instance->currencies && count(Currency::checkPaymentCurrencies($module_instance->id)))) {
1081 return true;
1082 }
1083 }
1084
1085 return false;
1086 }
1087
1088 /**
1089 * Fetch the content of $template_name inside the folder
1090 * current_theme/mails/current_iso_lang/ if found, otherwise in
1091 * mails/current_iso_lang.
1092 *
1093 * @param string $template_name template name with extension
1094 * @param int $mail_type Mail::TYPE_HTML or Mail::TYPE_TEXT
1095 * @param array $var sent to smarty as 'list'
1096 *
1097 * @return string
1098 */
1099 protected function getEmailTemplateContent($template_name, $mail_type, $var)
1100 {
1101 $email_configuration = Configuration::get('PS_MAIL_TYPE');
1102 if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
1103 return '';
1104 }
1105
1106 $pathToFindEmail = array(
1107 _PS_THEME_DIR_ . 'mails' . DIRECTORY_SEPARATOR . $this->context->language->iso_code . DIRECTORY_SEPARATOR . $template_name,
1108 _PS_THEME_DIR_ . 'mails' . DIRECTORY_SEPARATOR . 'en' . DIRECTORY_SEPARATOR . $template_name,
1109 _PS_MAIL_DIR_ . $this->context->language->iso_code . DIRECTORY_SEPARATOR . $template_name,
1110 _PS_MAIL_DIR_ . 'en' . DIRECTORY_SEPARATOR . $template_name,
1111 );
1112
1113 foreach ($pathToFindEmail as $path) {
1114 if (Tools::file_exists_cache($path)) {
1115 $this->context->smarty->assign('list', $var);
1116
1117 return $this->context->smarty->fetch($path);
1118 }
1119 }
1120
1121 return '';
1122 }
1123}